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