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);
46 * web-printing funcion. uses our vsnprintf wrapper
48 void wc_printf(const char *format,...)
53 if (WCC->WBuf == NULL)
54 WCC->WBuf = NewStrBuf();
56 va_start(arg_ptr, format);
57 StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
62 * http-header-printing funcion. uses our vsnprintf wrapper
64 void hprintf(const char *format,...)
69 va_start(arg_ptr, format);
70 StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
77 * wrap up an HTTP session, closes tags, etc.
79 * print_standard_html_footer should be set to:
80 * 0 - to transmit only,
81 * nonzero - to append the closing tags
83 void wDumpContent(int print_standard_html_footer)
85 if (print_standard_html_footer) {
86 wc_printf("</div> <!-- end of 'content' div -->\n");
87 do_template("trailing", NULL);
90 /* If we've been saving it all up for one big output burst,
91 * go ahead and do that now.
100 * Output HTTP headers and leading HTML for a page
102 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
103 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
105 int do_room_banner, /* 0=no, 1=yes,
106 * 2 = I'm going to embed my own, so don't open the
107 * <div id="content"> either.
110 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
111 int suppress_check, /* 1 = suppress check for instant messages */
112 int cache /* 1 = allow browser to cache this page */
117 hprintf("HTTP/1.1 200 OK\n");
118 http_datestring(httpnow, sizeof httpnow, time(NULL));
120 if (do_httpheaders) {
121 if (WCC->serv_info != NULL)
122 hprintf("Content-type: text/html; charset=utf-8\r\n"
124 "Connection: close\r\n",
126 ChrPtr(WCC->serv_info->serv_software));
128 hprintf("Content-type: text/html; charset=utf-8\r\n"
129 "Server: %s / [n/a]\n"
130 "Connection: close\r\n",
135 char httpTomorow[128];
137 http_datestring(httpTomorow, sizeof httpTomorow,
138 time(NULL) + 60 * 60 * 24 * 2);
140 hprintf("Pragma: public\r\n"
141 "Cache-Control: max-age=3600, must-revalidate\r\n"
142 "Last-modified: %s\r\n"
149 hprintf("Pragma: no-cache\r\n"
150 "Cache-Control: no-store\r\n"
155 if (cache < 2) stuff_to_cookie(unset_cookies);
159 do_template("head", NULL);
161 /* check for ImportantMessages (these display in a div overlaying the main screen) */
162 if (!IsEmptyStr(WCC->ImportantMessage)) {
163 wc_printf("<div id=\"important_message\">\n"
164 "<span class=\"imsg\">");
165 StrEscAppend(WCC->WBuf, NULL, WCC->ImportantMessage, 0, 0);
166 wc_printf("</span><br />\n"
169 StrBufAppendBufPlain(WCC->trailing_javascript,
170 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
173 WCC->ImportantMessage[0] = 0;
175 else if (StrLength(WCC->ImportantMsg) > 0) {
176 wc_printf("<div id=\"important_message\">\n"
177 "<span class=\"imsg\">");
178 StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
179 wc_printf("</span><br />\n"
182 StrBufAppendBufPlain(WCC->trailing_javascript,
183 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
186 FlushStrBuf(WCC->ImportantMsg);
188 if ( (WCC->logged_in) && (!unset_cookies) ) {
189 DoTemplate(HKEY("paging"), NULL, &NoCtx);
192 if (do_room_banner == 1) {
193 wc_printf("<div id=\"banner\">\n");
194 embed_room_banner(NULL, navbar_default);
195 wc_printf("</div>\n");
199 if (do_room_banner == 1) {
200 wc_printf("<div id=\"content\">\n");
204 void output_custom_content_header(const char *ctype) {
205 hprintf("HTTP/1.1 200 OK\r\n");
206 hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
207 hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
208 hprintf("Connection: close\r\n");
213 * Generic function to do an HTTP redirect. Easy and fun.
215 void http_redirect(const char *whichpage) {
216 hprintf("HTTP/1.1 302 Moved Temporarily\n");
217 hprintf("Location: %s\r\n", whichpage);
218 hprintf("URI: %s\r\n", whichpage);
219 hprintf("Content-type: text/html; charset=utf-8\r\n");
221 wc_printf("<html><body>");
222 wc_printf("Go <a href=\"%s\">here</A>.", whichpage);
223 wc_printf("</body></html>\n");
230 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
232 void http_transmit_thing(const char *content_type,
236 lprintf(9, "http_transmit_thing(%s)%s\n",
238 ((is_static > 0) ? " (static)" : "")
241 output_headers(0, 0, 0, 0, 0, is_static);
243 hprintf("Content-type: %s\r\n"
245 "Connection: close\r\n",
254 * Convenience functions to display a page containing only a string
256 * titlebarcolor color of the titlebar of the frame
257 * titlebarmsg text to display in the title bar
258 * messagetext body of the box
260 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
262 hprintf("HTTP/1.1 200 OK\n");
263 output_headers(1, 1, 2, 0, 0, 0);
264 wc_printf("<div id=\"banner\">\n");
265 wc_printf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
266 wc_printf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
267 wc_printf("</td></tr></table>\n");
268 wc_printf("</div>\n<div id=\"content\">\n");
269 escputs(messagetext);
271 wc_printf("<hr />\n");
277 * Display a blank page.
279 void blank_page(void) {
280 output_headers(1, 1, 0, 0, 0, 0);
286 * A template has been requested
288 void url_do_template(void) {
289 const StrBuf *MimeType;
290 const StrBuf *Tmpl = sbstr("template");
292 MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
293 http_transmit_thing(ChrPtr(MimeType), 0);
299 * convenience function to indicate success
301 void display_success(char *successmessage)
303 convenience_page("007700", "OK", successmessage);
308 * Authorization required page
309 * This is probably temporary and should be revisited
311 void authorization_required(void)
314 const char *message = "";
316 hprintf("HTTP/1.1 401 Authorization Required\r\n");
318 "Server: %s / %s\r\n"
319 "Connection: close\r\n",
320 PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
322 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
323 hprintf("Content-Type: text/html\r\n");
326 wc_printf(_("Authorization Required"));
327 wc_printf("</h1>\r\n");
330 if (WCC->ImportantMsg != NULL)
331 message = ChrPtr(WCC->ImportantMsg);
332 else if (WCC->ImportantMessage != NULL)
333 message = WCC->ImportantMessage;
335 wc_printf(_("The resource you requested requires a valid username and password. "
336 "You could not be logged in: %s\n"), message);
338 end_webcit_session();
342 * Convenience functions to wrap around asynchronous ajax responses
344 void begin_ajax_response(void) {
347 FlushStrBuf(WCC->HBuf);
348 output_headers(0, 0, 0, 0, 0, 0);
350 hprintf("Content-type: text/html; charset=UTF-8\r\n"
352 "Connection: close\r\n"
359 * print ajax response footer
361 void end_ajax_response(void) {
368 * Wraps a Citadel server command in an AJAX transaction.
370 void ajax_servcmd(void)
378 begin_ajax_response();
380 serv_puts(bstr("g_cmd"));
381 StrBuf_ServGetln(Buf);
382 StrBufAppendBuf(WCC->WBuf, Buf, 0);
383 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
385 switch (GetServerStatus(Buf, NULL)) {
387 serv_puts("\n\n000");
388 if ( (StrLength(Buf)==3) &&
389 !strcmp(ChrPtr(Buf), "000")) {
390 StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
395 StrBuf_ServGetln(Buf);
396 if ( (StrLength(Buf)==3) &&
397 !strcmp(ChrPtr(Buf), "000")) {
400 StrBufAppendBuf(WCC->WBuf, Buf, 0);
401 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
405 text_to_server(bstr("g_input"));
409 len = atol(&ChrPtr(Buf)[4]);
410 StrBuf_ServGetBLOBBuffered(Buf, len);
413 len = atol(&ChrPtr(Buf)[4]);
415 memset(junk, 0, len);
416 serv_write(junk, len);
423 * This is kind of an ugly hack, but this is the only place it can go.
424 * If the command was GEXP, then the instant messenger window must be
425 * running, so reset the "last_pager_check" watchdog timer so
426 * that page_popup() doesn't try to open it a second time.
428 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
429 WCC->last_pager_check = time(NULL);
436 * Helper function for the asynchronous check to see if we need
437 * to open the instant messenger window.
439 void seconds_since_last_gexp(void)
443 if ( (time(NULL) - WC->last_pager_check) < 30) {
449 serv_getln(buf, sizeof buf);
461 void ReadPostData(void)
465 StrBuf *content = NULL;
467 content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
469 StrBufPrintf(content,
471 "Content-length: %ld\n\n",
472 ChrPtr(WCC->Hdr->HR.ContentType),
473 WCC->Hdr->HR.ContentLength);
475 hprintf("Content-type: %s\n"
476 "Content-length: %d\n\n",
477 ContentType, ContentLength);
479 body_start = StrLength(content);
481 /** Read the entire input data at once. */
482 client_read_to(WCC->Hdr, content,
483 WCC->Hdr->HR.ContentLength,
486 if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33)) {
487 StrBufCutLeft(content, body_start);
488 ParseURLParams(content);
489 } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
494 len = StrLength(content);
495 Buf = SmashStrBuf(&content);
497 mime_parser(Buf, BufEnd, *upload_handler, NULL, NULL, NULL, 0);
499 } else if (WCC->Hdr->HR.ContentLength > 0) {
500 WCC->upload = content;
501 WCC->upload_length = StrLength(WCC->upload);
504 FreeStrBuf(&content);
508 void ParseREST_URL(void)
511 StrBuf *pFloor = NULL;
514 const char *pCh = NULL;
518 WCC->Directory = NewHash(1, Flathash);
521 while (StrBufExtract_NextToken(WCC->Hdr->HR.ReqLine,
522 Buf, &pCh, '/') >= 0)
524 Put(WCC->Directory, IKEY(i), Buf, HFreeStrBuf);
532 else if (pFloor != NULL)
534 Floors = GetFloorListHash(NULL, NULL);
538 if (GetHash(Floors, SKEY(pFloor), &vFloor))
539 WCC->CurrentFloor = (floor*) vFloor;
548 * Entry point for WebCit transaction
550 void session_loop(void)
557 * We stuff these with the values coming from the client cookies,
558 * so we can use them to reconnect a timed out session if we have to.
567 WCC->upload_length = 0;
570 WCC->trailing_javascript = NewStrBuf();
571 WCC->Hdr->nWildfireHeaders = 0;
572 if (WCC->Hdr->HR.Handler != NULL)
573 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
575 if (WCC->Hdr->HR.ContentLength > 0) {
579 /* If there are variables in the URL, we must grab them now */
580 if (WCC->Hdr->PlainArgs != NULL)
581 ParseURLParams(WCC->Hdr->PlainArgs);
583 /* If the client sent a nonce that is incorrect, kill the request. */
584 if (havebstr("nonce")) {
585 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
586 bstr("nonce"), WCC->nonce);
587 if (ibstr("nonce") != WCC->nonce) {
588 lprintf(9, "Ignoring request with mismatched nonce.\n");
589 hprintf("HTTP/1.1 404 Security check failed\r\n");
590 hprintf("Content-Type: text/plain\r\n");
592 wc_printf("Security check failed.\r\n");
594 goto SKIP_ALL_THIS_CRAP;
599 * If we're not connected to a Citadel server, try to hook up the
602 if (!WCC->connected) {
604 goto SKIP_ALL_THIS_CRAP;
609 * If we're not logged in, but we have authentication data (either from
610 * a cookie or from http-auth), try logging in to Citadel using that.
612 if ((!WCC->logged_in)
613 && (StrLength(WCC->Hdr->c_username) > 0)
614 && (StrLength(WCC->Hdr->c_password) > 0))
617 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
618 StrBuf_ServGetln(Buf);
619 if (GetServerStatus(Buf, NULL) == 3) {
620 serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
621 StrBuf_ServGetln(Buf);
622 if (GetServerStatus(Buf, NULL) == 2) {
623 become_logged_in(WCC->Hdr->c_username,
624 WCC->Hdr->c_password, Buf);
626 /* Should only display when password is wrong */
627 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
628 authorization_required();
630 goto SKIP_ALL_THIS_CRAP;
635 xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
636 (WCC->Hdr->HR.eReqType != ePOST) &&
637 (WCC->Hdr->HR.eReqType != eHEAD);
640 * If a 'gotofirst' parameter has been specified, attempt to goto that room
641 * prior to doing anything else.
643 if (havebstr("gotofirst")) {
645 ret = gotoroom(sbstr("gotofirst")); /* do quietly to avoid session output! */
646 if ((ret/100) != 2) {
647 lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
648 bstr("gotofirst"), ret);
653 * If we aren't in any room yet, but we have cookie data telling us where we're
654 * supposed to be, and 'gotofirst' was not specified, then go there.
656 else if ( (StrLength(WCC->CurRoom.name) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
659 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
660 ChrPtr(WCC->CurRoom.name),
661 ChrPtr(WCC->Hdr->c_roomname)
663 ret = gotoroom(WCC->Hdr->c_roomname); /* do quietly to avoid session output! */
664 if ((ret/100) != 2) {
665 lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
666 ChrPtr(WCC->Hdr->c_roomname), ret);
670 if (WCC->Hdr->HR.Handler != NULL) {
671 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
676 if ((WCC->Hdr->HR.Handler->Flags & PARSE_REST_URL) != 0)
679 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
680 begin_ajax_response();
681 WCC->Hdr->HR.Handler->F();
682 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
686 /* When all else fais, display the main menu. */
689 * ordinary browser users get a nice login screen, DAV etc. requsets
690 * are given a 401 so they can handle it appropriate.
692 if (!WCC->logged_in) {
694 authorization_required();
699 * Toplevel dav requests? or just a flat browser request?
716 * Replacement for sleep() that uses select() in order to avoid SIGALRM
718 void sleeeeeeeeeep(int seconds)
724 select(0, NULL, NULL, NULL, &tv);
728 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
732 return ((!IsEmptyStr(WCC->ImportantMessage)) ||
733 (StrLength(WCC->ImportantMsg) > 0));
738 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
743 if (!IsEmptyStr(WCC->ImportantMessage)) {
744 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
745 WCC->ImportantMessage[0] = '\0';
747 else if (StrLength(WCC->ImportantMsg) > 0) {
748 StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
749 FlushStrBuf(WCC->ImportantMsg);
754 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
759 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
762 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
764 StrBufAppendBuf(Target,
768 extern char static_local_dir[PATH_MAX];
776 WebcitAddUrlHandler(HKEY("blank"), "", 0, blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
777 WebcitAddUrlHandler(HKEY("do_template"), "", 0, url_do_template, ANONYMOUS);
778 WebcitAddUrlHandler(HKEY("sslg"), "", 0, seconds_since_last_gexp, AJAX|LOGCHATTY);
779 WebcitAddUrlHandler(HKEY("ajax_servcmd"), "", 0, ajax_servcmd, 0);
780 WebcitAddUrlHandler(HKEY("webcit"), "", 0, blank_page, URLNAMESPACE);
782 WebcitAddUrlHandler(HKEY("401"), "", 0, authorization_required, ANONYMOUS|COOKIEUNNEEDED);
783 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
784 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, NULL, CTX_NONE);
785 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, NULL, CTX_NONE);
786 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, NULL, CTX_NONE);
788 snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
789 if (!access(dir, R_OK)) {
790 lprintf(9, "Using local Stylesheet [%s]\n", dir);
791 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\" />"));
794 lprintf(9, "No Site-local Stylesheet [%s] installed. \n", dir);
799 ServerStartModule_WEBCIT
802 HandlerHash = NewHash(1, NULL);
807 ServerShutdownModule_WEBCIT
810 FreeStrBuf(&csslocal);
811 DeleteHash(&HandlerHash);
817 SessionNewModule_WEBCIT
820 sess->ImportantMsg = NewStrBuf();
821 sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
822 sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
826 SessionDetachModule_WEBCIT
829 DeleteHash(&sess->Directory);
831 FreeStrBuf(&sess->upload);
832 sess->upload_length = 0;
834 FreeStrBuf(&sess->trailing_javascript);
836 if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
838 FreeStrBuf(&sess->WBuf);
839 sess->WBuf = NewStrBuf();
842 FlushStrBuf(sess->WBuf);
843 FlushStrBuf(sess->HBuf);
847 SessionDestroyModule_WEBCIT
850 FreeStrBuf(&sess->WBuf);
851 FreeStrBuf(&sess->HBuf);
852 FreeStrBuf(&sess->ImportantMsg);