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