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 int request_get;
45 static char *query_string;
47 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 return a particular cgi variable
252 ***************************************************************************/
253 char *cgi_vnum(int i, char **name)
255 if (i < 0 || i >= num_variables) return NULL;
256 *name = variables[i].name;
257 return variables[i].value;
260 /***************************************************************************
261 return the value of a CGI boolean variable.
262 ***************************************************************************/
263 int cgi_boolean(char *name, int def)
265 char *p = cgi_variable(name);
269 return strcmp(p, "1") == 0;
272 /***************************************************************************
273 like strdup() but quotes < > and &
274 ***************************************************************************/
275 char *quotedup(char *s)
282 if (!s) return strdup("");
287 if (s[i] == '<' || s[i] == '>' || s[i] == '&')
290 ret = malloc(len + n*6 + 1);
292 if (!ret) return NULL;
296 for (i=0;i<len;i++) {
299 safe_strcpy(d, "<", len + n*6 - (d - ret));
304 safe_strcpy(d, ">", len + n*6 - (d - ret));
309 safe_strcpy(d, "&", len + n*6 - (d - ret));
324 /***************************************************************************
325 like strdup() but quotes a wide range of characters
326 ***************************************************************************/
327 char *urlquote(char *s)
333 char *qlist = "\"\n\r'&<> \t+;";
335 if (!s) return strdup("");
340 if (strchr(qlist, s[i])) n++;
342 ret = malloc(len + n*2 + 1);
344 if (!ret) return NULL;
348 for (i=0;i<len;i++) {
349 if (strchr(qlist,s[i])) {
350 slprintf(d, len + n*2 - (d - ret), "%%%02X", (int)s[i]);
363 /***************************************************************************
364 like strdup() but quotes " characters
365 ***************************************************************************/
366 char *quotequotes(char *s)
373 if (!s) return strdup("");
381 ret = malloc(len + n*6 + 1);
383 if (!ret) return NULL;
387 for (i=0;i<len;i++) {
390 safe_strcpy(d, """, len + n*6 - (d - ret));
405 /***************************************************************************
406 quote spaces in a buffer
407 ***************************************************************************/
408 void quote_spaces(char *buf)
411 if (*buf == ' ') *buf = '+';
418 /***************************************************************************
419 tell a browser about a fatal error in the http processing
420 ***************************************************************************/
421 static void cgi_setup_error(char *err, char *header, char *info)
423 printf("HTTP/1.1 %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);
428 /***************************************************************************
429 decode a base64 string in-place - simple and slow algorithm
430 ***************************************************************************/
431 static void base64_decode(char *s)
433 char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
434 int bit_offset, byte_offset, idx, i, n;
435 unsigned char *d = (unsigned char *)s;
440 while (*s && (p=strchr(b64,*s))) {
441 idx = (int)(p - b64);
442 byte_offset = (i*6)/8;
443 bit_offset = (i*6)%8;
444 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
445 if (bit_offset < 3) {
446 d[byte_offset] |= (idx << (2-bit_offset));
449 d[byte_offset] |= (idx >> (bit_offset-2));
450 d[byte_offset+1] = 0;
451 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
461 /***************************************************************************
462 handle a http authentication line
463 ***************************************************************************/
464 static int cgi_handle_authorization(char *line)
466 char *p, *user, *pass;
468 if (strncasecmp(line,"Basic ", 6)) {
469 cgi_setup_error("401 Bad Authorization", "",
470 "Only basic authorization is understood");
473 while (line[0] == ' ') line++;
475 if (!(p=strchr(line,':'))) {
476 cgi_setup_error("401 Bad Authorization", "",
477 "username/password must be supplied");
483 /* currently only allow connections as root */
484 if (strcmp(user,"root")) {
485 cgi_setup_error("401 Bad Authorization", "",
486 "incorrect username/password");
490 return pass_check(user, pass, strlen(pass), NULL, NULL);
494 /***************************************************************************
495 handle a file download
496 ***************************************************************************/
497 static void cgi_download(char *file)
504 /* sanitise the filename */
505 for (i=0;file[i];i++) {
506 if (!isalnum((int)file[i]) && !strchr("/.-_", file[i])) {
507 cgi_setup_error("404 File Not Found","",
508 "Illegal character in filename");
512 if (!file_exist(file, &st)) {
513 cgi_setup_error("404 File Not Found","",
514 "The requested file was not found");
516 fd = open(file,O_RDONLY);
518 cgi_setup_error("404 File Not Found","",
519 "The requested file was not found");
521 printf("HTTP/1.1 200 OK\r\n");
522 if ((p=strrchr(file,'.'))) {
523 if (strcmp(p,".gif")==0) {
524 printf("Content-Type: image/gif\r\n");
525 } else if (strcmp(p,".jpg")==0) {
526 printf("Content-Type: image/jpeg\r\n");
528 printf("Content-Type: text/html\r\n");
531 printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
533 printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
534 while ((l=read(fd,buf,sizeof(buf)))>0) {
535 fwrite(buf, 1, l, stdout);
542 /***************************************************************************
543 setup the cgi framework, handling the possability that this program is either
544 run as a true cgi program by a web browser or is itself a mini web server
545 ***************************************************************************/
546 void cgi_setup(char *rootdir, int auth_required)
548 int authenticated = 0;
556 if (chdir(rootdir)) {
557 cgi_setup_error("400 Server Error", "",
558 "chdir failed - the server is not configured correctly");
561 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
562 /* assume we are running under a real web server */
567 f = fopen("/tmp/cgi.log", "a");
568 if (f) fprintf(f,"\n[Date: %s %s (%s)]\n",
569 http_timestring(time(NULL)),
570 client_name(1), client_addr(1));
573 /* we are a mini-web server. We need to read the request from stdin
574 and handle authentication etc */
575 while (fgets(line, sizeof(line)-1, stdin)) {
577 if (f) fputs(line, f);
579 if (line[0] == '\r' || line[0] == '\n') break;
580 if (strncasecmp(line,"GET ", 4)==0) {
582 url = strdup(&line[4]);
583 } else if (strncasecmp(line,"POST ", 5)==0) {
585 url = strdup(&line[5]);
586 } else if (strncasecmp(line,"PUT ", 4)==0) {
587 cgi_setup_error("400 Bad Request", "",
588 "This server does not accept PUT requests");
589 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
590 authenticated = cgi_handle_authorization(&line[15]);
591 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
592 content_length = atoi(&line[16]);
594 /* ignore all other requests! */
600 if (auth_required && !authenticated) {
601 cgi_setup_error("401 Authorization Required",
602 "WWW-Authenticate: Basic realm=\"root\"\r\n",
603 "You must be authenticated to use this service");
607 cgi_setup_error("400 Bad Request", "",
608 "You must specify a GET or POST request");
612 if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
615 while (*url && strchr("\r\n",url[strlen(url)-1])) {
616 url[strlen(url)-1] = 0;
619 /* anything following a ? in the URL is part of the query string */
620 if ((p=strchr(url,'?'))) {
625 if (strstr(url+1,"..")==0 && file_exist(url+1, NULL)) {
629 printf("HTTP/1.1 200 OK\r\nConnection: close\r\n");
630 printf("Date: %s\r\n", http_timestring(time(NULL)));
636 /***************************************************************************
637 return the current pages URL
638 ***************************************************************************/
639 char *cgi_baseurl(void)
644 return getenv("SCRIPT_NAME");
647 /***************************************************************************
648 return the root URL for images etc
649 ***************************************************************************/
650 char *cgi_rooturl(void)
659 /***************************************************************************
660 return the current pages path info
661 ***************************************************************************/
662 char *cgi_pathinfo(void)
668 r = getenv("PATH_INFO");
674 /***************************************************************************
675 return the hostname of the client
676 ***************************************************************************/
677 char *cgi_remote_host(void)
680 return client_name(1);
682 return getenv("REMOTE_HOST");
685 /***************************************************************************
686 return the hostname of the client
687 ***************************************************************************/
688 char *cgi_remote_addr(void)
691 return client_addr(1);
693 return getenv("REMOTE_ADDR");
697 /***************************************************************************
698 return True if the request was a POST
699 ***************************************************************************/
700 BOOL cgi_waspost(void)
705 return strequal(getenv("REQUEST_METHOD"), "POST");