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