if we are adding a new sambaAccount, make sure that we add a
[Samba.git] / source / web / cgi.c
blob0b86265a1e5feca1a87da6f1b2447576f63615ca
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 "smb.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 char *baseurl;
44 static char *pathinfo;
45 static char *C_user;
46 static BOOL inetd_server;
47 static BOOL got_request;
49 static void unescape(char *buf)
51 char *p=buf;
53 while ((p=strchr(p,'+')))
54 *p = ' ';
56 p = buf;
58 while (p && *p && (p=strchr(p,'%'))) {
59 int c1 = p[1];
60 int c2 = p[2];
62 if (c1 >= '0' && c1 <= '9')
63 c1 = c1 - '0';
64 else if (c1 >= 'A' && c1 <= 'F')
65 c1 = 10 + c1 - 'A';
66 else if (c1 >= 'a' && c1 <= 'f')
67 c1 = 10 + c1 - 'a';
68 else {p++; continue;}
70 if (c2 >= '0' && c2 <= '9')
71 c2 = c2 - '0';
72 else if (c2 >= 'A' && c2 <= 'F')
73 c2 = 10 + c2 - 'A';
74 else if (c2 >= 'a' && c2 <= 'f')
75 c2 = 10 + c2 - 'a';
76 else {p++; continue;}
78 *p = (c1<<4) | c2;
80 memcpy(p+1, p+3, strlen(p+3)+1);
81 p++;
86 static char *grab_line(FILE *f, int *cl)
88 char *ret = NULL;
89 int i = 0;
90 int len = 0;
92 while ((*cl)) {
93 int c;
95 if (i == len) {
96 char *ret2;
97 if (len == 0) len = 1024;
98 else len *= 2;
99 ret2 = (char *)Realloc(ret, len);
100 if (!ret2) return ret;
101 ret = ret2;
104 c = fgetc(f);
105 (*cl)--;
107 if (c == EOF) {
108 (*cl) = 0;
109 break;
112 if (c == '\r') continue;
114 if (strchr("\n&", c)) break;
116 ret[i++] = c;
121 ret[i] = 0;
122 return ret;
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(FILE *f1)
132 FILE *f = f1;
133 static char *line;
134 char *p, *s, *tok;
135 int len;
137 #ifdef DEBUG_COMMENTS
138 char dummy[100]="";
139 print_title(dummy);
140 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
141 #endif
143 if (!f1) {
144 f = stdin;
145 if (!content_length) {
146 p = getenv("CONTENT_LENGTH");
147 len = p?atoi(p):0;
148 } else {
149 len = content_length;
151 } else {
152 fseek(f, 0, SEEK_END);
153 len = ftell(f);
154 fseek(f, 0, SEEK_SET);
158 if (len > 0 &&
159 (f1 || request_post ||
160 ((s=getenv("REQUEST_METHOD")) &&
161 strcasecmp(s,"POST")==0))) {
162 while (len && (line=grab_line(f, &len))) {
163 p = strchr(line,'=');
164 if (!p) continue;
166 *p = 0;
168 variables[num_variables].name = strdup(line);
169 variables[num_variables].value = strdup(p+1);
171 SAFE_FREE(line);
173 if (!variables[num_variables].name ||
174 !variables[num_variables].value)
175 continue;
177 unescape(variables[num_variables].value);
178 unescape(variables[num_variables].name);
180 #ifdef DEBUG_COMMENTS
181 printf("<!== POST var %s has value \"%s\" ==>\n",
182 variables[num_variables].name,
183 variables[num_variables].value);
184 #endif
186 num_variables++;
187 if (num_variables == MAX_VARIABLES) break;
191 if (f1) {
192 #ifdef DEBUG_COMMENTS
193 printf("<!== End dump in cgi_load_variables() ==>\n");
194 #endif
195 return;
198 fclose(stdin);
199 open("/dev/null", O_RDWR);
201 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
202 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
203 p = strchr(tok,'=');
204 if (!p) continue;
206 *p = 0;
208 variables[num_variables].name = strdup(tok);
209 variables[num_variables].value = strdup(p+1);
211 if (!variables[num_variables].name ||
212 !variables[num_variables].value)
213 continue;
215 unescape(variables[num_variables].value);
216 unescape(variables[num_variables].name);
218 #ifdef DEBUG_COMMENTS
219 printf("<!== Commandline var %s has value \"%s\" ==>\n",
220 variables[num_variables].name,
221 variables[num_variables].value);
222 #endif
223 num_variables++;
224 if (num_variables == MAX_VARIABLES) break;
228 #ifdef DEBUG_COMMENTS
229 printf("<!== End dump in cgi_load_variables() ==>\n");
230 #endif
234 /***************************************************************************
235 find a variable passed via CGI
236 Doesn't quite do what you think in the case of POST text variables, because
237 if they exist they might have a value of "" or even " ", depending on the
238 browser. Also doesn't allow for variables[] containing multiple variables
239 with the same name and the same or different values.
240 ***************************************************************************/
241 char *cgi_variable(char *name)
243 int i;
245 for (i=0;i<num_variables;i++)
246 if (strcmp(variables[i].name, name) == 0)
247 return variables[i].value;
248 return NULL;
251 /***************************************************************************
252 tell a browser about a fatal error in the http processing
253 ***************************************************************************/
254 static void cgi_setup_error(char *err, char *header, char *info)
256 if (!got_request) {
257 /* damn browsers don't like getting cut off before they give a request */
258 char line[1024];
259 while (fgets(line, sizeof(line)-1, stdin)) {
260 if (strncasecmp(line,"GET ", 4)==0 ||
261 strncasecmp(line,"POST ", 5)==0 ||
262 strncasecmp(line,"PUT ", 4)==0) {
263 break;
268 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);
269 fclose(stdin);
270 fclose(stdout);
271 exit(0);
275 /***************************************************************************
276 tell a browser about a fatal authentication error
277 ***************************************************************************/
278 static void cgi_auth_error(void)
280 if (inetd_server) {
281 cgi_setup_error("401 Authorization Required",
282 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
283 "You must be authenticated to use this service");
284 } else {
285 printf("Content-Type: text/html\r\n");
287 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
288 printf("<BODY><H1>Installation Error</H1>\n");
289 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
290 printf("</BODY></HTML>\r\n");
292 exit(0);
296 /***************************************************************************
297 decode a base64 string in-place - simple and slow algorithm
298 ***************************************************************************/
299 static void base64_decode(char *s)
301 char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
302 int bit_offset, byte_offset, idx, i, n;
303 unsigned char *d = (unsigned char *)s;
304 char *p;
306 n=i=0;
308 while (*s && (p=strchr(b64,*s))) {
309 idx = (int)(p - b64);
310 byte_offset = (i*6)/8;
311 bit_offset = (i*6)%8;
312 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
313 if (bit_offset < 3) {
314 d[byte_offset] |= (idx << (2-bit_offset));
315 n = byte_offset+1;
316 } else {
317 d[byte_offset] |= (idx >> (bit_offset-2));
318 d[byte_offset+1] = 0;
319 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
320 n = byte_offset+2;
322 s++; i++;
324 /* null terminate */
325 d[n] = 0;
328 /***************************************************************************
329 handle a http authentication line
330 ***************************************************************************/
331 static BOOL cgi_handle_authorization(char *line)
333 char *p, *user, *user_pass;
334 struct passwd *pass = NULL;
335 BOOL got_name = False;
336 BOOL tested_pass = False;
337 fstring default_user_lookup;
338 fstring default_user_pass;
340 /* Dummy user lookup to take the same time as a valid user. */
341 fstrcpy(default_user_lookup, "zzzz bibble");
342 fstrcpy(default_user_pass, "123456789");
344 if (strncasecmp(line,"Basic ", 6)) {
345 goto err;
347 line += 6;
348 while (line[0] == ' ') line++;
349 base64_decode(line);
350 if (!(p=strchr(line,':'))) {
352 * Always give the same error so a cracker
353 * cannot tell why we fail.
355 goto err;
357 *p = 0;
358 user = line;
359 user_pass = p+1;
362 * Try and get the user from the UNIX password file.
365 if(!(pass = Get_Pwnam(user,False))) {
367 * Always give the same error so a cracker
368 * cannot tell why we fail.
370 got_name = True;
371 goto err;
375 * Validate the password they have given.
378 tested_pass = True;
380 if(pass_check(user, user_pass, strlen(user_pass), NULL, NULL) == True) {
383 * Password was ok.
386 if(pass->pw_uid != 0) {
388 * We have not authenticated as root,
389 * become the user *permanently*.
391 become_user_permanently(pass->pw_uid, pass->pw_gid);
394 /* Save the users name */
395 C_user = strdup(user);
396 return True;
399 err:
401 /* Always take the same time. */
402 if (!got_name)
403 Get_Pwnam(default_user_lookup,False);
405 if (!tested_pass)
406 pass_check(default_user_lookup, default_user_pass,
407 strlen(default_user_pass), NULL, NULL);
409 cgi_setup_error("401 Bad Authorization", "",
410 "username or password incorrect");
412 return False;
415 /***************************************************************************
416 is this root?
417 ***************************************************************************/
418 BOOL am_root(void)
420 if (geteuid() == 0) {
421 return( True);
422 } else {
423 return( False);
427 /***************************************************************************
428 return a ptr to the users name
429 ***************************************************************************/
430 char *cgi_user_name(void)
432 return(C_user);
436 /***************************************************************************
437 handle a file download
438 ***************************************************************************/
439 static void cgi_download(char *file)
441 SMB_STRUCT_STAT st;
442 char buf[1024];
443 int fd, l, i;
444 char *p;
446 /* sanitise the filename */
447 for (i=0;file[i];i++) {
448 if (!isalnum((int)file[i]) && !strchr("/.-_", file[i])) {
449 cgi_setup_error("404 File Not Found","",
450 "Illegal character in filename");
454 if (!file_exist(file, &st)) {
455 cgi_setup_error("404 File Not Found","",
456 "The requested file was not found");
458 fd = sys_open(file,O_RDONLY,0);
459 if (fd == -1) {
460 cgi_setup_error("404 File Not Found","",
461 "The requested file was not found");
463 printf("HTTP/1.0 200 OK\r\n");
464 if ((p=strrchr(file,'.'))) {
465 if (strcmp(p,".gif")==0) {
466 printf("Content-Type: image/gif\r\n");
467 } else if (strcmp(p,".jpg")==0) {
468 printf("Content-Type: image/jpeg\r\n");
469 } else if (strcmp(p,".txt")==0) {
470 printf("Content-Type: text/plain\r\n");
471 } else {
472 printf("Content-Type: text/html\r\n");
475 printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
477 printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
478 while ((l=read(fd,buf,sizeof(buf)))>0) {
479 fwrite(buf, 1, l, stdout);
481 close(fd);
482 exit(0);
486 /***************************************************************************
487 setup the cgi framework, handling the possability that this program is either
488 run as a true cgi program by a web browser or is itself a mini web server
489 ***************************************************************************/
490 void cgi_setup(char *rootdir, int auth_required)
492 BOOL authenticated = False;
493 char line[1024];
494 char *url=NULL;
495 char *p;
497 if (chdir(rootdir)) {
498 cgi_setup_error("400 Server Error", "",
499 "chdir failed - the server is not configured correctly");
502 /* maybe we are running under a web server */
503 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
504 if (auth_required) {
505 cgi_auth_error();
507 return;
510 inetd_server = True;
512 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
513 cgi_setup_error("400 Server Error", "",
514 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
517 /* we are a mini-web server. We need to read the request from stdin
518 and handle authentication etc */
519 while (fgets(line, sizeof(line)-1, stdin)) {
520 if (line[0] == '\r' || line[0] == '\n') break;
521 if (strncasecmp(line,"GET ", 4)==0) {
522 got_request = True;
523 url = strdup(&line[4]);
524 } else if (strncasecmp(line,"POST ", 5)==0) {
525 got_request = True;
526 request_post = 1;
527 url = strdup(&line[5]);
528 } else if (strncasecmp(line,"PUT ", 4)==0) {
529 got_request = True;
530 cgi_setup_error("400 Bad Request", "",
531 "This server does not accept PUT requests");
532 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
533 authenticated = cgi_handle_authorization(&line[15]);
534 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
535 content_length = atoi(&line[16]);
537 /* ignore all other requests! */
540 if (auth_required && !authenticated) {
541 cgi_auth_error();
544 if (!url) {
545 cgi_setup_error("400 Bad Request", "",
546 "You must specify a GET or POST request");
549 /* trim the URL */
550 if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
551 *p = 0;
553 while (*url && strchr("\r\n",url[strlen(url)-1])) {
554 url[strlen(url)-1] = 0;
557 /* anything following a ? in the URL is part of the query string */
558 if ((p=strchr(url,'?'))) {
559 query_string = p+1;
560 *p = 0;
563 string_sub(url, "/swat/", "", 0);
565 if (url[0] != '/' && strstr(url,"..")==0 && file_exist(url, NULL)) {
566 cgi_download(url);
569 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
570 printf("Date: %s\r\n", http_timestring(time(NULL)));
571 baseurl = "";
572 pathinfo = url+1;
576 /***************************************************************************
577 return the current pages URL
578 ***************************************************************************/
579 char *cgi_baseurl(void)
581 if (inetd_server) {
582 return baseurl;
584 return getenv("SCRIPT_NAME");
587 /***************************************************************************
588 return the current pages path info
589 ***************************************************************************/
590 char *cgi_pathinfo(void)
592 char *r;
593 if (inetd_server) {
594 return pathinfo;
596 r = getenv("PATH_INFO");
597 if (!r) return "";
598 if (*r == '/') r++;
599 return r;
602 /***************************************************************************
603 return the hostname of the client
604 ***************************************************************************/
605 char *cgi_remote_host(void)
607 if (inetd_server) {
608 return get_socket_name(1);
610 return getenv("REMOTE_HOST");
613 /***************************************************************************
614 return the hostname of the client
615 ***************************************************************************/
616 char *cgi_remote_addr(void)
618 if (inetd_server) {
619 return get_socket_addr(1);
621 return getenv("REMOTE_ADDR");
625 /***************************************************************************
626 return True if the request was a POST
627 ***************************************************************************/
628 BOOL cgi_waspost(void)
630 if (inetd_server) {
631 return request_post;
633 return strequal(getenv("REQUEST_METHOD"), "POST");