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