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 2 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, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #define MAX_VARIABLES 10000
26 /* set the expiry on fixed pages */
27 #define EXPIRY_TIME (60*60*24*7)
30 extern void print_title(char *fmt, ...);
38 static struct var variables[MAX_VARIABLES];
39 static int num_variables;
40 static int content_length;
41 static int request_post;
42 static char *query_string;
44 static char *pathinfo;
46 static BOOL inetd_server;
47 static BOOL got_request;
49 static void unescape(char *buf)
53 while ((p=strchr_m(p,'+')))
58 while (p && *p && (p=strchr_m(p,'%'))) {
62 if (c1 >= '0' && c1 <= '9')
64 else if (c1 >= 'A' && c1 <= 'F')
66 else if (c1 >= 'a' && c1 <= 'f')
70 if (c2 >= '0' && c2 <= '9')
72 else if (c2 >= 'A' && c2 <= 'F')
74 else if (c2 >= 'a' && c2 <= 'f')
80 memcpy(p+1, p+3, strlen(p+3)+1);
86 static char *grab_line(FILE *f, int *cl)
97 if (len == 0) len = 1024;
99 ret2 = (char *)Realloc(ret, len);
100 if (!ret2) return ret;
112 if (c == '\r') continue;
114 if (strchr_m("\n&", c)) break;
125 /***************************************************************************
126 load all the variables passed to the CGI program. May have multiple variables
127 with the same name and the same or different values. Takes a file parameter
128 for simulating CGI invocation eg loading saved preferences.
129 ***************************************************************************/
130 void cgi_load_variables(void)
137 #ifdef DEBUG_COMMENTS
140 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
143 if (!content_length) {
144 p = getenv("CONTENT_LENGTH");
147 len = content_length;
153 ((s=getenv("REQUEST_METHOD")) &&
154 strcasecmp(s,"POST")==0))) {
155 while (len && (line=grab_line(f, &len))) {
156 p = strchr_m(line,'=');
161 variables[num_variables].name = strdup(line);
162 variables[num_variables].value = strdup(p+1);
166 if (!variables[num_variables].name ||
167 !variables[num_variables].value)
170 unescape(variables[num_variables].value);
171 unescape(variables[num_variables].name);
173 #ifdef DEBUG_COMMENTS
174 printf("<!== POST var %s has value \"%s\" ==>\n",
175 variables[num_variables].name,
176 variables[num_variables].value);
180 if (num_variables == MAX_VARIABLES) break;
185 open("/dev/null", O_RDWR);
187 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
188 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
189 p = strchr_m(tok,'=');
194 variables[num_variables].name = strdup(tok);
195 variables[num_variables].value = strdup(p+1);
197 if (!variables[num_variables].name ||
198 !variables[num_variables].value)
201 unescape(variables[num_variables].value);
202 unescape(variables[num_variables].name);
204 #ifdef DEBUG_COMMENTS
205 printf("<!== Commandline var %s has value \"%s\" ==>\n",
206 variables[num_variables].name,
207 variables[num_variables].value);
210 if (num_variables == MAX_VARIABLES) break;
214 #ifdef DEBUG_COMMENTS
215 printf("<!== End dump in cgi_load_variables() ==>\n");
218 /* variables from the client are in display charset - convert them
219 to our internal charset before use */
220 for (i=0;i<num_variables;i++) {
223 convert_string(CH_DISPLAY, CH_UNIX,
224 variables[i].name, strlen(variables[i].name),
226 free(variables[i].name);
227 variables[i].name = strdup(dest);
229 convert_string(CH_DISPLAY, CH_UNIX,
230 variables[i].value, strlen(variables[i].name),
232 free(variables[i].value);
233 variables[i].value = strdup(dest);
238 /***************************************************************************
239 find a variable passed via CGI
240 Doesn't quite do what you think in the case of POST text variables, because
241 if they exist they might have a value of "" or even " ", depending on the
242 browser. Also doesn't allow for variables[] containing multiple variables
243 with the same name and the same or different values.
244 ***************************************************************************/
245 char *cgi_variable(char *name)
249 for (i=0;i<num_variables;i++)
250 if (strcmp(variables[i].name, name) == 0)
251 return variables[i].value;
255 /***************************************************************************
256 tell a browser about a fatal error in the http processing
257 ***************************************************************************/
258 static void cgi_setup_error(char *err, char *header, char *info)
261 /* damn browsers don't like getting cut off before they give a request */
263 while (fgets(line, sizeof(line)-1, stdin)) {
264 if (strncasecmp(line,"GET ", 4)==0 ||
265 strncasecmp(line,"POST ", 5)==0 ||
266 strncasecmp(line,"PUT ", 4)==0) {
272 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);
279 /***************************************************************************
280 tell a browser about a fatal authentication error
281 ***************************************************************************/
282 static void cgi_auth_error(void)
285 cgi_setup_error("401 Authorization Required",
286 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
287 "You must be authenticated to use this service");
289 printf("Content-Type: text/html\r\n");
291 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
292 printf("<BODY><H1>Installation Error</H1>\n");
293 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
294 printf("</BODY></HTML>\r\n");
299 /***************************************************************************
300 authenticate when we are running as a CGI
301 ***************************************************************************/
302 static void cgi_web_auth(void)
304 char *user = getenv("REMOTE_USER");
306 char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
307 char *tail = "</BODY></HTML>\r\n";
310 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
315 pwd = getpwnam(user);
317 printf("%sCannot find user %s<br>%s\n", head, user, tail);
323 if (geteuid() != pwd->pw_uid || getuid() != pwd->pw_uid) {
324 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
325 head, user, (int)geteuid(), (int)getuid(), tail);
330 /***************************************************************************
331 decode a base64 string in-place - simple and slow algorithm
332 ***************************************************************************/
333 static void base64_decode(char *s)
335 char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
336 int bit_offset, byte_offset, idx, i, n;
337 unsigned char *d = (unsigned char *)s;
342 while (*s && (p=strchr_m(b64,*s))) {
343 idx = (int)(p - b64);
344 byte_offset = (i*6)/8;
345 bit_offset = (i*6)%8;
346 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
347 if (bit_offset < 3) {
348 d[byte_offset] |= (idx << (2-bit_offset));
351 d[byte_offset] |= (idx >> (bit_offset-2));
352 d[byte_offset+1] = 0;
353 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
362 /***************************************************************************
363 handle a http authentication line
364 ***************************************************************************/
365 static BOOL cgi_handle_authorization(char *line)
367 char *p, *user, *user_pass;
368 struct passwd *pass = NULL;
370 if (strncasecmp(line,"Basic ", 6)) {
374 while (line[0] == ' ') line++;
376 if (!(p=strchr_m(line,':'))) {
378 * Always give the same error so a cracker
379 * cannot tell why we fail.
388 * Try and get the user from the UNIX password file.
391 pass = sys_getpwnam(user);
394 * Validate the password they have given.
397 if NT_STATUS_IS_OK(pass_check(pass, user, user_pass,
398 strlen(user_pass), NULL, False)) {
405 become_user_permanently(pass->pw_uid, pass->pw_gid);
407 /* Save the users name */
408 C_user = strdup(user);
414 cgi_setup_error("401 Bad Authorization", "",
415 "username or password incorrect");
420 /***************************************************************************
422 ***************************************************************************/
425 if (geteuid() == 0) {
432 /***************************************************************************
433 return a ptr to the users name
434 ***************************************************************************/
435 char *cgi_user_name(void)
441 /***************************************************************************
442 handle a file download
443 ***************************************************************************/
444 static void cgi_download(char *file)
451 /* sanitise the filename */
452 for (i=0;file[i];i++) {
453 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
454 cgi_setup_error("404 File Not Found","",
455 "Illegal character in filename");
459 if (!file_exist(file, &st)) {
460 cgi_setup_error("404 File Not Found","",
461 "The requested file was not found");
463 fd = sys_open(file,O_RDONLY,0);
465 cgi_setup_error("404 File Not Found","",
466 "The requested file was not found");
468 printf("HTTP/1.0 200 OK\r\n");
469 if ((p=strrchr_m(file,'.'))) {
470 if (strcmp(p,".gif")==0) {
471 printf("Content-Type: image/gif\r\n");
472 } else if (strcmp(p,".jpg")==0) {
473 printf("Content-Type: image/jpeg\r\n");
474 } else if (strcmp(p,".txt")==0) {
475 printf("Content-Type: text/plain\r\n");
477 printf("Content-Type: text/html\r\n");
480 printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
482 printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
483 while ((l=read(fd,buf,sizeof(buf)))>0) {
484 fwrite(buf, 1, l, stdout);
493 /***************************************************************************
494 setup the cgi framework, handling the possability that this program is either
495 run as a true cgi program by a web browser or is itself a mini web server
496 ***************************************************************************/
497 void cgi_setup(char *rootdir, int auth_required)
499 BOOL authenticated = False;
504 if (chdir(rootdir)) {
505 cgi_setup_error("400 Server Error", "",
506 "chdir failed - the server is not configured correctly");
509 /* Handle the possability we might be running as non-root */
512 /* maybe we are running under a web server */
513 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
522 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
523 cgi_setup_error("400 Server Error", "",
524 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
527 /* we are a mini-web server. We need to read the request from stdin
528 and handle authentication etc */
529 while (fgets(line, sizeof(line)-1, stdin)) {
530 if (line[0] == '\r' || line[0] == '\n') break;
531 if (strncasecmp(line,"GET ", 4)==0) {
533 url = strdup(&line[4]);
534 } else if (strncasecmp(line,"POST ", 5)==0) {
537 url = strdup(&line[5]);
538 } else if (strncasecmp(line,"PUT ", 4)==0) {
540 cgi_setup_error("400 Bad Request", "",
541 "This server does not accept PUT requests");
542 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
543 authenticated = cgi_handle_authorization(&line[15]);
544 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
545 content_length = atoi(&line[16]);
547 /* ignore all other requests! */
550 if (auth_required && !authenticated) {
555 cgi_setup_error("400 Bad Request", "",
556 "You must specify a GET or POST request");
560 if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
563 while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
564 url[strlen(url)-1] = 0;
567 /* anything following a ? in the URL is part of the query string */
568 if ((p=strchr_m(url,'?'))) {
573 string_sub(url, "/swat/", "", 0);
575 if (url[0] != '/' && strstr(url,"..")==0 && file_exist(url, NULL)) {
579 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
580 printf("Date: %s\r\n", http_timestring(time(NULL)));
586 /***************************************************************************
587 return the current pages URL
588 ***************************************************************************/
589 char *cgi_baseurl(void)
594 return getenv("SCRIPT_NAME");
597 /***************************************************************************
598 return the current pages path info
599 ***************************************************************************/
600 char *cgi_pathinfo(void)
606 r = getenv("PATH_INFO");
612 /***************************************************************************
613 return the hostname of the client
614 ***************************************************************************/
615 char *cgi_remote_host(void)
618 return get_socket_name(1);
620 return getenv("REMOTE_HOST");
623 /***************************************************************************
624 return the hostname of the client
625 ***************************************************************************/
626 char *cgi_remote_addr(void)
629 return get_socket_addr(1);
631 return getenv("REMOTE_ADDR");
635 /***************************************************************************
636 return True if the request was a POST
637 ***************************************************************************/
638 BOOL cgi_waspost(void)
643 return strequal(getenv("REQUEST_METHOD"), "POST");