2 some simple CGI helper routines
3 Copyright (C) Andrew Tridgell 1997-1998
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #define MAX_VARIABLES 10000
26 /* set the expiry on fixed pages */
27 #define EXPIRY_TIME (60*60*24*7)
32 extern void print_title(char *fmt, ...);
40 static struct var variables[MAX_VARIABLES];
41 static int num_variables;
42 static int content_length;
43 static int request_post;
44 static char *query_string;
46 static char *pathinfo;
49 static void unescape(char *buf)
53 while ((p=strchr(p,'+')))
58 while (p && *p && (p=strchr(p,'%'))) {
62 if (c1 >= '0' && c1 <= '9')
64 else if (c1 >= 'A' && c1 <= 'F')
66 else if (c1 >= 'a' && c1 <= 'f')
70 if (c2 >= '0' && c2 <= '9')
72 else if (c2 >= 'A' && c2 <= 'F')
74 else if (c2 >= 'a' && c2 <= 'f')
80 memcpy(p+1, p+3, strlen(p+3)+1);
86 static char *grab_line(FILE *f, int *cl)
92 ret = (char *)malloc(len);
93 if (!ret) return NULL;
105 if (c == '\r') continue;
107 if (strchr("\n&", c)) break;
113 ret2 = (char *)realloc(ret, len*2);
114 if (!ret2) return ret;
125 /***************************************************************************
126 load all the variables passed to the CGI program. May have multiple variables
127 with the same name and the same or different values. Takes a file parameter
128 for simulating CGI invocation eg loading saved preferences.
129 ***************************************************************************/
130 void cgi_load_variables(FILE *f1)
137 #ifdef DEBUG_COMMENTS
140 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
145 if (!content_length) {
146 p = getenv("CONTENT_LENGTH");
149 len = content_length;
152 fseek(f, 0, SEEK_END);
154 fseek(f, 0, SEEK_SET);
159 (f1 || request_post ||
160 ((s=getenv("REQUEST_METHOD")) &&
161 strcasecmp(s,"POST")==0))) {
162 while (len && (line=grab_line(f, &len))) {
163 p = strchr(line,'=');
168 variables[num_variables].name = strdup(line);
169 variables[num_variables].value = strdup(p+1);
173 if (!variables[num_variables].name ||
174 !variables[num_variables].value)
177 unescape(variables[num_variables].value);
178 unescape(variables[num_variables].name);
180 #ifdef DEBUG_COMMENTS
181 printf("<!== POST var %s has value \"%s\" ==>\n",
182 variables[num_variables].name,
183 variables[num_variables].value);
187 if (num_variables == MAX_VARIABLES) break;
192 #ifdef DEBUG_COMMENTS
193 printf("<!== End dump in cgi_load_variables() ==>\n");
200 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
201 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
207 variables[num_variables].name = strdup(tok);
208 variables[num_variables].value = strdup(p+1);
210 if (!variables[num_variables].name ||
211 !variables[num_variables].value)
214 unescape(variables[num_variables].value);
215 unescape(variables[num_variables].name);
217 #ifdef DEBUG_COMMENTS
218 printf("<!== Commandline var %s has value \"%s\" ==>\n",
219 variables[num_variables].name,
220 variables[num_variables].value);
223 if (num_variables == MAX_VARIABLES) break;
227 #ifdef DEBUG_COMMENTS
228 printf("<!== End dump in cgi_load_variables() ==>\n");
233 /***************************************************************************
234 find a variable passed via CGI
235 Doesn't quite do what you think in the case of POST text variables, because
236 if they exist they might have a value of "" or even " ", depending on the
237 browser. Also doesn't allow for variables[] containing multiple variables
238 with the same name and the same or different values.
239 ***************************************************************************/
240 char *cgi_variable(char *name)
244 for (i=0;i<num_variables;i++)
245 if (strcmp(variables[i].name, name) == 0)
246 return variables[i].value;
250 /***************************************************************************
251 tell a browser about a fatal error in the http processing
252 ***************************************************************************/
253 static void cgi_setup_error(char *err, char *header, char *info)
255 printf("HTTP/1.0 %s\r\n%sConnection: close\r\nContent-Type: text/html\r\n\r\n<HTML><HEAD><TITLE>%s</TITLE></HEAD><BODY><H1>%s</H1>%s<p></BODY></HTML>\r\n", err, header, err, err, info);
260 /***************************************************************************
261 decode a base64 string in-place - simple and slow algorithm
262 ***************************************************************************/
263 static void base64_decode(char *s)
265 char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
266 int bit_offset, byte_offset, idx, i, n;
267 unsigned char *d = (unsigned char *)s;
272 while (*s && (p=strchr(b64,*s))) {
273 idx = (int)(p - b64);
274 byte_offset = (i*6)/8;
275 bit_offset = (i*6)%8;
276 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
277 if (bit_offset < 3) {
278 d[byte_offset] |= (idx << (2-bit_offset));
281 d[byte_offset] |= (idx >> (bit_offset-2));
282 d[byte_offset+1] = 0;
283 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
293 /***************************************************************************
294 handle a http authentication line
295 ***************************************************************************/
296 static BOOL cgi_handle_authorization(char *line)
298 char *p, *user, *user_pass;
299 struct passwd *pass = NULL;
302 if (strncasecmp(line,"Basic ", 6)) {
303 cgi_setup_error("401 Bad Authorization", "",
304 "Only basic authorization is understood");
308 while (line[0] == ' ') line++;
310 if (!(p=strchr(line,':'))) {
312 * Always give the same error so a cracker
313 * cannot tell why we fail.
315 cgi_setup_error("401 Bad Authorization", "",
316 "username/password must be supplied");
324 * Try and get the user from the UNIX password file.
327 if(!(pass = Get_Pwnam(user,False))) {
329 * Always give the same error so a cracker
330 * cannot tell why we fail.
332 cgi_setup_error("401 Bad Authorization", "",
333 "username/password must be supplied");
338 * Validate the password they have given.
341 if((ret = pass_check(user, user_pass, strlen(user_pass), NULL, NULL)) == True) {
347 if(pass->pw_uid != 0) {
349 * We have not authenticated as root,
350 * become the user *permanently*.
352 if(!become_user_permanently(pass->pw_uid, pass->pw_gid)) {
354 * Always give the same error so a cracker
355 * cannot tell why we fail.
357 cgi_setup_error("401 Bad Authorization", "",
358 "username/password must be supplied");
363 * On exit from here we are the authenticated
364 * user - no way back.
368 /* Save the users name */
369 C_user = strdup(user);
375 /***************************************************************************
377 ***************************************************************************/
380 if (geteuid() == 0) {
387 /***************************************************************************
388 return a ptr to the users name
389 ***************************************************************************/
390 char *get_user_name(void)
396 /***************************************************************************
397 handle a file download
398 ***************************************************************************/
399 static void cgi_download(char *file)
406 /* sanitise the filename */
407 for (i=0;file[i];i++) {
408 if (!isalnum((int)file[i]) && !strchr("/.-_", file[i])) {
409 cgi_setup_error("404 File Not Found","",
410 "Illegal character in filename");
414 if (!file_exist(file, &st)) {
415 cgi_setup_error("404 File Not Found","",
416 "The requested file was not found");
418 fd = open(file,O_RDONLY);
420 cgi_setup_error("404 File Not Found","",
421 "The requested file was not found");
423 printf("HTTP/1.0 200 OK\r\n");
424 if ((p=strrchr(file,'.'))) {
425 if (strcmp(p,".gif")==0) {
426 printf("Content-Type: image/gif\r\n");
427 } else if (strcmp(p,".jpg")==0) {
428 printf("Content-Type: image/jpeg\r\n");
430 printf("Content-Type: text/html\r\n");
433 printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
435 printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
436 while ((l=read(fd,buf,sizeof(buf)))>0) {
437 fwrite(buf, 1, l, stdout);
444 /***************************************************************************
445 setup the cgi framework, handling the possability that this program is either
446 run as a true cgi program by a web browser or is itself a mini web server
447 ***************************************************************************/
448 void cgi_setup(char *rootdir, int auth_required)
450 BOOL authenticated = False;
458 if (chdir(rootdir)) {
459 cgi_setup_error("400 Server Error", "",
460 "chdir failed - the server is not configured correctly");
463 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
467 /* Save the users name if available */
468 if ((x = getenv("REMOTE_USER"))) {
474 /* assume we are running under a real web server */
479 f = fopen("/tmp/cgi.log", "a");
480 if (f) fprintf(f,"\n[Date: %s %s (%s)]\n",
481 http_timestring(time(NULL)),
482 client_name(1), client_addr(1));
485 /* we are a mini-web server. We need to read the request from stdin
486 and handle authentication etc */
487 while (fgets(line, sizeof(line)-1, stdin)) {
489 if (f) fputs(line, f);
491 if (line[0] == '\r' || line[0] == '\n') break;
492 if (strncasecmp(line,"GET ", 4)==0) {
493 url = strdup(&line[4]);
494 } else if (strncasecmp(line,"POST ", 5)==0) {
496 url = strdup(&line[5]);
497 } else if (strncasecmp(line,"PUT ", 4)==0) {
498 cgi_setup_error("400 Bad Request", "",
499 "This server does not accept PUT requests");
500 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
501 authenticated = cgi_handle_authorization(&line[15]);
502 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
503 content_length = atoi(&line[16]);
505 /* ignore all other requests! */
511 if (auth_required && !authenticated) {
512 cgi_setup_error("401 Authorization Required",
513 "WWW-Authenticate: Basic realm=\"root\"\r\n",
514 "You must be authenticated to use this service");
518 cgi_setup_error("400 Bad Request", "",
519 "You must specify a GET or POST request");
523 if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
526 while (*url && strchr("\r\n",url[strlen(url)-1])) {
527 url[strlen(url)-1] = 0;
530 /* anything following a ? in the URL is part of the query string */
531 if ((p=strchr(url,'?'))) {
536 string_sub(url, "/swat/", "");
538 if (strstr(url,"..")==0 && file_exist(url, NULL)) {
542 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
543 printf("Date: %s\r\n", http_timestring(time(NULL)));
549 /***************************************************************************
550 return the current pages URL
551 ***************************************************************************/
552 char *cgi_baseurl(void)
557 return getenv("SCRIPT_NAME");
560 /***************************************************************************
561 return the current pages path info
562 ***************************************************************************/
563 char *cgi_pathinfo(void)
569 r = getenv("PATH_INFO");
575 /***************************************************************************
576 return the hostname of the client
577 ***************************************************************************/
578 char *cgi_remote_host(void)
581 return client_name(1);
583 return getenv("REMOTE_HOST");
586 /***************************************************************************
587 return the hostname of the client
588 ***************************************************************************/
589 char *cgi_remote_addr(void)
592 return client_addr(1);
594 return getenv("REMOTE_ADDR");
598 /***************************************************************************
599 return True if the request was a POST
600 ***************************************************************************/
601 BOOL cgi_waspost(void)
606 return strequal(getenv("REQUEST_METHOD"), "POST");