Change all realloc() statements to Realloc() (ecxept for tdb.c)
[nivanova/samba-autobuild/.git] / source3 / web / cgi.c
1 /* 
2    some simple CGI helper routines
3    Copyright (C) Andrew Tridgell 1997-1998
4    
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.
9    
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.
14    
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.
18 */
19
20
21 #include "includes.h"
22 #include "smb.h"
23
24 #define MAX_VARIABLES 10000
25
26 /* set the expiry on fixed pages */
27 #define EXPIRY_TIME (60*60*24*7)
28
29 #ifdef DEBUG_COMMENTS
30 extern void print_title(char *fmt, ...);
31 #endif
32
33 struct var {
34         char *name;
35         char *value;
36 };
37
38 static struct var variables[MAX_VARIABLES];
39 static int num_variables;
40 static int content_length;
41 static int request_post;
42 static char *query_string;
43 static char *baseurl;
44 static char *pathinfo;
45 static char *C_user;
46 static BOOL inetd_server;
47 static BOOL got_request;
48
49 static void unescape(char *buf)
50 {
51         char *p=buf;
52
53         while ((p=strchr_m(p,'+')))
54                 *p = ' ';
55
56         p = buf;
57
58         while (p && *p && (p=strchr_m(p,'%'))) {
59                 int c1 = p[1];
60                 int c2 = p[2];
61
62                 if (c1 >= '0' && c1 <= '9')
63                         c1 = c1 - '0';
64                 else if (c1 >= 'A' && c1 <= 'F')
65                         c1 = 10 + c1 - 'A';
66                 else if (c1 >= 'a' && c1 <= 'f')
67                         c1 = 10 + c1 - 'a';
68                 else {p++; continue;}
69
70                 if (c2 >= '0' && c2 <= '9')
71                         c2 = c2 - '0';
72                 else if (c2 >= 'A' && c2 <= 'F')
73                         c2 = 10 + c2 - 'A';
74                 else if (c2 >= 'a' && c2 <= 'f')
75                         c2 = 10 + c2 - 'a';
76                 else {p++; continue;}
77                         
78                 *p = (c1<<4) | c2;
79
80                 memcpy(p+1, p+3, strlen(p+3)+1);
81                 p++;
82         }
83 }
84
85
86 static char *grab_line(FILE *f, int *cl)
87 {
88         char *ret = NULL;
89         int i = 0;
90         int len = 1024;
91
92         while ((*cl)) {
93                 int c;
94         
95                 if (i == len) {
96                         char *ret2;
97                         if (len == 0) len = 1024;
98                         else len *= 2;
99                         ret2 = (char *)Realloc(ret, len*2);
100                         if (!ret2) return ret;
101                         ret = ret2;
102                 }
103         
104                 c = fgetc(f);
105                 (*cl)--;
106
107                 if (c == EOF) {
108                         (*cl) = 0;
109                         break;
110                 }
111                 
112                 if (c == '\r') continue;
113
114                 if (strchr_m("\n&", c)) break;
115
116                 ret[i++] = c;
117
118         }
119         
120
121         ret[i] = 0;
122         return ret;
123 }
124
125 /***************************************************************************
126   load all the variables passed to the CGI program. May have multiple variables
127   with the same name and the same or different values. Takes a file parameter
128   for simulating CGI invocation eg loading saved preferences.
129   ***************************************************************************/
130 void cgi_load_variables(FILE *f1)
131 {
132         FILE *f = f1;
133         static char *line;
134         char *p, *s, *tok;
135         int len;
136
137 #ifdef DEBUG_COMMENTS
138         char dummy[100]="";
139         print_title(dummy);
140         printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
141 #endif
142
143         if (!f1) {
144                 f = stdin;
145                 if (!content_length) {
146                         p = getenv("CONTENT_LENGTH");
147                         len = p?atoi(p):0;
148                 } else {
149                         len = content_length;
150                 }
151         } else {
152                 fseek(f, 0, SEEK_END);
153                 len = ftell(f);
154                 fseek(f, 0, SEEK_SET);
155         }
156
157
158         if (len > 0 && 
159             (f1 || request_post ||
160              ((s=getenv("REQUEST_METHOD")) && 
161               strcasecmp(s,"POST")==0))) {
162                 while (len && (line=grab_line(f, &len))) {
163                         p = strchr_m(line,'=');
164                         if (!p) continue;
165                         
166                         *p = 0;
167                         
168                         variables[num_variables].name = strdup(line);
169                         variables[num_variables].value = strdup(p+1);
170
171                         free(line);
172                         
173                         if (!variables[num_variables].name || 
174                             !variables[num_variables].value)
175                                 continue;
176
177                         unescape(variables[num_variables].value);
178                         unescape(variables[num_variables].name);
179
180 #ifdef DEBUG_COMMENTS
181                         printf("<!== POST var %s has value \"%s\"  ==>\n",
182                                variables[num_variables].name,
183                                variables[num_variables].value);
184 #endif
185                         
186                         num_variables++;
187                         if (num_variables == MAX_VARIABLES) break;
188                 }
189         }
190
191         if (f1) {
192 #ifdef DEBUG_COMMENTS
193                 printf("<!== End dump in cgi_load_variables() ==>\n"); 
194 #endif
195                 return;
196         }
197
198         fclose(stdin);
199         open("/dev/null", O_RDWR);
200
201         if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
202                 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
203                         p = strchr_m(tok,'=');
204                         if (!p) continue;
205                         
206                         *p = 0;
207                         
208                         variables[num_variables].name = strdup(tok);
209                         variables[num_variables].value = strdup(p+1);
210
211                         if (!variables[num_variables].name || 
212                             !variables[num_variables].value)
213                                 continue;
214
215                         unescape(variables[num_variables].value);
216                         unescape(variables[num_variables].name);
217
218 #ifdef DEBUG_COMMENTS
219                         printf("<!== Commandline var %s has value \"%s\"  ==>\n",
220                                variables[num_variables].name,
221                                variables[num_variables].value);
222 #endif                                          
223                         num_variables++;
224                         if (num_variables == MAX_VARIABLES) break;
225                 }
226
227         }
228 #ifdef DEBUG_COMMENTS
229         printf("<!== End dump in cgi_load_variables() ==>\n");   
230 #endif
231 }
232
233
234 /***************************************************************************
235   find a variable passed via CGI
236   Doesn't quite do what you think in the case of POST text variables, because
237   if they exist they might have a value of "" or even " ", depending on the 
238   browser. Also doesn't allow for variables[] containing multiple variables
239   with the same name and the same or different values.
240   ***************************************************************************/
241 char *cgi_variable(char *name)
242 {
243         int i;
244
245         for (i=0;i<num_variables;i++)
246                 if (strcmp(variables[i].name, name) == 0)
247                         return variables[i].value;
248         return NULL;
249 }
250
251 /***************************************************************************
252 tell a browser about a fatal error in the http processing
253   ***************************************************************************/
254 static void cgi_setup_error(char *err, char *header, char *info)
255 {
256         if (!got_request) {
257                 /* damn browsers don't like getting cut off before they give a request */
258                 char line[1024];
259                 while (fgets(line, sizeof(line)-1, stdin)) {
260                         if (strncasecmp(line,"GET ", 4)==0 || 
261                             strncasecmp(line,"POST ", 5)==0 ||
262                             strncasecmp(line,"PUT ", 4)==0) {
263                                 break;
264                         }
265                 }
266         }
267
268         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);
269         fclose(stdin);
270         fclose(stdout);
271         exit(0);
272 }
273
274
275 /***************************************************************************
276 tell a browser about a fatal authentication error
277   ***************************************************************************/
278 static void cgi_auth_error(void)
279 {
280         if (inetd_server) {
281                 cgi_setup_error("401 Authorization Required", 
282                                 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
283                                 "You must be authenticated to use this service");
284         } else {
285                 printf("Content-Type: text/html\r\n");
286
287                 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
288                 printf("<BODY><H1>Installation Error</H1>\n");
289                 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
290                 printf("</BODY></HTML>\r\n");
291         }
292         exit(0);
293 }
294
295 /***************************************************************************
296 authenticate when we are running as a CGI
297   ***************************************************************************/
298 static void cgi_web_auth(void)
299 {
300         char *user = getenv("REMOTE_USER");
301         struct passwd *pwd;
302         char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
303         char *tail = "</BODY></HTML>\r\n";
304
305         if (!user) {
306                 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
307                        head, tail);
308                 exit(0);
309         }
310
311         pwd = getpwnam(user);
312         if (!pwd) {
313                 printf("%sCannot find user %s<br>%s\n", head, user, tail);
314                 exit(0);
315         }
316
317         setuid(0);
318         setuid(pwd->pw_uid);
319         if (geteuid() != pwd->pw_uid || getuid() != pwd->pw_uid) {
320                 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n", 
321                        head, user, (int)geteuid(), (int)getuid(), tail);
322                 exit(0);
323         }
324 }
325
326 /***************************************************************************
327 decode a base64 string in-place - simple and slow algorithm
328   ***************************************************************************/
329 static void base64_decode(char *s)
330 {
331         char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
332         int bit_offset, byte_offset, idx, i, n;
333         unsigned char *d = (unsigned char *)s;
334         char *p;
335
336         n=i=0;
337
338         while (*s && (p=strchr_m(b64,*s))) {
339                 idx = (int)(p - b64);
340                 byte_offset = (i*6)/8;
341                 bit_offset = (i*6)%8;
342                 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
343                 if (bit_offset < 3) {
344                         d[byte_offset] |= (idx << (2-bit_offset));
345                         n = byte_offset+1;
346                 } else {
347                         d[byte_offset] |= (idx >> (bit_offset-2));
348                         d[byte_offset+1] = 0;
349                         d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
350                         n = byte_offset+2;
351                 }
352                 s++; i++;
353         }
354         /* null terminate */
355         d[n] = 0;
356 }
357
358 /***************************************************************************
359 handle a http authentication line
360   ***************************************************************************/
361 static BOOL cgi_handle_authorization(char *line)
362 {
363         char *p, *user, *user_pass;
364         struct passwd *pass = NULL;
365         BOOL got_name = False;
366         BOOL tested_pass = False;
367         fstring default_user_lookup;
368         fstring default_user_pass;
369
370         /* Dummy user lookup to take the same time as a valid user. */
371         fstrcpy(default_user_lookup, "zzzz bibble");
372         fstrcpy(default_user_pass, "123456789");
373
374         if (strncasecmp(line,"Basic ", 6)) {
375                 goto err;
376         }
377         line += 6;
378         while (line[0] == ' ') line++;
379         base64_decode(line);
380         if (!(p=strchr_m(line,':'))) {
381                 /*
382                  * Always give the same error so a cracker
383                  * cannot tell why we fail.
384                  */
385                 goto err;
386         }
387         *p = 0;
388         user = line;
389         user_pass = p+1;
390
391         /*
392          * Try and get the user from the UNIX password file.
393          */
394
395         if(!(pass = Get_Pwnam(user,False))) {
396                 /*
397                  * Always give the same error so a cracker
398                  * cannot tell why we fail.
399                  */
400                 got_name = True;
401                 goto err;
402         }
403
404         /*
405          * Validate the password they have given.
406          */
407
408         tested_pass = True;
409
410         if(pass_check(user, user_pass, strlen(user_pass), NULL) == True) {
411
412                 /*
413                  * Password was ok.
414                  */
415
416                 if(pass->pw_uid != 0) {
417                         /*
418                          * We have not authenticated as root,
419                          * become the user *permanently*.
420                          */
421                         become_user_permanently(pass->pw_uid, pass->pw_gid);
422                 }
423
424                 /* Save the users name */
425                 C_user = strdup(user);
426                 return True;
427         }
428
429   err:
430
431         /* Always take the same time. */
432         if (!got_name)
433                 Get_Pwnam(default_user_lookup,False);
434
435         if (!tested_pass)
436                 pass_check(default_user_lookup, default_user_pass,
437                                         strlen(default_user_pass), NULL);
438
439         cgi_setup_error("401 Bad Authorization", "", 
440                         "username or password incorrect");
441
442         return False;
443 }
444
445 /***************************************************************************
446 is this root?
447   ***************************************************************************/
448 BOOL am_root(void)
449 {
450         if (geteuid() == 0) {
451                 return( True);
452         } else {
453                 return( False);
454         }
455 }
456
457 /***************************************************************************
458 return a ptr to the users name
459   ***************************************************************************/
460 char *cgi_user_name(void)
461 {
462         return(C_user);
463 }
464
465
466 /***************************************************************************
467 handle a file download
468   ***************************************************************************/
469 static void cgi_download(char *file)
470 {
471         SMB_STRUCT_STAT st;
472         char buf[1024];
473         int fd, l, i;
474         char *p;
475
476         /* sanitise the filename */
477         for (i=0;file[i];i++) {
478                 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
479                         cgi_setup_error("404 File Not Found","",
480                                         "Illegal character in filename");
481                 }
482         }
483
484         if (!file_exist(file, &st)) {
485                 cgi_setup_error("404 File Not Found","",
486                                 "The requested file was not found");
487         }
488         fd = sys_open(file,O_RDONLY,0);
489         if (fd == -1) {
490                 cgi_setup_error("404 File Not Found","",
491                                 "The requested file was not found");
492         }
493         printf("HTTP/1.0 200 OK\r\n");
494         if ((p=strrchr_m(file,'.'))) {
495                 if (strcmp(p,".gif")==0) {
496                         printf("Content-Type: image/gif\r\n");
497                 } else if (strcmp(p,".jpg")==0) {
498                         printf("Content-Type: image/jpeg\r\n");
499                 } else if (strcmp(p,".txt")==0) {
500                         printf("Content-Type: text/plain\r\n");
501                 } else {
502                         printf("Content-Type: text/html\r\n");
503                 }
504         }
505         printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
506
507         printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
508         while ((l=read(fd,buf,sizeof(buf)))>0) {
509                 fwrite(buf, 1, l, stdout);
510         }
511         close(fd);
512         exit(0);
513 }
514
515
516
517
518 /***************************************************************************
519 setup the cgi framework, handling the possability that this program is either
520 run as a true cgi program by a web browser or is itself a mini web server
521   ***************************************************************************/
522 void cgi_setup(char *rootdir, int auth_required)
523 {
524         BOOL authenticated = False;
525         char line[1024];
526         char *url=NULL;
527         char *p;
528
529         if (chdir(rootdir)) {
530                 cgi_setup_error("400 Server Error", "",
531                                 "chdir failed - the server is not configured correctly");
532         }
533
534         /* maybe we are running under a web server */
535         if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
536                 if (auth_required) {
537                         cgi_web_auth();
538                 }
539                 return;
540         }
541
542         inetd_server = True;
543
544         if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
545                 cgi_setup_error("400 Server Error", "",
546                                 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
547         }
548
549         /* we are a mini-web server. We need to read the request from stdin
550            and handle authentication etc */
551         while (fgets(line, sizeof(line)-1, stdin)) {
552                 if (line[0] == '\r' || line[0] == '\n') break;
553                 if (strncasecmp(line,"GET ", 4)==0) {
554                         got_request = True;
555                         url = strdup(&line[4]);
556                 } else if (strncasecmp(line,"POST ", 5)==0) {
557                         got_request = True;
558                         request_post = 1;
559                         url = strdup(&line[5]);
560                 } else if (strncasecmp(line,"PUT ", 4)==0) {
561                         got_request = True;
562                         cgi_setup_error("400 Bad Request", "",
563                                         "This server does not accept PUT requests");
564                 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
565                         authenticated = cgi_handle_authorization(&line[15]);
566                 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
567                         content_length = atoi(&line[16]);
568                 }
569                 /* ignore all other requests! */
570         }
571
572         if (auth_required && !authenticated) {
573                 cgi_auth_error();
574         }
575
576         if (!url) {
577                 cgi_setup_error("400 Bad Request", "",
578                                 "You must specify a GET or POST request");
579         }
580
581         /* trim the URL */
582         if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
583                 *p = 0;
584         }
585         while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
586                 url[strlen(url)-1] = 0;
587         }
588
589         /* anything following a ? in the URL is part of the query string */
590         if ((p=strchr_m(url,'?'))) {
591                 query_string = p+1;
592                 *p = 0;
593         }
594
595         string_sub(url, "/swat/", "", 0);
596
597         if (url[0] != '/' && strstr(url,"..")==0 && file_exist(url, NULL)) {
598                 cgi_download(url);
599         }
600
601         printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
602         printf("Date: %s\r\n", http_timestring(time(NULL)));
603         baseurl = "";
604         pathinfo = url+1;
605 }
606
607
608 /***************************************************************************
609 return the current pages URL
610   ***************************************************************************/
611 char *cgi_baseurl(void)
612 {
613         if (inetd_server) {
614                 return baseurl;
615         }
616         return getenv("SCRIPT_NAME");
617 }
618
619 /***************************************************************************
620 return the current pages path info
621   ***************************************************************************/
622 char *cgi_pathinfo(void)
623 {
624         char *r;
625         if (inetd_server) {
626                 return pathinfo;
627         }
628         r = getenv("PATH_INFO");
629         if (!r) return "";
630         if (*r == '/') r++;
631         return r;
632 }
633
634 /***************************************************************************
635 return the hostname of the client
636   ***************************************************************************/
637 char *cgi_remote_host(void)
638 {
639         if (inetd_server) {
640                 return get_socket_name(1);
641         }
642         return getenv("REMOTE_HOST");
643 }
644
645 /***************************************************************************
646 return the hostname of the client
647   ***************************************************************************/
648 char *cgi_remote_addr(void)
649 {
650         if (inetd_server) {
651                 return get_socket_addr(1);
652         }
653         return getenv("REMOTE_ADDR");
654 }
655
656
657 /***************************************************************************
658 return True if the request was a POST
659   ***************************************************************************/
660 BOOL cgi_waspost(void)
661 {
662         if (inetd_server) {
663                 return request_post;
664         }
665         return strequal(getenv("REQUEST_METHOD"), "POST");
666 }