first pass at updating head branch to be to be the same as the SAMBA_2_0 branch
[kai/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 #define CGI_LOGGING 0
30
31 #ifdef DEBUG_COMMENTS
32 extern void print_title(char *fmt, ...);
33 #endif
34
35 struct var {
36         char *name;
37         char *value;
38 };
39
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;
50
51 static void unescape(char *buf)
52 {
53         char *p=buf;
54
55         while ((p=strchr(p,'+')))
56                 *p = ' ';
57
58         p = buf;
59
60         while (p && *p && (p=strchr(p,'%'))) {
61                 int c1 = p[1];
62                 int c2 = p[2];
63
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;}
71
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;}
79                         
80                 *p = (c1<<4) | c2;
81
82                 memcpy(p+1, p+3, strlen(p+3)+1);
83                 p++;
84         }
85 }
86
87
88 static char *grab_line(FILE *f, int *cl)
89 {
90         char *ret;
91         int i = 0;
92         int len = 1024;
93
94         ret = (char *)malloc(len);
95         if (!ret) return NULL;
96         
97
98         while ((*cl)) {
99                 int c = fgetc(f);
100                 (*cl)--;
101
102                 if (c == EOF) {
103                         (*cl) = 0;
104                         break;
105                 }
106                 
107                 if (c == '\r') continue;
108
109                 if (strchr("\n&", c)) break;
110
111                 ret[i++] = c;
112
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;
119                 }
120         }
121         
122
123         ret[i] = 0;
124         return ret;
125 }
126
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)
133 {
134         FILE *f = f1;
135         static char *line;
136         char *p, *s, *tok;
137         int len;
138
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
144
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;
152                 }
153         } else {
154                 fseek(f, 0, SEEK_END);
155                 len = ftell(f);
156                 fseek(f, 0, SEEK_SET);
157         }
158
159
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;
167                         
168                         *p = 0;
169                         
170                         variables[num_variables].name = strdup(line);
171                         variables[num_variables].value = strdup(p+1);
172
173                         free(line);
174                         
175                         if (!variables[num_variables].name || 
176                             !variables[num_variables].value)
177                                 continue;
178
179                         unescape(variables[num_variables].value);
180                         unescape(variables[num_variables].name);
181
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
187                         
188                         num_variables++;
189                         if (num_variables == MAX_VARIABLES) break;
190                 }
191         }
192
193         if (f1) {
194 #ifdef DEBUG_COMMENTS
195                 printf("<!== End dump in cgi_load_variables() ==>\n"); 
196 #endif
197                 return;
198         }
199
200         fclose(stdin);
201
202         if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
203                 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
204                         p = strchr(tok,'=');
205                         if (!p) continue;
206                         
207                         *p = 0;
208                         
209                         variables[num_variables].name = strdup(tok);
210                         variables[num_variables].value = strdup(p+1);
211
212                         if (!variables[num_variables].name || 
213                             !variables[num_variables].value)
214                                 continue;
215
216                         unescape(variables[num_variables].value);
217                         unescape(variables[num_variables].name);
218
219 #ifdef DEBUG_COMMENTS
220                         printf("<!== Commandline var %s has value \"%s\"  ==>\n",
221                                variables[num_variables].name,
222                                variables[num_variables].value);
223 #endif                                          
224                         num_variables++;
225                         if (num_variables == MAX_VARIABLES) break;
226                 }
227
228         }
229 #ifdef DEBUG_COMMENTS
230         printf("<!== End dump in cgi_load_variables() ==>\n");   
231 #endif
232 }
233
234
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)
243 {
244         int i;
245
246         for (i=0;i<num_variables;i++)
247                 if (strcmp(variables[i].name, name) == 0)
248                         return variables[i].value;
249         return NULL;
250 }
251
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)
256 {
257         if (!got_request) {
258                 /* damn browsers don't like getting cut off before they give a request */
259                 char line[1024];
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) {
264                                 break;
265                         }
266                 }
267         }
268
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);
270         fclose(stdin);
271         fclose(stdout);
272         exit(0);
273 }
274
275
276 /***************************************************************************
277 tell a browser about a fatal authentication error
278   ***************************************************************************/
279 static void cgi_auth_error(void)
280 {
281         if (inetd_server) {
282                 cgi_setup_error("401 Authorization Required", 
283                                 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
284                                 "You must be authenticated to use this service");
285         } else {
286                 printf("Content-Type: text/html\r\n");
287
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");
292         }
293         exit(0);
294 }
295
296
297 /***************************************************************************
298 decode a base64 string in-place - simple and slow algorithm
299   ***************************************************************************/
300 static void base64_decode(char *s)
301 {
302         char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
303         int bit_offset, byte_offset, idx, i, n;
304         unsigned char *d = (unsigned char *)s;
305         char *p;
306
307         n=i=0;
308
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));
316                         n = byte_offset+1;
317                 } else {
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;
321                         n = byte_offset+2;
322                 }
323                 s++; i++;
324         }
325         /* null terminate */
326         d[n] = 0;
327 }
328
329
330 /***************************************************************************
331 handle a http authentication line
332   ***************************************************************************/
333 static BOOL cgi_handle_authorization(char *line)
334 {
335         char *p, *user, *user_pass;
336         struct passwd *pass = NULL;
337         BOOL ret = False;
338
339         if (strncasecmp(line,"Basic ", 6)) {
340                 cgi_setup_error("401 Bad Authorization", "", 
341                                 "Only basic authorization is understood");
342                 return False;
343         }
344         line += 6;
345         while (line[0] == ' ') line++;
346         base64_decode(line);
347         if (!(p=strchr(line,':'))) {
348                 /*
349                  * Always give the same error so a cracker
350                  * cannot tell why we fail.
351                  */
352                 cgi_setup_error("401 Bad Authorization", "", 
353                                 "username/password must be supplied");
354                 return False;
355         }
356         *p = 0;
357         user = line;
358         user_pass = p+1;
359
360         /*
361          * Try and get the user from the UNIX password file.
362          */
363
364         if(!(pass = Get_Pwnam(user,False))) {
365                 /*
366                  * Always give the same error so a cracker
367                  * cannot tell why we fail.
368                  */
369                 cgi_setup_error("401 Bad Authorization", "",
370                                 "username/password must be supplied");
371                 return False;
372         }
373
374         /*
375          * Validate the password they have given.
376          */
377
378         if((ret = pass_check(user, user_pass, strlen(user_pass), NULL, NULL)) == True) {
379
380                 /*
381                  * Password was ok.
382                  */
383
384                 if(pass->pw_uid != 0) {
385                         /*
386                          * We have not authenticated as root,
387                          * become the user *permanently*.
388                          */
389                         become_user_permanently(pass->pw_uid, pass->pw_gid);
390                 }
391
392                 /* Save the users name */
393                 C_user = strdup(user);
394         }
395
396         return ret;
397 }
398
399 /***************************************************************************
400 is this root?
401   ***************************************************************************/
402 BOOL am_root(void)
403 {
404         if (geteuid() == 0) {
405                 return( True);
406         } else {
407                 return( False);
408         }
409 }
410
411 /***************************************************************************
412 return a ptr to the users name
413   ***************************************************************************/
414 char *cgi_user_name(void)
415 {
416         return(C_user);
417 }
418
419
420 /***************************************************************************
421 handle a file download
422   ***************************************************************************/
423 static void cgi_download(char *file)
424 {
425         SMB_STRUCT_STAT st;
426         char buf[1024];
427         int fd, l, i;
428         char *p;
429
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");
435                 }
436         }
437
438         if (!file_exist(file, &st)) {
439                 cgi_setup_error("404 File Not Found","",
440                                 "The requested file was not found");
441         }
442         fd = sys_open(file,O_RDONLY,0);
443         if (fd == -1) {
444                 cgi_setup_error("404 File Not Found","",
445                                 "The requested file was not found");
446         }
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");
453                 } else {
454                         printf("Content-Type: text/html\r\n");
455                 }
456         }
457         printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
458
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);
462         }
463         close(fd);
464         exit(0);
465 }
466
467
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)
473 {
474         BOOL authenticated = False;
475         char line[1024];
476         char *url=NULL;
477         char *p;
478 #if CGI_LOGGING
479         FILE *f;
480 #endif
481
482         if (chdir(rootdir)) {
483                 cgi_setup_error("400 Server Error", "",
484                                 "chdir failed - the server is not configured correctly");
485         }
486
487         /* maybe we are running under a web server */
488         if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
489                 if (auth_required) {
490                         cgi_auth_error();
491                 }
492                 return;
493         }
494
495         inetd_server = True;
496
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 ");
500         }
501
502 #if CGI_LOGGING
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));
507 #endif
508
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)) {
512 #if CGI_LOGGING
513                 if (f) fputs(line, f);
514 #endif
515                 if (line[0] == '\r' || line[0] == '\n') break;
516                 if (strncasecmp(line,"GET ", 4)==0) {
517                         got_request = True;
518                         url = strdup(&line[4]);
519                 } else if (strncasecmp(line,"POST ", 5)==0) {
520                         got_request = True;
521                         request_post = 1;
522                         url = strdup(&line[5]);
523                 } else if (strncasecmp(line,"PUT ", 4)==0) {
524                         got_request = True;
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]);
531                 }
532                 /* ignore all other requests! */
533         }
534 #if CGI_LOGGING
535         if (f) fclose(f);
536 #endif
537
538         if (auth_required && !authenticated) {
539                 cgi_auth_error();
540         }
541
542         if (!url) {
543                 cgi_setup_error("400 Bad Request", "",
544                                 "You must specify a GET or POST request");
545         }
546
547         /* trim the URL */
548         if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
549                 *p = 0;
550         }
551         while (*url && strchr("\r\n",url[strlen(url)-1])) {
552                 url[strlen(url)-1] = 0;
553         }
554
555         /* anything following a ? in the URL is part of the query string */
556         if ((p=strchr(url,'?'))) {
557                 query_string = p+1;
558                 *p = 0;
559         }
560
561         string_sub(url, "/swat/", "", 0);
562
563         if (url[0] != '/' && strstr(url,"..")==0 && file_exist(url, NULL)) {
564                 cgi_download(url);
565         }
566
567         printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
568         printf("Date: %s\r\n", http_timestring(time(NULL)));
569         baseurl = "";
570         pathinfo = url+1;
571 }
572
573
574 /***************************************************************************
575 return the current pages URL
576   ***************************************************************************/
577 char *cgi_baseurl(void)
578 {
579         if (inetd_server) {
580                 return baseurl;
581         }
582         return getenv("SCRIPT_NAME");
583 }
584
585 /***************************************************************************
586 return the current pages path info
587   ***************************************************************************/
588 char *cgi_pathinfo(void)
589 {
590         char *r;
591         if (inetd_server) {
592                 return pathinfo;
593         }
594         r = getenv("PATH_INFO");
595         if (!r) return "";
596         if (*r == '/') r++;
597         return r;
598 }
599
600 /***************************************************************************
601 return the hostname of the client
602   ***************************************************************************/
603 char *cgi_remote_host(void)
604 {
605         if (inetd_server) {
606                 return client_name(1);
607         }
608         return getenv("REMOTE_HOST");
609 }
610
611 /***************************************************************************
612 return the hostname of the client
613   ***************************************************************************/
614 char *cgi_remote_addr(void)
615 {
616         if (inetd_server) {
617                 return client_addr(1);
618         }
619         return getenv("REMOTE_ADDR");
620 }
621
622
623 /***************************************************************************
624 return True if the request was a POST
625   ***************************************************************************/
626 BOOL cgi_waspost(void)
627 {
628         if (inetd_server) {
629                 return request_post;
630         }
631         return strequal(getenv("REQUEST_METHOD"), "POST");
632 }