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