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