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
;
52 static bool inetd_server
;
53 static bool got_request
;
55 static char *grab_line(FILE *f
, int *cl
)
66 if (len
== 0) len
= 1024;
68 ret2
= (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret
, len
);
69 if (!ret2
) return ret
;
81 if (c
== '\r') continue;
83 if (strchr_m("\n&", c
)) break;
96 URL encoded strings can have a '+', which should be replaced with a space
98 (This was in rfc1738_unescape(), but that broke the squid helper)
101 static void plus_to_space_unescape(char *buf
)
105 while ((p
=strchr_m(p
,'+')))
109 /***************************************************************************
110 load all the variables passed to the CGI program. May have multiple variables
111 with the same name and the same or different values. Takes a file parameter
112 for simulating CGI invocation eg loading saved preferences.
113 ***************************************************************************/
114 void cgi_load_variables(void)
121 #ifdef DEBUG_COMMENTS
124 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__
);
127 if (!content_length
) {
128 p
= getenv("CONTENT_LENGTH");
131 len
= content_length
;
137 ((s
=getenv("REQUEST_METHOD")) &&
138 strequal(s
,"POST")))) {
139 while (len
&& (line
=grab_line(f
, &len
))) {
140 p
= strchr_m(line
,'=');
145 variables
[num_variables
].name
= SMB_STRDUP(line
);
146 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
150 if (!variables
[num_variables
].name
||
151 !variables
[num_variables
].value
)
154 plus_to_space_unescape(variables
[num_variables
].value
);
155 rfc1738_unescape(variables
[num_variables
].value
);
156 plus_to_space_unescape(variables
[num_variables
].name
);
157 rfc1738_unescape(variables
[num_variables
].name
);
159 #ifdef DEBUG_COMMENTS
160 printf("<!== POST var %s has value \"%s\" ==>\n",
161 variables
[num_variables
].name
,
162 variables
[num_variables
].value
);
166 if (num_variables
== MAX_VARIABLES
) break;
171 open("/dev/null", O_RDWR
);
173 if ((s
=query_string
) || (s
=getenv("QUERY_STRING"))) {
175 for (tok
=strtok_r(s
, "&;", &saveptr
); tok
;
176 tok
=strtok_r(NULL
, "&;", &saveptr
)) {
177 p
= strchr_m(tok
,'=');
182 variables
[num_variables
].name
= SMB_STRDUP(tok
);
183 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
185 if (!variables
[num_variables
].name
||
186 !variables
[num_variables
].value
)
189 plus_to_space_unescape(variables
[num_variables
].value
);
190 rfc1738_unescape(variables
[num_variables
].value
);
191 plus_to_space_unescape(variables
[num_variables
].name
);
192 rfc1738_unescape(variables
[num_variables
].name
);
194 #ifdef DEBUG_COMMENTS
195 printf("<!== Commandline var %s has value \"%s\" ==>\n",
196 variables
[num_variables
].name
,
197 variables
[num_variables
].value
);
200 if (num_variables
== MAX_VARIABLES
) break;
204 #ifdef DEBUG_COMMENTS
205 printf("<!== End dump in cgi_load_variables() ==>\n");
208 /* variables from the client are in UTF-8 - convert them
209 to our internal unix charset before use */
210 for (i
=0;i
<num_variables
;i
++) {
211 TALLOC_CTX
*frame
= talloc_stackframe();
215 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
216 variables
[i
].name
, strlen(variables
[i
].name
),
217 &dest
, &dest_len
, True
);
218 SAFE_FREE(variables
[i
].name
);
219 variables
[i
].name
= SMB_STRDUP(dest
? dest
: "");
222 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
223 variables
[i
].value
, strlen(variables
[i
].value
),
224 &dest
, &dest_len
, True
);
225 SAFE_FREE(variables
[i
].value
);
226 variables
[i
].value
= SMB_STRDUP(dest
? dest
: "");
232 /***************************************************************************
233 find a variable passed via CGI
234 Doesn't quite do what you think in the case of POST text variables, because
235 if they exist they might have a value of "" or even " ", depending on the
236 browser. Also doesn't allow for variables[] containing multiple variables
237 with the same name and the same or different values.
238 ***************************************************************************/
240 const char *cgi_variable(const char *name
)
244 for (i
=0;i
<num_variables
;i
++)
245 if (strcmp(variables
[i
].name
, name
) == 0)
246 return variables
[i
].value
;
250 /***************************************************************************
251 Version of the above that can't return a NULL pointer.
252 ***************************************************************************/
254 const char *cgi_variable_nonull(const char *name
)
256 const char *var
= cgi_variable(name
);
264 /***************************************************************************
265 tell a browser about a fatal error in the http processing
266 ***************************************************************************/
267 static void cgi_setup_error(const char *err
, const char *header
, const char *info
)
270 /* damn browsers don't like getting cut off before they give a request */
272 while (fgets(line
, sizeof(line
)-1, stdin
)) {
273 if (strnequal(line
,"GET ", 4) ||
274 strnequal(line
,"POST ", 5) ||
275 strnequal(line
,"PUT ", 4)) {
281 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
);
288 /***************************************************************************
289 tell a browser about a fatal authentication error
290 ***************************************************************************/
291 static void cgi_auth_error(void)
294 cgi_setup_error("401 Authorization Required",
295 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
296 "You must be authenticated to use this service");
298 printf("Content-Type: text/html\r\n");
300 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
301 printf("<BODY><H1>Installation Error</H1>\n");
302 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
303 printf("</BODY></HTML>\r\n");
308 /***************************************************************************
309 authenticate when we are running as a CGI
310 ***************************************************************************/
311 static void cgi_web_auth(void)
313 const char *user
= getenv("REMOTE_USER");
315 const char *head
= "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
316 const char *tail
= "</BODY></HTML>\r\n";
319 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
324 pwd
= Get_Pwnam_alloc(talloc_tos(), user
);
326 printf("%sCannot find user %s<br>%s\n", head
, user
, tail
);
330 C_user
= SMB_STRDUP(user
);
333 C_pass
= SMB_STRDUP(cgi_nonce());
336 if (geteuid() != pwd
->pw_uid
|| getuid() != pwd
->pw_uid
) {
337 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
338 head
, user
, (int)geteuid(), (int)getuid(), tail
);
345 /***************************************************************************
346 handle a http authentication line
347 ***************************************************************************/
348 static bool cgi_handle_authorization(char *line
)
351 fstring user
, user_pass
;
352 struct passwd
*pass
= NULL
;
354 char addr
[INET6_ADDRSTRLEN
];
356 if (!strnequal(line
,"Basic ", 6)) {
360 while (line
[0] == ' ') line
++;
361 base64_decode_inplace(line
);
362 if (!(p
=strchr_m(line
,':'))) {
364 * Always give the same error so a cracker
365 * cannot tell why we fail.
371 convert_string(CH_UTF8
, CH_UNIX
,
373 user
, sizeof(user
), True
);
375 convert_string(CH_UTF8
, CH_UNIX
,
377 user_pass
, sizeof(user_pass
), True
);
380 * Try and get the user from the UNIX password file.
383 pass
= Get_Pwnam_alloc(talloc_tos(), user
);
385 rhost
= client_name(1);
386 if (strequal(rhost
,"UNKNOWN"))
387 rhost
= client_addr(1, addr
, sizeof(addr
));
390 * Validate the password they have given.
393 if NT_STATUS_IS_OK(pass_check(pass
, user
, rhost
, user_pass
, false)) {
399 if ( initgroups(pass
->pw_name
, pass
->pw_gid
) != 0 )
402 become_user_permanently(pass
->pw_uid
, pass
->pw_gid
);
404 /* Save the users name */
405 C_user
= SMB_STRDUP(user
);
406 C_pass
= SMB_STRDUP(user_pass
);
413 cgi_setup_error("401 Bad Authorization",
414 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
415 "username or password incorrect");
421 /***************************************************************************
423 ***************************************************************************/
426 if (geteuid() == 0) {
433 /***************************************************************************
434 return a ptr to the users name
435 ***************************************************************************/
436 char *cgi_user_name(void)
441 /***************************************************************************
442 return a ptr to the users password
443 ***************************************************************************/
444 char *cgi_user_pass(void)
449 /***************************************************************************
450 return a ptr to the nonce
451 ***************************************************************************/
452 char *cgi_nonce(void)
454 const char *head
= "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
455 const char *tail
= "</BODY></HTML>\r\n";
456 C_nonce
= secrets_fetch_generic("root", "SWAT");
457 if (C_nonce
== NULL
) {
458 char *tmp_pass
= NULL
;
459 tmp_pass
= generate_random_password(talloc_tos(),
461 if (tmp_pass
== NULL
) {
462 printf("%sFailed to create random nonce for "
463 "SWAT session\n<br>%s\n", head
, tail
);
466 secrets_store_generic("root", "SWAT", tmp_pass
);
467 C_nonce
= SMB_STRDUP(tmp_pass
);
468 TALLOC_FREE(tmp_pass
);
473 /***************************************************************************
474 handle a file download
475 ***************************************************************************/
476 static void cgi_download(char *file
)
484 /* sanitise the filename */
485 for (i
=0;file
[i
];i
++) {
486 if (!isalnum((int)file
[i
]) && !strchr_m("/.-_", file
[i
])) {
487 cgi_setup_error("404 File Not Found","",
488 "Illegal character in filename");
492 if (sys_stat(file
, &st
, false) != 0) {
493 cgi_setup_error("404 File Not Found","",
494 "The requested file was not found");
497 if (S_ISDIR(st
.st_ex_mode
))
499 snprintf(buf
, sizeof(buf
), "%s/index.html", file
);
500 if (!file_exist_stat(buf
, &st
, false)
501 || !S_ISREG(st
.st_ex_mode
))
503 cgi_setup_error("404 File Not Found","",
504 "The requested file was not found");
507 else if (S_ISREG(st
.st_ex_mode
))
509 snprintf(buf
, sizeof(buf
), "%s", file
);
513 cgi_setup_error("404 File Not Found","",
514 "The requested file was not found");
517 fd
= web_open(buf
,O_RDONLY
,0);
519 cgi_setup_error("404 File Not Found","",
520 "The requested file was not found");
522 printf("HTTP/1.0 200 OK\r\n");
523 if ((p
=strrchr_m(buf
, '.'))) {
524 if (strcmp(p
,".gif")==0) {
525 printf("Content-Type: image/gif\r\n");
526 } else if (strcmp(p
,".jpg")==0) {
527 printf("Content-Type: image/jpeg\r\n");
528 } else if (strcmp(p
,".png")==0) {
529 printf("Content-Type: image/png\r\n");
530 } else if (strcmp(p
,".css")==0) {
531 printf("Content-Type: text/css\r\n");
532 } else if (strcmp(p
,".txt")==0) {
533 printf("Content-Type: text/plain\r\n");
535 printf("Content-Type: text/html\r\n");
538 printf("Expires: %s\r\n",
539 http_timestring(talloc_tos(), time(NULL
)+EXPIRY_TIME
));
541 lang
= lang_tdb_current();
543 printf("Content-Language: %s\r\n", lang
);
546 printf("Content-Length: %d\r\n\r\n", (int)st
.st_ex_size
);
547 while ((l
=read(fd
,buf
,sizeof(buf
)))>0) {
548 if (fwrite(buf
, 1, l
, stdout
) != l
) {
558 /* return true if the char* contains ip addrs only. Used to avoid
561 static bool only_ipaddrs_in_list(const char **list
)
569 for (; *list
; list
++) {
570 /* factor out the special strings */
571 if (strequal(*list
, "ALL") || strequal(*list
, "FAIL") ||
572 strequal(*list
, "EXCEPT")) {
576 if (!is_ipaddress(*list
)) {
578 * If we failed, make sure that it was not because
579 * the token was a network/netmask pair. Only
580 * network/netmask pairs have a '/' in them.
582 if ((strchr_m(*list
, '/')) == NULL
) {
584 DEBUG(3,("only_ipaddrs_in_list: list has "
585 "non-ip address (%s)\n",
595 /* return true if access should be allowed to a service for a socket */
596 static bool check_access(int sock
, const char **allow_list
,
597 const char **deny_list
)
600 bool only_ip
= false;
601 char addr
[INET6_ADDRSTRLEN
];
603 if ((!deny_list
|| *deny_list
==0) && (!allow_list
|| *allow_list
==0)) {
607 /* Bypass name resolution calls if the lists
608 * only contain IP addrs */
609 if (only_ipaddrs_in_list(allow_list
) &&
610 only_ipaddrs_in_list(deny_list
)) {
612 DEBUG (3, ("check_access: no hostnames "
613 "in host allow/deny list.\n"));
614 ret
= allow_access(deny_list
,
617 get_peer_addr(sock
,addr
,sizeof(addr
)));
619 DEBUG (3, ("check_access: hostnames in "
620 "host allow/deny list.\n"));
621 ret
= allow_access(deny_list
,
623 get_peer_name(sock
,true),
624 get_peer_addr(sock
,addr
,sizeof(addr
)));
628 DEBUG(2,("Allowed connection from %s (%s)\n",
629 only_ip
? "" : get_peer_name(sock
,true),
630 get_peer_addr(sock
,addr
,sizeof(addr
))));
632 DEBUG(0,("Denied connection from %s (%s)\n",
633 only_ip
? "" : get_peer_name(sock
,true),
634 get_peer_addr(sock
,addr
,sizeof(addr
))));
641 * @brief Setup the CGI framework.
643 * Setup the cgi framework, handling the possibility that this program
644 * is either run as a true CGI program with a gateway to a web server, or
645 * is itself a mini web server.
647 void cgi_setup(const char *rootdir
, int auth_required
)
649 bool authenticated
= False
;
655 if (chdir(rootdir
)) {
656 cgi_setup_error("500 Server Error", "",
657 "chdir failed - the server is not configured correctly");
660 /* Handle the possibility we might be running as non-root */
663 if ((lang
=getenv("HTTP_ACCEPT_LANGUAGE"))) {
664 /* if running as a cgi program */
668 /* maybe we are running under a web server */
669 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
678 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
679 cgi_setup_error("403 Forbidden", "",
680 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
683 /* we are a mini-web server. We need to read the request from stdin
684 and handle authentication etc */
685 while (fgets(line
, sizeof(line
)-1, stdin
)) {
686 if (line
[0] == '\r' || line
[0] == '\n') break;
687 if (strnequal(line
,"GET ", 4)) {
689 url
= SMB_STRDUP(&line
[4]);
690 } else if (strnequal(line
,"POST ", 5)) {
693 url
= SMB_STRDUP(&line
[5]);
694 } else if (strnequal(line
,"PUT ", 4)) {
696 cgi_setup_error("400 Bad Request", "",
697 "This server does not accept PUT requests");
698 } else if (strnequal(line
,"Authorization: ", 15)) {
699 authenticated
= cgi_handle_authorization(&line
[15]);
700 } else if (strnequal(line
,"Content-Length: ", 16)) {
701 content_length
= atoi(&line
[16]);
702 } else if (strnequal(line
,"Accept-Language: ", 17)) {
703 web_set_lang(&line
[17]);
705 /* ignore all other requests! */
708 if (auth_required
&& !authenticated
) {
713 cgi_setup_error("400 Bad Request", "",
714 "You must specify a GET or POST request");
718 if ((p
= strchr_m(url
,' ')) || (p
=strchr_m(url
,'\t'))) {
721 while (*url
&& strchr_m("\r\n",url
[strlen(url
)-1])) {
722 url
[strlen(url
)-1] = 0;
725 /* anything following a ? in the URL is part of the query string */
726 if ((p
=strchr_m(url
,'?'))) {
731 string_sub(url
, "/swat/", "", 0);
733 if (url
[0] != '/' && strstr(url
,"..")==0) {
737 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
738 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL
)));
744 /***************************************************************************
745 return the current pages URL
746 ***************************************************************************/
747 const char *cgi_baseurl(void)
752 return getenv("SCRIPT_NAME");
755 /***************************************************************************
756 return the current pages path info
757 ***************************************************************************/
758 const char *cgi_pathinfo(void)
764 r
= getenv("PATH_INFO");
770 /***************************************************************************
771 return the hostname of the client
772 ***************************************************************************/
773 const char *cgi_remote_host(void)
776 return get_peer_name(1,False
);
778 return getenv("REMOTE_HOST");
781 /***************************************************************************
782 return the hostname of the client
783 ***************************************************************************/
784 const char *cgi_remote_addr(void)
787 char addr
[INET6_ADDRSTRLEN
];
788 get_peer_addr(1,addr
,sizeof(addr
));
789 return talloc_strdup(talloc_tos(), addr
);
791 return getenv("REMOTE_ADDR");
795 /***************************************************************************
796 return True if the request was a POST
797 ***************************************************************************/
798 bool cgi_waspost(void)
803 return strequal(getenv("REQUEST_METHOD"), "POST");