J.F.'s latest printer fixes plus his gcc -picky fix for web/cgi.c
[ira/wip.git] / source3 / 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 char *query_string;
45 static char *baseurl;
46 static char *pathinfo;
47 static char *C_user;
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 tell a browser about a fatal error in the http processing
252   ***************************************************************************/
253 static void cgi_setup_error(char *err, char *header, char *info)
254 {
255         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", err, header, err, err, info);
256         exit(0);
257 }
258
259
260 /***************************************************************************
261 decode a base64 string in-place - simple and slow algorithm
262   ***************************************************************************/
263 static void base64_decode(char *s)
264 {
265         char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
266         int bit_offset, byte_offset, idx, i, n;
267         unsigned char *d = (unsigned char *)s;
268         char *p;
269
270         n=i=0;
271
272         while (*s && (p=strchr(b64,*s))) {
273                 idx = (int)(p - b64);
274                 byte_offset = (i*6)/8;
275                 bit_offset = (i*6)%8;
276                 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
277                 if (bit_offset < 3) {
278                         d[byte_offset] |= (idx << (2-bit_offset));
279                         n = byte_offset+1;
280                 } else {
281                         d[byte_offset] |= (idx >> (bit_offset-2));
282                         d[byte_offset+1] = 0;
283                         d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
284                         n = byte_offset+2;
285                 }
286                 s++; i++;
287         }
288         /* null terminate */
289         d[n] = 0;
290 }
291
292
293 /***************************************************************************
294 handle a http authentication line
295   ***************************************************************************/
296 static int cgi_handle_authorization(char *line)
297 {
298         char *p, *user, *pass;
299
300         if (strncasecmp(line,"Basic ", 6)) {
301                 cgi_setup_error("401 Bad Authorization", "", 
302                                 "Only basic authorization is understood");
303         }
304         line += 6;
305         while (line[0] == ' ') line++;
306         base64_decode(line);
307         if (!(p=strchr(line,':'))) {
308                 cgi_setup_error("401 Bad Authorization", "", 
309                                 "username/password must be supplied");
310         }
311         *p = 0;
312         user = line;
313         pass = p+1;
314
315         /* Save the users name */
316         C_user = strdup(user);
317
318         return pass_check(user, pass, strlen(pass), NULL, NULL);
319 }
320
321 /***************************************************************************
322 is this root?
323   ***************************************************************************/
324 BOOL is_root(void)
325 {
326         if ((C_user) && (strcmp(C_user,"root") == 0)) {
327                 return( True);
328         } else {
329                 return( False);
330         }
331 }
332
333 /***************************************************************************
334 return a ptr to the users name
335   ***************************************************************************/
336 char *get_user_name(void)
337 {
338         return(C_user);
339 }
340
341
342 /***************************************************************************
343 handle a file download
344   ***************************************************************************/
345 static void cgi_download(char *file)
346 {
347         SMB_STRUCT_STAT st;
348         char buf[1024];
349         int fd, l, i;
350         char *p;
351
352         /* sanitise the filename */
353         for (i=0;file[i];i++) {
354                 if (!isalnum((int)file[i]) && !strchr("/.-_", file[i])) {
355                         cgi_setup_error("404 File Not Found","",
356                                         "Illegal character in filename");
357                 }
358         }
359
360         if (!file_exist(file, &st)) {
361                 cgi_setup_error("404 File Not Found","",
362                                 "The requested file was not found");
363         }
364         fd = open(file,O_RDONLY);
365         if (fd == -1) {
366                 cgi_setup_error("404 File Not Found","",
367                                 "The requested file was not found");
368         }
369         printf("HTTP/1.0 200 OK\r\n");
370         if ((p=strrchr(file,'.'))) {
371                 if (strcmp(p,".gif")==0) {
372                         printf("Content-Type: image/gif\r\n");
373                 } else if (strcmp(p,".jpg")==0) {
374                         printf("Content-Type: image/jpeg\r\n");
375                 } else {
376                         printf("Content-Type: text/html\r\n");
377                 }
378         }
379         printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
380
381         printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
382         while ((l=read(fd,buf,sizeof(buf)))>0) {
383                 fwrite(buf, 1, l, stdout);
384         }
385         close(fd);
386         exit(0);
387 }
388
389
390 /***************************************************************************
391 setup the cgi framework, handling the possability that this program is either
392 run as a true cgi program by a web browser or is itself a mini web server
393   ***************************************************************************/
394 void cgi_setup(char *rootdir, int auth_required)
395 {
396         int authenticated = 0;
397         char line[1024];
398         char *url=NULL;
399         char *p;
400 #if CGI_LOGGING
401         FILE *f;
402 #endif
403
404         if (chdir(rootdir)) {
405                 cgi_setup_error("400 Server Error", "",
406                                 "chdir failed - the server is not configured correctly");
407         }
408
409         if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
410
411                 char *x;
412
413                 /* Save the users name if available */
414                 if ((x = getenv("REMOTE_USER"))!=NULL) {
415                         C_user = strdup(x);
416                 } else {
417                         C_user = "";
418                 }
419
420                 /* assume we are running under a real web server */
421                 return;
422         }
423
424 #if CGI_LOGGING
425         f = fopen("/tmp/cgi.log", "a");
426         if (f) fprintf(f,"\n[Date: %s   %s (%s)]\n", 
427                        http_timestring(time(NULL)),
428                        client_name(1), client_addr(1));
429 #endif
430
431         /* we are a mini-web server. We need to read the request from stdin
432            and handle authentication etc */
433         while (fgets(line, sizeof(line)-1, stdin)) {
434 #if CGI_LOGGING
435                 if (f) fputs(line, f);
436 #endif
437                 if (line[0] == '\r' || line[0] == '\n') break;
438                 if (strncasecmp(line,"GET ", 4)==0) {
439                         url = strdup(&line[4]);
440                 } else if (strncasecmp(line,"POST ", 5)==0) {
441                         request_post = 1;
442                         url = strdup(&line[5]);
443                 } else if (strncasecmp(line,"PUT ", 4)==0) {
444                         cgi_setup_error("400 Bad Request", "",
445                                         "This server does not accept PUT requests");
446                 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
447                         authenticated = cgi_handle_authorization(&line[15]);
448                 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
449                         content_length = atoi(&line[16]);
450                 }
451                 /* ignore all other requests! */
452         }
453 #if CGI_LOGGING
454         if (f) fclose(f);
455 #endif
456
457         if (auth_required && !authenticated) {
458                 cgi_setup_error("401 Authorization Required", 
459                                 "WWW-Authenticate: Basic realm=\"root\"\r\n",
460                                 "You must be authenticated to use this service");
461         }
462
463         if (!url) {
464                 cgi_setup_error("400 Bad Request", "",
465                                 "You must specify a GET or POST request");
466         }
467
468         /* trim the URL */
469         if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
470                 *p = 0;
471         }
472         while (*url && strchr("\r\n",url[strlen(url)-1])) {
473                 url[strlen(url)-1] = 0;
474         }
475
476         /* anything following a ? in the URL is part of the query string */
477         if ((p=strchr(url,'?'))) {
478                 query_string = p+1;
479                 *p = 0;
480         }
481
482         string_sub(url, "/swat/", "");
483
484         if (strstr(url,"..")==0 && file_exist(url, NULL)) {
485                 cgi_download(url);
486         }
487
488         printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
489         printf("Date: %s\r\n", http_timestring(time(NULL)));
490         baseurl = "";
491         pathinfo = url+1;
492 }
493
494
495 /***************************************************************************
496 return the current pages URL
497   ***************************************************************************/
498 char *cgi_baseurl(void)
499 {
500         if (baseurl) {
501                 return baseurl;
502         }
503         return getenv("SCRIPT_NAME");
504 }
505
506 /***************************************************************************
507 return the current pages path info
508   ***************************************************************************/
509 char *cgi_pathinfo(void)
510 {
511         char *r;
512         if (pathinfo) {
513                 return pathinfo;
514         }
515         r = getenv("PATH_INFO");
516         if (!r) return "";
517         if (*r == '/') r++;
518         return r;
519 }
520
521 /***************************************************************************
522 return the hostname of the client
523   ***************************************************************************/
524 char *cgi_remote_host(void)
525 {
526         if (baseurl) {
527                 return client_name(1);
528         }
529         return getenv("REMOTE_HOST");
530 }
531
532 /***************************************************************************
533 return the hostname of the client
534   ***************************************************************************/
535 char *cgi_remote_addr(void)
536 {
537         if (baseurl) {
538                 return client_addr(1);
539         }
540         return getenv("REMOTE_ADDR");
541 }
542
543
544 /***************************************************************************
545 return True if the request was a POST
546   ***************************************************************************/
547 BOOL cgi_waspost(void)
548 {
549         if (baseurl) {
550                 return request_post;
551         }
552         return strequal(getenv("REQUEST_METHOD"), "POST");
553 }