I’m working on a CGI file using C that does things only if the request method is POST.
int main(void)
{
char *method_str = getenv("REQUEST_METHOD");
int iMethod = strcmp(method_str,"POST");
int tid = 0;
int own_id = 0;
char key[16] = "\0";
if (iMethod == -1) {
puts("Location:start.cgi\n\n");
} else if (iMethod == 0) {
char *data = getenv("CONTENT_LENGTH");
int size = atoi(data);
char *buffer = malloc((size+1)*sizeof(char));
fgets(buffer,atoi(data)+1,stdin);
int counter = count(buffer);
char **names = malloc(counter*sizeof(char *));
char **values = malloc(counter*sizeof(char *));
parse(buffer, names, values);
int isDel = strcmp(*(values+1),"Back to Start");
if (isDel == 0) startpage(atoi(*values));
else {
own_id = atoi(*values);
sprintf(key,"%s",*(values+1));
int stat = login_status(own_id,key);
if (stat == -1) {
startpage(0);
} else userpage(own_id);
}
free_mallocs(names,values,counter);
free(buffer);
}
free(method_str);
return 0;
}
Running the CGI file in gdb tells me that the problem is in the line:
int iMethod = strcmp(method_str,"POST");. The error is SIGSEGV.
The CGI runs fine when I open it from a XAMPP server. However, when I run it in an Ubuntu server different from mine, Error 500 occurs. I tried comparing the value of getenv("REQUEST_METHOD") with NULL, and gdb tells me that the file ran normally. However, the CGI file failed to run properly on both my XAMPP server and the other server, with the two showing error 500.
What I can tell you is that the functions have their Content headers set. The functions count() and parse() were set appropriately and independent of the situation at hand.
Thanks in advance.
Update: If the user opens the CGI file directly, the browser will redirect to another CGI file.
strcmpwill segfault when the first parameter isNULL. Check forNULLand you’d be fine:As an extra, try to avoid
strcmpand always usestrncmpas it is safer: