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
;
47 static void unescape(char *buf
)
51 while ((p
=strchr(p
,'+')))
56 while (p
&& *p
&& (p
=strchr(p
,'%'))) {
60 if (c1
>= '0' && c1
<= '9')
62 else if (c1
>= 'A' && c1
<= 'F')
64 else if (c1
>= 'a' && c1
<= 'f')
68 if (c2
>= '0' && c2
<= '9')
70 else if (c2
>= 'A' && c2
<= 'F')
72 else if (c2
>= 'a' && c2
<= 'f')
78 memcpy(p
+1, p
+3, strlen(p
+3)+1);
84 static char *grab_line(FILE *f
, int *cl
)
90 ret
= (char *)malloc(len
);
91 if (!ret
) return NULL
;
103 if (c
== '\r') continue;
105 if (strchr("\n&", c
)) break;
111 ret2
= (char *)realloc(ret
, len
*2);
112 if (!ret2
) return ret
;
123 /***************************************************************************
124 load all the variables passed to the CGI program. May have multiple variables
125 with the same name and the same or different values. Takes a file parameter
126 for simulating CGI invocation eg loading saved preferences.
127 ***************************************************************************/
128 void cgi_load_variables(FILE *f1
)
135 #ifdef DEBUG_COMMENTS
138 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__
);
143 if (!content_length
) {
144 p
= getenv("CONTENT_LENGTH");
147 len
= content_length
;
150 fseek(f
, 0, SEEK_END
);
152 fseek(f
, 0, SEEK_SET
);
157 (f1
|| request_post
||
158 ((s
=getenv("REQUEST_METHOD")) &&
159 strcasecmp(s
,"POST")==0))) {
160 while (len
&& (line
=grab_line(f
, &len
))) {
161 p
= strchr(line
,'=');
166 variables
[num_variables
].name
= strdup(line
);
167 variables
[num_variables
].value
= strdup(p
+1);
171 if (!variables
[num_variables
].name
||
172 !variables
[num_variables
].value
)
175 unescape(variables
[num_variables
].value
);
176 unescape(variables
[num_variables
].name
);
178 #ifdef DEBUG_COMMENTS
179 printf("<!== POST var %s has value \"%s\" ==>\n",
180 variables
[num_variables
].name
,
181 variables
[num_variables
].value
);
185 if (num_variables
== MAX_VARIABLES
) break;
190 #ifdef DEBUG_COMMENTS
191 printf("<!== End dump in cgi_load_variables() ==>\n");
198 if ((s
=query_string
) || (s
=getenv("QUERY_STRING"))) {
199 for (tok
=strtok(s
,"&;");tok
;tok
=strtok(NULL
,"&;")) {
205 variables
[num_variables
].name
= strdup(tok
);
206 variables
[num_variables
].value
= strdup(p
+1);
208 if (!variables
[num_variables
].name
||
209 !variables
[num_variables
].value
)
212 unescape(variables
[num_variables
].value
);
213 unescape(variables
[num_variables
].name
);
215 #ifdef DEBUG_COMMENTS
216 printf("<!== Commandline var %s has value \"%s\" ==>\n",
217 variables
[num_variables
].name
,
218 variables
[num_variables
].value
);
221 if (num_variables
== MAX_VARIABLES
) break;
225 #ifdef DEBUG_COMMENTS
226 printf("<!== End dump in cgi_load_variables() ==>\n");
231 /***************************************************************************
232 find a variable passed via CGI
233 Doesn't quite do what you think in the case of POST text variables, because
234 if they exist they might have a value of "" or even " ", depending on the
235 browser. Also doesn't allow for variables[] containing multiple variables
236 with the same name and the same or different values.
237 ***************************************************************************/
238 char *cgi_variable(char *name
)
242 for (i
=0;i
<num_variables
;i
++)
243 if (strcmp(variables
[i
].name
, name
) == 0)
244 return variables
[i
].value
;
248 /***************************************************************************
249 return a particular cgi variable
250 ***************************************************************************/
251 char *cgi_vnum(int i
, char **name
)
253 if (i
< 0 || i
>= num_variables
) return NULL
;
254 *name
= variables
[i
].name
;
255 return variables
[i
].value
;
258 /***************************************************************************
259 return the value of a CGI boolean variable.
260 ***************************************************************************/
261 int cgi_boolean(char *name
, int def
)
263 char *p
= cgi_variable(name
);
267 return strcmp(p
, "1") == 0;
270 /***************************************************************************
271 like strdup() but quotes < > and &
272 ***************************************************************************/
273 char *quotedup(char *s
)
280 if (!s
) return strdup("");
285 if (s
[i
] == '<' || s
[i
] == '>' || s
[i
] == '&')
288 ret
= malloc(len
+ n
*6 + 1);
290 if (!ret
) return NULL
;
294 for (i
=0;i
<len
;i
++) {
322 /***************************************************************************
323 like strdup() but quotes a wide range of characters
324 ***************************************************************************/
325 char *urlquote(char *s
)
331 char *qlist
= "\"\n\r'&<> \t+;";
333 if (!s
) return strdup("");
338 if (strchr(qlist
, s
[i
])) n
++;
340 ret
= malloc(len
+ n
*2 + 1);
342 if (!ret
) return NULL
;
346 for (i
=0;i
<len
;i
++) {
347 if (strchr(qlist
,s
[i
])) {
348 sprintf(d
, "%%%02X", (int)s
[i
]);
361 /***************************************************************************
362 like strdup() but quotes " characters
363 ***************************************************************************/
364 char *quotequotes(char *s
)
371 if (!s
) return strdup("");
379 ret
= malloc(len
+ n
*6 + 1);
381 if (!ret
) return NULL
;
385 for (i
=0;i
<len
;i
++) {
403 /***************************************************************************
404 quote spaces in a buffer
405 ***************************************************************************/
406 void quote_spaces(char *buf
)
409 if (*buf
== ' ') *buf
= '+';
416 /***************************************************************************
417 tell a browser about a fatal error in the http processing
418 ***************************************************************************/
419 static void cgi_setup_error(char *err
, char *header
, char *info
)
421 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
);
426 /***************************************************************************
427 decode a base64 string in-place - simple and slow algorithm
428 ***************************************************************************/
429 static void base64_decode(char *s
)
431 char *b64
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
432 int bit_offset
, byte_offset
, idx
, i
;
433 unsigned char *d
= (unsigned char *)s
;
438 while (*s
&& (p
=strchr(b64
,*s
))) {
439 idx
= (int)(p
- b64
);
440 byte_offset
= (i
*6)/8;
441 bit_offset
= (i
*6)%8;
442 d
[byte_offset
] &= ~((1<<(8-bit_offset
))-1);
443 if (bit_offset
< 3) {
444 d
[byte_offset
] |= (idx
<< (2-bit_offset
));
446 d
[byte_offset
] |= (idx
>> (bit_offset
-2));
447 d
[byte_offset
+1] = 0;
448 d
[byte_offset
+1] |= (idx
<< (8-(bit_offset
-2))) & 0xFF;
455 /***************************************************************************
456 handle a http authentication line
457 ***************************************************************************/
458 static int cgi_handle_authorization(char *line
)
460 char *p
, *user
, *pass
;
464 if (strncasecmp(line
,"Basic ", 6)) {
465 cgi_setup_error("401 Bad Authorization", "",
466 "Only basic authorization is understood");
469 while (line
[0] == ' ') line
++;
471 if (!(p
=strchr(line
,':'))) {
472 cgi_setup_error("401 Bad Authorization", "",
473 "username/password must be supplied");
479 /* currently only allow connections as root */
480 if (strcasecmp(user
,"root")) {
481 cgi_setup_error("401 Bad Authorization", "",
482 "incorrect username/password");
485 pwd
= getpwnam(user
);
487 if (!strcmp((char *)crypt(pass
, pwd
->pw_passwd
),pwd
->pw_passwd
)) {
491 memset(pass
, 0, strlen(pass
));
497 /***************************************************************************
498 handle a file download
499 ***************************************************************************/
500 static void cgi_download(char *file
)
507 /* sanitise the filename */
508 for (i
=0;file
[i
];i
++) {
509 if (!isalnum(file
[i
]) && !strchr("/.-_", file
[i
])) {
510 cgi_setup_error("404 File Not Found","",
511 "Illegal character in filename");
515 if (strstr(file
,"..")) {
516 cgi_setup_error("404 File Not Found","",
517 "Relative paths not allowed");
520 if (!file_exist(file
, &st
)) {
521 cgi_setup_error("404 File Not Found","",
522 "The requested file was not found");
524 fd
= open(file
,O_RDONLY
);
526 cgi_setup_error("404 File Not Found","",
527 "The requested file was not found");
529 printf("HTTP/1.1 200 OK\r\n");
530 if ((p
=strrchr(file
,'.'))) {
531 if (strcmp(p
,".gif")==0 || strcmp(p
,".jpg")==0) {
532 printf("Content-Type: image/gif\r\n");
534 printf("Content-Type: text/html\r\n");
537 printf("Content-Length: %d\r\n\r\n", (int)st
.st_size
);
538 while ((l
=read(fd
,buf
,sizeof(buf
)))>0) {
539 fwrite(buf
, 1, l
, stdout
);
546 /***************************************************************************
547 setup the cgi framework, handling the possability that this program is either
548 run as a true cgi program by a web browser or is itself a mini web server
549 ***************************************************************************/
550 void cgi_setup(char *rootdir
)
552 int authenticated
= 0;
557 if (chdir(rootdir
)) {
558 cgi_setup_error("400 Server Error", "",
559 "chdir failed - the server is not configured correctly");
562 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
563 /* assume we are running under a real web server */
567 /* we are a mini-web server. We need to read the request from stdin
568 and handle authentication etc */
569 while (fgets(line
, sizeof(line
)-1, stdin
)) {
570 if (line
[0] == '\r' || line
[0] == '\n') break;
571 if (strncasecmp(line
,"GET ", 4)==0) {
573 url
= strdup(&line
[4]);
574 } else if (strncasecmp(line
,"POST ", 5)==0) {
576 url
= strdup(&line
[5]);
577 } else if (strncasecmp(line
,"PUT ", 4)==0) {
578 cgi_setup_error("400 Bad Request", "",
579 "This server does not accept PUT requests");
580 } else if (strncasecmp(line
,"Authorization: ", 15)==0) {
581 authenticated
= cgi_handle_authorization(&line
[15]);
582 } else if (strncasecmp(line
,"Content-Length: ", 16)==0) {
583 content_length
= atoi(&line
[16]);
585 /* ignore all other requests! */
588 if (!authenticated
) {
589 cgi_setup_error("401 Authorization Required",
590 "WWW-Authenticate: Basic realm=\"root\"\r\n",
591 "You must be authenticated to use this service");
595 cgi_setup_error("400 Bad Request", "",
596 "You must specify a GET or POST request");
600 if ((p
= strchr(url
,' ')) || (p
=strchr(url
,'\t'))) {
603 while (*url
&& strchr("\r\n",url
[strlen(url
)-1])) {
604 url
[strlen(url
)-1] = 0;
607 /* anything following a ? in the URL is part of the query string */
608 if ((p
=strchr(url
,'?'))) {
613 if (strcmp(url
,"/")) {
617 printf("HTTP/1.1 200 OK\r\nConnection: close\r\n");