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