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