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");
202 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
203 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
209 variables[num_variables].name = strdup(tok);
210 variables[num_variables].value = strdup(p+1);
212 if (!variables[num_variables].name ||
213 !variables[num_variables].value)
216 unescape(variables[num_variables].value);
217 unescape(variables[num_variables].name);
219 #ifdef DEBUG_COMMENTS
220 printf("<!== Commandline var %s has value \"%s\" ==>\n",
221 variables[num_variables].name,
222 variables[num_variables].value);
225 if (num_variables == MAX_VARIABLES) break;
229 #ifdef DEBUG_COMMENTS
230 printf("<!== End dump in cgi_load_variables() ==>\n");
235 /***************************************************************************
236 find a variable passed via CGI
237 Doesn't quite do what you think in the case of POST text variables, because
238 if they exist they might have a value of "" or even " ", depending on the
239 browser. Also doesn't allow for variables[] containing multiple variables
240 with the same name and the same or different values.
241 ***************************************************************************/
242 char *cgi_variable(char *name)
246 for (i=0;i<num_variables;i++)
247 if (strcmp(variables[i].name, name) == 0)
248 return variables[i].value;
252 /***************************************************************************
253 tell a browser about a fatal error in the http processing
254 ***************************************************************************/
255 static void cgi_setup_error(char *err, char *header, char *info)
258 /* damn browsers don't like getting cut off before they give a request */
260 while (fgets(line, sizeof(line)-1, stdin)) {
261 if (strncasecmp(line,"GET ", 4)==0 ||
262 strncasecmp(line,"POST ", 5)==0 ||
263 strncasecmp(line,"PUT ", 4)==0) {
269 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);
276 /***************************************************************************
277 tell a browser about a fatal authentication error
278 ***************************************************************************/
279 static void cgi_auth_error(void)
282 cgi_setup_error("401 Authorization Required",
283 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
284 "You must be authenticated to use this service");
286 printf("Content-Type: text/html\r\n");
288 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
289 printf("<BODY><H1>Installation Error</H1>\n");
290 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
291 printf("</BODY></HTML>\r\n");
297 /***************************************************************************
298 decode a base64 string in-place - simple and slow algorithm
299 ***************************************************************************/
300 static void base64_decode(char *s)
302 char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
303 int bit_offset, byte_offset, idx, i, n;
304 unsigned char *d = (unsigned char *)s;
309 while (*s && (p=strchr(b64,*s))) {
310 idx = (int)(p - b64);
311 byte_offset = (i*6)/8;
312 bit_offset = (i*6)%8;
313 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
314 if (bit_offset < 3) {
315 d[byte_offset] |= (idx << (2-bit_offset));
318 d[byte_offset] |= (idx >> (bit_offset-2));
319 d[byte_offset+1] = 0;
320 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
330 /***************************************************************************
331 handle a http authentication line
332 ***************************************************************************/
333 static BOOL cgi_handle_authorization(char *line)
335 char *p, *user, *user_pass;
336 struct passwd *pass = NULL;
339 if (strncasecmp(line,"Basic ", 6)) {
340 cgi_setup_error("401 Bad Authorization", "",
341 "Only basic authorization is understood");
345 while (line[0] == ' ') line++;
347 if (!(p=strchr(line,':'))) {
349 * Always give the same error so a cracker
350 * cannot tell why we fail.
352 cgi_setup_error("401 Bad Authorization", "",
353 "username/password must be supplied");
361 * Try and get the user from the UNIX password file.
364 if(!(pass = Get_Pwnam(user,False))) {
366 * Always give the same error so a cracker
367 * cannot tell why we fail.
369 cgi_setup_error("401 Bad Authorization", "",
370 "username/password must be supplied");
375 * Validate the password they have given.
378 if((ret = pass_check(user, user_pass, strlen(user_pass), NULL, NULL)) == True) {
384 if(pass->pw_uid != 0) {
386 * We have not authenticated as root,
387 * become the user *permanently*.
389 become_user_permanently(pass->pw_uid, pass->pw_gid);
392 /* Save the users name */
393 C_user = strdup(user);
399 /***************************************************************************
401 ***************************************************************************/
404 if (geteuid() == 0) {
411 /***************************************************************************
412 return a ptr to the users name
413 ***************************************************************************/
414 char *cgi_user_name(void)
420 /***************************************************************************
421 handle a file download
422 ***************************************************************************/
423 static void cgi_download(char *file)
430 /* sanitise the filename */
431 for (i=0;file[i];i++) {
432 if (!isalnum((int)file[i]) && !strchr("/.-_", file[i])) {
433 cgi_setup_error("404 File Not Found","",
434 "Illegal character in filename");
438 if (!file_exist(file, &st)) {
439 cgi_setup_error("404 File Not Found","",
440 "The requested file was not found");
442 fd = sys_open(file,O_RDONLY,0);
444 cgi_setup_error("404 File Not Found","",
445 "The requested file was not found");
447 printf("HTTP/1.0 200 OK\r\n");
448 if ((p=strrchr(file,'.'))) {
449 if (strcmp(p,".gif")==0) {
450 printf("Content-Type: image/gif\r\n");
451 } else if (strcmp(p,".jpg")==0) {
452 printf("Content-Type: image/jpeg\r\n");
454 printf("Content-Type: text/html\r\n");
457 printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
459 printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
460 while ((l=read(fd,buf,sizeof(buf)))>0) {
461 fwrite(buf, 1, l, stdout);
468 /***************************************************************************
469 setup the cgi framework, handling the possability that this program is either
470 run as a true cgi program by a web browser or is itself a mini web server
471 ***************************************************************************/
472 void cgi_setup(char *rootdir, int auth_required)
474 BOOL authenticated = False;
482 if (chdir(rootdir)) {
483 cgi_setup_error("400 Server Error", "",
484 "chdir failed - the server is not configured correctly");
487 /* maybe we are running under a web server */
488 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
497 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
498 cgi_setup_error("400 Server Error", "",
499 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
503 f = sys_fopen("/tmp/cgi.log", "a");
504 if (f) fprintf(f,"\n[Date: %s %s (%s)]\n",
505 http_timestring(time(NULL)),
506 client_name(1), client_addr(1));
509 /* we are a mini-web server. We need to read the request from stdin
510 and handle authentication etc */
511 while (fgets(line, sizeof(line)-1, stdin)) {
513 if (f) fputs(line, f);
515 if (line[0] == '\r' || line[0] == '\n') break;
516 if (strncasecmp(line,"GET ", 4)==0) {
518 url = strdup(&line[4]);
519 } else if (strncasecmp(line,"POST ", 5)==0) {
522 url = strdup(&line[5]);
523 } else if (strncasecmp(line,"PUT ", 4)==0) {
525 cgi_setup_error("400 Bad Request", "",
526 "This server does not accept PUT requests");
527 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
528 authenticated = cgi_handle_authorization(&line[15]);
529 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
530 content_length = atoi(&line[16]);
532 /* ignore all other requests! */
538 if (auth_required && !authenticated) {
543 cgi_setup_error("400 Bad Request", "",
544 "You must specify a GET or POST request");
548 if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
551 while (*url && strchr("\r\n",url[strlen(url)-1])) {
552 url[strlen(url)-1] = 0;
555 /* anything following a ? in the URL is part of the query string */
556 if ((p=strchr(url,'?'))) {
561 string_sub(url, "/swat/", "", 0);
563 if (url[0] != '/' && strstr(url,"..")==0 && file_exist(url, NULL)) {
567 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
568 printf("Date: %s\r\n", http_timestring(time(NULL)));
574 /***************************************************************************
575 return the current pages URL
576 ***************************************************************************/
577 char *cgi_baseurl(void)
582 return getenv("SCRIPT_NAME");
585 /***************************************************************************
586 return the current pages path info
587 ***************************************************************************/
588 char *cgi_pathinfo(void)
594 r = getenv("PATH_INFO");
600 /***************************************************************************
601 return the hostname of the client
602 ***************************************************************************/
603 char *cgi_remote_host(void)
606 return client_name(1);
608 return getenv("REMOTE_HOST");
611 /***************************************************************************
612 return the hostname of the client
613 ***************************************************************************/
614 char *cgi_remote_addr(void)
617 return client_addr(1);
619 return getenv("REMOTE_ADDR");
623 /***************************************************************************
624 return True if the request was a POST
625 ***************************************************************************/
626 BOOL cgi_waspost(void)
631 return strequal(getenv("REQUEST_METHOD"), "POST");