Skip to content

Commit a315e38

Browse files
author
git-core
committed
Clean up database_check
o don't use malloc/free, allocate space on stack o don't use unsafe sprintf o use ARG_MAX as cmd size for clarity, cmd isn't just a filename o remove unsafe logging, ensure last points inside cmd
1 parent 5bbd487 commit a315e38

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

db.c

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,29 +24,30 @@
2424
int database_check(const struct su_context *ctx)
2525
{
2626
FILE *fp;
27-
char allow = '-';
28-
char *filename = malloc(snprintf(NULL, 0, "%s/%u-%u", REQUESTOR_STORED_PATH, ctx->from.uid, ctx->to.uid) + 1);
29-
sprintf(filename, "%s/%u-%u", REQUESTOR_STORED_PATH, ctx->from.uid, ctx->to.uid);
27+
int allow = '-';
28+
char filename[PATH_MAX];
29+
30+
snprintf(filename, sizeof(filename),
31+
REQUESTOR_STORED_PATH "/%u-%u", ctx->from.uid, ctx->to.uid);
3032
if ((fp = fopen(filename, "r"))) {
31-
LOGD("Found file");
32-
char cmd[PATH_MAX];
33+
LOGD("Found file %s", filename);
34+
char cmd[ARG_MAX];
3335
fgets(cmd, sizeof(cmd), fp);
36+
/* skip trailing '\n' */
3437
int last = strlen(cmd) - 1;
35-
LOGD("this is the last character %u of the string", cmd[5]);
36-
if (cmd[last] == '\n') {
37-
cmd[last] = '\0';
38-
}
39-
LOGD("Comparing %c %s, %u to %s", cmd[last - 2], cmd, last, get_command(&ctx->to));
38+
if (last >= 0)
39+
cmd[last] = 0;
40+
41+
LOGD("Comparing '%s' to '%s'", cmd, get_command(&ctx->to));
4042
if (strcmp(cmd, get_command(&ctx->to)) == 0) {
4143
allow = fgetc(fp);
4244
}
4345
fclose(fp);
4446
} else if ((fp = fopen(REQUESTOR_STORED_DEFAULT, "r"))) {
45-
LOGD("Using default");
47+
LOGD("Using default file %s", REQUESTOR_STORED_DEFAULT);
4648
allow = fgetc(fp);
4749
fclose(fp);
4850
}
49-
free(filename);
5051

5152
if (allow == '1') {
5253
return DB_ALLOW;

0 commit comments

Comments
 (0)