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