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
;
48 static BOOL inetd_server
;
49 static BOOL got_request
;
51 static void unescape(char *buf
)
55 while ((p
=strchr(p
,'+')))
60 while (p
&& *p
&& (p
=strchr(p
,'%'))) {
64 if (c1
>= '0' && c1
<= '9')
66 else if (c1
>= 'A' && c1
<= 'F')
68 else if (c1
>= 'a' && c1
<= 'f')
72 if (c2
>= '0' && c2
<= '9')
74 else if (c2
>= 'A' && c2
<= 'F')
76 else if (c2
>= 'a' && c2
<= 'f')
82 memcpy(p
+1, p
+3, strlen(p
+3)+1);
88 static char *grab_line(FILE *f
, int *cl
)
94 ret
= (char *)malloc(len
);
95 if (!ret
) return NULL
;
107 if (c
== '\r') continue;
109 if (strchr("\n&", c
)) break;
115 ret2
= (char *)realloc(ret
, len
*2);
116 if (!ret2
) return ret
;
127 /***************************************************************************
128 load all the variables passed to the CGI program. May have multiple variables
129 with the same name and the same or different values. Takes a file parameter
130 for simulating CGI invocation eg loading saved preferences.
131 ***************************************************************************/
132 void cgi_load_variables(FILE *f1
)
139 #ifdef DEBUG_COMMENTS
142 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__
);
147 if (!content_length
) {
148 p
= getenv("CONTENT_LENGTH");
151 len
= content_length
;
154 fseek(f
, 0, SEEK_END
);
156 fseek(f
, 0, SEEK_SET
);
161 (f1
|| request_post
||
162 ((s
=getenv("REQUEST_METHOD")) &&
163 strcasecmp(s
,"POST")==0))) {
164 while (len
&& (line
=grab_line(f
, &len
))) {
165 p
= strchr(line
,'=');
170 variables
[num_variables
].name
= strdup(line
);
171 variables
[num_variables
].value
= strdup(p
+1);
175 if (!variables
[num_variables
].name
||
176 !variables
[num_variables
].value
)
179 unescape(variables
[num_variables
].value
);
180 unescape(variables
[num_variables
].name
);
182 #ifdef DEBUG_COMMENTS
183 printf("<!== POST var %s has value \"%s\" ==>\n",
184 variables
[num_variables
].name
,
185 variables
[num_variables
].value
);
189 if (num_variables
== MAX_VARIABLES
) break;
194 #ifdef DEBUG_COMMENTS
195 printf("<!== End dump in cgi_load_variables() ==>\n");
201 open("/dev/null", O_RDWR
);
203 if ((s
=query_string
) || (s
=getenv("QUERY_STRING"))) {
204 for (tok
=strtok(s
,"&;");tok
;tok
=strtok(NULL
,"&;")) {
210 variables
[num_variables
].name
= strdup(tok
);
211 variables
[num_variables
].value
= strdup(p
+1);
213 if (!variables
[num_variables
].name
||
214 !variables
[num_variables
].value
)
217 unescape(variables
[num_variables
].value
);
218 unescape(variables
[num_variables
].name
);
220 #ifdef DEBUG_COMMENTS
221 printf("<!== Commandline var %s has value \"%s\" ==>\n",
222 variables
[num_variables
].name
,
223 variables
[num_variables
].value
);
226 if (num_variables
== MAX_VARIABLES
) break;
230 #ifdef DEBUG_COMMENTS
231 printf("<!== End dump in cgi_load_variables() ==>\n");
236 /***************************************************************************
237 find a variable passed via CGI
238 Doesn't quite do what you think in the case of POST text variables, because
239 if they exist they might have a value of "" or even " ", depending on the
240 browser. Also doesn't allow for variables[] containing multiple variables
241 with the same name and the same or different values.
242 ***************************************************************************/
243 char *cgi_variable(char *name
)
247 for (i
=0;i
<num_variables
;i
++)
248 if (strcmp(variables
[i
].name
, name
) == 0)
249 return variables
[i
].value
;
253 /***************************************************************************
254 tell a browser about a fatal error in the http processing
255 ***************************************************************************/
256 static void cgi_setup_error(char *err
, char *header
, char *info
)
259 /* damn browsers don't like getting cut off before they give a request */
261 while (fgets(line
, sizeof(line
)-1, stdin
)) {
262 if (strncasecmp(line
,"GET ", 4)==0 ||
263 strncasecmp(line
,"POST ", 5)==0 ||
264 strncasecmp(line
,"PUT ", 4)==0) {
270 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\r\n", err
, header
, err
, err
, info
);
277 /***************************************************************************
278 tell a browser about a fatal authentication error
279 ***************************************************************************/
280 static void cgi_auth_error(void)
283 cgi_setup_error("401 Authorization Required",
284 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
285 "You must be authenticated to use this service");
287 printf("Content-Type: text/html\r\n");
289 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
290 printf("<BODY><H1>Installation Error</H1>\n");
291 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
292 printf("</BODY></HTML>\r\n");
298 /***************************************************************************
299 decode a base64 string in-place - simple and slow algorithm
300 ***************************************************************************/
301 static void base64_decode(char *s
)
303 char *b64
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
304 int bit_offset
, byte_offset
, idx
, i
, n
;
305 unsigned char *d
= (unsigned char *)s
;
310 while (*s
&& (p
=strchr(b64
,*s
))) {
311 idx
= (int)(p
- b64
);
312 byte_offset
= (i
*6)/8;
313 bit_offset
= (i
*6)%8;
314 d
[byte_offset
] &= ~((1<<(8-bit_offset
))-1);
315 if (bit_offset
< 3) {
316 d
[byte_offset
] |= (idx
<< (2-bit_offset
));
319 d
[byte_offset
] |= (idx
>> (bit_offset
-2));
320 d
[byte_offset
+1] = 0;
321 d
[byte_offset
+1] |= (idx
<< (8-(bit_offset
-2))) & 0xFF;
331 /***************************************************************************
332 handle a http authentication line
333 ***************************************************************************/
334 static BOOL
cgi_handle_authorization(char *line
)
336 char *p
, *user
, *user_pass
;
337 struct passwd
*pass
= NULL
;
340 if (strncasecmp(line
,"Basic ", 6)) {
341 cgi_setup_error("401 Bad Authorization", "",
342 "Only basic authorization is understood");
346 while (line
[0] == ' ') line
++;
348 if (!(p
=strchr(line
,':'))) {
350 * Always give the same error so a cracker
351 * cannot tell why we fail.
353 cgi_setup_error("401 Bad Authorization", "",
354 "username/password must be supplied");
362 * Try and get the user from the UNIX password file.
365 if(!(pass
= Get_Pwnam(user
,False
))) {
367 * Always give the same error so a cracker
368 * cannot tell why we fail.
370 cgi_setup_error("401 Bad Authorization", "",
371 "username/password must be supplied");
376 * Validate the password they have given.
379 if((ret
= pass_check(user
, user_pass
, strlen(user_pass
), NULL
, NULL
)) == True
) {
385 if(pass
->pw_uid
!= 0) {
387 * We have not authenticated as root,
388 * become the user *permanently*.
390 become_user_permanently(pass
->pw_uid
, pass
->pw_gid
);
393 /* Save the users name */
394 C_user
= strdup(user
);
400 /***************************************************************************
402 ***************************************************************************/
405 if (geteuid() == 0) {
412 /***************************************************************************
413 return a ptr to the users name
414 ***************************************************************************/
415 char *cgi_user_name(void)
421 /***************************************************************************
422 handle a file download
423 ***************************************************************************/
424 static void cgi_download(char *file
)
431 /* sanitise the filename */
432 for (i
=0;file
[i
];i
++) {
433 if (!isalnum((int)file
[i
]) && !strchr("/.-_", file
[i
])) {
434 cgi_setup_error("404 File Not Found","",
435 "Illegal character in filename");
439 if (!file_exist(file
, &st
)) {
440 cgi_setup_error("404 File Not Found","",
441 "The requested file was not found");
443 fd
= sys_open(file
,O_RDONLY
,0);
445 cgi_setup_error("404 File Not Found","",
446 "The requested file was not found");
448 printf("HTTP/1.0 200 OK\r\n");
449 if ((p
=strrchr(file
,'.'))) {
450 if (strcmp(p
,".gif")==0) {
451 printf("Content-Type: image/gif\r\n");
452 } else if (strcmp(p
,".jpg")==0) {
453 printf("Content-Type: image/jpeg\r\n");
455 printf("Content-Type: text/html\r\n");
458 printf("Expires: %s\r\n", http_timestring(time(NULL
)+EXPIRY_TIME
));
460 printf("Content-Length: %d\r\n\r\n", (int)st
.st_size
);
461 while ((l
=read(fd
,buf
,sizeof(buf
)))>0) {
462 fwrite(buf
, 1, l
, stdout
);
469 /***************************************************************************
470 setup the cgi framework, handling the possability that this program is either
471 run as a true cgi program by a web browser or is itself a mini web server
472 ***************************************************************************/
473 void cgi_setup(char *rootdir
, int auth_required
)
475 BOOL authenticated
= False
;
483 if (chdir(rootdir
)) {
484 cgi_setup_error("400 Server Error", "",
485 "chdir failed - the server is not configured correctly");
488 /* maybe we are running under a web server */
489 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
498 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
499 cgi_setup_error("400 Server Error", "",
500 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
504 f
= sys_fopen("/tmp/cgi.log", "a");
505 if (f
) fprintf(f
,"\n[Date: %s %s (%s)]\n",
506 http_timestring(time(NULL
)),
507 get_socket_name(1), get_socket_addr(1));
510 /* we are a mini-web server. We need to read the request from stdin
511 and handle authentication etc */
512 while (fgets(line
, sizeof(line
)-1, stdin
)) {
514 if (f
) fputs(line
, f
);
516 if (line
[0] == '\r' || line
[0] == '\n') break;
517 if (strncasecmp(line
,"GET ", 4)==0) {
519 url
= strdup(&line
[4]);
520 } else if (strncasecmp(line
,"POST ", 5)==0) {
523 url
= strdup(&line
[5]);
524 } else if (strncasecmp(line
,"PUT ", 4)==0) {
526 cgi_setup_error("400 Bad Request", "",
527 "This server does not accept PUT requests");
528 } else if (strncasecmp(line
,"Authorization: ", 15)==0) {
529 authenticated
= cgi_handle_authorization(&line
[15]);
530 } else if (strncasecmp(line
,"Content-Length: ", 16)==0) {
531 content_length
= atoi(&line
[16]);
533 /* ignore all other requests! */
539 if (auth_required
&& !authenticated
) {
544 cgi_setup_error("400 Bad Request", "",
545 "You must specify a GET or POST request");
549 if ((p
= strchr(url
,' ')) || (p
=strchr(url
,'\t'))) {
552 while (*url
&& strchr("\r\n",url
[strlen(url
)-1])) {
553 url
[strlen(url
)-1] = 0;
556 /* anything following a ? in the URL is part of the query string */
557 if ((p
=strchr(url
,'?'))) {
562 string_sub(url
, "/swat/", "", 0);
564 if (url
[0] != '/' && strstr(url
,"..")==0 && file_exist(url
, NULL
)) {
568 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
569 printf("Date: %s\r\n", http_timestring(time(NULL
)));
575 /***************************************************************************
576 return the current pages URL
577 ***************************************************************************/
578 char *cgi_baseurl(void)
583 return getenv("SCRIPT_NAME");
586 /***************************************************************************
587 return the current pages path info
588 ***************************************************************************/
589 char *cgi_pathinfo(void)
595 r
= getenv("PATH_INFO");
601 /***************************************************************************
602 return the hostname of the client
603 ***************************************************************************/
604 char *cgi_remote_host(void)
607 return get_socket_name(1);
609 return getenv("REMOTE_HOST");
612 /***************************************************************************
613 return the hostname of the client
614 ***************************************************************************/
615 char *cgi_remote_addr(void)
618 return get_socket_addr(1);
620 return getenv("REMOTE_ADDR");
624 /***************************************************************************
625 return True if the request was a POST
626 ***************************************************************************/
627 BOOL
cgi_waspost(void)
632 return strequal(getenv("REQUEST_METHOD"), "POST");