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"
28 #define MAX_VARIABLES 10000
30 /* set the expiry on fixed pages */
31 #define EXPIRY_TIME (60*60*24*7)
34 extern void print_title(char *fmt
, ...);
42 static struct cgi_var variables
[MAX_VARIABLES
];
43 static int num_variables
;
44 static int content_length
;
45 static int request_post
;
46 static char *query_string
;
47 static const char *baseurl
;
48 static char *pathinfo
;
51 static bool inetd_server
;
52 static bool got_request
;
54 static char *grab_line(FILE *f
, int *cl
)
65 if (len
== 0) len
= 1024;
67 ret2
= (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret
, len
);
68 if (!ret2
) return ret
;
80 if (c
== '\r') continue;
82 if (strchr_m("\n&", c
)) break;
95 URL encoded strings can have a '+', which should be replaced with a space
97 (This was in rfc1738_unescape(), but that broke the squid helper)
100 static void plus_to_space_unescape(char *buf
)
104 while ((p
=strchr_m(p
,'+')))
108 /***************************************************************************
109 load all the variables passed to the CGI program. May have multiple variables
110 with the same name and the same or different values. Takes a file parameter
111 for simulating CGI invocation eg loading saved preferences.
112 ***************************************************************************/
113 void cgi_load_variables(void)
120 #ifdef DEBUG_COMMENTS
123 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__
);
126 if (!content_length
) {
127 p
= getenv("CONTENT_LENGTH");
130 len
= content_length
;
136 ((s
=getenv("REQUEST_METHOD")) &&
137 strequal(s
,"POST")))) {
138 while (len
&& (line
=grab_line(f
, &len
))) {
139 p
= strchr_m(line
,'=');
144 variables
[num_variables
].name
= SMB_STRDUP(line
);
145 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
149 if (!variables
[num_variables
].name
||
150 !variables
[num_variables
].value
)
153 plus_to_space_unescape(variables
[num_variables
].value
);
154 rfc1738_unescape(variables
[num_variables
].value
);
155 plus_to_space_unescape(variables
[num_variables
].name
);
156 rfc1738_unescape(variables
[num_variables
].name
);
158 #ifdef DEBUG_COMMENTS
159 printf("<!== POST var %s has value \"%s\" ==>\n",
160 variables
[num_variables
].name
,
161 variables
[num_variables
].value
);
165 if (num_variables
== MAX_VARIABLES
) break;
170 open("/dev/null", O_RDWR
);
172 if ((s
=query_string
) || (s
=getenv("QUERY_STRING"))) {
174 for (tok
=strtok_r(s
, "&;", &saveptr
); tok
;
175 tok
=strtok_r(NULL
, "&;", &saveptr
)) {
176 p
= strchr_m(tok
,'=');
181 variables
[num_variables
].name
= SMB_STRDUP(tok
);
182 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
184 if (!variables
[num_variables
].name
||
185 !variables
[num_variables
].value
)
188 plus_to_space_unescape(variables
[num_variables
].value
);
189 rfc1738_unescape(variables
[num_variables
].value
);
190 plus_to_space_unescape(variables
[num_variables
].name
);
191 rfc1738_unescape(variables
[num_variables
].name
);
193 #ifdef DEBUG_COMMENTS
194 printf("<!== Commandline var %s has value \"%s\" ==>\n",
195 variables
[num_variables
].name
,
196 variables
[num_variables
].value
);
199 if (num_variables
== MAX_VARIABLES
) break;
203 #ifdef DEBUG_COMMENTS
204 printf("<!== End dump in cgi_load_variables() ==>\n");
207 /* variables from the client are in UTF-8 - convert them
208 to our internal unix charset before use */
209 for (i
=0;i
<num_variables
;i
++) {
210 TALLOC_CTX
*frame
= talloc_stackframe();
214 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
215 variables
[i
].name
, strlen(variables
[i
].name
),
216 &dest
, &dest_len
, True
);
217 SAFE_FREE(variables
[i
].name
);
218 variables
[i
].name
= SMB_STRDUP(dest
? dest
: "");
221 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
222 variables
[i
].value
, strlen(variables
[i
].value
),
223 &dest
, &dest_len
, True
);
224 SAFE_FREE(variables
[i
].value
);
225 variables
[i
].value
= SMB_STRDUP(dest
? dest
: "");
231 /***************************************************************************
232 find a variable passed via CGI
233 Doesn't quite do what you think in the case of POST text variables, because
234 if they exist they might have a value of "" or even " ", depending on the
235 browser. Also doesn't allow for variables[] containing multiple variables
236 with the same name and the same or different values.
237 ***************************************************************************/
239 const char *cgi_variable(const char *name
)
243 for (i
=0;i
<num_variables
;i
++)
244 if (strcmp(variables
[i
].name
, name
) == 0)
245 return variables
[i
].value
;
249 /***************************************************************************
250 Version of the above that can't return a NULL pointer.
251 ***************************************************************************/
253 const char *cgi_variable_nonull(const char *name
)
255 const char *var
= cgi_variable(name
);
263 /***************************************************************************
264 tell a browser about a fatal error in the http processing
265 ***************************************************************************/
266 static void cgi_setup_error(const char *err
, const char *header
, const char *info
)
269 /* damn browsers don't like getting cut off before they give a request */
271 while (fgets(line
, sizeof(line
)-1, stdin
)) {
272 if (strnequal(line
,"GET ", 4) ||
273 strnequal(line
,"POST ", 5) ||
274 strnequal(line
,"PUT ", 4)) {
280 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
);
287 /***************************************************************************
288 tell a browser about a fatal authentication error
289 ***************************************************************************/
290 static void cgi_auth_error(void)
293 cgi_setup_error("401 Authorization Required",
294 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
295 "You must be authenticated to use this service");
297 printf("Content-Type: text/html\r\n");
299 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
300 printf("<BODY><H1>Installation Error</H1>\n");
301 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
302 printf("</BODY></HTML>\r\n");
307 /***************************************************************************
308 authenticate when we are running as a CGI
309 ***************************************************************************/
310 static void cgi_web_auth(void)
312 const char *user
= getenv("REMOTE_USER");
314 const char *head
= "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
315 const char *tail
= "</BODY></HTML>\r\n";
318 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
323 pwd
= Get_Pwnam_alloc(talloc_tos(), user
);
325 printf("%sCannot find user %s<br>%s\n", head
, user
, tail
);
329 C_user
= SMB_STRDUP(user
);
332 C_pass
= secrets_fetch_generic("root", "SWAT");
333 if (C_pass
== NULL
) {
334 char *tmp_pass
= NULL
;
335 tmp_pass
= generate_random_password(talloc_tos(),
337 if (tmp_pass
== NULL
) {
338 printf("%sFailed to create random nonce for "
339 "SWAT session\n<br>%s\n", head
, tail
);
342 secrets_store_generic("root", "SWAT", tmp_pass
);
343 C_pass
= SMB_STRDUP(tmp_pass
);
344 TALLOC_FREE(tmp_pass
);
348 if (geteuid() != pwd
->pw_uid
|| getuid() != pwd
->pw_uid
) {
349 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
350 head
, user
, (int)geteuid(), (int)getuid(), tail
);
357 /***************************************************************************
358 handle a http authentication line
359 ***************************************************************************/
360 static bool cgi_handle_authorization(char *line
)
363 fstring user
, user_pass
;
364 struct passwd
*pass
= NULL
;
366 char addr
[INET6_ADDRSTRLEN
];
368 if (!strnequal(line
,"Basic ", 6)) {
372 while (line
[0] == ' ') line
++;
373 base64_decode_inplace(line
);
374 if (!(p
=strchr_m(line
,':'))) {
376 * Always give the same error so a cracker
377 * cannot tell why we fail.
383 convert_string(CH_UTF8
, CH_UNIX
,
385 user
, sizeof(user
), True
);
387 convert_string(CH_UTF8
, CH_UNIX
,
389 user_pass
, sizeof(user_pass
), True
);
392 * Try and get the user from the UNIX password file.
395 pass
= Get_Pwnam_alloc(talloc_tos(), user
);
397 rhost
= client_name(1);
398 if (strequal(rhost
,"UNKNOWN"))
399 rhost
= client_addr(1, addr
, sizeof(addr
));
402 * Validate the password they have given.
405 if NT_STATUS_IS_OK(pass_check(pass
, user
, rhost
, user_pass
, false)) {
411 if ( initgroups(pass
->pw_name
, pass
->pw_gid
) != 0 )
414 become_user_permanently(pass
->pw_uid
, pass
->pw_gid
);
416 /* Save the users name */
417 C_user
= SMB_STRDUP(user
);
418 C_pass
= SMB_STRDUP(user_pass
);
425 cgi_setup_error("401 Bad Authorization",
426 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
427 "username or password incorrect");
433 /***************************************************************************
435 ***************************************************************************/
438 if (geteuid() == 0) {
445 /***************************************************************************
446 return a ptr to the users name
447 ***************************************************************************/
448 char *cgi_user_name(void)
453 /***************************************************************************
454 return a ptr to the users password
455 ***************************************************************************/
456 char *cgi_user_pass(void)
461 /***************************************************************************
462 handle a file download
463 ***************************************************************************/
464 static void cgi_download(char *file
)
472 /* sanitise the filename */
473 for (i
=0;file
[i
];i
++) {
474 if (!isalnum((int)file
[i
]) && !strchr_m("/.-_", file
[i
])) {
475 cgi_setup_error("404 File Not Found","",
476 "Illegal character in filename");
480 if (sys_stat(file
, &st
, false) != 0) {
481 cgi_setup_error("404 File Not Found","",
482 "The requested file was not found");
485 if (S_ISDIR(st
.st_ex_mode
))
487 snprintf(buf
, sizeof(buf
), "%s/index.html", file
);
488 if (!file_exist_stat(buf
, &st
, false)
489 || !S_ISREG(st
.st_ex_mode
))
491 cgi_setup_error("404 File Not Found","",
492 "The requested file was not found");
495 else if (S_ISREG(st
.st_ex_mode
))
497 snprintf(buf
, sizeof(buf
), "%s", file
);
501 cgi_setup_error("404 File Not Found","",
502 "The requested file was not found");
505 fd
= web_open(buf
,O_RDONLY
,0);
507 cgi_setup_error("404 File Not Found","",
508 "The requested file was not found");
510 printf("HTTP/1.0 200 OK\r\n");
511 if ((p
=strrchr_m(buf
, '.'))) {
512 if (strcmp(p
,".gif")==0) {
513 printf("Content-Type: image/gif\r\n");
514 } else if (strcmp(p
,".jpg")==0) {
515 printf("Content-Type: image/jpeg\r\n");
516 } else if (strcmp(p
,".png")==0) {
517 printf("Content-Type: image/png\r\n");
518 } else if (strcmp(p
,".css")==0) {
519 printf("Content-Type: text/css\r\n");
520 } else if (strcmp(p
,".txt")==0) {
521 printf("Content-Type: text/plain\r\n");
523 printf("Content-Type: text/html\r\n");
526 printf("Expires: %s\r\n",
527 http_timestring(talloc_tos(), time(NULL
)+EXPIRY_TIME
));
529 lang
= lang_tdb_current();
531 printf("Content-Language: %s\r\n", lang
);
534 printf("Content-Length: %d\r\n\r\n", (int)st
.st_ex_size
);
535 while ((l
=read(fd
,buf
,sizeof(buf
)))>0) {
536 if (fwrite(buf
, 1, l
, stdout
) != l
) {
546 /* return true if the char* contains ip addrs only. Used to avoid
549 static bool only_ipaddrs_in_list(const char **list
)
557 for (; *list
; list
++) {
558 /* factor out the special strings */
559 if (strequal(*list
, "ALL") || strequal(*list
, "FAIL") ||
560 strequal(*list
, "EXCEPT")) {
564 if (!is_ipaddress(*list
)) {
566 * If we failed, make sure that it was not because
567 * the token was a network/netmask pair. Only
568 * network/netmask pairs have a '/' in them.
570 if ((strchr_m(*list
, '/')) == NULL
) {
572 DEBUG(3,("only_ipaddrs_in_list: list has "
573 "non-ip address (%s)\n",
583 /* return true if access should be allowed to a service for a socket */
584 static bool check_access(int sock
, const char **allow_list
,
585 const char **deny_list
)
588 bool only_ip
= false;
589 char addr
[INET6_ADDRSTRLEN
];
591 if ((!deny_list
|| *deny_list
==0) && (!allow_list
|| *allow_list
==0)) {
595 /* Bypass name resolution calls if the lists
596 * only contain IP addrs */
597 if (only_ipaddrs_in_list(allow_list
) &&
598 only_ipaddrs_in_list(deny_list
)) {
600 DEBUG (3, ("check_access: no hostnames "
601 "in host allow/deny list.\n"));
602 ret
= allow_access(deny_list
,
605 get_peer_addr(sock
,addr
,sizeof(addr
)));
607 DEBUG (3, ("check_access: hostnames in "
608 "host allow/deny list.\n"));
609 ret
= allow_access(deny_list
,
611 get_peer_name(sock
,true),
612 get_peer_addr(sock
,addr
,sizeof(addr
)));
616 DEBUG(2,("Allowed connection from %s (%s)\n",
617 only_ip
? "" : get_peer_name(sock
,true),
618 get_peer_addr(sock
,addr
,sizeof(addr
))));
620 DEBUG(0,("Denied connection from %s (%s)\n",
621 only_ip
? "" : get_peer_name(sock
,true),
622 get_peer_addr(sock
,addr
,sizeof(addr
))));
629 * @brief Setup the CGI framework.
631 * Setup the cgi framework, handling the possibility that this program
632 * is either run as a true CGI program with a gateway to a web server, or
633 * is itself a mini web server.
635 void cgi_setup(const char *rootdir
, int auth_required
)
637 bool authenticated
= False
;
643 if (chdir(rootdir
)) {
644 cgi_setup_error("500 Server Error", "",
645 "chdir failed - the server is not configured correctly");
648 /* Handle the possibility we might be running as non-root */
651 if ((lang
=getenv("HTTP_ACCEPT_LANGUAGE"))) {
652 /* if running as a cgi program */
656 /* maybe we are running under a web server */
657 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
666 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
667 cgi_setup_error("403 Forbidden", "",
668 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
671 /* we are a mini-web server. We need to read the request from stdin
672 and handle authentication etc */
673 while (fgets(line
, sizeof(line
)-1, stdin
)) {
674 if (line
[0] == '\r' || line
[0] == '\n') break;
675 if (strnequal(line
,"GET ", 4)) {
677 url
= SMB_STRDUP(&line
[4]);
678 } else if (strnequal(line
,"POST ", 5)) {
681 url
= SMB_STRDUP(&line
[5]);
682 } else if (strnequal(line
,"PUT ", 4)) {
684 cgi_setup_error("400 Bad Request", "",
685 "This server does not accept PUT requests");
686 } else if (strnequal(line
,"Authorization: ", 15)) {
687 authenticated
= cgi_handle_authorization(&line
[15]);
688 } else if (strnequal(line
,"Content-Length: ", 16)) {
689 content_length
= atoi(&line
[16]);
690 } else if (strnequal(line
,"Accept-Language: ", 17)) {
691 web_set_lang(&line
[17]);
693 /* ignore all other requests! */
696 if (auth_required
&& !authenticated
) {
701 cgi_setup_error("400 Bad Request", "",
702 "You must specify a GET or POST request");
706 if ((p
= strchr_m(url
,' ')) || (p
=strchr_m(url
,'\t'))) {
709 while (*url
&& strchr_m("\r\n",url
[strlen(url
)-1])) {
710 url
[strlen(url
)-1] = 0;
713 /* anything following a ? in the URL is part of the query string */
714 if ((p
=strchr_m(url
,'?'))) {
719 string_sub(url
, "/swat/", "", 0);
721 if (url
[0] != '/' && strstr(url
,"..")==0) {
725 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
726 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL
)));
732 /***************************************************************************
733 return the current pages URL
734 ***************************************************************************/
735 const char *cgi_baseurl(void)
740 return getenv("SCRIPT_NAME");
743 /***************************************************************************
744 return the current pages path info
745 ***************************************************************************/
746 const char *cgi_pathinfo(void)
752 r
= getenv("PATH_INFO");
758 /***************************************************************************
759 return the hostname of the client
760 ***************************************************************************/
761 const char *cgi_remote_host(void)
764 return get_peer_name(1,False
);
766 return getenv("REMOTE_HOST");
769 /***************************************************************************
770 return the hostname of the client
771 ***************************************************************************/
772 const char *cgi_remote_addr(void)
775 char addr
[INET6_ADDRSTRLEN
];
776 get_peer_addr(1,addr
,sizeof(addr
));
777 return talloc_strdup(talloc_tos(), addr
);
779 return getenv("REMOTE_ADDR");
783 /***************************************************************************
784 return True if the request was a POST
785 ***************************************************************************/
786 bool cgi_waspost(void)
791 return strequal(getenv("REQUEST_METHOD"), "POST");