debug: Restore the s3-style check in check_log_size()
[Samba.git] / source3 / web / cgi.c
blobfa2304016ec38d3870d9a6a7ade9c44ff960014c
1 /*
2 some simple CGI helper routines
3 Copyright (C) Andrew Tridgell 1997-1998
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.
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.
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/>.
20 #include "includes.h"
21 #include "system/passwd.h"
22 #include "system/filesys.h"
23 #include "web/swat_proto.h"
24 #include "intl/lang_tdb.h"
25 #include "auth.h"
27 #define MAX_VARIABLES 10000
29 /* set the expiry on fixed pages */
30 #define EXPIRY_TIME (60*60*24*7)
32 #ifdef DEBUG_COMMENTS
33 extern void print_title(char *fmt, ...);
34 #endif
36 struct cgi_var {
37 char *name;
38 char *value;
41 static struct cgi_var variables[MAX_VARIABLES];
42 static int num_variables;
43 static int content_length;
44 static int request_post;
45 static char *query_string;
46 static const char *baseurl;
47 static char *pathinfo;
48 static char *C_user;
49 static bool inetd_server;
50 static bool got_request;
52 static char *grab_line(FILE *f, int *cl)
54 char *ret = NULL;
55 int i = 0;
56 int len = 0;
58 while ((*cl)) {
59 int c;
61 if (i == len) {
62 char *ret2;
63 if (len == 0) len = 1024;
64 else len *= 2;
65 ret2 = (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret, len);
66 if (!ret2) return ret;
67 ret = ret2;
70 c = fgetc(f);
71 (*cl)--;
73 if (c == EOF) {
74 (*cl) = 0;
75 break;
78 if (c == '\r') continue;
80 if (strchr_m("\n&", c)) break;
82 ret[i++] = c;
86 if (ret) {
87 ret[i] = 0;
89 return ret;
92 /**
93 URL encoded strings can have a '+', which should be replaced with a space
95 (This was in rfc1738_unescape(), but that broke the squid helper)
96 **/
98 static void plus_to_space_unescape(char *buf)
100 char *p=buf;
102 while ((p=strchr_m(p,'+')))
103 *p = ' ';
106 /***************************************************************************
107 load all the variables passed to the CGI program. May have multiple variables
108 with the same name and the same or different values. Takes a file parameter
109 for simulating CGI invocation eg loading saved preferences.
110 ***************************************************************************/
111 void cgi_load_variables(void)
113 static char *line;
114 char *p, *s, *tok;
115 int len, i;
116 FILE *f = stdin;
118 #ifdef DEBUG_COMMENTS
119 char dummy[100]="";
120 print_title(dummy);
121 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
122 #endif
124 if (!content_length) {
125 p = getenv("CONTENT_LENGTH");
126 len = p?atoi(p):0;
127 } else {
128 len = content_length;
132 if (len > 0 &&
133 (request_post ||
134 ((s=getenv("REQUEST_METHOD")) &&
135 strequal(s,"POST")))) {
136 while (len && (line=grab_line(f, &len))) {
137 p = strchr_m(line,'=');
138 if (!p) continue;
140 *p = 0;
142 variables[num_variables].name = SMB_STRDUP(line);
143 variables[num_variables].value = SMB_STRDUP(p+1);
145 SAFE_FREE(line);
147 if (!variables[num_variables].name ||
148 !variables[num_variables].value)
149 continue;
151 plus_to_space_unescape(variables[num_variables].value);
152 rfc1738_unescape(variables[num_variables].value);
153 plus_to_space_unescape(variables[num_variables].name);
154 rfc1738_unescape(variables[num_variables].name);
156 #ifdef DEBUG_COMMENTS
157 printf("<!== POST var %s has value \"%s\" ==>\n",
158 variables[num_variables].name,
159 variables[num_variables].value);
160 #endif
162 num_variables++;
163 if (num_variables == MAX_VARIABLES) break;
167 fclose(stdin);
168 open("/dev/null", O_RDWR);
170 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
171 char *saveptr;
172 for (tok=strtok_r(s, "&;", &saveptr); tok;
173 tok=strtok_r(NULL, "&;", &saveptr)) {
174 p = strchr_m(tok,'=');
175 if (!p) continue;
177 *p = 0;
179 variables[num_variables].name = SMB_STRDUP(tok);
180 variables[num_variables].value = SMB_STRDUP(p+1);
182 if (!variables[num_variables].name ||
183 !variables[num_variables].value)
184 continue;
186 plus_to_space_unescape(variables[num_variables].value);
187 rfc1738_unescape(variables[num_variables].value);
188 plus_to_space_unescape(variables[num_variables].name);
189 rfc1738_unescape(variables[num_variables].name);
191 #ifdef DEBUG_COMMENTS
192 printf("<!== Commandline var %s has value \"%s\" ==>\n",
193 variables[num_variables].name,
194 variables[num_variables].value);
195 #endif
196 num_variables++;
197 if (num_variables == MAX_VARIABLES) break;
201 #ifdef DEBUG_COMMENTS
202 printf("<!== End dump in cgi_load_variables() ==>\n");
203 #endif
205 /* variables from the client are in UTF-8 - convert them
206 to our internal unix charset before use */
207 for (i=0;i<num_variables;i++) {
208 TALLOC_CTX *frame = talloc_stackframe();
209 char *dest = NULL;
210 size_t dest_len;
212 convert_string_talloc(frame, CH_UTF8, CH_UNIX,
213 variables[i].name, strlen(variables[i].name),
214 &dest, &dest_len);
215 SAFE_FREE(variables[i].name);
216 variables[i].name = SMB_STRDUP(dest ? dest : "");
218 dest = NULL;
219 convert_string_talloc(frame, CH_UTF8, CH_UNIX,
220 variables[i].value, strlen(variables[i].value),
221 &dest, &dest_len);
222 SAFE_FREE(variables[i].value);
223 variables[i].value = SMB_STRDUP(dest ? dest : "");
224 TALLOC_FREE(frame);
229 /***************************************************************************
230 find a variable passed via CGI
231 Doesn't quite do what you think in the case of POST text variables, because
232 if they exist they might have a value of "" or even " ", depending on the
233 browser. Also doesn't allow for variables[] containing multiple variables
234 with the same name and the same or different values.
235 ***************************************************************************/
237 const char *cgi_variable(const char *name)
239 int i;
241 for (i=0;i<num_variables;i++)
242 if (strcmp(variables[i].name, name) == 0)
243 return variables[i].value;
244 return NULL;
247 /***************************************************************************
248 Version of the above that can't return a NULL pointer.
249 ***************************************************************************/
251 const char *cgi_variable_nonull(const char *name)
253 const char *var = cgi_variable(name);
254 if (var) {
255 return var;
256 } else {
257 return "";
261 /***************************************************************************
262 tell a browser about a fatal error in the http processing
263 ***************************************************************************/
264 static void cgi_setup_error(const char *err, const char *header, const char *info)
266 if (!got_request) {
267 /* damn browsers don't like getting cut off before they give a request */
268 char line[1024];
269 while (fgets(line, sizeof(line)-1, stdin)) {
270 if (strnequal(line,"GET ", 4) ||
271 strnequal(line,"POST ", 5) ||
272 strnequal(line,"PUT ", 4)) {
273 break;
278 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);
279 fclose(stdin);
280 fclose(stdout);
281 exit(0);
285 /***************************************************************************
286 tell a browser about a fatal authentication error
287 ***************************************************************************/
288 static void cgi_auth_error(void)
290 if (inetd_server) {
291 cgi_setup_error("401 Authorization Required",
292 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
293 "You must be authenticated to use this service");
294 } else {
295 printf("Content-Type: text/html\r\n");
297 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
298 printf("<BODY><H1>Installation Error</H1>\n");
299 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
300 printf("</BODY></HTML>\r\n");
302 exit(0);
305 /***************************************************************************
306 authenticate when we are running as a CGI
307 ***************************************************************************/
308 static void cgi_web_auth(void)
310 const char *user = getenv("REMOTE_USER");
311 struct passwd *pwd;
312 const char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
313 const char *tail = "</BODY></HTML>\r\n";
315 if (!user) {
316 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
317 head, tail);
318 exit(0);
321 pwd = Get_Pwnam_alloc(talloc_tos(), user);
322 if (!pwd) {
323 printf("%sCannot find user %s<br>%s\n", head, user, tail);
324 exit(0);
327 setuid(0);
328 setuid(pwd->pw_uid);
329 if (geteuid() != pwd->pw_uid || getuid() != pwd->pw_uid) {
330 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
331 head, user, (int)geteuid(), (int)getuid(), tail);
332 exit(0);
334 TALLOC_FREE(pwd);
338 /***************************************************************************
339 handle a http authentication line
340 ***************************************************************************/
341 static bool cgi_handle_authorization(char *line)
343 char *p;
344 fstring user, user_pass;
345 struct passwd *pass = NULL;
346 const char *rhost;
347 char addr[INET6_ADDRSTRLEN];
348 size_t size = 0;
350 if (!strnequal(line,"Basic ", 6)) {
351 goto err;
353 line += 6;
354 while (line[0] == ' ') line++;
355 base64_decode_inplace(line);
356 if (!(p=strchr_m(line,':'))) {
358 * Always give the same error so a cracker
359 * cannot tell why we fail.
361 goto err;
363 *p = 0;
365 if (!convert_string(CH_UTF8, CH_UNIX,
366 line, -1,
367 user, sizeof(user), &size)) {
368 goto err;
371 if (!convert_string(CH_UTF8, CH_UNIX,
372 p+1, -1,
373 user_pass, sizeof(user_pass), &size)) {
374 goto err;
378 * Try and get the user from the UNIX password file.
381 pass = Get_Pwnam_alloc(talloc_tos(), user);
383 rhost = client_name(1);
384 if (strequal(rhost,"UNKNOWN"))
385 rhost = client_addr(1, addr, sizeof(addr));
388 * Validate the password they have given.
391 if NT_STATUS_IS_OK(pass_check(pass, user, rhost, user_pass, false)) {
392 if (pass) {
394 * Password was ok.
397 if ( initgroups(pass->pw_name, pass->pw_gid) != 0 )
398 goto err;
400 become_user_permanently(pass->pw_uid, pass->pw_gid);
402 /* Save the users name */
403 C_user = SMB_STRDUP(user);
404 TALLOC_FREE(pass);
405 return True;
409 err:
410 cgi_setup_error("401 Bad Authorization",
411 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
412 "username or password incorrect");
414 TALLOC_FREE(pass);
415 return False;
418 /***************************************************************************
419 is this root?
420 ***************************************************************************/
421 bool am_root(void)
423 if (geteuid() == 0) {
424 return( True);
425 } else {
426 return( False);
430 /***************************************************************************
431 return a ptr to the users name
432 ***************************************************************************/
433 char *cgi_user_name(void)
435 return(C_user);
439 /***************************************************************************
440 handle a file download
441 ***************************************************************************/
442 static void cgi_download(char *file)
444 SMB_STRUCT_STAT st;
445 char buf[1024];
446 int fd, l, i;
447 char *p;
448 char *lang;
450 /* sanitise the filename */
451 for (i=0;file[i];i++) {
452 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
453 cgi_setup_error("404 File Not Found","",
454 "Illegal character in filename");
458 if (sys_stat(file, &st, false) != 0) {
459 cgi_setup_error("404 File Not Found","",
460 "The requested file was not found");
463 if (S_ISDIR(st.st_ex_mode))
465 snprintf(buf, sizeof(buf), "%s/index.html", file);
466 if (!file_exist_stat(buf, &st, false)
467 || !S_ISREG(st.st_ex_mode))
469 cgi_setup_error("404 File Not Found","",
470 "The requested file was not found");
473 else if (S_ISREG(st.st_ex_mode))
475 snprintf(buf, sizeof(buf), "%s", file);
477 else
479 cgi_setup_error("404 File Not Found","",
480 "The requested file was not found");
483 fd = web_open(buf,O_RDONLY,0);
484 if (fd == -1) {
485 cgi_setup_error("404 File Not Found","",
486 "The requested file was not found");
488 printf("HTTP/1.0 200 OK\r\n");
489 if ((p=strrchr_m(buf, '.'))) {
490 if (strcmp(p,".gif")==0) {
491 printf("Content-Type: image/gif\r\n");
492 } else if (strcmp(p,".jpg")==0) {
493 printf("Content-Type: image/jpeg\r\n");
494 } else if (strcmp(p,".png")==0) {
495 printf("Content-Type: image/png\r\n");
496 } else if (strcmp(p,".css")==0) {
497 printf("Content-Type: text/css\r\n");
498 } else if (strcmp(p,".txt")==0) {
499 printf("Content-Type: text/plain\r\n");
500 } else {
501 printf("Content-Type: text/html\r\n");
504 printf("Expires: %s\r\n",
505 http_timestring(talloc_tos(), time(NULL)+EXPIRY_TIME));
507 lang = lang_tdb_current();
508 if (lang) {
509 printf("Content-Language: %s\r\n", lang);
512 printf("Content-Length: %d\r\n\r\n", (int)st.st_ex_size);
513 while ((l=read(fd,buf,sizeof(buf)))>0) {
514 if (fwrite(buf, 1, l, stdout) != l) {
515 break;
518 close(fd);
519 exit(0);
524 /* return true if the char* contains ip addrs only. Used to avoid
525 name lookup calls */
527 static bool only_ipaddrs_in_list(const char **list)
529 bool only_ip = true;
531 if (!list) {
532 return true;
535 for (; *list ; list++) {
536 /* factor out the special strings */
537 if (strequal(*list, "ALL") || strequal(*list, "FAIL") ||
538 strequal(*list, "EXCEPT")) {
539 continue;
542 if (!is_ipaddress(*list)) {
544 * If we failed, make sure that it was not because
545 * the token was a network/netmask pair. Only
546 * network/netmask pairs have a '/' in them.
548 if ((strchr_m(*list, '/')) == NULL) {
549 only_ip = false;
550 DEBUG(3,("only_ipaddrs_in_list: list has "
551 "non-ip address (%s)\n",
552 *list));
553 break;
558 return only_ip;
561 /* return true if access should be allowed to a service for a socket */
562 static bool check_access(int sock, const char **allow_list,
563 const char **deny_list)
565 bool ret = false;
566 bool only_ip = false;
567 char addr[INET6_ADDRSTRLEN];
569 if ((!deny_list || *deny_list==0) && (!allow_list || *allow_list==0)) {
570 return true;
573 /* Bypass name resolution calls if the lists
574 * only contain IP addrs */
575 if (only_ipaddrs_in_list(allow_list) &&
576 only_ipaddrs_in_list(deny_list)) {
577 only_ip = true;
578 DEBUG (3, ("check_access: no hostnames "
579 "in host allow/deny list.\n"));
580 ret = allow_access(deny_list,
581 allow_list,
583 get_peer_addr(sock,addr,sizeof(addr)));
584 } else {
585 DEBUG (3, ("check_access: hostnames in "
586 "host allow/deny list.\n"));
587 ret = allow_access(deny_list,
588 allow_list,
589 get_peer_name(sock,true),
590 get_peer_addr(sock,addr,sizeof(addr)));
593 if (ret) {
594 DEBUG(2,("Allowed connection from %s (%s)\n",
595 only_ip ? "" : get_peer_name(sock,true),
596 get_peer_addr(sock,addr,sizeof(addr))));
597 } else {
598 DEBUG(0,("Denied connection from %s (%s)\n",
599 only_ip ? "" : get_peer_name(sock,true),
600 get_peer_addr(sock,addr,sizeof(addr))));
603 return(ret);
607 * @brief Setup the CGI framework.
609 * Setup the cgi framework, handling the possibility that this program
610 * is either run as a true CGI program with a gateway to a web server, or
611 * is itself a mini web server.
613 void cgi_setup(const char *rootdir, int auth_required)
615 bool authenticated = False;
616 char line[1024];
617 char *url=NULL;
618 char *p;
619 char *lang;
621 if (chdir(rootdir)) {
622 cgi_setup_error("500 Server Error", "",
623 "chdir failed - the server is not configured correctly");
626 /* Handle the possibility we might be running as non-root */
627 sec_init();
629 if ((lang=getenv("HTTP_ACCEPT_LANGUAGE"))) {
630 /* if running as a cgi program */
631 web_set_lang(lang);
634 /* maybe we are running under a web server */
635 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
636 if (auth_required) {
637 cgi_web_auth();
639 return;
642 inetd_server = True;
644 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
645 cgi_setup_error("403 Forbidden", "",
646 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
649 /* we are a mini-web server. We need to read the request from stdin
650 and handle authentication etc */
651 while (fgets(line, sizeof(line)-1, stdin)) {
652 if (line[0] == '\r' || line[0] == '\n') break;
653 if (strnequal(line,"GET ", 4)) {
654 got_request = True;
655 url = SMB_STRDUP(&line[4]);
656 } else if (strnequal(line,"POST ", 5)) {
657 got_request = True;
658 request_post = 1;
659 url = SMB_STRDUP(&line[5]);
660 } else if (strnequal(line,"PUT ", 4)) {
661 got_request = True;
662 cgi_setup_error("400 Bad Request", "",
663 "This server does not accept PUT requests");
664 } else if (strnequal(line,"Authorization: ", 15)) {
665 authenticated = cgi_handle_authorization(&line[15]);
666 } else if (strnequal(line,"Content-Length: ", 16)) {
667 content_length = atoi(&line[16]);
668 } else if (strnequal(line,"Accept-Language: ", 17)) {
669 web_set_lang(&line[17]);
671 /* ignore all other requests! */
674 if (auth_required && !authenticated) {
675 cgi_auth_error();
678 if (!url) {
679 cgi_setup_error("400 Bad Request", "",
680 "You must specify a GET or POST request");
683 /* trim the URL */
684 if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
685 *p = 0;
687 while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
688 url[strlen(url)-1] = 0;
691 /* anything following a ? in the URL is part of the query string */
692 if ((p=strchr_m(url,'?'))) {
693 query_string = p+1;
694 *p = 0;
697 string_sub(url, "/swat/", "", 0);
699 if (url[0] != '/' && strstr(url,"..")==0) {
700 cgi_download(url);
703 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
704 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL)));
705 baseurl = "";
706 pathinfo = url+1;
710 /***************************************************************************
711 return the current pages URL
712 ***************************************************************************/
713 const char *cgi_baseurl(void)
715 if (inetd_server) {
716 return baseurl;
718 return getenv("SCRIPT_NAME");
721 /***************************************************************************
722 return the current pages path info
723 ***************************************************************************/
724 const char *cgi_pathinfo(void)
726 char *r;
727 if (inetd_server) {
728 return pathinfo;
730 r = getenv("PATH_INFO");
731 if (!r) return "";
732 if (*r == '/') r++;
733 return r;
736 /***************************************************************************
737 return the hostname of the client
738 ***************************************************************************/
739 const char *cgi_remote_host(void)
741 if (inetd_server) {
742 return get_peer_name(1,False);
744 return getenv("REMOTE_HOST");
747 /***************************************************************************
748 return the hostname of the client
749 ***************************************************************************/
750 const char *cgi_remote_addr(void)
752 if (inetd_server) {
753 char addr[INET6_ADDRSTRLEN];
754 get_peer_addr(1,addr,sizeof(addr));
755 return talloc_strdup(talloc_tos(), addr);
757 return getenv("REMOTE_ADDR");
761 /***************************************************************************
762 return True if the request was a POST
763 ***************************************************************************/
764 bool cgi_waspost(void)
766 if (inetd_server) {
767 return request_post;
769 return strequal(getenv("REQUEST_METHOD"), "POST");