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.
29 #define MAX_VARIABLES 10000
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;
48 static void unescape(char *buf)
52 while ((p=strchr(p,'+')))
57 while (p && *p && (p=strchr(p,'%'))) {
61 if (c1 >= '0' && c1 <= '9')
63 else if (c1 >= 'A' && c1 <= 'F')
65 else if (c1 >= 'a' && c1 <= 'f')
69 if (c2 >= '0' && c2 <= '9')
71 else if (c2 >= 'A' && c2 <= 'F')
73 else if (c2 >= 'a' && c2 <= 'f')
79 memcpy(p+1, p+3, strlen(p+3)+1);
85 static char *grab_line(FILE *f, int *cl)
91 ret = (char *)malloc(len);
92 if (!ret) return NULL;
104 if (c == '\r') continue;
106 if (strchr("\n&", c)) break;
112 ret2 = (char *)realloc(ret, len*2);
113 if (!ret2) return ret;
124 /***************************************************************************
125 load all the variables passed to the CGI program. May have multiple variables
126 with the same name and the same or different values. Takes a file parameter
127 for simulating CGI invocation eg loading saved preferences.
128 ***************************************************************************/
129 void cgi_load_variables(FILE *f1)
136 #ifdef DEBUG_COMMENTS
139 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
144 if (!content_length) {
145 p = getenv("CONTENT_LENGTH");
148 len = content_length;
151 fseek(f, 0, SEEK_END);
153 fseek(f, 0, SEEK_SET);
158 (f1 || request_post ||
159 ((s=getenv("REQUEST_METHOD")) &&
160 strcasecmp(s,"POST")==0))) {
161 while (len && (line=grab_line(f, &len))) {
162 p = strchr(line,'=');
167 variables[num_variables].name = strdup(line);
168 variables[num_variables].value = strdup(p+1);
172 if (!variables[num_variables].name ||
173 !variables[num_variables].value)
176 unescape(variables[num_variables].value);
177 unescape(variables[num_variables].name);
179 #ifdef DEBUG_COMMENTS
180 printf("<!== POST var %s has value \"%s\" ==>\n",
181 variables[num_variables].name,
182 variables[num_variables].value);
186 if (num_variables == MAX_VARIABLES) break;
191 #ifdef DEBUG_COMMENTS
192 printf("<!== End dump in cgi_load_variables() ==>\n");
199 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
200 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
206 variables[num_variables].name = strdup(tok);
207 variables[num_variables].value = strdup(p+1);
209 if (!variables[num_variables].name ||
210 !variables[num_variables].value)
213 unescape(variables[num_variables].value);
214 unescape(variables[num_variables].name);
216 #ifdef DEBUG_COMMENTS
217 printf("<!== Commandline var %s has value \"%s\" ==>\n",
218 variables[num_variables].name,
219 variables[num_variables].value);
222 if (num_variables == MAX_VARIABLES) break;
226 #ifdef DEBUG_COMMENTS
227 printf("<!== End dump in cgi_load_variables() ==>\n");
232 /***************************************************************************
233 find a variable passed via CGI
234 Doesn't quite do what you think in the case of POST text variables, because
235 if they exist they might have a value of "" or even " ", depending on the
236 browser. Also doesn't allow for variables[] containing multiple variables
237 with the same name and the same or different values.
238 ***************************************************************************/
239 char *cgi_variable(char *name)
243 for (i=0;i<num_variables;i++)
244 if (strcmp(variables[i].name, name) == 0)
245 return variables[i].value;
249 /***************************************************************************
250 return a particular cgi variable
251 ***************************************************************************/
252 char *cgi_vnum(int i, char **name)
254 if (i < 0 || i >= num_variables) return NULL;
255 *name = variables[i].name;
256 return variables[i].value;
259 /***************************************************************************
260 return the value of a CGI boolean variable.
261 ***************************************************************************/
262 int cgi_boolean(char *name, int def)
264 char *p = cgi_variable(name);
268 return strcmp(p, "1") == 0;
271 /***************************************************************************
272 like strdup() but quotes < > and &
273 ***************************************************************************/
274 char *quotedup(char *s)
281 if (!s) return strdup("");
286 if (s[i] == '<' || s[i] == '>' || s[i] == '&')
289 ret = malloc(len + n*6 + 1);
291 if (!ret) return NULL;
295 for (i=0;i<len;i++) {
323 /***************************************************************************
324 like strdup() but quotes a wide range of characters
325 ***************************************************************************/
326 char *urlquote(char *s)
332 char *qlist = "\"\n\r'&<> \t+;";
334 if (!s) return strdup("");
339 if (strchr(qlist, s[i])) n++;
341 ret = malloc(len + n*2 + 1);
343 if (!ret) return NULL;
347 for (i=0;i<len;i++) {
348 if (strchr(qlist,s[i])) {
349 sprintf(d, "%%%02X", (int)s[i]);
362 /***************************************************************************
363 like strdup() but quotes " characters
364 ***************************************************************************/
365 char *quotequotes(char *s)
372 if (!s) return strdup("");
380 ret = malloc(len + n*6 + 1);
382 if (!ret) return NULL;
386 for (i=0;i<len;i++) {
404 /***************************************************************************
405 quote spaces in a buffer
406 ***************************************************************************/
407 void quote_spaces(char *buf)
410 if (*buf == ' ') *buf = '+';
417 /***************************************************************************
418 tell a browser about a fatal error in the http processing
419 ***************************************************************************/
420 static void cgi_setup_error(char *err, char *header, char *info)
422 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);
427 /***************************************************************************
428 decode a base64 string in-place - simple and slow algorithm
429 ***************************************************************************/
430 static void base64_decode(char *s)
432 char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
433 int bit_offset, byte_offset, idx, i;
434 unsigned char *d = (unsigned char *)s;
439 while (*s && (p=strchr(b64,*s))) {
440 idx = (int)(p - b64);
441 byte_offset = (i*6)/8;
442 bit_offset = (i*6)%8;
443 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
444 if (bit_offset < 3) {
445 d[byte_offset] |= (idx << (2-bit_offset));
447 d[byte_offset] |= (idx >> (bit_offset-2));
448 d[byte_offset+1] = 0;
449 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
456 /***************************************************************************
457 handle a http authentication line
458 ***************************************************************************/
459 static int cgi_handle_authorization(char *line)
461 char *p, *user, *pass;
465 if (strncasecmp(line,"Basic ", 6)) {
466 cgi_setup_error("401 Bad Authorization", "",
467 "Only basic authorization is understood");
470 while (line[0] == ' ') line++;
472 if (!(p=strchr(line,':'))) {
473 cgi_setup_error("401 Bad Authorization", "",
474 "username/password must be supplied");
480 /* currently only allow connections as root */
481 if (strcasecmp(user,"root")) {
482 cgi_setup_error("401 Bad Authorization", "",
483 "incorrect username/password");
486 pwd = getpwnam(user);
488 if (!strcmp((char *)crypt(pass, pwd->pw_passwd),pwd->pw_passwd)) {
492 memset(pass, 0, strlen(pass));
498 /***************************************************************************
499 handle a file download
500 ***************************************************************************/
501 static void cgi_download(char *file)
508 /* sanitise the filename */
509 for (i=0;file[i];i++) {
510 if (!isalnum(file[i]) && !strchr("/.-_", file[i])) {
511 cgi_setup_error("404 File Not Found","",
512 "Illegal character in filename");
516 if (!file_exist(file, &st)) {
517 cgi_setup_error("404 File Not Found","",
518 "The requested file was not found");
520 fd = open(file,O_RDONLY);
522 cgi_setup_error("404 File Not Found","",
523 "The requested file was not found");
525 printf("HTTP/1.1 200 OK\r\n");
526 if ((p=strrchr(file,'.'))) {
527 if (strcmp(p,".gif")==0 || strcmp(p,".jpg")==0) {
528 printf("Content-Type: image/gif\r\n");
530 printf("Content-Type: text/html\r\n");
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;
553 if (chdir(rootdir)) {
554 cgi_setup_error("400 Server Error", "",
555 "chdir failed - the server is not configured correctly");
558 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
559 /* assume we are running under a real web server */
563 /* we are a mini-web server. We need to read the request from stdin
564 and handle authentication etc */
565 while (fgets(line, sizeof(line)-1, stdin)) {
566 if (line[0] == '\r' || line[0] == '\n') break;
567 if (strncasecmp(line,"GET ", 4)==0) {
569 url = strdup(&line[4]);
570 } else if (strncasecmp(line,"POST ", 5)==0) {
572 url = strdup(&line[5]);
573 } else if (strncasecmp(line,"PUT ", 4)==0) {
574 cgi_setup_error("400 Bad Request", "",
575 "This server does not accept PUT requests");
576 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
577 authenticated = cgi_handle_authorization(&line[15]);
578 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
579 content_length = atoi(&line[16]);
581 /* ignore all other requests! */
584 if (auth_required && !authenticated) {
585 cgi_setup_error("401 Authorization Required",
586 "WWW-Authenticate: Basic realm=\"root\"\r\n",
587 "You must be authenticated to use this service");
591 cgi_setup_error("400 Bad Request", "",
592 "You must specify a GET or POST request");
596 if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
599 while (*url && strchr("\r\n",url[strlen(url)-1])) {
600 url[strlen(url)-1] = 0;
603 /* anything following a ? in the URL is part of the query string */
604 if ((p=strchr(url,'?'))) {
609 if (strstr(url+1,"..")==0 && file_exist(url+1)) {
613 printf("HTTP/1.1 200 OK\r\nConnection: close\r\n");
619 /***************************************************************************
620 return the current pages URL
621 ***************************************************************************/
622 char *cgi_baseurl(void)