Getting ready for first Red Hat Linux RPMs for 1.9.19 pre-alpha release
[samba.git] / source / web / 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 static char *pathinfo;
48
49 static void unescape(char *buf)
50 {
51         char *p=buf;
52
53         while ((p=strchr(p,'+')))
54                 *p = ' ';
55
56         p = buf;
57
58         while (p && *p && (p=strchr(p,'%'))) {
59                 int c1 = p[1];
60                 int c2 = p[2];
61
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;}
69
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;}
77                         
78                 *p = (c1<<4) | c2;
79
80                 memcpy(p+1, p+3, strlen(p+3)+1);
81                 p++;
82         }
83 }
84
85
86 static char *grab_line(FILE *f, int *cl)
87 {
88         char *ret;
89         int i = 0;
90         int len = 1024;
91
92         ret = (char *)malloc(len);
93         if (!ret) return NULL;
94         
95
96         while ((*cl)) {
97                 int c = fgetc(f);
98                 (*cl)--;
99
100                 if (c == EOF) {
101                         (*cl) = 0;
102                         break;
103                 }
104                 
105                 if (c == '\r') continue;
106
107                 if (strchr("\n&", c)) break;
108
109                 ret[i++] = c;
110
111                 if (i == len-1) {
112                         char *ret2;
113                         ret2 = (char *)realloc(ret, len*2);
114                         if (!ret2) return ret;
115                         len *= 2;
116                         ret = ret2;
117                 }
118         }
119         
120
121         ret[i] = 0;
122         return ret;
123 }
124
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)
131 {
132         FILE *f = f1;
133         static char *line;
134         char *p, *s, *tok;
135         int len;
136
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
142
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;
150                 }
151         } else {
152                 fseek(f, 0, SEEK_END);
153                 len = ftell(f);
154                 fseek(f, 0, SEEK_SET);
155         }
156
157
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;
165                         
166                         *p = 0;
167                         
168                         variables[num_variables].name = strdup(line);
169                         variables[num_variables].value = strdup(p+1);
170
171                         free(line);
172                         
173                         if (!variables[num_variables].name || 
174                             !variables[num_variables].value)
175                                 continue;
176
177                         unescape(variables[num_variables].value);
178                         unescape(variables[num_variables].name);
179
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
185                         
186                         num_variables++;
187                         if (num_variables == MAX_VARIABLES) break;
188                 }
189         }
190
191         if (f1) {
192 #ifdef DEBUG_COMMENTS
193                 printf("<!== End dump in cgi_load_variables() ==>\n"); 
194 #endif
195                 return;
196         }
197
198         fclose(stdin);
199
200         if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
201                 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
202                         p = strchr(tok,'=');
203                         if (!p) continue;
204                         
205                         *p = 0;
206                         
207                         variables[num_variables].name = strdup(tok);
208                         variables[num_variables].value = strdup(p+1);
209
210                         if (!variables[num_variables].name || 
211                             !variables[num_variables].value)
212                                 continue;
213
214                         unescape(variables[num_variables].value);
215                         unescape(variables[num_variables].name);
216
217 #ifdef DEBUG_COMMENTS
218                         printf("<!== Commandline var %s has value \"%s\"  ==>\n",
219                                variables[num_variables].name,
220                                variables[num_variables].value);
221 #endif                                          
222                         num_variables++;
223                         if (num_variables == MAX_VARIABLES) break;
224                 }
225
226         }
227 #ifdef DEBUG_COMMENTS
228         printf("<!== End dump in cgi_load_variables() ==>\n");   
229 #endif
230 }
231
232
233 /***************************************************************************
234   find a variable passed via CGI
235   Doesn't quite do what you think in the case of POST text variables, because
236   if they exist they might have a value of "" or even " ", depending on the 
237   browser. Also doesn't allow for variables[] containing multiple variables
238   with the same name and the same or different values.
239   ***************************************************************************/
240 char *cgi_variable(char *name)
241 {
242         int i;
243
244         for (i=0;i<num_variables;i++)
245                 if (strcmp(variables[i].name, name) == 0)
246                         return variables[i].value;
247         return NULL;
248 }
249
250 /***************************************************************************
251 return a particular cgi variable
252   ***************************************************************************/
253 char *cgi_vnum(int i, char **name)
254 {
255         if (i < 0 || i >= num_variables) return NULL;
256         *name = variables[i].name;
257         return variables[i].value;
258 }
259
260 /***************************************************************************
261   return the value of a CGI boolean variable.
262   ***************************************************************************/
263 int cgi_boolean(char *name, int def)
264 {
265         char *p = cgi_variable(name);
266
267         if (!p) return def;
268
269         return strcmp(p, "1") == 0;
270 }
271
272 /***************************************************************************
273 like strdup() but quotes < > and &
274   ***************************************************************************/
275 char *quotedup(char *s)
276 {
277         int i, n=0;
278         int len;
279         char *ret;
280         char *d;
281
282         if (!s) return strdup("");
283
284         len = strlen(s);
285
286         for (i=0;i<len;i++)
287                 if (s[i] == '<' || s[i] == '>' || s[i] == '&')
288                         n++;
289
290         ret = malloc(len + n*6 + 1);
291
292         if (!ret) return NULL;
293
294         d = ret;
295
296         for (i=0;i<len;i++) {
297                 switch (s[i]) {
298                 case '<':
299                         strcpy(d, "&lt;");
300                         d += 4;
301                         break;
302
303                 case '>':
304                         strcpy(d, "&gt;");
305                         d += 4;
306                         break;
307
308                 case '&':
309                         strcpy(d, "&amp;");
310                         d += 5;
311                         break;
312
313                 default:
314                         *d++ = s[i];
315                 }
316         }
317
318         *d = 0;
319
320         return ret;
321 }
322
323
324 /***************************************************************************
325 like strdup() but quotes a wide range of characters
326   ***************************************************************************/
327 char *urlquote(char *s)
328 {
329         int i, n=0;
330         int len;
331         char *ret;
332         char *d;
333         char *qlist = "\"\n\r'&<> \t+;";
334
335         if (!s) return strdup("");
336
337         len = strlen(s);
338
339         for (i=0;i<len;i++)
340                 if (strchr(qlist, s[i])) n++;
341
342         ret = malloc(len + n*2 + 1);
343
344         if (!ret) return NULL;
345
346         d = ret;
347
348         for (i=0;i<len;i++) {
349                 if (strchr(qlist,s[i])) {
350                         sprintf(d, "%%%02X", (int)s[i]);
351                         d += 3;
352                 } else {
353                         *d++ = s[i];
354                 }
355         }
356
357         *d = 0;
358
359         return ret;
360 }
361
362
363 /***************************************************************************
364 like strdup() but quotes " characters
365   ***************************************************************************/
366 char *quotequotes(char *s)
367 {
368         int i, n=0;
369         int len;
370         char *ret;
371         char *d;
372
373         if (!s) return strdup("");
374
375         len = strlen(s);
376
377         for (i=0;i<len;i++)
378                 if (s[i] == '"')
379                         n++;
380
381         ret = malloc(len + n*6 + 1);
382
383         if (!ret) return NULL;
384
385         d = ret;
386
387         for (i=0;i<len;i++) {
388                 switch (s[i]) {
389                 case '"':
390                         strcpy(d, "&quot;");
391                         d += 6;
392                         break;
393
394                 default:
395                         *d++ = s[i];
396                 }
397         }
398
399         *d = 0;
400
401         return ret;
402 }
403
404
405 /***************************************************************************
406 quote spaces in a buffer
407   ***************************************************************************/
408 void quote_spaces(char *buf)
409 {
410         while (*buf) {
411                 if (*buf == ' ') *buf = '+';
412                 buf++;
413         }
414 }
415
416
417
418 /***************************************************************************
419 tell a browser about a fatal error in the http processing
420   ***************************************************************************/
421 static void cgi_setup_error(char *err, char *header, char *info)
422 {
423         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);
424         exit(0);
425 }
426
427
428 /***************************************************************************
429 decode a base64 string in-place - simple and slow algorithm
430   ***************************************************************************/
431 static void base64_decode(char *s)
432 {
433         char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
434         int bit_offset, byte_offset, idx, i;
435         unsigned char *d = (unsigned char *)s;
436         char *p;
437
438         i=0;
439
440         while (*s && (p=strchr(b64,*s))) {
441                 idx = (int)(p - b64);
442                 byte_offset = (i*6)/8;
443                 bit_offset = (i*6)%8;
444                 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
445                 if (bit_offset < 3) {
446                         d[byte_offset] |= (idx << (2-bit_offset));
447                 } else {
448                         d[byte_offset] |= (idx >> (bit_offset-2));
449                         d[byte_offset+1] = 0;
450                         d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
451                 }
452                 s++; i++;
453         }
454 }
455
456
457 /***************************************************************************
458 handle a http authentication line
459   ***************************************************************************/
460 static int cgi_handle_authorization(char *line)
461 {
462         char *p, *user, *pass;
463
464         if (strncasecmp(line,"Basic ", 6)) {
465                 cgi_setup_error("401 Bad Authorization", "", 
466                                 "Only basic authorization is understood");
467         }
468         line += 6;
469         while (line[0] == ' ') line++;
470         base64_decode(line);
471         if (!(p=strchr(line,':'))) {
472                 cgi_setup_error("401 Bad Authorization", "", 
473                                 "username/password must be supplied");
474         }
475         *p = 0;
476         user = line;
477         pass = p+1;
478
479         /* currently only allow connections as root */
480         if (strcmp(user,"root")) {
481                 cgi_setup_error("401 Bad Authorization", "", 
482                                 "incorrect username/password");
483         }
484
485
486         return password_ok(user, pass, strlen(pass), NULL);
487 }
488
489
490 /***************************************************************************
491 handle a file download
492   ***************************************************************************/
493 static void cgi_download(char *file)
494 {
495         struct stat st;
496         char buf[1024];
497         int fd, l, i;
498         char *p;
499
500         /* sanitise the filename */
501         for (i=0;file[i];i++) {
502                 if (!isalnum(file[i]) && !strchr("/.-_", file[i])) {
503                         cgi_setup_error("404 File Not Found","",
504                                         "Illegal character in filename");
505                 }
506         }
507
508         if (!file_exist(file, &st)) {
509                 cgi_setup_error("404 File Not Found","",
510                                 "The requested file was not found");
511         }
512         fd = open(file,O_RDONLY);
513         if (fd == -1) {
514                 cgi_setup_error("404 File Not Found","",
515                                 "The requested file was not found");
516         }
517         printf("HTTP/1.1 200 OK\r\n");
518         if ((p=strrchr(file,'.'))) {
519                 if (strcmp(p,".gif")==0) {
520                         printf("Content-Type: image/gif\r\n");
521                 } else if (strcmp(p,".jpg")==0) {
522                         printf("Content-Type: image/jpeg\r\n");
523                 } else {
524                         printf("Content-Type: text/html\r\n");
525                 }
526         }
527         printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
528
529         printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
530         while ((l=read(fd,buf,sizeof(buf)))>0) {
531                 fwrite(buf, 1, l, stdout);
532         }
533         close(fd);
534         exit(0);
535 }
536
537
538 /***************************************************************************
539 setup the cgi framework, handling the possability that this program is either
540 run as a true cgi program by a web browser or is itself a mini web server
541   ***************************************************************************/
542 void cgi_setup(char *rootdir, int auth_required)
543 {
544         int authenticated = 0;
545         char line[1024];
546         char *url=NULL;
547         char *p;
548 #if CGI_LOGGING
549         FILE *f;
550 #endif
551
552         if (chdir(rootdir)) {
553                 cgi_setup_error("400 Server Error", "",
554                                 "chdir failed - the server is not configured correctly");
555         }
556
557         if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
558                 /* assume we are running under a real web server */
559                 return;
560         }
561
562 #if CGI_LOGGING
563         f = fopen("/tmp/cgi.log", "a");
564         if (f) fprintf(f,"\n[Date: %s   %s (%s)]\n", 
565                        http_timestring(time(NULL)),
566                        client_name(1), client_addr(1));
567 #endif
568
569         /* we are a mini-web server. We need to read the request from stdin
570            and handle authentication etc */
571         while (fgets(line, sizeof(line)-1, stdin)) {
572 #if CGI_LOGGING
573                 if (f) fputs(line, f);
574 #endif
575                 if (line[0] == '\r' || line[0] == '\n') break;
576                 if (strncasecmp(line,"GET ", 4)==0) {
577                         request_get = 1;
578                         url = strdup(&line[4]);
579                 } else if (strncasecmp(line,"POST ", 5)==0) {
580                         request_post = 1;
581                         url = strdup(&line[5]);
582                 } else if (strncasecmp(line,"PUT ", 4)==0) {
583                         cgi_setup_error("400 Bad Request", "",
584                                         "This server does not accept PUT requests");
585                 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
586                         authenticated = cgi_handle_authorization(&line[15]);
587                 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
588                         content_length = atoi(&line[16]);
589                 }
590                 /* ignore all other requests! */
591         }
592 #if CGI_LOGGING
593         if (f) fclose(f);
594 #endif
595
596         if (auth_required && !authenticated) {
597                 cgi_setup_error("401 Authorization Required", 
598                                 "WWW-Authenticate: Basic realm=\"root\"\r\n",
599                                 "You must be authenticated to use this service");
600         }
601
602         if (!url) {
603                 cgi_setup_error("400 Bad Request", "",
604                                 "You must specify a GET or POST request");
605         }
606
607         /* trim the URL */
608         if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
609                 *p = 0;
610         }
611         while (*url && strchr("\r\n",url[strlen(url)-1])) {
612                 url[strlen(url)-1] = 0;
613         }
614
615         /* anything following a ? in the URL is part of the query string */
616         if ((p=strchr(url,'?'))) {
617                 query_string = p+1;
618                 *p = 0;
619         }
620
621         if (strstr(url+1,"..")==0 && file_exist(url+1, NULL)) {
622                 cgi_download(url+1);
623         }
624
625         printf("HTTP/1.1 200 OK\r\nConnection: close\r\n");
626         printf("Date: %s\r\n", http_timestring(time(NULL)));
627         baseurl = "";
628         pathinfo = url+1;
629 }
630
631
632 /***************************************************************************
633 return the current pages URL
634   ***************************************************************************/
635 char *cgi_baseurl(void)
636 {
637         if (baseurl) {
638                 return baseurl;
639         }
640         return getenv("SCRIPT_NAME");
641 }
642
643 /***************************************************************************
644 return the root URL for images etc
645   ***************************************************************************/
646 char *cgi_rooturl(void)
647 {
648         if (baseurl) {
649                 return "/";
650         }
651         return "/swat/";
652 }
653
654
655 /***************************************************************************
656 return the current pages path info
657   ***************************************************************************/
658 char *cgi_pathinfo(void)
659 {
660         char *r;
661         if (pathinfo) {
662                 return pathinfo;
663         }
664         r = getenv("PATH_INFO");
665         if (!r) return "";
666         if (*r == '/') r++;
667         return r;
668 }
669
670 /***************************************************************************
671 return the hostname of the client
672   ***************************************************************************/
673 char *cgi_remote_host(void)
674 {
675         if (baseurl) {
676                 return client_name(1);
677         }
678         return getenv("REMOTE_HOST");
679 }
680
681 /***************************************************************************
682 return the hostname of the client
683   ***************************************************************************/
684 char *cgi_remote_addr(void)
685 {
686         if (baseurl) {
687                 return client_addr(1);
688         }
689         return getenv("REMOTE_ADDR");
690 }
691
692
693 /***************************************************************************
694 return True if the request was a POST
695   ***************************************************************************/
696 BOOL cgi_waspost(void)
697 {
698         if (baseurl) {
699                 return request_post;
700         }
701         return strequal(getenv("REQUEST_METHOD"), "POST");
702 }