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