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/>.
21 #include "system/passwd.h"
22 #include "system/filesys.h"
23 #include "web/swat_proto.h"
24 #include "intl/lang_tdb.h"
26 #define MAX_VARIABLES 10000
28 /* set the expiry on fixed pages */
29 #define EXPIRY_TIME (60*60*24*7)
32 extern void print_title(char *fmt, ...);
40 static struct cgi_var variables[MAX_VARIABLES];
41 static int num_variables;
42 static int content_length;
43 static int request_post;
44 static char *query_string;
45 static const char *baseurl;
46 static char *pathinfo;
48 static bool inetd_server;
49 static bool got_request;
51 static char *grab_line(FILE *f, int *cl)
62 if (len == 0) len = 1024;
64 ret2 = (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret, len);
65 if (!ret2) return ret;
77 if (c == '\r') continue;
79 if (strchr_m("\n&", c)) break;
92 URL encoded strings can have a '+', which should be replaced with a space
94 (This was in rfc1738_unescape(), but that broke the squid helper)
97 static void plus_to_space_unescape(char *buf)
101 while ((p=strchr_m(p,'+')))
105 /***************************************************************************
106 load all the variables passed to the CGI program. May have multiple variables
107 with the same name and the same or different values. Takes a file parameter
108 for simulating CGI invocation eg loading saved preferences.
109 ***************************************************************************/
110 void cgi_load_variables(void)
117 #ifdef DEBUG_COMMENTS
120 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
123 if (!content_length) {
124 p = getenv("CONTENT_LENGTH");
127 len = content_length;
133 ((s=getenv("REQUEST_METHOD")) &&
134 strequal(s,"POST")))) {
135 while (len && (line=grab_line(f, &len))) {
136 p = strchr_m(line,'=');
141 variables[num_variables].name = SMB_STRDUP(line);
142 variables[num_variables].value = SMB_STRDUP(p+1);
146 if (!variables[num_variables].name ||
147 !variables[num_variables].value)
150 plus_to_space_unescape(variables[num_variables].value);
151 rfc1738_unescape(variables[num_variables].value);
152 plus_to_space_unescape(variables[num_variables].name);
153 rfc1738_unescape(variables[num_variables].name);
155 #ifdef DEBUG_COMMENTS
156 printf("<!== POST var %s has value \"%s\" ==>\n",
157 variables[num_variables].name,
158 variables[num_variables].value);
162 if (num_variables == MAX_VARIABLES) break;
167 open("/dev/null", O_RDWR);
169 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
171 for (tok=strtok_r(s, "&;", &saveptr); tok;
172 tok=strtok_r(NULL, "&;", &saveptr)) {
173 p = strchr_m(tok,'=');
178 variables[num_variables].name = SMB_STRDUP(tok);
179 variables[num_variables].value = SMB_STRDUP(p+1);
181 if (!variables[num_variables].name ||
182 !variables[num_variables].value)
185 plus_to_space_unescape(variables[num_variables].value);
186 rfc1738_unescape(variables[num_variables].value);
187 plus_to_space_unescape(variables[num_variables].name);
188 rfc1738_unescape(variables[num_variables].name);
190 #ifdef DEBUG_COMMENTS
191 printf("<!== Commandline var %s has value \"%s\" ==>\n",
192 variables[num_variables].name,
193 variables[num_variables].value);
196 if (num_variables == MAX_VARIABLES) break;
200 #ifdef DEBUG_COMMENTS
201 printf("<!== End dump in cgi_load_variables() ==>\n");
204 /* variables from the client are in UTF-8 - convert them
205 to our internal unix charset before use */
206 for (i=0;i<num_variables;i++) {
207 TALLOC_CTX *frame = talloc_stackframe();
211 convert_string_talloc(frame, CH_UTF8, CH_UNIX,
212 variables[i].name, strlen(variables[i].name),
214 SAFE_FREE(variables[i].name);
215 variables[i].name = SMB_STRDUP(dest ? dest : "");
218 convert_string_talloc(frame, CH_UTF8, CH_UNIX,
219 variables[i].value, strlen(variables[i].value),
221 SAFE_FREE(variables[i].value);
222 variables[i].value = SMB_STRDUP(dest ? dest : "");
228 /***************************************************************************
229 find a variable passed via CGI
230 Doesn't quite do what you think in the case of POST text variables, because
231 if they exist they might have a value of "" or even " ", depending on the
232 browser. Also doesn't allow for variables[] containing multiple variables
233 with the same name and the same or different values.
234 ***************************************************************************/
236 const char *cgi_variable(const char *name)
240 for (i=0;i<num_variables;i++)
241 if (strcmp(variables[i].name, name) == 0)
242 return variables[i].value;
246 /***************************************************************************
247 Version of the above that can't return a NULL pointer.
248 ***************************************************************************/
250 const char *cgi_variable_nonull(const char *name)
252 const char *var = cgi_variable(name);
260 /***************************************************************************
261 tell a browser about a fatal error in the http processing
262 ***************************************************************************/
263 static void cgi_setup_error(const char *err, const char *header, const char *info)
266 /* damn browsers don't like getting cut off before they give a request */
268 while (fgets(line, sizeof(line)-1, stdin)) {
269 if (strnequal(line,"GET ", 4) ||
270 strnequal(line,"POST ", 5) ||
271 strnequal(line,"PUT ", 4)) {
277 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);
284 /***************************************************************************
285 tell a browser about a fatal authentication error
286 ***************************************************************************/
287 static void cgi_auth_error(void)
290 cgi_setup_error("401 Authorization Required",
291 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
292 "You must be authenticated to use this service");
294 printf("Content-Type: text/html\r\n");
296 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
297 printf("<BODY><H1>Installation Error</H1>\n");
298 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
299 printf("</BODY></HTML>\r\n");
304 /***************************************************************************
305 authenticate when we are running as a CGI
306 ***************************************************************************/
307 static void cgi_web_auth(void)
309 const char *user = getenv("REMOTE_USER");
311 const char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
312 const char *tail = "</BODY></HTML>\r\n";
315 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
320 pwd = Get_Pwnam_alloc(talloc_tos(), user);
322 printf("%sCannot find user %s<br>%s\n", head, user, tail);
328 if (geteuid() != pwd->pw_uid || getuid() != pwd->pw_uid) {
329 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
330 head, user, (int)geteuid(), (int)getuid(), tail);
337 /***************************************************************************
338 handle a http authentication line
339 ***************************************************************************/
340 static bool cgi_handle_authorization(char *line)
343 fstring user, user_pass;
344 struct passwd *pass = NULL;
346 char addr[INET6_ADDRSTRLEN];
348 if (!strnequal(line,"Basic ", 6)) {
352 while (line[0] == ' ') line++;
353 base64_decode_inplace(line);
354 if (!(p=strchr_m(line,':'))) {
356 * Always give the same error so a cracker
357 * cannot tell why we fail.
363 convert_string(CH_UTF8, CH_UNIX,
367 convert_string(CH_UTF8, CH_UNIX,
369 user_pass, sizeof(user_pass));
372 * Try and get the user from the UNIX password file.
375 pass = Get_Pwnam_alloc(talloc_tos(), user);
377 rhost = client_name(1);
378 if (strequal(rhost,"UNKNOWN"))
379 rhost = client_addr(1, addr, sizeof(addr));
382 * Validate the password they have given.
385 if NT_STATUS_IS_OK(pass_check(pass, user, rhost, user_pass, false)) {
391 if ( initgroups(pass->pw_name, pass->pw_gid) != 0 )
394 become_user_permanently(pass->pw_uid, pass->pw_gid);
396 /* Save the users name */
397 C_user = SMB_STRDUP(user);
404 cgi_setup_error("401 Bad Authorization",
405 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
406 "username or password incorrect");
412 /***************************************************************************
414 ***************************************************************************/
417 if (geteuid() == 0) {
424 /***************************************************************************
425 return a ptr to the users name
426 ***************************************************************************/
427 char *cgi_user_name(void)
433 /***************************************************************************
434 handle a file download
435 ***************************************************************************/
436 static void cgi_download(char *file)
444 /* sanitise the filename */
445 for (i=0;file[i];i++) {
446 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
447 cgi_setup_error("404 File Not Found","",
448 "Illegal character in filename");
452 if (sys_stat(file, &st, false) != 0) {
453 cgi_setup_error("404 File Not Found","",
454 "The requested file was not found");
457 if (S_ISDIR(st.st_ex_mode))
459 snprintf(buf, sizeof(buf), "%s/index.html", file);
460 if (!file_exist_stat(buf, &st, false)
461 || !S_ISREG(st.st_ex_mode))
463 cgi_setup_error("404 File Not Found","",
464 "The requested file was not found");
467 else if (S_ISREG(st.st_ex_mode))
469 snprintf(buf, sizeof(buf), "%s", file);
473 cgi_setup_error("404 File Not Found","",
474 "The requested file was not found");
477 fd = web_open(buf,O_RDONLY,0);
479 cgi_setup_error("404 File Not Found","",
480 "The requested file was not found");
482 printf("HTTP/1.0 200 OK\r\n");
483 if ((p=strrchr_m(buf, '.'))) {
484 if (strcmp(p,".gif")==0) {
485 printf("Content-Type: image/gif\r\n");
486 } else if (strcmp(p,".jpg")==0) {
487 printf("Content-Type: image/jpeg\r\n");
488 } else if (strcmp(p,".png")==0) {
489 printf("Content-Type: image/png\r\n");
490 } else if (strcmp(p,".css")==0) {
491 printf("Content-Type: text/css\r\n");
492 } else if (strcmp(p,".txt")==0) {
493 printf("Content-Type: text/plain\r\n");
495 printf("Content-Type: text/html\r\n");
498 printf("Expires: %s\r\n",
499 http_timestring(talloc_tos(), time(NULL)+EXPIRY_TIME));
501 lang = lang_tdb_current();
503 printf("Content-Language: %s\r\n", lang);
506 printf("Content-Length: %d\r\n\r\n", (int)st.st_ex_size);
507 while ((l=read(fd,buf,sizeof(buf)))>0) {
508 if (fwrite(buf, 1, l, stdout) != l) {
518 /* return true if the char* contains ip addrs only. Used to avoid
521 static bool only_ipaddrs_in_list(const char **list)
529 for (; *list ; list++) {
530 /* factor out the special strings */
531 if (strequal(*list, "ALL") || strequal(*list, "FAIL") ||
532 strequal(*list, "EXCEPT")) {
536 if (!is_ipaddress(*list)) {
538 * If we failed, make sure that it was not because
539 * the token was a network/netmask pair. Only
540 * network/netmask pairs have a '/' in them.
542 if ((strchr_m(*list, '/')) == NULL) {
544 DEBUG(3,("only_ipaddrs_in_list: list has "
545 "non-ip address (%s)\n",
555 /* return true if access should be allowed to a service for a socket */
556 static bool check_access(int sock, const char **allow_list,
557 const char **deny_list)
560 bool only_ip = false;
561 char addr[INET6_ADDRSTRLEN];
563 if ((!deny_list || *deny_list==0) && (!allow_list || *allow_list==0)) {
567 /* Bypass name resolution calls if the lists
568 * only contain IP addrs */
569 if (only_ipaddrs_in_list(allow_list) &&
570 only_ipaddrs_in_list(deny_list)) {
572 DEBUG (3, ("check_access: no hostnames "
573 "in host allow/deny list.\n"));
574 ret = allow_access(deny_list,
577 get_peer_addr(sock,addr,sizeof(addr)));
579 DEBUG (3, ("check_access: hostnames in "
580 "host allow/deny list.\n"));
581 ret = allow_access(deny_list,
583 get_peer_name(sock,true),
584 get_peer_addr(sock,addr,sizeof(addr)));
588 DEBUG(2,("Allowed connection from %s (%s)\n",
589 only_ip ? "" : get_peer_name(sock,true),
590 get_peer_addr(sock,addr,sizeof(addr))));
592 DEBUG(0,("Denied connection from %s (%s)\n",
593 only_ip ? "" : get_peer_name(sock,true),
594 get_peer_addr(sock,addr,sizeof(addr))));
601 * @brief Setup the CGI framework.
603 * Setup the cgi framework, handling the possibility that this program
604 * is either run as a true CGI program with a gateway to a web server, or
605 * is itself a mini web server.
607 void cgi_setup(const char *rootdir, int auth_required)
609 bool authenticated = False;
615 if (chdir(rootdir)) {
616 cgi_setup_error("500 Server Error", "",
617 "chdir failed - the server is not configured correctly");
620 /* Handle the possibility we might be running as non-root */
623 if ((lang=getenv("HTTP_ACCEPT_LANGUAGE"))) {
624 /* if running as a cgi program */
628 /* maybe we are running under a web server */
629 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
638 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
639 cgi_setup_error("403 Forbidden", "",
640 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
643 /* we are a mini-web server. We need to read the request from stdin
644 and handle authentication etc */
645 while (fgets(line, sizeof(line)-1, stdin)) {
646 if (line[0] == '\r' || line[0] == '\n') break;
647 if (strnequal(line,"GET ", 4)) {
649 url = SMB_STRDUP(&line[4]);
650 } else if (strnequal(line,"POST ", 5)) {
653 url = SMB_STRDUP(&line[5]);
654 } else if (strnequal(line,"PUT ", 4)) {
656 cgi_setup_error("400 Bad Request", "",
657 "This server does not accept PUT requests");
658 } else if (strnequal(line,"Authorization: ", 15)) {
659 authenticated = cgi_handle_authorization(&line[15]);
660 } else if (strnequal(line,"Content-Length: ", 16)) {
661 content_length = atoi(&line[16]);
662 } else if (strnequal(line,"Accept-Language: ", 17)) {
663 web_set_lang(&line[17]);
665 /* ignore all other requests! */
668 if (auth_required && !authenticated) {
673 cgi_setup_error("400 Bad Request", "",
674 "You must specify a GET or POST request");
678 if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
681 while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
682 url[strlen(url)-1] = 0;
685 /* anything following a ? in the URL is part of the query string */
686 if ((p=strchr_m(url,'?'))) {
691 string_sub(url, "/swat/", "", 0);
693 if (url[0] != '/' && strstr(url,"..")==0) {
697 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
698 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL)));
704 /***************************************************************************
705 return the current pages URL
706 ***************************************************************************/
707 const char *cgi_baseurl(void)
712 return getenv("SCRIPT_NAME");
715 /***************************************************************************
716 return the current pages path info
717 ***************************************************************************/
718 const char *cgi_pathinfo(void)
724 r = getenv("PATH_INFO");
730 /***************************************************************************
731 return the hostname of the client
732 ***************************************************************************/
733 const char *cgi_remote_host(void)
736 return get_peer_name(1,False);
738 return getenv("REMOTE_HOST");
741 /***************************************************************************
742 return the hostname of the client
743 ***************************************************************************/
744 const char *cgi_remote_addr(void)
747 char addr[INET6_ADDRSTRLEN];
748 get_peer_addr(1,addr,sizeof(addr));
749 return talloc_strdup(talloc_tos(), addr);
751 return getenv("REMOTE_ADDR");
755 /***************************************************************************
756 return True if the request was a POST
757 ***************************************************************************/
758 bool cgi_waspost(void)
763 return strequal(getenv("REQUEST_METHOD"), "POST");