This commit was manufactured by cvs2svn to create tag
[Samba.git] / source / web / cgi.c
blobea73a0f1a704d64d2aa4e77f00e13b35c067537f
1 /*
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.
21 #include "includes.h"
22 #include "smb.h"
24 #define MAX_VARIABLES 10000
26 /* set the expiry on fixed pages */
27 #define EXPIRY_TIME (60*60*24*7)
29 #define CGI_LOGGING 0
31 #ifdef DEBUG_COMMENTS
32 extern void print_title(char *fmt, ...);
33 #endif
35 struct var {
36 char *name;
37 char *value;
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;
45 static char *baseurl;
46 static char *pathinfo;
47 static char *C_user;
48 static BOOL inetd_server;
49 static BOOL got_request;
51 static void unescape(char *buf)
53 char *p=buf;
55 while ((p=strchr(p,'+')))
56 *p = ' ';
58 p = buf;
60 while (p && *p && (p=strchr(p,'%'))) {
61 int c1 = p[1];
62 int c2 = p[2];
64 if (c1 >= '0' && c1 <= '9')
65 c1 = c1 - '0';
66 else if (c1 >= 'A' && c1 <= 'F')
67 c1 = 10 + c1 - 'A';
68 else if (c1 >= 'a' && c1 <= 'f')
69 c1 = 10 + c1 - 'a';
70 else {p++; continue;}
72 if (c2 >= '0' && c2 <= '9')
73 c2 = c2 - '0';
74 else if (c2 >= 'A' && c2 <= 'F')
75 c2 = 10 + c2 - 'A';
76 else if (c2 >= 'a' && c2 <= 'f')
77 c2 = 10 + c2 - 'a';
78 else {p++; continue;}
80 *p = (c1<<4) | c2;
82 memcpy(p+1, p+3, strlen(p+3)+1);
83 p++;
88 static char *grab_line(FILE *f, int *cl)
90 char *ret;
91 int i = 0;
92 int len = 1024;
94 ret = (char *)malloc(len);
95 if (!ret) return NULL;
98 while ((*cl)) {
99 int c = fgetc(f);
100 (*cl)--;
102 if (c == EOF) {
103 (*cl) = 0;
104 break;
107 if (c == '\r') continue;
109 if (strchr("\n&", c)) break;
111 ret[i++] = c;
113 if (i == len-1) {
114 char *ret2;
115 ret2 = (char *)realloc(ret, len*2);
116 if (!ret2) return ret;
117 len *= 2;
118 ret = ret2;
123 ret[i] = 0;
124 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)
134 FILE *f = f1;
135 static char *line;
136 char *p, *s, *tok;
137 int len;
139 #ifdef DEBUG_COMMENTS
140 char dummy[100]="";
141 print_title(dummy);
142 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
143 #endif
145 if (!f1) {
146 f = stdin;
147 if (!content_length) {
148 p = getenv("CONTENT_LENGTH");
149 len = p?atoi(p):0;
150 } else {
151 len = content_length;
153 } else {
154 fseek(f, 0, SEEK_END);
155 len = ftell(f);
156 fseek(f, 0, SEEK_SET);
160 if (len > 0 &&
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,'=');
166 if (!p) continue;
168 *p = 0;
170 variables[num_variables].name = strdup(line);
171 variables[num_variables].value = strdup(p+1);
173 free(line);
175 if (!variables[num_variables].name ||
176 !variables[num_variables].value)
177 continue;
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);
186 #endif
188 num_variables++;
189 if (num_variables == MAX_VARIABLES) break;
193 if (f1) {
194 #ifdef DEBUG_COMMENTS
195 printf("<!== End dump in cgi_load_variables() ==>\n");
196 #endif
197 return;
200 fclose(stdin);
201 open("/dev/null", O_RDWR);
203 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
204 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
205 p = strchr(tok,'=');
206 if (!p) continue;
208 *p = 0;
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)
215 continue;
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);
224 #endif
225 num_variables++;
226 if (num_variables == MAX_VARIABLES) break;
230 #ifdef DEBUG_COMMENTS
231 printf("<!== End dump in cgi_load_variables() ==>\n");
232 #endif
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)
245 int i;
247 for (i=0;i<num_variables;i++)
248 if (strcmp(variables[i].name, name) == 0)
249 return variables[i].value;
250 return NULL;
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)
258 if (!got_request) {
259 /* damn browsers don't like getting cut off before they give a request */
260 char line[1024];
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) {
265 break;
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);
271 fclose(stdin);
272 fclose(stdout);
273 exit(0);
277 /***************************************************************************
278 tell a browser about a fatal authentication error
279 ***************************************************************************/
280 static void cgi_auth_error(void)
282 if (inetd_server) {
283 cgi_setup_error("401 Authorization Required",
284 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
285 "You must be authenticated to use this service");
286 } else {
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");
294 exit(0);
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;
306 char *p;
308 n=i=0;
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));
317 n = byte_offset+1;
318 } else {
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;
322 n = byte_offset+2;
324 s++; i++;
326 /* null terminate */
327 d[n] = 0;
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;
338 BOOL ret = False;
340 if (strncasecmp(line,"Basic ", 6)) {
341 cgi_setup_error("401 Bad Authorization", "",
342 "Only basic authorization is understood");
343 return False;
345 line += 6;
346 while (line[0] == ' ') line++;
347 base64_decode(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");
355 return False;
357 *p = 0;
358 user = line;
359 user_pass = p+1;
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");
372 return False;
376 * Validate the password they have given.
379 if((ret = pass_check(user, user_pass, strlen(user_pass), NULL, NULL)) == True) {
382 * Password was ok.
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);
397 return ret;
400 /***************************************************************************
401 is this root?
402 ***************************************************************************/
403 BOOL am_root(void)
405 if (geteuid() == 0) {
406 return( True);
407 } else {
408 return( False);
412 /***************************************************************************
413 return a ptr to the users name
414 ***************************************************************************/
415 char *cgi_user_name(void)
417 return(C_user);
421 /***************************************************************************
422 handle a file download
423 ***************************************************************************/
424 static void cgi_download(char *file)
426 SMB_STRUCT_STAT st;
427 char buf[1024];
428 int fd, l, i;
429 char *p;
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);
444 if (fd == -1) {
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");
454 } else {
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);
464 close(fd);
465 exit(0);
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;
476 char line[1024];
477 char *url=NULL;
478 char *p;
479 #if CGI_LOGGING
480 FILE *f;
481 #endif
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")) {
490 if (auth_required) {
491 cgi_auth_error();
493 return;
496 inetd_server = True;
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 ");
503 #if CGI_LOGGING
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));
508 #endif
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)) {
513 #if CGI_LOGGING
514 if (f) fputs(line, f);
515 #endif
516 if (line[0] == '\r' || line[0] == '\n') break;
517 if (strncasecmp(line,"GET ", 4)==0) {
518 got_request = True;
519 url = strdup(&line[4]);
520 } else if (strncasecmp(line,"POST ", 5)==0) {
521 got_request = True;
522 request_post = 1;
523 url = strdup(&line[5]);
524 } else if (strncasecmp(line,"PUT ", 4)==0) {
525 got_request = True;
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! */
535 #if CGI_LOGGING
536 if (f) fclose(f);
537 #endif
539 if (auth_required && !authenticated) {
540 cgi_auth_error();
543 if (!url) {
544 cgi_setup_error("400 Bad Request", "",
545 "You must specify a GET or POST request");
548 /* trim the URL */
549 if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
550 *p = 0;
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,'?'))) {
558 query_string = p+1;
559 *p = 0;
562 string_sub(url, "/swat/", "", 0);
564 if (url[0] != '/' && strstr(url,"..")==0 && file_exist(url, NULL)) {
565 cgi_download(url);
568 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
569 printf("Date: %s\r\n", http_timestring(time(NULL)));
570 baseurl = "";
571 pathinfo = url+1;
575 /***************************************************************************
576 return the current pages URL
577 ***************************************************************************/
578 char *cgi_baseurl(void)
580 if (inetd_server) {
581 return baseurl;
583 return getenv("SCRIPT_NAME");
586 /***************************************************************************
587 return the current pages path info
588 ***************************************************************************/
589 char *cgi_pathinfo(void)
591 char *r;
592 if (inetd_server) {
593 return pathinfo;
595 r = getenv("PATH_INFO");
596 if (!r) return "";
597 if (*r == '/') r++;
598 return r;
601 /***************************************************************************
602 return the hostname of the client
603 ***************************************************************************/
604 char *cgi_remote_host(void)
606 if (inetd_server) {
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)
617 if (inetd_server) {
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)
629 if (inetd_server) {
630 return request_post;
632 return strequal(getenv("REQUEST_METHOD"), "POST");