move setup_groups() into password.c so that swat can link without
[samba.git] / source / cgi.c
1 /* 
2    some simple CGI helper routines
3    Copyright (C) Andrew Tridgell 1997-1998
4    
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.
9    
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.
14    
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.
18 */
19
20
21 #include "includes.h"
22 #include "smb.h"
23
24 #define MAX_VARIABLES 10000
25
26 /* set the expiry on fixed pages */
27 #define EXPIRY_TIME (60*60*24*7)
28
29 #define CGI_LOGGING 0
30
31 #ifdef DEBUG_COMMENTS
32 extern void print_title(char *fmt, ...);
33 #endif
34
35 struct var {
36         char *name;
37         char *value;
38 };
39
40 static struct var variables[MAX_VARIABLES];
41 static int num_variables;
42 static int content_length;
43 static int request_post;
44 static int request_get;
45 static char *query_string;
46 static char *baseurl;
47
48 static void unescape(char *buf)
49 {
50         char *p=buf;
51
52         while ((p=strchr(p,'+')))
53                 *p = ' ';
54
55         p = buf;
56
57         while (p && *p && (p=strchr(p,'%'))) {
58                 int c1 = p[1];
59                 int c2 = p[2];
60
61                 if (c1 >= '0' && c1 <= '9')
62                         c1 = c1 - '0';
63                 else if (c1 >= 'A' && c1 <= 'F')
64                         c1 = 10 + c1 - 'A';
65                 else if (c1 >= 'a' && c1 <= 'f')
66                         c1 = 10 + c1 - 'a';
67                 else {p++; continue;}
68
69                 if (c2 >= '0' && c2 <= '9')
70                         c2 = c2 - '0';
71                 else if (c2 >= 'A' && c2 <= 'F')
72                         c2 = 10 + c2 - 'A';
73                 else if (c2 >= 'a' && c2 <= 'f')
74                         c2 = 10 + c2 - 'a';
75                 else {p++; continue;}
76                         
77                 *p = (c1<<4) | c2;
78
79                 memcpy(p+1, p+3, strlen(p+3)+1);
80                 p++;
81         }
82 }
83
84
85 static char *grab_line(FILE *f, int *cl)
86 {
87         char *ret;
88         int i = 0;
89         int len = 1024;
90
91         ret = (char *)malloc(len);
92         if (!ret) return NULL;
93         
94
95         while ((*cl)) {
96                 int c = fgetc(f);
97                 (*cl)--;
98
99                 if (c == EOF) {
100                         (*cl) = 0;
101                         break;
102                 }
103                 
104                 if (c == '\r') continue;
105
106                 if (strchr("\n&", c)) break;
107
108                 ret[i++] = c;
109
110                 if (i == len-1) {
111                         char *ret2;
112                         ret2 = (char *)realloc(ret, len*2);
113                         if (!ret2) return ret;
114                         len *= 2;
115                         ret = ret2;
116                 }
117         }
118         
119
120         ret[i] = 0;
121         return ret;
122 }
123
124 /***************************************************************************
125   load all the variables passed to the CGI program. May have multiple variables
126   with the same name and the same or different values. Takes a file parameter
127   for simulating CGI invocation eg loading saved preferences.
128   ***************************************************************************/
129 void cgi_load_variables(FILE *f1)
130 {
131         FILE *f = f1;
132         static char *line;
133         char *p, *s, *tok;
134         int len;
135
136 #ifdef DEBUG_COMMENTS
137         char dummy[100]="";
138         print_title(dummy);
139         printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
140 #endif
141
142         if (!f1) {
143                 f = stdin;
144                 if (!content_length) {
145                         p = getenv("CONTENT_LENGTH");
146                         len = p?atoi(p):0;
147                 } else {
148                         len = content_length;
149                 }
150         } else {
151                 fseek(f, 0, SEEK_END);
152                 len = ftell(f);
153                 fseek(f, 0, SEEK_SET);
154         }
155
156
157         if (len > 0 && 
158             (f1 || request_post ||
159              ((s=getenv("REQUEST_METHOD")) && 
160               strcasecmp(s,"POST")==0))) {
161                 while (len && (line=grab_line(f, &len))) {
162                         p = strchr(line,'=');
163                         if (!p) continue;
164                         
165                         *p = 0;
166                         
167                         variables[num_variables].name = strdup(line);
168                         variables[num_variables].value = strdup(p+1);
169
170                         free(line);
171                         
172                         if (!variables[num_variables].name || 
173                             !variables[num_variables].value)
174                                 continue;
175
176                         unescape(variables[num_variables].value);
177                         unescape(variables[num_variables].name);
178
179 #ifdef DEBUG_COMMENTS
180                         printf("<!== POST var %s has value \"%s\"  ==>\n",
181                                variables[num_variables].name,
182                                variables[num_variables].value);
183 #endif
184                         
185                         num_variables++;
186                         if (num_variables == MAX_VARIABLES) break;
187                 }
188         }
189
190         if (f1) {
191 #ifdef DEBUG_COMMENTS
192                 printf("<!== End dump in cgi_load_variables() ==>\n"); 
193 #endif
194                 return;
195         }
196
197         fclose(stdin);
198
199         if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
200                 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
201                         p = strchr(tok,'=');
202                         if (!p) continue;
203                         
204                         *p = 0;
205                         
206                         variables[num_variables].name = strdup(tok);
207                         variables[num_variables].value = strdup(p+1);
208
209                         if (!variables[num_variables].name || 
210                             !variables[num_variables].value)
211                                 continue;
212
213                         unescape(variables[num_variables].value);
214                         unescape(variables[num_variables].name);
215
216 #ifdef DEBUG_COMMENTS
217                         printf("<!== Commandline var %s has value \"%s\"  ==>\n",
218                                variables[num_variables].name,
219                                variables[num_variables].value);
220 #endif                                          
221                         num_variables++;
222                         if (num_variables == MAX_VARIABLES) break;
223                 }
224
225         }
226 #ifdef DEBUG_COMMENTS
227         printf("<!== End dump in cgi_load_variables() ==>\n");   
228 #endif
229 }
230
231
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   ***************************************************************************/
239 char *cgi_variable(char *name)
240 {
241         int i;
242
243         for (i=0;i<num_variables;i++)
244                 if (strcmp(variables[i].name, name) == 0)
245                         return variables[i].value;
246         return NULL;
247 }
248
249 /***************************************************************************
250 return a particular cgi variable
251   ***************************************************************************/
252 char *cgi_vnum(int i, char **name)
253 {
254         if (i < 0 || i >= num_variables) return NULL;
255         *name = variables[i].name;
256         return variables[i].value;
257 }
258
259 /***************************************************************************
260   return the value of a CGI boolean variable.
261   ***************************************************************************/
262 int cgi_boolean(char *name, int def)
263 {
264         char *p = cgi_variable(name);
265
266         if (!p) return def;
267
268         return strcmp(p, "1") == 0;
269 }
270
271 /***************************************************************************
272 like strdup() but quotes < > and &
273   ***************************************************************************/
274 char *quotedup(char *s)
275 {
276         int i, n=0;
277         int len;
278         char *ret;
279         char *d;
280
281         if (!s) return strdup("");
282
283         len = strlen(s);
284
285         for (i=0;i<len;i++)
286                 if (s[i] == '<' || s[i] == '>' || s[i] == '&')
287                         n++;
288
289         ret = malloc(len + n*6 + 1);
290
291         if (!ret) return NULL;
292
293         d = ret;
294
295         for (i=0;i<len;i++) {
296                 switch (s[i]) {
297                 case '<':
298                         strcpy(d, "&lt;");
299                         d += 4;
300                         break;
301
302                 case '>':
303                         strcpy(d, "&gt;");
304                         d += 4;
305                         break;
306
307                 case '&':
308                         strcpy(d, "&amp;");
309                         d += 5;
310                         break;
311
312                 default:
313                         *d++ = s[i];
314                 }
315         }
316
317         *d = 0;
318
319         return ret;
320 }
321
322
323 /***************************************************************************
324 like strdup() but quotes a wide range of characters
325   ***************************************************************************/
326 char *urlquote(char *s)
327 {
328         int i, n=0;
329         int len;
330         char *ret;
331         char *d;
332         char *qlist = "\"\n\r'&<> \t+;";
333
334         if (!s) return strdup("");
335
336         len = strlen(s);
337
338         for (i=0;i<len;i++)
339                 if (strchr(qlist, s[i])) n++;
340
341         ret = malloc(len + n*2 + 1);
342
343         if (!ret) return NULL;
344
345         d = ret;
346
347         for (i=0;i<len;i++) {
348                 if (strchr(qlist,s[i])) {
349                         sprintf(d, "%%%02X", (int)s[i]);
350                         d += 3;
351                 } else {
352                         *d++ = s[i];
353                 }
354         }
355
356         *d = 0;
357
358         return ret;
359 }
360
361
362 /***************************************************************************
363 like strdup() but quotes " characters
364   ***************************************************************************/
365 char *quotequotes(char *s)
366 {
367         int i, n=0;
368         int len;
369         char *ret;
370         char *d;
371
372         if (!s) return strdup("");
373
374         len = strlen(s);
375
376         for (i=0;i<len;i++)
377                 if (s[i] == '"')
378                         n++;
379
380         ret = malloc(len + n*6 + 1);
381
382         if (!ret) return NULL;
383
384         d = ret;
385
386         for (i=0;i<len;i++) {
387                 switch (s[i]) {
388                 case '"':
389                         strcpy(d, "&quot;");
390                         d += 6;
391                         break;
392
393                 default:
394                         *d++ = s[i];
395                 }
396         }
397
398         *d = 0;
399
400         return ret;
401 }
402
403
404 /***************************************************************************
405 quote spaces in a buffer
406   ***************************************************************************/
407 void quote_spaces(char *buf)
408 {
409         while (*buf) {
410                 if (*buf == ' ') *buf = '+';
411                 buf++;
412         }
413 }
414
415
416
417 /***************************************************************************
418 tell a browser about a fatal error in the http processing
419   ***************************************************************************/
420 static void cgi_setup_error(char *err, char *header, char *info)
421 {
422         printf("HTTP/1.1 %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", err, header, err, err, info);
423         exit(0);
424 }
425
426
427 /***************************************************************************
428 decode a base64 string in-place - simple and slow algorithm
429   ***************************************************************************/
430 static void base64_decode(char *s)
431 {
432         char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
433         int bit_offset, byte_offset, idx, i;
434         unsigned char *d = (unsigned char *)s;
435         char *p;
436
437         i=0;
438
439         while (*s && (p=strchr(b64,*s))) {
440                 idx = (int)(p - b64);
441                 byte_offset = (i*6)/8;
442                 bit_offset = (i*6)%8;
443                 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
444                 if (bit_offset < 3) {
445                         d[byte_offset] |= (idx << (2-bit_offset));
446                 } else {
447                         d[byte_offset] |= (idx >> (bit_offset-2));
448                         d[byte_offset+1] = 0;
449                         d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
450                 }
451                 s++; i++;
452         }
453 }
454
455
456 /***************************************************************************
457 handle a http authentication line
458   ***************************************************************************/
459 static int cgi_handle_authorization(char *line)
460 {
461         char *p, *user, *pass;
462
463         if (strncasecmp(line,"Basic ", 6)) {
464                 cgi_setup_error("401 Bad Authorization", "", 
465                                 "Only basic authorization is understood");
466         }
467         line += 6;
468         while (line[0] == ' ') line++;
469         base64_decode(line);
470         if (!(p=strchr(line,':'))) {
471                 cgi_setup_error("401 Bad Authorization", "", 
472                                 "username/password must be supplied");
473         }
474         *p = 0;
475         user = line;
476         pass = p+1;
477
478         /* currently only allow connections as root */
479         if (strcmp(user,"root")) {
480                 cgi_setup_error("401 Bad Authorization", "", 
481                                 "incorrect username/password");
482         }
483
484
485         return password_ok(user, pass, strlen(pass), NULL);
486 }
487
488
489 /***************************************************************************
490 handle a file download
491   ***************************************************************************/
492 static void cgi_download(char *file)
493 {
494         struct stat st;
495         char buf[1024];
496         int fd, l, i;
497         char *p;
498
499         /* sanitise the filename */
500         for (i=0;file[i];i++) {
501                 if (!isalnum(file[i]) && !strchr("/.-_", file[i])) {
502                         cgi_setup_error("404 File Not Found","",
503                                         "Illegal character in filename");
504                 }
505         }
506
507         if (!file_exist(file, &st)) {
508                 cgi_setup_error("404 File Not Found","",
509                                 "The requested file was not found");
510         }
511         fd = open(file,O_RDONLY);
512         if (fd == -1) {
513                 cgi_setup_error("404 File Not Found","",
514                                 "The requested file was not found");
515         }
516         printf("HTTP/1.1 200 OK\r\n");
517         if ((p=strrchr(file,'.'))) {
518                 if (strcmp(p,".gif")==0) {
519                         printf("Content-Type: image/gif\r\n");
520                 } else if (strcmp(p,".jpg")==0) {
521                         printf("Content-Type: image/jpeg\r\n");
522                 } else {
523                         printf("Content-Type: text/html\r\n");
524                 }
525         }
526         printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
527
528         printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
529         while ((l=read(fd,buf,sizeof(buf)))>0) {
530                 fwrite(buf, 1, l, stdout);
531         }
532         close(fd);
533         exit(0);
534 }
535
536
537 /***************************************************************************
538 setup the cgi framework, handling the possability that this program is either
539 run as a true cgi program by a web browser or is itself a mini web server
540   ***************************************************************************/
541 void cgi_setup(char *rootdir, int auth_required)
542 {
543         int authenticated = 0;
544         char line[1024];
545         char *url=NULL;
546         char *p;
547 #if CGI_LOGGING
548         FILE *f = fopen("/tmp/cgi.log", "a");
549
550         fprintf(f,"\n[Date: %s]\n", http_timestring(time(NULL)));
551 #endif
552
553         if (chdir(rootdir)) {
554                 cgi_setup_error("400 Server Error", "",
555                                 "chdir failed - the server is not configured correctly");
556         }
557
558         if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
559                 /* assume we are running under a real web server */
560                 return;
561         }
562
563         /* we are a mini-web server. We need to read the request from stdin
564            and handle authentication etc */
565         while (fgets(line, sizeof(line)-1, stdin)) {
566 #if CGI_LOGGING
567                 fputs(line, f);
568 #endif
569                 if (line[0] == '\r' || line[0] == '\n') break;
570                 if (strncasecmp(line,"GET ", 4)==0) {
571                         request_get = 1;
572                         url = strdup(&line[4]);
573                 } else if (strncasecmp(line,"POST ", 5)==0) {
574                         request_post = 1;
575                         url = strdup(&line[5]);
576                 } else if (strncasecmp(line,"PUT ", 4)==0) {
577                         cgi_setup_error("400 Bad Request", "",
578                                         "This server does not accept PUT requests");
579                 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
580                         authenticated = cgi_handle_authorization(&line[15]);
581                 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
582                         content_length = atoi(&line[16]);
583                 }
584                 /* ignore all other requests! */
585         }
586 #if CGI_LOGGING
587         fclose(f);
588 #endif
589
590         if (auth_required && !authenticated) {
591                 cgi_setup_error("401 Authorization Required", 
592                                 "WWW-Authenticate: Basic realm=\"root\"\r\n",
593                                 "You must be authenticated to use this service");
594         }
595
596         if (!url) {
597                 cgi_setup_error("400 Bad Request", "",
598                                 "You must specify a GET or POST request");
599         }
600
601         /* trim the URL */
602         if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
603                 *p = 0;
604         }
605         while (*url && strchr("\r\n",url[strlen(url)-1])) {
606                 url[strlen(url)-1] = 0;
607         }
608
609         /* anything following a ? in the URL is part of the query string */
610         if ((p=strchr(url,'?'))) {
611                 query_string = p+1;
612                 *p = 0;
613         }
614
615         if (strstr(url+1,"..")==0 && file_exist(url+1, NULL)) {
616                 cgi_download(url+1);
617         }
618
619         printf("HTTP/1.1 200 OK\r\nConnection: close\r\n");
620         printf("Date: %s\r\n", http_timestring(time(NULL)));
621         baseurl = url+1;
622 }
623
624
625 /***************************************************************************
626 return the current pages URL
627   ***************************************************************************/
628 char *cgi_baseurl(void)
629 {
630         return baseurl;
631 }