4 * This is the main transaction loop of the web service. It maintains a
5 * persistent session to the Citadel server, handling HTTP WebCit requests as
6 * they arrive and presenting a user interface.
8 #define SHOW_ME_VAPPEND_PRINTF
13 #include "webserver.h"
16 StrBuf *csslocal = NULL;
17 HashList *HandlerHash = NULL;
20 void DeleteWebcitHandler(void *vHandler)
22 WebcitHandler *Handler = (WebcitHandler*) vHandler;
23 FreeStrBuf(&Handler->Name);
24 FreeStrBuf(&Handler->DisplayName);
28 void WebcitAddUrlHandler(const char * UrlString, long UrlSLen,
29 const char *DisplayName, long dslen,
33 WebcitHandler *NewHandler;
34 NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
36 NewHandler->Flags = Flags;
37 NewHandler->Name = NewStrBufPlain(UrlString, UrlSLen);
38 StrBufShrinkToFit(NewHandler->Name, 1);
39 NewHandler->DisplayName = NewStrBufPlain(DisplayName, dslen);
40 StrBufShrinkToFit(NewHandler->DisplayName, 1);
41 Put(HandlerHash, UrlString, UrlSLen, NewHandler, DeleteWebcitHandler);
44 void tmplput_HANDLER_DISPLAYNAME(StrBuf *Target, WCTemplputParams *TP)
47 if (WCC->Hdr->HR.Handler != NULL)
48 StrBufAppendTemplate(Target, TP, WCC->Hdr->HR.Handler->DisplayName, 0);
51 * web-printing funcion. uses our vsnprintf wrapper
53 #ifdef UBER_VERBOSE_DEBUGGING
54 void wcc_printf(const char *FILE, const char *FUNCTION, long LINE, const char *format,...)
56 void wc_printf(const char *format,...)
62 if (WCC->WBuf == NULL)
63 WCC->WBuf = NewStrBuf();
64 #ifdef UBER_VERBOSE_DEBUGGING
65 StrBufAppendPrintf(WCC->WBuf, "\n%s:%s:%d[", FILE, FUNCTION, LINE);
68 va_start(arg_ptr, format);
69 StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
71 #ifdef UBER_VERBOSE_DEBUGGING
72 StrBufAppendPrintf(WCC->WBuf, "]\n");
77 * http-header-printing funcion. uses our vsnprintf wrapper
79 void hprintf(const char *format,...)
84 va_start(arg_ptr, format);
85 StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
92 * wrap up an HTTP session, closes tags, etc.
94 * print_standard_html_footer should be set to:
95 * 0 - to transmit only,
96 * nonzero - to append the closing tags
98 void wDumpContent(int print_standard_html_footer)
100 if (print_standard_html_footer) {
101 wc_printf("</div> <!-- end of 'content' div -->\n");
102 do_template("trailing", NULL);
105 /* If we've been saving it all up for one big output burst,
106 * go ahead and do that now.
115 * Output HTTP headers and leading HTML for a page
117 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
118 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
120 int do_room_banner, /* 0=no, 1=yes,
121 * 2 = I'm going to embed my own, so don't open the
122 * <div id="content"> either.
125 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
126 int suppress_check, /* 1 = suppress check for instant messages */
127 int cache /* 1 = allow browser to cache this page */
132 hprintf("HTTP/1.1 200 OK\n");
133 http_datestring(httpnow, sizeof httpnow, time(NULL));
135 if (do_httpheaders) {
136 if (WCC->serv_info != NULL)
137 hprintf("Content-type: text/html; charset=utf-8\r\n"
139 "Connection: close\r\n",
141 ChrPtr(WCC->serv_info->serv_software));
143 hprintf("Content-type: text/html; charset=utf-8\r\n"
144 "Server: %s / [n/a]\n"
145 "Connection: close\r\n",
150 char httpTomorow[128];
152 http_datestring(httpTomorow, sizeof httpTomorow,
153 time(NULL) + 60 * 60 * 24 * 2);
155 hprintf("Pragma: public\r\n"
156 "Cache-Control: max-age=3600, must-revalidate\r\n"
157 "Last-modified: %s\r\n"
164 hprintf("Pragma: no-cache\r\n"
165 "Cache-Control: no-store\r\n"
170 if (cache < 2) stuff_to_cookie(unset_cookies);
174 do_template("head", NULL);
176 /* check for ImportantMessages (these display in a div overlaying the main screen) */
177 if (!IsEmptyStr(WCC->ImportantMessage)) {
178 wc_printf("<div id=\"important_message\">\n"
179 "<span class=\"imsg\">");
180 StrEscAppend(WCC->WBuf, NULL, WCC->ImportantMessage, 0, 0);
181 wc_printf("</span><br />\n"
184 StrBufAppendBufPlain(WCC->trailing_javascript,
185 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
188 WCC->ImportantMessage[0] = 0;
190 else if (StrLength(WCC->ImportantMsg) > 0) {
191 wc_printf("<div id=\"important_message\">\n"
192 "<span class=\"imsg\">");
193 StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
194 wc_printf("</span><br />\n"
197 StrBufAppendBufPlain(WCC->trailing_javascript,
198 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
201 FlushStrBuf(WCC->ImportantMsg);
203 if ( (WCC->logged_in) && (!unset_cookies) ) {
204 DoTemplate(HKEY("paging"), NULL, &NoCtx);
207 if (do_room_banner == 1) {
208 wc_printf("<div id=\"banner\">\n");
209 embed_room_banner(NULL, navbar_default);
210 wc_printf("</div>\n");
214 if (do_room_banner == 1) {
215 wc_printf("<div id=\"content\">\n");
219 void output_custom_content_header(const char *ctype) {
220 hprintf("HTTP/1.1 200 OK\r\n");
221 hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
222 hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
223 hprintf("Connection: close\r\n");
228 * Generic function to do an HTTP redirect. Easy and fun.
230 void http_redirect(const char *whichpage) {
231 hprintf("HTTP/1.1 302 Moved Temporarily\n");
232 hprintf("Location: %s\r\n", whichpage);
233 hprintf("URI: %s\r\n", whichpage);
234 hprintf("Content-type: text/html; charset=utf-8\r\n");
236 wc_printf("<html><body>");
237 wc_printf("Go <a href=\"%s\">here</A>.", whichpage);
238 wc_printf("</body></html>\n");
245 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
247 void http_transmit_thing(const char *content_type,
251 lprintf(9, "http_transmit_thing(%s)%s\n",
253 ((is_static > 0) ? " (static)" : "")
256 output_headers(0, 0, 0, 0, 0, is_static);
258 hprintf("Content-type: %s\r\n"
260 "Connection: close\r\n",
269 * Convenience functions to display a page containing only a string
271 * titlebarcolor color of the titlebar of the frame
272 * titlebarmsg text to display in the title bar
273 * messagetext body of the box
275 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
277 hprintf("HTTP/1.1 200 OK\n");
278 output_headers(1, 1, 2, 0, 0, 0);
279 wc_printf("<div id=\"banner\">\n");
280 wc_printf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
281 wc_printf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
282 wc_printf("</td></tr></table>\n");
283 wc_printf("</div>\n<div id=\"content\">\n");
284 escputs(messagetext);
286 wc_printf("<hr />\n");
292 * Display a blank page.
294 void blank_page(void) {
295 output_headers(1, 1, 0, 0, 0, 0);
301 * A template has been requested
303 void url_do_template(void) {
304 const StrBuf *MimeType;
305 const StrBuf *Tmpl = sbstr("template");
307 MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
308 http_transmit_thing(ChrPtr(MimeType), 0);
314 * convenience function to indicate success
316 void display_success(char *successmessage)
318 convenience_page("007700", "OK", successmessage);
323 * Authorization required page
324 * This is probably temporary and should be revisited
326 void authorization_required(void)
329 const char *message = "";
331 hprintf("HTTP/1.1 401 Authorization Required\r\n");
333 "Server: %s / %s\r\n"
334 "Connection: close\r\n",
335 PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
337 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
338 hprintf("Content-Type: text/html\r\n");
341 wc_printf(_("Authorization Required"));
342 wc_printf("</h1>\r\n");
345 if (WCC->ImportantMsg != NULL)
346 message = ChrPtr(WCC->ImportantMsg);
347 else if (WCC->ImportantMessage != NULL)
348 message = WCC->ImportantMessage;
350 wc_printf(_("The resource you requested requires a valid username and password. "
351 "You could not be logged in: %s\n"), message);
353 end_webcit_session();
357 * Convenience functions to wrap around asynchronous ajax responses
359 void begin_ajax_response(void) {
362 FlushStrBuf(WCC->HBuf);
363 output_headers(0, 0, 0, 0, 0, 0);
365 hprintf("Content-type: text/html; charset=UTF-8\r\n"
367 "Connection: close\r\n"
374 * print ajax response footer
376 void end_ajax_response(void) {
383 * Wraps a Citadel server command in an AJAX transaction.
385 void ajax_servcmd(void)
393 begin_ajax_response();
395 serv_puts(bstr("g_cmd"));
396 StrBuf_ServGetln(Buf);
397 StrBufAppendBuf(WCC->WBuf, Buf, 0);
398 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
400 switch (GetServerStatus(Buf, NULL)) {
402 serv_puts("\n\n000");
403 if ( (StrLength(Buf)==3) &&
404 !strcmp(ChrPtr(Buf), "000")) {
405 StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
410 StrBuf_ServGetln(Buf);
411 if ( (StrLength(Buf)==3) &&
412 !strcmp(ChrPtr(Buf), "000")) {
415 StrBufAppendBuf(WCC->WBuf, Buf, 0);
416 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
420 text_to_server(bstr("g_input"));
424 len = atol(&ChrPtr(Buf)[4]);
425 StrBuf_ServGetBLOBBuffered(Buf, len);
428 len = atol(&ChrPtr(Buf)[4]);
430 memset(junk, 0, len);
431 serv_write(junk, len);
438 * This is kind of an ugly hack, but this is the only place it can go.
439 * If the command was GEXP, then the instant messenger window must be
440 * running, so reset the "last_pager_check" watchdog timer so
441 * that page_popup() doesn't try to open it a second time.
443 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
444 WCC->last_pager_check = time(NULL);
451 * Helper function for the asynchronous check to see if we need
452 * to open the instant messenger window.
454 void seconds_since_last_gexp(void)
458 if ( (time(NULL) - WC->last_pager_check) < 30) {
464 serv_getln(buf, sizeof buf);
476 void ReadPostData(void)
480 StrBuf *content = NULL;
482 content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
484 StrBufPrintf(content,
486 "Content-length: %ld\n\n",
487 ChrPtr(WCC->Hdr->HR.ContentType),
488 WCC->Hdr->HR.ContentLength);
490 hprintf("Content-type: %s\n"
491 "Content-length: %d\n\n",
492 ContentType, ContentLength);
494 body_start = StrLength(content);
496 /** Read the entire input data at once. */
497 client_read_to(WCC->Hdr, content,
498 WCC->Hdr->HR.ContentLength,
501 if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33)) {
502 StrBufCutLeft(content, body_start);
503 ParseURLParams(content);
504 } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
509 len = StrLength(content);
510 Buf = SmashStrBuf(&content);
512 mime_parser(Buf, BufEnd, *upload_handler, NULL, NULL, NULL, 0);
514 } else if (WCC->Hdr->HR.ContentLength > 0) {
515 WCC->upload = content;
516 WCC->upload_length = StrLength(WCC->upload);
519 FreeStrBuf(&content);
523 void ParseREST_URL(void)
526 StrBuf *pFloor = NULL;
529 const char *pCh = NULL;
533 lprintf(1, "parsing rest URL: %s\n", ChrPtr(WCC->Hdr->HR.ReqLine));
535 WCC->Directory = NewHash(1, Flathash);
536 WCC->CurrentFloor = NULL;
539 while (StrBufExtract_NextToken(Buf, WCC->Hdr->HR.ReqLine, &pCh, '/') >= 0)
541 if (StrLength(Buf) != 0) {
542 /* ignore empty path segments */
543 StrBufUnescape(Buf, 1);
544 Put(WCC->Directory, IKEY(i), Buf, HFreeStrBuf);
555 Floors = GetFloorListHash(NULL, NULL);
559 if (GetHash(WCC->FloorsByName, SKEY(pFloor), &vFloor))
560 WCC->CurrentFloor = (Floor*) vFloor;
565 int Conditional_REST_DEPTH(StrBuf *Target, WCTemplputParams *TP)
571 if (WCC->Hdr->HR.Handler != NULL)
573 Depth = GetTemplateTokenNumber(Target, TP, 2, 0);
574 IsDepth = GetCount(WCC->Directory) + offset;
576 // LogTemplateError(Target, "bla", 1, TP, "REST_DEPTH: %ld : %ld\n", Depth, IsDepth);
579 return IsDepth > Depth;
582 return Depth == IsDepth;
588 * Entry point for WebCit transaction
590 void session_loop(void)
597 * We stuff these with the values coming from the client cookies,
598 * so we can use them to reconnect a timed out session if we have to.
607 WCC->upload_length = 0;
610 WCC->trailing_javascript = NewStrBuf();
611 WCC->Hdr->nWildfireHeaders = 0;
612 if (WCC->Hdr->HR.Handler != NULL)
613 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
615 if (WCC->Hdr->HR.ContentLength > 0) {
619 /* If there are variables in the URL, we must grab them now */
620 if (WCC->Hdr->PlainArgs != NULL)
621 ParseURLParams(WCC->Hdr->PlainArgs);
623 /* If the client sent a nonce that is incorrect, kill the request. */
624 if (havebstr("nonce")) {
625 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
626 bstr("nonce"), WCC->nonce);
627 if (ibstr("nonce") != WCC->nonce) {
628 lprintf(9, "Ignoring request with mismatched nonce.\n");
629 hprintf("HTTP/1.1 404 Security check failed\r\n");
630 hprintf("Content-Type: text/plain\r\n");
632 wc_printf("Security check failed.\r\n");
634 goto SKIP_ALL_THIS_CRAP;
639 * If we're not connected to a Citadel server, try to hook up the
642 if (!WCC->connected) {
644 goto SKIP_ALL_THIS_CRAP;
649 * If we're not logged in, but we have authentication data (either from
650 * a cookie or from http-auth), try logging in to Citadel using that.
652 if ((!WCC->logged_in)
653 && (StrLength(WCC->Hdr->c_username) > 0)
654 && (StrLength(WCC->Hdr->c_password) > 0))
657 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
658 StrBuf_ServGetln(Buf);
659 if (GetServerStatus(Buf, NULL) == 3) {
660 serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
661 StrBuf_ServGetln(Buf);
662 if (GetServerStatus(Buf, NULL) == 2) {
663 become_logged_in(WCC->Hdr->c_username,
664 WCC->Hdr->c_password, Buf);
666 /* Should only display when password is wrong */
667 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
668 authorization_required();
670 goto SKIP_ALL_THIS_CRAP;
675 xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
676 (WCC->Hdr->HR.eReqType != ePOST) &&
677 (WCC->Hdr->HR.eReqType != eHEAD);
680 * If a 'gotofirst' parameter has been specified, attempt to goto that room
681 * prior to doing anything else.
683 if (havebstr("gotofirst")) {
685 ret = gotoroom(sbstr("gotofirst")); /* do quietly to avoid session output! */
686 if ((ret/100) != 2) {
687 lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
688 bstr("gotofirst"), ret);
693 * If we aren't in any room yet, but we have cookie data telling us where we're
694 * supposed to be, and 'gotofirst' was not specified, then go there.
696 else if ( (StrLength(WCC->CurRoom.name) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
699 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
700 ChrPtr(WCC->CurRoom.name),
701 ChrPtr(WCC->Hdr->c_roomname)
703 ret = gotoroom(WCC->Hdr->c_roomname); /* do quietly to avoid session output! */
704 if ((ret/100) != 2) {
705 lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
706 ChrPtr(WCC->Hdr->c_roomname), ret);
710 if (WCC->Hdr->HR.Handler != NULL) {
711 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
716 if ((WCC->Hdr->HR.Handler->Flags & PARSE_REST_URL) != 0)
719 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
720 begin_ajax_response();
721 WCC->Hdr->HR.Handler->F();
722 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
726 /* When all else fais, display the main menu. */
729 * ordinary browser users get a nice login screen, DAV etc. requsets
730 * are given a 401 so they can handle it appropriate.
732 if (!WCC->logged_in) {
734 authorization_required();
739 * Toplevel dav requests? or just a flat browser request?
756 * Replacement for sleep() that uses select() in order to avoid SIGALRM
758 void sleeeeeeeeeep(int seconds)
764 select(0, NULL, NULL, NULL, &tv);
767 int Conditional_IS_HTTPS(StrBuf *Target, WCTemplputParams *TP)
769 return is_https != 0;
772 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
776 return ((!IsEmptyStr(WCC->ImportantMessage)) ||
777 (StrLength(WCC->ImportantMsg) > 0));
782 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
787 if (!IsEmptyStr(WCC->ImportantMessage)) {
788 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
789 WCC->ImportantMessage[0] = '\0';
791 else if (StrLength(WCC->ImportantMsg) > 0) {
792 StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
793 FlushStrBuf(WCC->ImportantMsg);
798 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
803 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
806 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
808 StrBufAppendBuf(Target,
812 extern char static_local_dir[PATH_MAX];
820 WebcitAddUrlHandler(HKEY("blank"), "", 0, blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
821 WebcitAddUrlHandler(HKEY("do_template"), "", 0, url_do_template, ANONYMOUS);
822 WebcitAddUrlHandler(HKEY("sslg"), "", 0, seconds_since_last_gexp, AJAX|LOGCHATTY);
823 WebcitAddUrlHandler(HKEY("ajax_servcmd"), "", 0, ajax_servcmd, 0);
824 WebcitAddUrlHandler(HKEY("webcit"), "", 0, blank_page, URLNAMESPACE);
826 WebcitAddUrlHandler(HKEY("401"), "", 0, authorization_required, ANONYMOUS|COOKIEUNNEEDED);
827 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
828 RegisterConditional(HKEY("COND:REST:DEPTH"), 0, Conditional_REST_DEPTH, CTX_NONE);
829 RegisterConditional(HKEY("COND:IS_HTTPS"), 0, Conditional_IS_HTTPS, CTX_NONE);
831 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, NULL, CTX_NONE);
832 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, NULL, CTX_NONE);
833 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, NULL, CTX_NONE);
834 RegisterNamespace("URL:DISPLAYNAME", 0, 1, tmplput_HANDLER_DISPLAYNAME, NULL, CTX_NONE);
836 snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
837 if (!access(dir, R_OK)) {
838 lprintf(9, "Using local Stylesheet [%s]\n", dir);
839 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\" />"));
842 lprintf(9, "No Site-local Stylesheet [%s] installed. \n", dir);
847 ServerStartModule_WEBCIT
850 HandlerHash = NewHash(1, NULL);
855 ServerShutdownModule_WEBCIT
858 FreeStrBuf(&csslocal);
859 DeleteHash(&HandlerHash);
865 SessionNewModule_WEBCIT
868 sess->ImportantMsg = NewStrBuf();
869 sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
870 sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
874 SessionDetachModule_WEBCIT
877 DeleteHash(&sess->Directory);
879 FreeStrBuf(&sess->upload);
880 sess->upload_length = 0;
882 FreeStrBuf(&sess->trailing_javascript);
884 if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
886 FreeStrBuf(&sess->WBuf);
887 sess->WBuf = NewStrBuf();
890 FlushStrBuf(sess->WBuf);
891 FlushStrBuf(sess->HBuf);
895 SessionDestroyModule_WEBCIT
898 FreeStrBuf(&sess->WBuf);
899 FreeStrBuf(&sess->HBuf);
900 FreeStrBuf(&sess->ImportantMsg);