* BIG rewrite of header handling and slimming of context_loop and session_loop; shuff...
[citadel.git] / webcit / webcit.c
1 /*
2  * $Id$
3  *
4  * This is the main transaction loop of the web service.  It maintains a
5  * persistent session to the Citadel server, handling HTTP WebCit requests as
6  * they arrive and presenting a user interface.
7  */
8 #define SHOW_ME_VAPPEND_PRINTF
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include "webcit.h"
12 #include "groupdav.h"
13 #include "webserver.h"
14
15
16 /*
17  * String to unset the cookie.
18  * Any date "in the past" will work, so I chose my birthday, right down to
19  * the exact minute.  :)
20  */
21 static char *unset = "; expires=28-May-1971 18:10:00 GMT";
22 StrBuf *csslocal = NULL;
23 HashList *HandlerHash = NULL;
24
25 void WebcitAddUrlHandler(const char * UrlString, 
26                          long UrlSLen, 
27                          WebcitHandlerFunc F, 
28                          long Flags)
29 {
30         WebcitHandler *NewHandler;      
31         NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
32         NewHandler->F = F;
33         NewHandler->Flags = Flags;
34         Put(HandlerHash, UrlString, UrlSLen, NewHandler, NULL);
35 }
36
37
38 /*
39  * web-printing funcion. uses our vsnprintf wrapper
40  */
41 void wprintf(const char *format,...)
42 {
43         wcsession *WCC = WC;
44         va_list arg_ptr;
45
46         if (WCC->WBuf == NULL)
47                 WCC->WBuf = NewStrBuf();
48
49         va_start(arg_ptr, format);
50         StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
51         va_end(arg_ptr);
52 }
53
54 /*
55  * http-header-printing funcion. uses our vsnprintf wrapper
56  */
57 void hprintf(const char *format,...)
58 {
59         wcsession *WCC = WC;
60         va_list arg_ptr;
61
62         va_start(arg_ptr, format);
63         StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
64         va_end(arg_ptr);
65 }
66
67
68
69 /*
70  * wrap up an HTTP session, closes tags, etc.
71  *
72  * print_standard_html_footer should be set to:
73  * 0            - to transmit only,
74  * nonzero      - to append the closing tags
75  */
76 void wDumpContent(int print_standard_html_footer)
77 {
78         if (print_standard_html_footer) {
79                 wprintf("</div> <!-- end of 'content' div -->\n");
80                 do_template("trailing", NULL);
81         }
82
83         /* If we've been saving it all up for one big output burst,
84          * go ahead and do that now.
85          */
86         end_burst();
87 }
88
89
90  
91
92 /*
93  * Output HTTP headers and leading HTML for a page
94  */
95 void output_headers(    int do_httpheaders,     /* 1 = output HTTP headers                          */
96                         int do_htmlhead,        /* 1 = output HTML <head> section and <body> opener */
97
98                         int do_room_banner,     /* 0=no, 1=yes,                                     
99                                                  * 2 = I'm going to embed my own, so don't open the 
100                                                  *     <div id="content"> either.                   
101                                                  */
102
103                         int unset_cookies,      /* 1 = session is terminating, so unset the cookies */
104                         int suppress_check,     /* 1 = suppress check for instant messages          */
105                         int cache               /* 1 = allow browser to cache this page             */
106 ) {
107         wcsession *WCC = WC;
108         char cookie[1024];
109         char httpnow[128];
110
111         hprintf("HTTP/1.1 200 OK\n");
112         http_datestring(httpnow, sizeof httpnow, time(NULL));
113
114         if (do_httpheaders) {
115                 if (WCC->serv_info != NULL)
116                         hprintf("Content-type: text/html; charset=utf-8\r\n"
117                                 "Server: %s / %s\n"
118                                 "Connection: close\r\n",
119                                 PACKAGE_STRING, 
120                                 ChrPtr(WCC->serv_info->serv_software));
121                 else
122                         hprintf("Content-type: text/html; charset=utf-8\r\n"
123                                 "Server: %s / [n/a]\n"
124                                 "Connection: close\r\n",
125                                 PACKAGE_STRING);
126         }
127
128         if (cache) {
129                 char httpTomorow[128];
130
131                 http_datestring(httpTomorow, sizeof httpTomorow, 
132                                 time(NULL) + 60 * 60 * 24 * 2);
133
134                 hprintf("Pragma: public\r\n"
135                         "Cache-Control: max-age=3600, must-revalidate\r\n"
136                         "Last-modified: %s\r\n"
137                         "Expires: %s\r\n",
138                         httpnow,
139                         httpTomorow
140                 );
141         }
142         else {
143                 hprintf("Pragma: no-cache\r\n"
144                         "Cache-Control: no-store\r\n"
145                         "Expires: -1\r\n"
146                 );
147         }
148
149         stuff_to_cookie(cookie, 1024, 
150                         WCC->wc_session, WCC->wc_username,
151                         WCC->wc_password, WCC->wc_roomname);
152
153         if (unset_cookies) {
154                 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
155         } else {
156                 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
157                 if (server_cookie != NULL) {
158                         hprintf("%s\n", server_cookie);
159                 }
160         }
161
162         if (do_htmlhead) {
163                 begin_burst();
164                 do_template("head", NULL);
165
166                 /* check for ImportantMessages (these display in a div overlaying the main screen) */
167                 if (!IsEmptyStr(WCC->ImportantMessage)) {
168                         wprintf("<div id=\"important_message\">\n"
169                                 "<span class=\"imsg\">");
170                         StrEscAppend(WCC->WBuf, NULL, WCC->ImportantMessage, 0, 0);
171                         wprintf("</span><br />\n"
172                                 "</div>\n"
173                         );
174                         StrBufAppendBufPlain(WCC->trailing_javascript,
175                                              HKEY("setTimeout('hide_imsg_popup()', 5000);       \n"), 
176                                              0
177                         );
178                         WCC->ImportantMessage[0] = 0;
179                 }
180                 else if (StrLength(WCC->ImportantMsg) > 0) {
181                         wprintf("<div id=\"important_message\">\n"
182                                 "<span class=\"imsg\">");
183                         StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
184                         wprintf("</span><br />\n"
185                                 "</div>\n"
186                         );
187                         StrBufAppendBufPlain(WCC->trailing_javascript,
188                                              HKEY("setTimeout('hide_imsg_popup()', 5000);       \n"),
189                                              0
190                         );
191                         FlushStrBuf(WCC->ImportantMsg);
192                 }
193                 if ( (WCC->logged_in) && (!unset_cookies) ) {
194                         /*DoTemplate(HKEY("iconbar"), NULL, &NoCtx);*/
195                         page_popup();
196                 }
197
198                 if (do_room_banner == 1) {
199                         wprintf("<div id=\"banner\">\n");
200                         embed_room_banner(NULL, navbar_default);
201                         wprintf("</div>\n");
202                 }
203         }
204
205         if (do_room_banner == 1) {
206                 wprintf("<div id=\"content\">\n");
207         }
208 }
209
210 void output_custom_content_header(const char *ctype) {
211   hprintf("HTTP/1.1 200 OK\r\n");
212   hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
213   hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
214   hprintf("Connection: close\r\n");
215 }
216
217
218 /*
219  * Generic function to do an HTTP redirect.  Easy and fun.
220  */
221 void http_redirect(const char *whichpage) {
222         hprintf("HTTP/1.1 302 Moved Temporarily\n");
223         hprintf("Location: %s\r\n", whichpage);
224         hprintf("URI: %s\r\n", whichpage);
225         hprintf("Content-type: text/html; charset=utf-8\r\n");
226         wprintf("<html><body>");
227         wprintf("Go <a href=\"%s\">here</A>.", whichpage);
228         wprintf("</body></html>\n");
229         end_burst();
230 }
231
232
233
234 /*
235  * Output a piece of content to the web browser using conformant HTTP and MIME semantics
236  */
237 void http_transmit_thing(const char *content_type,
238                          int is_static) {
239
240 #ifndef TECH_PREVIEW
241         lprintf(9, "http_transmit_thing(%s)%s\n",
242                 content_type,
243                 (is_static ? " (static)" : "")
244         );
245 #endif
246         output_headers(0, 0, 0, 0, 0, is_static);
247
248         hprintf("Content-type: %s\r\n"
249                 "Server: %s\r\n"
250                 "Connection: close\r\n",
251                 content_type,
252                 PACKAGE_STRING);
253
254         end_burst();
255 }
256
257 /*
258  * print menu box like used in the floor view or admin interface.
259  * This function takes pair of strings as va_args, 
260  * Title        Title string of the box
261  * Class        CSS Class for the box
262  * nLines       How many string pairs should we print? (URL, UrlText)
263  * ...          Pairs of URL Strings and their Names
264  */
265 void print_menu_box(char* Title, char *Class, int nLines, ...)
266 {
267         va_list arg_list;
268         long i;
269         
270         svput("BOXTITLE", WCS_STRING, Title);
271         do_template("beginboxx", NULL);
272         
273         wprintf("<ul class=\"%s\">", Class);
274         
275         va_start(arg_list, nLines);
276         for (i = 0; i < nLines; ++i)
277         { 
278                 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
279                 wprintf((char *) va_arg(arg_list, char *));
280                 wprintf("</a></li>\n");
281         }
282         va_end (arg_list);
283         
284         wprintf("</a></li>\n");
285         
286         wprintf("</ul>");
287         
288         do_template("endbox", NULL);
289 }
290
291
292 /*
293  * dump out static pages from disk
294  */
295 void output_static(void)
296 {
297         int fd;
298         struct stat statbuf;
299         off_t bytes;
300         off_t count = 0;
301         const char *content_type;
302         int len;
303         const char *Err;
304         char what[] = "TODO";
305         fd = open(what, O_RDONLY);
306         if (fd <= 0) {
307                 lprintf(9, "output_static('%s')  -- NOT FOUND --\n", what);
308                 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
309                 hprintf("Content-Type: text/plain\r\n");
310                 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
311                 end_burst();
312         } else {
313                 len = strlen (what);
314                 content_type = GuessMimeByFilename(what, len);
315
316                 if (fstat(fd, &statbuf) == -1) {
317                         lprintf(9, "output_static('%s')  -- FSTAT FAILED --\n", what);
318                         hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
319                         hprintf("Content-Type: text/plain\r\n");
320                         wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
321                         end_burst();
322                         return;
323                 }
324
325                 count = 0;
326                 bytes = statbuf.st_size;
327
328                 if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
329                 {
330                         if (fd > 0) close(fd);
331                         lprintf(9, "output_static('%s')  -- FREAD FAILED (%s) --\n", what, strerror(errno));
332                                 hprintf("HTTP/1.1 500 internal server error \r\n");
333                                 hprintf("Content-Type: text/plain\r\n");
334                                 end_burst();
335                                 return;
336                 }
337
338
339                 close(fd);
340 #ifndef TECH_PREVIEW
341                 lprintf(9, "output_static('%s')  %s\n", what, content_type);
342 #endif
343                 http_transmit_thing(content_type, 1);
344         }
345         if (yesbstr("force_close_session")) {
346                 end_webcit_session();
347         }
348 }
349
350
351 /*
352  * Convenience functions to display a page containing only a string
353  *
354  * titlebarcolor        color of the titlebar of the frame
355  * titlebarmsg          text to display in the title bar
356  * messagetext          body of the box
357  */
358 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
359 {
360         hprintf("HTTP/1.1 200 OK\n");
361         output_headers(1, 1, 2, 0, 0, 0);
362         wprintf("<div id=\"banner\">\n");
363         wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
364         wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
365         wprintf("</td></tr></table>\n");
366         wprintf("</div>\n<div id=\"content\">\n");
367         escputs(messagetext);
368
369         wprintf("<hr />\n");
370         wDumpContent(1);
371 }
372
373
374 /*
375  * Display a blank page.
376  */
377 void blank_page(void) {
378         output_headers(1, 1, 0, 0, 0, 0);
379         wDumpContent(2);
380 }
381
382
383 /*
384  * A template has been requested
385  */
386 void url_do_template(void) {
387         const StrBuf *MimeType;
388         const StrBuf *Tmpl = sbstr("template");
389         begin_burst();
390         MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
391         http_transmit_thing(ChrPtr(MimeType), 0);
392 }
393
394
395
396 /*
397  * convenience function to indicate success
398  */
399 void display_success(char *successmessage)
400 {
401         convenience_page("007700", "OK", successmessage);
402 }
403
404
405 /*
406  * Authorization required page 
407  * This is probably temporary and should be revisited 
408  */
409 void authorization_required(const char *message)
410 {
411         hprintf("HTTP/1.1 401 Authorization Required\r\n");
412         hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
413         hprintf("Content-Type: text/html\r\n");
414         wprintf("<h1>");
415         wprintf(_("Authorization Required"));
416         wprintf("</h1>\r\n");
417         wprintf(_("The resource you requested requires a valid username and password. "
418                 "You could not be logged in: %s\n"), message);
419         wDumpContent(0);
420         
421 }
422
423 /*
424  * Convenience functions to wrap around asynchronous ajax responses
425  */
426 void begin_ajax_response(void) {
427         wcsession *WCC = WC;
428
429         FlushStrBuf(WCC->HBuf);
430         output_headers(0, 0, 0, 0, 0, 0);
431
432         hprintf("Content-type: text/html; charset=UTF-8\r\n"
433                 "Server: %s\r\n"
434                 "Connection: close\r\n"
435                 ,
436                 PACKAGE_STRING);
437         begin_burst();
438 }
439
440 /*
441  * print ajax response footer 
442  */
443 void end_ajax_response(void) {
444         wDumpContent(0);
445 }
446
447         /* If it's a "force 404" situation then display the error and bail. */
448 void do_404(void)
449 {
450         hprintf("HTTP/1.1 404 Not found\r\n");
451         hprintf("Content-Type: text/plain\r\n");
452         wprintf("Not found\r\n");
453         end_burst();
454 }
455 /* TODO: staticdata
456 {
457         /* Static content can be sent without connecting to Citadel. * /
458         is_static = 0;
459         for (a=0; a<ndirs && ! is_static; ++a) {
460                 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location * /
461                         is_static = 1;
462                         n_static = a;
463                 }
464         }
465         if (is_static) {
466                 if (nBackDots < 2)
467                 {
468                         snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
469                                  static_dirs[n_static], 
470                                  index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
471                         for (a=0; a<8; ++a) {
472                                 if (buf[strlen(buf)-1] == '/') {
473                                         buf[strlen(buf)-1] = 0;
474                                 }
475                         }
476                         for (a = 0; a < strlen(buf); ++a) {
477                                 if (isspace(buf[a])) {
478                                         buf[a] = 0;
479                                 }
480                         }
481                         output_static(buf);
482                 }
483                 else 
484                 {
485                         lprintf(9, "Suspicious request. Ignoring.");
486                         hprintf("HTTP/1.1 404 Security check failed\r\n");
487                         hprintf("Content-Type: text/plain\r\n\r\n");
488                         wprintf("You have sent a malformed or invalid request.\r\n");
489                         end_burst();
490                 }
491                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect * /
492         }
493         }*/
494
495
496 /*
497  * Wraps a Citadel server command in an AJAX transaction.
498  */
499 void ajax_servcmd(void)
500 {
501         wcsession *WCC = WC;
502         int Done = 0;
503         StrBuf *Buf;
504         char *junk;
505         size_t len;
506
507         begin_ajax_response();
508         Buf = NewStrBuf();
509         serv_puts(bstr("g_cmd"));
510         StrBuf_ServGetln(Buf);
511         StrBufAppendBuf(WCC->WBuf, Buf, 0);
512         StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
513         
514         switch (GetServerStatus(Buf, NULL)) {
515         case 8:
516                 serv_puts("\n\n000");
517                 if ( (StrLength(Buf)==3) && 
518                      !strcmp(ChrPtr(Buf), "000")) {
519                         StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
520                         break;
521                 }
522         case 1:
523                 while (!Done) {
524                         StrBuf_ServGetln(Buf);
525                         if ( (StrLength(Buf)==3) && 
526                              !strcmp(ChrPtr(Buf), "000")) {
527                                 Done = 1;
528                         }
529                         StrBufAppendBuf(WCC->WBuf, Buf, 0);
530                         StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
531                 }
532                 break;
533         case 4:
534                 text_to_server(bstr("g_input"));
535                 serv_puts("000");
536                 break;
537         case 6:
538                 len = atol(&ChrPtr(Buf)[4]);
539                 StrBuf_ServGetBLOBBuffered(Buf, len);
540                 break;
541         case 7:
542                 len = atol(&ChrPtr(Buf)[4]);
543                 junk = malloc(len);
544                 memset(junk, 0, len);
545                 serv_write(junk, len);
546                 free(junk);
547         }
548         
549         end_ajax_response();
550         
551         /*
552          * This is kind of an ugly hack, but this is the only place it can go.
553          * If the command was GEXP, then the instant messenger window must be
554          * running, so reset the "last_pager_check" watchdog timer so
555          * that page_popup() doesn't try to open it a second time.
556          */
557         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
558                 WCC->last_pager_check = time(NULL);
559         }
560         FreeStrBuf(&Buf);
561 }
562
563
564 /*
565  * Helper function for the asynchronous check to see if we need
566  * to open the instant messenger window.
567  */
568 void seconds_since_last_gexp(void)
569 {
570         char buf[256];
571
572         if ( (time(NULL) - WC->last_pager_check) < 30) {
573                 wprintf("NO\n");
574         }
575         else {
576                 memset(buf, 0, 5);
577                 serv_puts("NOOP");
578                 serv_getln(buf, sizeof buf);
579                 if (buf[3] == '*') {
580                         wprintf("YES");
581                 }
582                 else {
583                         wprintf("NO");
584                 }
585         }
586 }
587
588
589
590 void ReadPostData(void)
591 {
592         const char *content_end = NULL;
593         int body_start = 0;
594         wcsession *WCC = WC;
595         StrBuf *content = NULL;
596         
597         content = NewStrBuf();
598
599         StrBufPrintf(content, 
600                      "Content-type: %s\n"
601                      "Content-length: %ld\n\n",
602                      ChrPtr(WCC->Hdr->ContentType), 
603                              WCC->Hdr->ContentLength);
604 /*
605   hprintf("Content-type: %s\n"
606   "Content-length: %d\n\n",
607   ContentType, ContentLength);
608 */
609         body_start = StrLength(content);
610
611         /** Read the entire input data at once. */
612         client_read_to(&WCC->Hdr->http_sock, 
613                        content, 
614                        WCC->Hdr->ReadBuf, &WCC->Hdr->Pos,
615                        WCC->Hdr->ContentLength,
616                        SLEEPING);
617         
618         if (!strncasecmp(ChrPtr(WCC->Hdr->ContentType), "application/x-www-form-urlencoded", 33)) {
619                 StrBufCutLeft(content, body_start);
620                 ParseURLParams(content);
621         } else if (!strncasecmp(ChrPtr(WCC->Hdr->ContentType), "multipart", 9)) {
622                 content_end = ChrPtr(content) + 
623                         WCC->Hdr->ContentLength + 
624                         body_start;
625                 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
626         }
627         FreeStrBuf(&content);
628 }
629
630
631 /*
632  * Entry point for WebCit transaction
633  */
634 void session_loop(void)
635 {
636         int Flags = 0;
637         int xhttp;
638         StrBuf *Buf;
639         
640         char buf[SIZ];
641
642         /*
643          * We stuff these with the values coming from the client cookies,
644          * so we can use them to reconnect a timed out session if we have to.
645          */
646         wcsession *WCC;
647
648         
649         Buf = NewStrBuf();
650
651         WCC= WC;
652
653         WCC->upload_length = 0;
654         WCC->upload = NULL;
655         WCC->is_mobile = 0;
656         WCC->trailing_javascript = NewStrBuf();
657         WCC->Hdr->nWildfireHeaders = 0;
658         if (WCC->Hdr->Handler != NULL)
659                 Flags = WCC->Hdr->Handler->Flags; /* so we can temporarily add our own... */
660         /** Figure out the action * /
661         index[0] = action;
662         sizes[0] = sizeof action;
663         for (a=1; a<9; a++)
664         {
665                 index[a] = arg[a-1];
666                 sizes[a] = sizeof arg[a-1];
667         }
668         nBackDots = 0;
669         nEmpty = 0;
670 /*
671   for ( a = 0; a < 9; ++a)
672   {
673   extract_token(index[a], ChrPtr(ReqLine), a + 1, '/', sizes[a]);
674   if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
675   if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
676   if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
677   if ((index[a][0] == '.') && (index[a][1] == '.'))
678   nBackDots++;
679   if (index[a][0] == '\0')
680   nEmpty++;
681   }
682 */
683         if (WCC->Hdr->ContentLength > 0) {
684                 ReadPostData();
685         }
686
687         /* If there are variables in the URL, we must grab them now */
688         if (WCC->Hdr->PlainArgs != NULL)
689                 ParseURLParams(WCC->Hdr->PlainArgs);
690
691         /* If the client sent a nonce that is incorrect, kill the request. */
692         if (havebstr("nonce")) {
693                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
694                         bstr("nonce"), WCC->nonce);
695                 if (ibstr("nonce") != WCC->nonce) {
696                         lprintf(9, "Ignoring request with mismatched nonce.\n");
697                         hprintf("HTTP/1.1 404 Security check failed\r\n");
698                         hprintf("Content-Type: text/plain\r\n\r\n");
699                         wprintf("Security check failed.\r\n");
700                         end_burst();
701                         goto SKIP_ALL_THIS_CRAP;
702                 }
703         }
704
705         /*
706          * If we're not connected to a Citadel server, try to hook up the
707          * connection now.
708          */
709         if (!WCC->connected) {
710                 if (GetConnected ())
711                         goto SKIP_ALL_THIS_CRAP;
712         }
713
714
715         /*
716          * If we're not logged in, but we have HTTP Authentication data,
717          * try logging in to Citadel using that.
718          */
719         if ((!WCC->logged_in)
720             && (StrLength(WCC->Hdr->c_username) > 0)
721             && (StrLength(WCC->Hdr->c_password) > 0))
722         {
723                 FlushStrBuf(Buf);
724                 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
725                 StrBuf_ServGetln(Buf);
726                 if (GetServerStatus(Buf, NULL) == 3) {
727                         serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
728                         StrBuf_ServGetln(Buf);
729                         if (GetServerStatus(Buf, NULL) == 2) {
730                                 become_logged_in(WCC->Hdr->c_username,
731                                                  WCC->Hdr->c_password, Buf);
732                         } else {
733                                 /* Should only display when password is wrong */
734                                 authorization_required(&buf[4]);
735                                 FreeStrBuf(&Buf);
736                                 goto SKIP_ALL_THIS_CRAP;
737                         }
738                 }
739         }
740
741         xhttp = (WCC->Hdr->eReqType != eGET) &&
742                 (WCC->Hdr->eReqType != ePOST) &&
743                 (WCC->Hdr->eReqType != eHEAD);
744
745         /*
746          * If we're not logged in, but we have username and password cookies
747          * supplied by the browser, try using them to log in.
748          */
749         if ((!WCC->logged_in)
750            && (StrLength(WCC->Hdr->c_username)>0)
751            && (StrLength(WCC->Hdr->c_password)>0)) {
752                 ReEstablish_Session();
753         }
754
755         /*
756          * If a 'gotofirst' parameter has been specified, attempt to goto that room
757          * prior to doing anything else.
758          */
759         if (havebstr("gotofirst")) {
760                 int ret;
761                 ret = gotoroom(sbstr("gotofirst"));     /* do this quietly to avoid session output! */
762                 if (ret != 0)
763                         lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n", bstr("gotofirst"), ret);
764         }
765
766         if (WCC->Hdr->Handler != NULL) {
767                 if (!WCC->logged_in && ((WCC->Hdr->Handler->Flags & ANONYMOUS) == 0)) {
768                         display_login(NULL);
769                 }
770                 else {
771 /*
772                         if((WCC->Hdr->Handler->Flags & NEED_URL)) {
773                                 if (WCC->UrlFragment1 == NULL)
774                                         WCC->UrlFragment1 = NewStrBuf();
775                                 if (WCC->UrlFragment2 == NULL)
776                                         WCC->UrlFragment2 = NewStrBuf();
777                                 if (WCC->UrlFragment3 == NULL)
778                                         WCC->UrlFragment3 = NewStrBuf();
779                                 if (WCC->UrlFragment4 == NULL)
780                                         WCC->UrlFragment4 = NewStrBuf();
781                                 StrBufPlain(WCC->UrlFragment1, index[0], -1);
782                                 StrBufPlain(WCC->UrlFragment2, index[1], -1);
783                                 StrBufPlain(WCC->UrlFragment3, index[2], -1);
784                                 StrBufPlain(WCC->UrlFragment4, index[3], -1);
785                         }
786 */
787                         if ((WCC->Hdr->Handler->Flags & AJAX) != 0)
788                                 begin_ajax_response();
789                         WCC->Hdr->Handler->F();
790                         if ((WCC->Hdr->Handler->Flags & AJAX) != 0)
791                                 end_ajax_response();
792                 }
793         }
794         /* When all else fais, display the main menu. */
795         else {
796                 if (!WCC->logged_in) 
797                         display_login(NULL);
798                 else
799                         display_main_menu();
800         }
801
802 SKIP_ALL_THIS_CRAP:
803         if (WCC->SavePrefsToServer) {
804                 save_preferences();
805                 WCC->SavePrefsToServer = 0;
806         }
807         FreeStrBuf(&Buf);
808         fflush(stdout);
809         WCC->Hdr->http_host = NULL;
810 }
811
812
813 /*
814  * Replacement for sleep() that uses select() in order to avoid SIGALRM
815  */
816 void sleeeeeeeeeep(int seconds)
817 {
818         struct timeval tv;
819
820         tv.tv_sec = seconds;
821         tv.tv_usec = 0;
822         select(0, NULL, NULL, NULL, &tv);
823 }
824
825
826 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
827 {
828         wcsession *WCC = WC;
829         if (WCC != NULL)
830                 return ((!IsEmptyStr(WCC->ImportantMessage)) || 
831                         (StrLength(WCC->ImportantMsg) > 0));
832         else
833                 return 0;
834 }
835
836 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
837 {
838         wcsession *WCC = WC;
839         
840         if (WCC != NULL) {
841                 if (!IsEmptyStr(WCC->ImportantMessage)) {
842                         StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
843                         WCC->ImportantMessage[0] = '\0';
844                 }
845                 else if (StrLength(WCC->ImportantMsg) > 0) {
846                         StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
847                         FlushStrBuf(WCC->ImportantMsg);
848                 }
849         }
850 }
851
852 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
853 {
854         wcsession *WCC = WC;
855
856         if (WCC != NULL)
857                 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
858 }
859
860 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
861 {
862         StrBufAppendBuf(Target, 
863                         csslocal, 0);
864 }
865
866 extern char static_local_dir[PATH_MAX];
867
868
869         /* TODO: integrate this into the static startup logic
870
871          * While we're at it, gracefully handle requests for the
872          * robots.txt and favicon.ico files.
873          * /
874         if ((StrLength(ReqLine) >= 11) &&
875             !strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
876                 StrBufPlain(ReqLine, 
877                             HKEY("/static/robots.txt"
878                                  "?force_close_session=yes HTTP/1.1"));
879                 Hdr.eReqType = eGET;
880         }
881         else if ((StrLength(ReqLine) >= 11) &&
882                  !strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
883                 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
884                 Hdr.eReqType = eGET;
885         }
886
887 */
888 void 
889 InitModule_WEBCIT
890 (void)
891 {
892         char dir[SIZ];
893         WebcitAddUrlHandler(HKEY("404"), do_404, ANONYMOUS|COOKIEUNNEEDED);
894         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
895
896         WebcitAddUrlHandler(HKEY("robots.txt"), output_static, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
897         WebcitAddUrlHandler(HKEY("favicon.ico"), output_static, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
898         WebcitAddUrlHandler(HKEY("static"), output_static, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
899         WebcitAddUrlHandler(HKEY("static.local"), output_static, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
900         WebcitAddUrlHandler(HKEY("tinymce"), output_static, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
901
902         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
903         WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
904         WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX|LOGCHATTY);
905         WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
906
907         RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
908         RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
909         RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
910         RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
911
912         snprintf(dir, SIZ, "%s/static.local/webcit.css", static_local_dir);
913         if (!access(dir, R_OK)) {
914                 lprintf(9, "Using local Stylesheet [%s]\n", dir);
915                 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
916         }
917         else
918                 lprintf(9, "Didn't find site local Stylesheet [%s]\n", dir);
919
920 }
921
922 void
923 ServerStartModule_WEBCIT
924 (void)
925 {
926         HandlerHash = NewHash(1, NULL);
927 }
928
929
930 void 
931 ServerShutdownModule_WEBCIT
932 (void)
933 {
934         FreeStrBuf(&csslocal);
935         DeleteHash(&HandlerHash);
936 }
937
938
939
940 void
941 SessionNewModule_WEBCIT
942 (wcsession *sess)
943 {
944         sess->ImportantMsg = NewStrBuf();
945         sess->WBuf = NewStrBuf();
946         sess->HBuf = NewStrBuf();
947 }
948
949 void
950 SessionDetachModule_WEBCIT
951 (wcsession *sess)
952 {
953         DeleteHash(&sess->Hdr->urlstrings);// TODO?
954         if (sess->upload_length > 0) {
955                 free(sess->upload);
956                 sess->upload_length = 0;
957         }
958         FreeStrBuf(&sess->trailing_javascript);
959
960         if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
961         {
962                 FreeStrBuf(&sess->WBuf);
963                 sess->WBuf = NewStrBuf();
964         }
965         else
966                 FlushStrBuf(sess->WBuf);
967         FlushStrBuf(sess->HBuf);
968 }
969
970 void 
971 SessionDestroyModule_WEBCIT
972 (wcsession *sess)
973 {
974         FreeStrBuf(&sess->WBuf);
975         FreeStrBuf(&sess->HBuf);
976         /*
977         FreeStrBuf(&sess->UrlFragment1);
978         FreeStrBuf(&sess->UrlFragment2);
979         FreeStrBuf(&sess->UrlFragment3);
980         FreeStrBuf(&sess->UrlFragment4);
981         */
982         FreeStrBuf(&sess->ImportantMsg);
983 }
984