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"
27 #define MAX_VARIABLES 10000
29 /* set the expiry on fixed pages */
30 #define EXPIRY_TIME (60*60*24*7)
33 extern void print_title(char *fmt
, ...);
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
;
49 static bool inetd_server
;
50 static bool got_request
;
52 static char *grab_line(FILE *f
, int *cl
)
63 if (len
== 0) len
= 1024;
65 ret2
= (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret
, len
);
66 if (!ret2
) return ret
;
78 if (c
== '\r') continue;
80 if (strchr_m("\n&", c
)) break;
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)
98 static void plus_to_space_unescape(char *buf
)
102 while ((p
=strchr_m(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)
118 #ifdef DEBUG_COMMENTS
121 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__
);
124 if (!content_length
) {
125 p
= getenv("CONTENT_LENGTH");
128 len
= content_length
;
134 ((s
=getenv("REQUEST_METHOD")) &&
135 strequal(s
,"POST")))) {
136 while (len
&& (line
=grab_line(f
, &len
))) {
137 p
= strchr_m(line
,'=');
142 variables
[num_variables
].name
= SMB_STRDUP(line
);
143 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
147 if (!variables
[num_variables
].name
||
148 !variables
[num_variables
].value
)
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
);
163 if (num_variables
== MAX_VARIABLES
) break;
168 open("/dev/null", O_RDWR
);
170 if ((s
=query_string
) || (s
=getenv("QUERY_STRING"))) {
172 for (tok
=strtok_r(s
, "&;", &saveptr
); tok
;
173 tok
=strtok_r(NULL
, "&;", &saveptr
)) {
174 p
= strchr_m(tok
,'=');
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
)
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
);
197 if (num_variables
== MAX_VARIABLES
) break;
201 #ifdef DEBUG_COMMENTS
202 printf("<!== End dump in cgi_load_variables() ==>\n");
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();
212 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
213 variables
[i
].name
, strlen(variables
[i
].name
),
215 SAFE_FREE(variables
[i
].name
);
216 variables
[i
].name
= SMB_STRDUP(dest
? dest
: "");
219 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
220 variables
[i
].value
, strlen(variables
[i
].value
),
222 SAFE_FREE(variables
[i
].value
);
223 variables
[i
].value
= SMB_STRDUP(dest
? dest
: "");
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
)
241 for (i
=0;i
<num_variables
;i
++)
242 if (strcmp(variables
[i
].name
, name
) == 0)
243 return variables
[i
].value
;
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
);
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
)
267 /* damn browsers don't like getting cut off before they give a request */
269 while (fgets(line
, sizeof(line
)-1, stdin
)) {
270 if (strnequal(line
,"GET ", 4) ||
271 strnequal(line
,"POST ", 5) ||
272 strnequal(line
,"PUT ", 4)) {
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
);
285 /***************************************************************************
286 tell a browser about a fatal authentication error
287 ***************************************************************************/
288 static void cgi_auth_error(void)
291 cgi_setup_error("401 Authorization Required",
292 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
293 "You must be authenticated to use this service");
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");
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");
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";
316 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
321 pwd
= Get_Pwnam_alloc(talloc_tos(), user
);
323 printf("%sCannot find user %s<br>%s\n", head
, user
, tail
);
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
);
338 /***************************************************************************
339 handle a http authentication line
340 ***************************************************************************/
341 static bool cgi_handle_authorization(char *line
)
344 fstring user
, user_pass
;
345 struct passwd
*pass
= NULL
;
347 char addr
[INET6_ADDRSTRLEN
];
350 if (!strnequal(line
,"Basic ", 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.
365 if (!convert_string(CH_UTF8
, CH_UNIX
,
367 user
, sizeof(user
), &size
)) {
371 if (!convert_string(CH_UTF8
, CH_UNIX
,
373 user_pass
, sizeof(user_pass
), &size
)) {
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)) {
397 if ( initgroups(pass
->pw_name
, pass
->pw_gid
) != 0 )
400 become_user_permanently(pass
->pw_uid
, pass
->pw_gid
);
402 /* Save the users name */
403 C_user
= SMB_STRDUP(user
);
410 cgi_setup_error("401 Bad Authorization",
411 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
412 "username or password incorrect");
418 /***************************************************************************
420 ***************************************************************************/
423 if (geteuid() == 0) {
430 /***************************************************************************
431 return a ptr to the users name
432 ***************************************************************************/
433 char *cgi_user_name(void)
439 /***************************************************************************
440 handle a file download
441 ***************************************************************************/
442 static void cgi_download(char *file
)
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
);
479 cgi_setup_error("404 File Not Found","",
480 "The requested file was not found");
483 fd
= web_open(buf
,O_RDONLY
,0);
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");
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();
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
) {
524 /* return true if the char* contains ip addrs only. Used to avoid
527 static bool only_ipaddrs_in_list(const char **list
)
535 for (; *list
; list
++) {
536 /* factor out the special strings */
537 if (strequal(*list
, "ALL") || strequal(*list
, "FAIL") ||
538 strequal(*list
, "EXCEPT")) {
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
) {
550 DEBUG(3,("only_ipaddrs_in_list: list has "
551 "non-ip address (%s)\n",
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
)
566 bool only_ip
= false;
567 char addr
[INET6_ADDRSTRLEN
];
569 if ((!deny_list
|| *deny_list
==0) && (!allow_list
|| *allow_list
==0)) {
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
)) {
578 DEBUG (3, ("check_access: no hostnames "
579 "in host allow/deny list.\n"));
580 ret
= allow_access(deny_list
,
583 get_peer_addr(sock
,addr
,sizeof(addr
)));
585 DEBUG (3, ("check_access: hostnames in "
586 "host allow/deny list.\n"));
587 ret
= allow_access(deny_list
,
589 get_peer_name(sock
,true),
590 get_peer_addr(sock
,addr
,sizeof(addr
)));
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
))));
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
))));
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
;
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 */
629 if ((lang
=getenv("HTTP_ACCEPT_LANGUAGE"))) {
630 /* if running as a cgi program */
634 /* maybe we are running under a web server */
635 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
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)) {
655 url
= SMB_STRDUP(&line
[4]);
656 } else if (strnequal(line
,"POST ", 5)) {
659 url
= SMB_STRDUP(&line
[5]);
660 } else if (strnequal(line
,"PUT ", 4)) {
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
) {
679 cgi_setup_error("400 Bad Request", "",
680 "You must specify a GET or POST request");
684 if ((p
= strchr_m(url
,' ')) || (p
=strchr_m(url
,'\t'))) {
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
,'?'))) {
697 string_sub(url
, "/swat/", "", 0);
699 if (url
[0] != '/' && strstr(url
,"..")==0) {
703 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
704 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL
)));
710 /***************************************************************************
711 return the current pages URL
712 ***************************************************************************/
713 const char *cgi_baseurl(void)
718 return getenv("SCRIPT_NAME");
721 /***************************************************************************
722 return the current pages path info
723 ***************************************************************************/
724 const char *cgi_pathinfo(void)
730 r
= getenv("PATH_INFO");
736 /***************************************************************************
737 return the hostname of the client
738 ***************************************************************************/
739 const char *cgi_remote_host(void)
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)
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)
769 return strequal(getenv("REQUEST_METHOD"), "POST");