Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug cgi program written in C and running in Apache2?

I have a complex cgi executable written in C, I configured in Apache2 and now it is running succesfully. How can I debug this program in the source code, such as set break points and inspect variables? Any tools like gdb or eclipse? Any tutorial of how to set up the debugging environment?

Thanks in advance!!

like image 299
Joe Avatar asked Dec 14 '22 23:12

Joe


2 Answers

The CGI interface basically consists in passing the HTTP request to the executable's standard input and getting the response on the standard output. Therefore you can write test requests to files and manually execute your CGI without having to use Apache. The debugging can then be done with GDB :

gdb ./my_cgi
>> break some_func
>> run < my_req.txt

with my_req.txt containing the full request:

GET /some/func HTTP/1.0
Host: myhost

If you absolutely need the CGI to be run by Apache it may become tricky to attach GDB to the right process. You can for example configure Apache to have only one worker process, attach to it with gdb -p and use set follow-fork-mode child to make sure it switches to the CGI process when a request arrives.

like image 73
Grapsus Avatar answered Jan 04 '23 22:01

Grapsus


I did this: in cgi main i added code to look for an existing file, like /var/tmp/flag. While existing, i run in a loop. Time enough to attach to cgi process via gdb. After then i delete /var/tmp/flag and from now I can debug my cgi code.

bool file_exists(const char *filename)
{
   ifstream ifile(filename);
   return ifile;
}

int cgiMain()
{

    while (file_exists ("/var/tmp/flag"))
    sleep (1);
    ...
    your code 
like image 20
Schraubenkarl Avatar answered Jan 05 '23 00:01

Schraubenkarl