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 "web/swat_proto.h"
23 #define MAX_VARIABLES 10000
25 /* set the expiry on fixed pages */
26 #define EXPIRY_TIME (60*60*24*7)
29 extern void print_title(char *fmt
, ...);
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
;
45 static bool inetd_server
;
46 static bool got_request
;
48 static char *grab_line(FILE *f
, int *cl
)
59 if (len
== 0) len
= 1024;
61 ret2
= (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret
, len
);
62 if (!ret2
) return ret
;
74 if (c
== '\r') continue;
76 if (strchr_m("\n&", c
)) break;
89 URL encoded strings can have a '+', which should be replaced with a space
91 (This was in rfc1738_unescape(), but that broke the squid helper)
94 static void plus_to_space_unescape(char *buf
)
98 while ((p
=strchr_m(p
,'+')))
102 /***************************************************************************
103 load all the variables passed to the CGI program. May have multiple variables
104 with the same name and the same or different values. Takes a file parameter
105 for simulating CGI invocation eg loading saved preferences.
106 ***************************************************************************/
107 void cgi_load_variables(void)
114 #ifdef DEBUG_COMMENTS
117 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__
);
120 if (!content_length
) {
121 p
= getenv("CONTENT_LENGTH");
124 len
= content_length
;
130 ((s
=getenv("REQUEST_METHOD")) &&
131 strequal(s
,"POST")))) {
132 while (len
&& (line
=grab_line(f
, &len
))) {
133 p
= strchr_m(line
,'=');
138 variables
[num_variables
].name
= SMB_STRDUP(line
);
139 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
143 if (!variables
[num_variables
].name
||
144 !variables
[num_variables
].value
)
147 plus_to_space_unescape(variables
[num_variables
].value
);
148 rfc1738_unescape(variables
[num_variables
].value
);
149 plus_to_space_unescape(variables
[num_variables
].name
);
150 rfc1738_unescape(variables
[num_variables
].name
);
152 #ifdef DEBUG_COMMENTS
153 printf("<!== POST var %s has value \"%s\" ==>\n",
154 variables
[num_variables
].name
,
155 variables
[num_variables
].value
);
159 if (num_variables
== MAX_VARIABLES
) break;
164 open("/dev/null", O_RDWR
);
166 if ((s
=query_string
) || (s
=getenv("QUERY_STRING"))) {
168 for (tok
=strtok_r(s
, "&;", &saveptr
); tok
;
169 tok
=strtok_r(NULL
, "&;", &saveptr
)) {
170 p
= strchr_m(tok
,'=');
175 variables
[num_variables
].name
= SMB_STRDUP(tok
);
176 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
178 if (!variables
[num_variables
].name
||
179 !variables
[num_variables
].value
)
182 plus_to_space_unescape(variables
[num_variables
].value
);
183 rfc1738_unescape(variables
[num_variables
].value
);
184 plus_to_space_unescape(variables
[num_variables
].name
);
185 rfc1738_unescape(variables
[num_variables
].name
);
187 #ifdef DEBUG_COMMENTS
188 printf("<!== Commandline var %s has value \"%s\" ==>\n",
189 variables
[num_variables
].name
,
190 variables
[num_variables
].value
);
193 if (num_variables
== MAX_VARIABLES
) break;
197 #ifdef DEBUG_COMMENTS
198 printf("<!== End dump in cgi_load_variables() ==>\n");
201 /* variables from the client are in UTF-8 - convert them
202 to our internal unix charset before use */
203 for (i
=0;i
<num_variables
;i
++) {
204 TALLOC_CTX
*frame
= talloc_stackframe();
208 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
209 variables
[i
].name
, strlen(variables
[i
].name
),
210 &dest
, &dest_len
, True
);
211 SAFE_FREE(variables
[i
].name
);
212 variables
[i
].name
= SMB_STRDUP(dest
? dest
: "");
215 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
216 variables
[i
].value
, strlen(variables
[i
].value
),
217 &dest
, &dest_len
, True
);
218 SAFE_FREE(variables
[i
].value
);
219 variables
[i
].value
= SMB_STRDUP(dest
? dest
: "");
225 /***************************************************************************
226 find a variable passed via CGI
227 Doesn't quite do what you think in the case of POST text variables, because
228 if they exist they might have a value of "" or even " ", depending on the
229 browser. Also doesn't allow for variables[] containing multiple variables
230 with the same name and the same or different values.
231 ***************************************************************************/
233 const char *cgi_variable(const char *name
)
237 for (i
=0;i
<num_variables
;i
++)
238 if (strcmp(variables
[i
].name
, name
) == 0)
239 return variables
[i
].value
;
243 /***************************************************************************
244 Version of the above that can't return a NULL pointer.
245 ***************************************************************************/
247 const char *cgi_variable_nonull(const char *name
)
249 const char *var
= cgi_variable(name
);
257 /***************************************************************************
258 tell a browser about a fatal error in the http processing
259 ***************************************************************************/
260 static void cgi_setup_error(const char *err
, const char *header
, const char *info
)
263 /* damn browsers don't like getting cut off before they give a request */
265 while (fgets(line
, sizeof(line
)-1, stdin
)) {
266 if (strnequal(line
,"GET ", 4) ||
267 strnequal(line
,"POST ", 5) ||
268 strnequal(line
,"PUT ", 4)) {
274 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
);
281 /***************************************************************************
282 tell a browser about a fatal authentication error
283 ***************************************************************************/
284 static void cgi_auth_error(void)
287 cgi_setup_error("401 Authorization Required",
288 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
289 "You must be authenticated to use this service");
291 printf("Content-Type: text/html\r\n");
293 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
294 printf("<BODY><H1>Installation Error</H1>\n");
295 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
296 printf("</BODY></HTML>\r\n");
301 /***************************************************************************
302 authenticate when we are running as a CGI
303 ***************************************************************************/
304 static void cgi_web_auth(void)
306 const char *user
= getenv("REMOTE_USER");
308 const char *head
= "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
309 const char *tail
= "</BODY></HTML>\r\n";
312 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
317 pwd
= getpwnam_alloc(talloc_autofree_context(), user
);
319 printf("%sCannot find user %s<br>%s\n", head
, user
, tail
);
325 if (geteuid() != pwd
->pw_uid
|| getuid() != pwd
->pw_uid
) {
326 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
327 head
, user
, (int)geteuid(), (int)getuid(), tail
);
334 /***************************************************************************
335 handle a http authentication line
336 ***************************************************************************/
337 static bool cgi_handle_authorization(char *line
)
340 fstring user
, user_pass
;
341 struct passwd
*pass
= NULL
;
343 char addr
[INET6_ADDRSTRLEN
];
345 if (!strnequal(line
,"Basic ", 6)) {
349 while (line
[0] == ' ') line
++;
350 base64_decode_inplace(line
);
351 if (!(p
=strchr_m(line
,':'))) {
353 * Always give the same error so a cracker
354 * cannot tell why we fail.
360 convert_string(CH_UTF8
, CH_UNIX
,
362 user
, sizeof(user
), True
);
364 convert_string(CH_UTF8
, CH_UNIX
,
366 user_pass
, sizeof(user_pass
), True
);
369 * Try and get the user from the UNIX password file.
372 pass
= getpwnam_alloc(talloc_autofree_context(), user
);
374 rhost
= client_name(1);
375 if (strequal(rhost
,"UNKNOWN"))
376 rhost
= client_addr(1, addr
, sizeof(addr
));
379 * Validate the password they have given.
382 if NT_STATUS_IS_OK(pass_check(pass
, user
, rhost
, user_pass
, false)) {
388 if ( initgroups(pass
->pw_name
, pass
->pw_gid
) != 0 )
391 become_user_permanently(pass
->pw_uid
, pass
->pw_gid
);
393 /* Save the users name */
394 C_user
= SMB_STRDUP(user
);
401 cgi_setup_error("401 Bad Authorization",
402 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
403 "username or password incorrect");
409 /***************************************************************************
411 ***************************************************************************/
414 if (geteuid() == 0) {
421 /***************************************************************************
422 return a ptr to the users name
423 ***************************************************************************/
424 char *cgi_user_name(void)
430 /***************************************************************************
431 handle a file download
432 ***************************************************************************/
433 static void cgi_download(char *file
)
441 /* sanitise the filename */
442 for (i
=0;file
[i
];i
++) {
443 if (!isalnum((int)file
[i
]) && !strchr_m("/.-_", file
[i
])) {
444 cgi_setup_error("404 File Not Found","",
445 "Illegal character in filename");
449 if (sys_stat(file
, &st
, false) != 0) {
450 cgi_setup_error("404 File Not Found","",
451 "The requested file was not found");
454 if (S_ISDIR(st
.st_ex_mode
))
456 snprintf(buf
, sizeof(buf
), "%s/index.html", file
);
457 if (!file_exist_stat(buf
, &st
, false)
458 || !S_ISREG(st
.st_ex_mode
))
460 cgi_setup_error("404 File Not Found","",
461 "The requested file was not found");
464 else if (S_ISREG(st
.st_ex_mode
))
466 snprintf(buf
, sizeof(buf
), "%s", file
);
470 cgi_setup_error("404 File Not Found","",
471 "The requested file was not found");
474 fd
= web_open(buf
,O_RDONLY
,0);
476 cgi_setup_error("404 File Not Found","",
477 "The requested file was not found");
479 printf("HTTP/1.0 200 OK\r\n");
480 if ((p
=strrchr_m(buf
, '.'))) {
481 if (strcmp(p
,".gif")==0) {
482 printf("Content-Type: image/gif\r\n");
483 } else if (strcmp(p
,".jpg")==0) {
484 printf("Content-Type: image/jpeg\r\n");
485 } else if (strcmp(p
,".png")==0) {
486 printf("Content-Type: image/png\r\n");
487 } else if (strcmp(p
,".css")==0) {
488 printf("Content-Type: text/css\r\n");
489 } else if (strcmp(p
,".txt")==0) {
490 printf("Content-Type: text/plain\r\n");
492 printf("Content-Type: text/html\r\n");
495 printf("Expires: %s\r\n",
496 http_timestring(talloc_tos(), time(NULL
)+EXPIRY_TIME
));
498 lang
= lang_tdb_current();
500 printf("Content-Language: %s\r\n", lang
);
503 printf("Content-Length: %d\r\n\r\n", (int)st
.st_ex_size
);
504 while ((l
=read(fd
,buf
,sizeof(buf
)))>0) {
505 if (fwrite(buf
, 1, l
, stdout
) != l
) {
515 /* return true if the char* contains ip addrs only. Used to avoid
518 static bool only_ipaddrs_in_list(const char **list
)
526 for (; *list
; list
++) {
527 /* factor out the special strings */
528 if (strequal(*list
, "ALL") || strequal(*list
, "FAIL") ||
529 strequal(*list
, "EXCEPT")) {
533 if (!is_ipaddress(*list
)) {
535 * If we failed, make sure that it was not because
536 * the token was a network/netmask pair. Only
537 * network/netmask pairs have a '/' in them.
539 if ((strchr_m(*list
, '/')) == NULL
) {
541 DEBUG(3,("only_ipaddrs_in_list: list has "
542 "non-ip address (%s)\n",
552 /* return true if access should be allowed to a service for a socket */
553 static bool check_access(int sock
, const char **allow_list
,
554 const char **deny_list
)
557 bool only_ip
= false;
558 char addr
[INET6_ADDRSTRLEN
];
560 if ((!deny_list
|| *deny_list
==0) && (!allow_list
|| *allow_list
==0)) {
564 /* Bypass name resolution calls if the lists
565 * only contain IP addrs */
566 if (only_ipaddrs_in_list(allow_list
) &&
567 only_ipaddrs_in_list(deny_list
)) {
569 DEBUG (3, ("check_access: no hostnames "
570 "in host allow/deny list.\n"));
571 ret
= allow_access(deny_list
,
574 get_peer_addr(sock
,addr
,sizeof(addr
)));
576 DEBUG (3, ("check_access: hostnames in "
577 "host allow/deny list.\n"));
578 ret
= allow_access(deny_list
,
580 get_peer_name(sock
,true),
581 get_peer_addr(sock
,addr
,sizeof(addr
)));
585 DEBUG(2,("Allowed connection from %s (%s)\n",
586 only_ip
? "" : get_peer_name(sock
,true),
587 get_peer_addr(sock
,addr
,sizeof(addr
))));
589 DEBUG(0,("Denied connection from %s (%s)\n",
590 only_ip
? "" : get_peer_name(sock
,true),
591 get_peer_addr(sock
,addr
,sizeof(addr
))));
598 * @brief Setup the CGI framework.
600 * Setup the cgi framework, handling the possibility that this program
601 * is either run as a true CGI program with a gateway to a web server, or
602 * is itself a mini web server.
604 void cgi_setup(const char *rootdir
, int auth_required
)
606 bool authenticated
= False
;
612 if (chdir(rootdir
)) {
613 cgi_setup_error("500 Server Error", "",
614 "chdir failed - the server is not configured correctly");
617 /* Handle the possibility we might be running as non-root */
620 if ((lang
=getenv("HTTP_ACCEPT_LANGUAGE"))) {
621 /* if running as a cgi program */
625 /* maybe we are running under a web server */
626 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
635 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
636 cgi_setup_error("403 Forbidden", "",
637 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
640 /* we are a mini-web server. We need to read the request from stdin
641 and handle authentication etc */
642 while (fgets(line
, sizeof(line
)-1, stdin
)) {
643 if (line
[0] == '\r' || line
[0] == '\n') break;
644 if (strnequal(line
,"GET ", 4)) {
646 url
= SMB_STRDUP(&line
[4]);
647 } else if (strnequal(line
,"POST ", 5)) {
650 url
= SMB_STRDUP(&line
[5]);
651 } else if (strnequal(line
,"PUT ", 4)) {
653 cgi_setup_error("400 Bad Request", "",
654 "This server does not accept PUT requests");
655 } else if (strnequal(line
,"Authorization: ", 15)) {
656 authenticated
= cgi_handle_authorization(&line
[15]);
657 } else if (strnequal(line
,"Content-Length: ", 16)) {
658 content_length
= atoi(&line
[16]);
659 } else if (strnequal(line
,"Accept-Language: ", 17)) {
660 web_set_lang(&line
[17]);
662 /* ignore all other requests! */
665 if (auth_required
&& !authenticated
) {
670 cgi_setup_error("400 Bad Request", "",
671 "You must specify a GET or POST request");
675 if ((p
= strchr_m(url
,' ')) || (p
=strchr_m(url
,'\t'))) {
678 while (*url
&& strchr_m("\r\n",url
[strlen(url
)-1])) {
679 url
[strlen(url
)-1] = 0;
682 /* anything following a ? in the URL is part of the query string */
683 if ((p
=strchr_m(url
,'?'))) {
688 string_sub(url
, "/swat/", "", 0);
690 if (url
[0] != '/' && strstr(url
,"..")==0) {
694 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
695 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL
)));
701 /***************************************************************************
702 return the current pages URL
703 ***************************************************************************/
704 const char *cgi_baseurl(void)
709 return getenv("SCRIPT_NAME");
712 /***************************************************************************
713 return the current pages path info
714 ***************************************************************************/
715 const char *cgi_pathinfo(void)
721 r
= getenv("PATH_INFO");
727 /***************************************************************************
728 return the hostname of the client
729 ***************************************************************************/
730 const char *cgi_remote_host(void)
733 return get_peer_name(1,False
);
735 return getenv("REMOTE_HOST");
738 /***************************************************************************
739 return the hostname of the client
740 ***************************************************************************/
741 const char *cgi_remote_addr(void)
744 char addr
[INET6_ADDRSTRLEN
];
745 get_peer_addr(1,addr
,sizeof(addr
));
746 return talloc_strdup(talloc_tos(), addr
);
748 return getenv("REMOTE_ADDR");
752 /***************************************************************************
753 return True if the request was a POST
754 ***************************************************************************/
755 bool cgi_waspost(void)
760 return strequal(getenv("REQUEST_METHOD"), "POST");