Clean up a comment noticed by Jonathan Shao@Panasas.com and remove an
[Samba/gebeck_regimport.git] / source3 / web / cgi.c
blob07e3ee38fbf68b49dafd16203cd25244adbbc441
1 /*
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.
21 #include "includes.h"
22 #include "../web/swat_proto.h"
24 #define MAX_VARIABLES 10000
26 /* set the expiry on fixed pages */
27 #define EXPIRY_TIME (60*60*24*7)
29 #ifdef DEBUG_COMMENTS
30 extern void print_title(char *fmt, ...);
31 #endif
33 struct var {
34 char *name;
35 char *value;
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;
43 static const char *baseurl;
44 static char *pathinfo;
45 static char *C_user;
46 static BOOL inetd_server;
47 static BOOL got_request;
49 static char *grab_line(FILE *f, int *cl)
51 char *ret = NULL;
52 int i = 0;
53 int len = 0;
55 while ((*cl)) {
56 int c;
58 if (i == len) {
59 char *ret2;
60 if (len == 0) len = 1024;
61 else len *= 2;
62 ret2 = (char *)Realloc(ret, len);
63 if (!ret2) return ret;
64 ret = ret2;
67 c = fgetc(f);
68 (*cl)--;
70 if (c == EOF) {
71 (*cl) = 0;
72 break;
75 if (c == '\r') continue;
77 if (strchr_m("\n&", c)) break;
79 ret[i++] = c;
84 ret[i] = 0;
85 return ret;
88 /***************************************************************************
89 load all the variables passed to the CGI program. May have multiple variables
90 with the same name and the same or different values. Takes a file parameter
91 for simulating CGI invocation eg loading saved preferences.
92 ***************************************************************************/
93 void cgi_load_variables(void)
95 static char *line;
96 char *p, *s, *tok;
97 int len, i;
98 FILE *f = stdin;
100 #ifdef DEBUG_COMMENTS
101 char dummy[100]="";
102 print_title(dummy);
103 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
104 #endif
106 if (!content_length) {
107 p = getenv("CONTENT_LENGTH");
108 len = p?atoi(p):0;
109 } else {
110 len = content_length;
114 if (len > 0 &&
115 (request_post ||
116 ((s=getenv("REQUEST_METHOD")) &&
117 strequal(s,"POST")))) {
118 while (len && (line=grab_line(f, &len))) {
119 p = strchr_m(line,'=');
120 if (!p) continue;
122 *p = 0;
124 variables[num_variables].name = strdup(line);
125 variables[num_variables].value = strdup(p+1);
127 SAFE_FREE(line);
129 if (!variables[num_variables].name ||
130 !variables[num_variables].value)
131 continue;
133 rfc1738_unescape(variables[num_variables].value);
134 rfc1738_unescape(variables[num_variables].name);
136 #ifdef DEBUG_COMMENTS
137 printf("<!== POST var %s has value \"%s\" ==>\n",
138 variables[num_variables].name,
139 variables[num_variables].value);
140 #endif
142 num_variables++;
143 if (num_variables == MAX_VARIABLES) break;
147 fclose(stdin);
148 open("/dev/null", O_RDWR);
150 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
151 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
152 p = strchr_m(tok,'=');
153 if (!p) continue;
155 *p = 0;
157 variables[num_variables].name = strdup(tok);
158 variables[num_variables].value = strdup(p+1);
160 if (!variables[num_variables].name ||
161 !variables[num_variables].value)
162 continue;
164 rfc1738_unescape(variables[num_variables].value);
165 rfc1738_unescape(variables[num_variables].name);
167 #ifdef DEBUG_COMMENTS
168 printf("<!== Commandline var %s has value \"%s\" ==>\n",
169 variables[num_variables].name,
170 variables[num_variables].value);
171 #endif
172 num_variables++;
173 if (num_variables == MAX_VARIABLES) break;
177 #ifdef DEBUG_COMMENTS
178 printf("<!== End dump in cgi_load_variables() ==>\n");
179 #endif
181 /* variables from the client are in display charset - convert them
182 to our internal charset before use */
183 for (i=0;i<num_variables;i++) {
184 pstring dest;
186 convert_string(CH_DISPLAY, CH_UNIX,
187 variables[i].name, -1,
188 dest, sizeof(dest));
189 free(variables[i].name);
190 variables[i].name = strdup(dest);
192 convert_string(CH_DISPLAY, CH_UNIX,
193 variables[i].value, -1,
194 dest, sizeof(dest));
195 free(variables[i].value);
196 variables[i].value = strdup(dest);
201 /***************************************************************************
202 find a variable passed via CGI
203 Doesn't quite do what you think in the case of POST text variables, because
204 if they exist they might have a value of "" or even " ", depending on the
205 browser. Also doesn't allow for variables[] containing multiple variables
206 with the same name and the same or different values.
207 ***************************************************************************/
208 const char *cgi_variable(const char *name)
210 int i;
212 for (i=0;i<num_variables;i++)
213 if (strcmp(variables[i].name, name) == 0)
214 return variables[i].value;
215 return NULL;
218 /***************************************************************************
219 tell a browser about a fatal error in the http processing
220 ***************************************************************************/
221 static void cgi_setup_error(const char *err, const char *header, const char *info)
223 if (!got_request) {
224 /* damn browsers don't like getting cut off before they give a request */
225 char line[1024];
226 while (fgets(line, sizeof(line)-1, stdin)) {
227 if (strnequal(line,"GET ", 4) ||
228 strnequal(line,"POST ", 5) ||
229 strnequal(line,"PUT ", 4)) {
230 break;
235 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);
236 fclose(stdin);
237 fclose(stdout);
238 exit(0);
242 /***************************************************************************
243 tell a browser about a fatal authentication error
244 ***************************************************************************/
245 static void cgi_auth_error(void)
247 if (inetd_server) {
248 cgi_setup_error("401 Authorization Required",
249 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
250 "You must be authenticated to use this service");
251 } else {
252 printf("Content-Type: text/html\r\n");
254 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
255 printf("<BODY><H1>Installation Error</H1>\n");
256 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
257 printf("</BODY></HTML>\r\n");
259 exit(0);
262 /***************************************************************************
263 authenticate when we are running as a CGI
264 ***************************************************************************/
265 static void cgi_web_auth(void)
267 const char *user = getenv("REMOTE_USER");
268 struct passwd *pwd;
269 const char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
270 const char *tail = "</BODY></HTML>\r\n";
272 if (!user) {
273 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
274 head, tail);
275 exit(0);
278 pwd = getpwnam_alloc(user);
279 if (!pwd) {
280 printf("%sCannot find user %s<br>%s\n", head, user, tail);
281 exit(0);
284 setuid(0);
285 setuid(pwd->pw_uid);
286 if (geteuid() != pwd->pw_uid || getuid() != pwd->pw_uid) {
287 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
288 head, user, (int)geteuid(), (int)getuid(), tail);
289 exit(0);
291 passwd_free(&pwd);
295 /***************************************************************************
296 handle a http authentication line
297 ***************************************************************************/
298 static BOOL cgi_handle_authorization(char *line)
300 char *p;
301 fstring user, user_pass;
302 struct passwd *pass = NULL;
304 if (!strnequal(line,"Basic ", 6)) {
305 goto err;
307 line += 6;
308 while (line[0] == ' ') line++;
309 base64_decode_inplace(line);
310 if (!(p=strchr_m(line,':'))) {
312 * Always give the same error so a cracker
313 * cannot tell why we fail.
315 goto err;
317 *p = 0;
319 convert_string(CH_DISPLAY, CH_UNIX,
320 line, -1,
321 user, sizeof(user));
323 convert_string(CH_DISPLAY, CH_UNIX,
324 p+1, -1,
325 user_pass, sizeof(user_pass));
328 * Try and get the user from the UNIX password file.
331 pass = getpwnam_alloc(user);
334 * Validate the password they have given.
337 if NT_STATUS_IS_OK(pass_check(pass, user, user_pass,
338 strlen(user_pass), NULL, False)) {
340 if (pass) {
342 * Password was ok.
345 if ( initgroups(pass->pw_name, pass->pw_gid) != 0 )
346 goto err;
348 become_user_permanently(pass->pw_uid, pass->pw_gid);
350 /* Save the users name */
351 C_user = strdup(user);
352 passwd_free(&pass);
353 return True;
357 err:
358 cgi_setup_error("401 Bad Authorization",
359 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
360 "username or password incorrect");
362 passwd_free(&pass);
363 return False;
366 /***************************************************************************
367 is this root?
368 ***************************************************************************/
369 BOOL am_root(void)
371 if (geteuid() == 0) {
372 return( True);
373 } else {
374 return( False);
378 /***************************************************************************
379 return a ptr to the users name
380 ***************************************************************************/
381 char *cgi_user_name(void)
383 return(C_user);
387 /***************************************************************************
388 handle a file download
389 ***************************************************************************/
390 static void cgi_download(char *file)
392 SMB_STRUCT_STAT st;
393 char buf[1024];
394 int fd, l, i;
395 char *p;
396 char *lang;
398 /* sanitise the filename */
399 for (i=0;file[i];i++) {
400 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
401 cgi_setup_error("404 File Not Found","",
402 "Illegal character in filename");
406 if (!file_exist(file, &st)) {
407 cgi_setup_error("404 File Not Found","",
408 "The requested file was not found");
411 fd = web_open(file,O_RDONLY,0);
412 if (fd == -1) {
413 cgi_setup_error("404 File Not Found","",
414 "The requested file was not found");
416 printf("HTTP/1.0 200 OK\r\n");
417 if ((p=strrchr_m(file,'.'))) {
418 if (strcmp(p,".gif")==0) {
419 printf("Content-Type: image/gif\r\n");
420 } else if (strcmp(p,".jpg")==0) {
421 printf("Content-Type: image/jpeg\r\n");
422 } else if (strcmp(p,".txt")==0) {
423 printf("Content-Type: text/plain\r\n");
424 } else {
425 printf("Content-Type: text/html\r\n");
428 printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
430 lang = lang_tdb_current();
431 if (lang) {
432 printf("Content-Language: %s\r\n", lang);
435 printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
436 while ((l=read(fd,buf,sizeof(buf)))>0) {
437 fwrite(buf, 1, l, stdout);
439 close(fd);
440 exit(0);
447 * @brief Setup the CGI framework.
449 * Setup the cgi framework, handling the possibility that this program
450 * is either run as a true CGI program with a gateway to a web server, or
451 * is itself a mini web server.
453 void cgi_setup(const char *rootdir, int auth_required)
455 BOOL authenticated = False;
456 char line[1024];
457 char *url=NULL;
458 char *p;
459 char *lang;
461 if (chdir(rootdir)) {
462 cgi_setup_error("500 Server Error", "",
463 "chdir failed - the server is not configured correctly");
466 /* Handle the possibility we might be running as non-root */
467 sec_init();
469 if ((lang=getenv("HTTP_ACCEPT_LANGUAGE"))) {
470 /* if running as a cgi program */
471 web_set_lang(lang);
474 /* maybe we are running under a web server */
475 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
476 if (auth_required) {
477 cgi_web_auth();
479 return;
482 inetd_server = True;
484 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
485 cgi_setup_error("403 Forbidden", "",
486 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
489 /* we are a mini-web server. We need to read the request from stdin
490 and handle authentication etc */
491 while (fgets(line, sizeof(line)-1, stdin)) {
492 if (line[0] == '\r' || line[0] == '\n') break;
493 if (strnequal(line,"GET ", 4)) {
494 got_request = True;
495 url = strdup(&line[4]);
496 } else if (strnequal(line,"POST ", 5)) {
497 got_request = True;
498 request_post = 1;
499 url = strdup(&line[5]);
500 } else if (strnequal(line,"PUT ", 4)) {
501 got_request = True;
502 cgi_setup_error("400 Bad Request", "",
503 "This server does not accept PUT requests");
504 } else if (strnequal(line,"Authorization: ", 15)) {
505 authenticated = cgi_handle_authorization(&line[15]);
506 } else if (strnequal(line,"Content-Length: ", 16)) {
507 content_length = atoi(&line[16]);
508 } else if (strnequal(line,"Accept-Language: ", 17)) {
509 web_set_lang(&line[17]);
511 /* ignore all other requests! */
514 if (auth_required && !authenticated) {
515 cgi_auth_error();
518 if (!url) {
519 cgi_setup_error("400 Bad Request", "",
520 "You must specify a GET or POST request");
523 /* trim the URL */
524 if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
525 *p = 0;
527 while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
528 url[strlen(url)-1] = 0;
531 /* anything following a ? in the URL is part of the query string */
532 if ((p=strchr_m(url,'?'))) {
533 query_string = p+1;
534 *p = 0;
537 string_sub(url, "/swat/", "", 0);
539 if (url[0] != '/' && strstr(url,"..")==0 && file_exist(url, NULL)) {
540 cgi_download(url);
543 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
544 printf("Date: %s\r\n", http_timestring(time(NULL)));
545 baseurl = "";
546 pathinfo = url+1;
550 /***************************************************************************
551 return the current pages URL
552 ***************************************************************************/
553 const char *cgi_baseurl(void)
555 if (inetd_server) {
556 return baseurl;
558 return getenv("SCRIPT_NAME");
561 /***************************************************************************
562 return the current pages path info
563 ***************************************************************************/
564 const char *cgi_pathinfo(void)
566 char *r;
567 if (inetd_server) {
568 return pathinfo;
570 r = getenv("PATH_INFO");
571 if (!r) return "";
572 if (*r == '/') r++;
573 return r;
576 /***************************************************************************
577 return the hostname of the client
578 ***************************************************************************/
579 char *cgi_remote_host(void)
581 if (inetd_server) {
582 return get_peer_name(1,False);
584 return getenv("REMOTE_HOST");
587 /***************************************************************************
588 return the hostname of the client
589 ***************************************************************************/
590 char *cgi_remote_addr(void)
592 if (inetd_server) {
593 return get_peer_addr(1);
595 return getenv("REMOTE_ADDR");
599 /***************************************************************************
600 return True if the request was a POST
601 ***************************************************************************/
602 BOOL cgi_waspost(void)
604 if (inetd_server) {
605 return request_post;
607 return strequal(getenv("REQUEST_METHOD"), "POST");