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