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