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"
17 * String to unset the cookie.
18 * Any date "in the past" will work, so I chose my birthday, right down to
19 * the exact minute. :)
21 static char *unset = "; expires=28-May-1971 18:10:00 GMT";
22 StrBuf *csslocal = NULL;
23 HashList *HandlerHash = NULL;
26 void DeleteWebcitHandler(void *vHandler)
28 WebcitHandler *Handler = (WebcitHandler*) vHandler;
29 FreeStrBuf(&Handler->Name);
34 void WebcitAddUrlHandler(const char * UrlString,
39 WebcitHandler *NewHandler;
40 NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
42 NewHandler->Flags = Flags;
43 NewHandler->Name = NewStrBufPlain(UrlString, UrlSLen);
44 StrBufShrinkToFit(NewHandler->Name, 1);
45 Put(HandlerHash, UrlString, UrlSLen, NewHandler, DeleteWebcitHandler);
50 * web-printing funcion. uses our vsnprintf wrapper
52 void wprintf(const char *format,...)
57 if (WCC->WBuf == NULL)
58 WCC->WBuf = NewStrBuf();
60 va_start(arg_ptr, format);
61 StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
66 * http-header-printing funcion. uses our vsnprintf wrapper
68 void hprintf(const char *format,...)
73 va_start(arg_ptr, format);
74 StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
81 * wrap up an HTTP session, closes tags, etc.
83 * print_standard_html_footer should be set to:
84 * 0 - to transmit only,
85 * nonzero - to append the closing tags
87 void wDumpContent(int print_standard_html_footer)
89 if (print_standard_html_footer) {
90 wprintf("</div> <!-- end of 'content' div -->\n");
91 do_template("trailing", NULL);
94 /* If we've been saving it all up for one big output burst,
95 * go ahead and do that now.
104 * Output HTTP headers and leading HTML for a page
106 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
107 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
109 int do_room_banner, /* 0=no, 1=yes,
110 * 2 = I'm going to embed my own, so don't open the
111 * <div id="content"> either.
114 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
115 int suppress_check, /* 1 = suppress check for instant messages */
116 int cache /* 1 = allow browser to cache this page */
122 hprintf("HTTP/1.1 200 OK\n");
123 http_datestring(httpnow, sizeof httpnow, time(NULL));
125 if (do_httpheaders) {
126 if (WCC->serv_info != NULL)
127 hprintf("Content-type: text/html; charset=utf-8\r\n"
129 "Connection: close\r\n",
131 ChrPtr(WCC->serv_info->serv_software));
133 hprintf("Content-type: text/html; charset=utf-8\r\n"
134 "Server: %s / [n/a]\n"
135 "Connection: close\r\n",
140 char httpTomorow[128];
142 http_datestring(httpTomorow, sizeof httpTomorow,
143 time(NULL) + 60 * 60 * 24 * 2);
145 hprintf("Pragma: public\r\n"
146 "Cache-Control: max-age=3600, must-revalidate\r\n"
147 "Last-modified: %s\r\n"
154 hprintf("Pragma: no-cache\r\n"
155 "Cache-Control: no-store\r\n"
162 stuff_to_cookie(cookie, 1024,
167 get_selected_language()
171 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
173 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
174 if (server_cookie != NULL) {
175 hprintf("%s\n", server_cookie);
182 do_template("head", NULL);
184 /* check for ImportantMessages (these display in a div overlaying the main screen) */
185 if (!IsEmptyStr(WCC->ImportantMessage)) {
186 wprintf("<div id=\"important_message\">\n"
187 "<span class=\"imsg\">");
188 StrEscAppend(WCC->WBuf, NULL, WCC->ImportantMessage, 0, 0);
189 wprintf("</span><br />\n"
192 StrBufAppendBufPlain(WCC->trailing_javascript,
193 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
196 WCC->ImportantMessage[0] = 0;
198 else if (StrLength(WCC->ImportantMsg) > 0) {
199 wprintf("<div id=\"important_message\">\n"
200 "<span class=\"imsg\">");
201 StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
202 wprintf("</span><br />\n"
205 StrBufAppendBufPlain(WCC->trailing_javascript,
206 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
209 FlushStrBuf(WCC->ImportantMsg);
211 if ( (WCC->logged_in) && (!unset_cookies) ) {
212 /*DoTemplate(HKEY("iconbar"), NULL, &NoCtx);*/
216 if (do_room_banner == 1) {
217 wprintf("<div id=\"banner\">\n");
218 embed_room_banner(NULL, navbar_default);
223 if (do_room_banner == 1) {
224 wprintf("<div id=\"content\">\n");
228 void output_custom_content_header(const char *ctype) {
229 hprintf("HTTP/1.1 200 OK\r\n");
230 hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
231 hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
232 hprintf("Connection: close\r\n");
237 * Generic function to do an HTTP redirect. Easy and fun.
239 void http_redirect(const char *whichpage) {
240 hprintf("HTTP/1.1 302 Moved Temporarily\n");
241 hprintf("Location: %s\r\n", whichpage);
242 hprintf("URI: %s\r\n", whichpage);
243 hprintf("Content-type: text/html; charset=utf-8\r\n");
244 wprintf("<html><body>");
245 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
246 wprintf("</body></html>\n");
253 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
255 void http_transmit_thing(const char *content_type,
259 lprintf(9, "http_transmit_thing(%s)%s\n",
261 ((is_static > 0) ? " (static)" : "")
264 output_headers(0, 0, 0, 0, 0, is_static);
266 hprintf("Content-type: %s\r\n"
268 "Connection: close\r\n",
276 * print menu box like used in the floor view or admin interface.
277 * This function takes pair of strings as va_args,
278 * Title Title string of the box
279 * Class CSS Class for the box
280 * nLines How many string pairs should we print? (URL, UrlText)
281 * ... Pairs of URL Strings and their Names
283 void print_menu_box(char* Title, char *Class, int nLines, ...)
288 svput("BOXTITLE", WCS_STRING, Title);
289 do_template("beginboxx", NULL);
291 wprintf("<ul class=\"%s\">", Class);
293 va_start(arg_list, nLines);
294 for (i = 0; i < nLines; ++i)
296 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
297 wprintf((char *) va_arg(arg_list, char *));
298 wprintf("</a></li>\n");
302 wprintf("</a></li>\n");
306 do_template("endbox", NULL);
312 * Convenience functions to display a page containing only a string
314 * titlebarcolor color of the titlebar of the frame
315 * titlebarmsg text to display in the title bar
316 * messagetext body of the box
318 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
320 hprintf("HTTP/1.1 200 OK\n");
321 output_headers(1, 1, 2, 0, 0, 0);
322 wprintf("<div id=\"banner\">\n");
323 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
324 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
325 wprintf("</td></tr></table>\n");
326 wprintf("</div>\n<div id=\"content\">\n");
327 escputs(messagetext);
335 * Display a blank page.
337 void blank_page(void) {
338 output_headers(1, 1, 0, 0, 0, 0);
344 * A template has been requested
346 void url_do_template(void) {
347 const StrBuf *MimeType;
348 const StrBuf *Tmpl = sbstr("template");
350 MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
351 http_transmit_thing(ChrPtr(MimeType), 0);
357 * convenience function to indicate success
359 void display_success(char *successmessage)
361 convenience_page("007700", "OK", successmessage);
366 * Authorization required page
367 * This is probably temporary and should be revisited
369 void authorization_required(void)
372 const char *message = "";
374 hprintf("HTTP/1.1 401 Authorization Required\r\n");
376 "Server: %s / %s\r\n"
377 "Connection: close\r\n",
378 PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
380 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
381 hprintf("Content-Type: text/html\r\n");
383 wprintf(_("Authorization Required"));
384 wprintf("</h1>\r\n");
387 if (WCC->ImportantMsg != NULL)
388 message = ChrPtr(WCC->ImportantMsg);
389 else if (WCC->ImportantMessage != NULL)
390 message = WCC->ImportantMessage;
392 wprintf(_("The resource you requested requires a valid username and password. "
393 "You could not be logged in: %s\n"), message);
399 * Convenience functions to wrap around asynchronous ajax responses
401 void begin_ajax_response(void) {
404 FlushStrBuf(WCC->HBuf);
405 output_headers(0, 0, 0, 0, 0, 0);
407 hprintf("Content-type: text/html; charset=UTF-8\r\n"
409 "Connection: close\r\n"
416 * print ajax response footer
418 void end_ajax_response(void) {
425 * Wraps a Citadel server command in an AJAX transaction.
427 void ajax_servcmd(void)
435 begin_ajax_response();
437 serv_puts(bstr("g_cmd"));
438 StrBuf_ServGetln(Buf);
439 StrBufAppendBuf(WCC->WBuf, Buf, 0);
440 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
442 switch (GetServerStatus(Buf, NULL)) {
444 serv_puts("\n\n000");
445 if ( (StrLength(Buf)==3) &&
446 !strcmp(ChrPtr(Buf), "000")) {
447 StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
452 StrBuf_ServGetln(Buf);
453 if ( (StrLength(Buf)==3) &&
454 !strcmp(ChrPtr(Buf), "000")) {
457 StrBufAppendBuf(WCC->WBuf, Buf, 0);
458 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
462 text_to_server(bstr("g_input"));
466 len = atol(&ChrPtr(Buf)[4]);
467 StrBuf_ServGetBLOBBuffered(Buf, len);
470 len = atol(&ChrPtr(Buf)[4]);
472 memset(junk, 0, len);
473 serv_write(junk, len);
480 * This is kind of an ugly hack, but this is the only place it can go.
481 * If the command was GEXP, then the instant messenger window must be
482 * running, so reset the "last_pager_check" watchdog timer so
483 * that page_popup() doesn't try to open it a second time.
485 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
486 WCC->last_pager_check = time(NULL);
493 * Helper function for the asynchronous check to see if we need
494 * to open the instant messenger window.
496 void seconds_since_last_gexp(void)
500 if ( (time(NULL) - WC->last_pager_check) < 30) {
506 serv_getln(buf, sizeof buf);
518 void ReadPostData(void)
520 const char *content_end = NULL;
523 StrBuf *content = NULL;
525 content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
527 StrBufPrintf(content,
529 "Content-length: %ld\n\n",
530 ChrPtr(WCC->Hdr->HR.ContentType),
531 WCC->Hdr->HR.ContentLength);
533 hprintf("Content-type: %s\n"
534 "Content-length: %d\n\n",
535 ContentType, ContentLength);
537 body_start = StrLength(content);
539 /** Read the entire input data at once. */
540 client_read_to(WCC->Hdr, content,
541 WCC->Hdr->HR.ContentLength,
544 if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33)) {
545 StrBufCutLeft(content, body_start);
546 ParseURLParams(content);
547 } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
548 content_end = ChrPtr(content) +
549 WCC->Hdr->HR.ContentLength +
551 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
552 } else if (WCC->Hdr->HR.ContentLength > 0) {
553 WCC->upload = content;
556 FreeStrBuf(&content);
561 * Entry point for WebCit transaction
563 void session_loop(void)
570 * We stuff these with the values coming from the client cookies,
571 * so we can use them to reconnect a timed out session if we have to.
580 WCC->upload_length = 0;
583 WCC->trailing_javascript = NewStrBuf();
584 WCC->Hdr->nWildfireHeaders = 0;
585 if (WCC->Hdr->HR.Handler != NULL)
586 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
588 if (WCC->Hdr->HR.ContentLength > 0) {
592 /* If there are variables in the URL, we must grab them now */
593 if (WCC->Hdr->PlainArgs != NULL)
594 ParseURLParams(WCC->Hdr->PlainArgs);
596 /* If the client sent a nonce that is incorrect, kill the request. */
597 if (havebstr("nonce")) {
598 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
599 bstr("nonce"), WCC->nonce);
600 if (ibstr("nonce") != WCC->nonce) {
601 lprintf(9, "Ignoring request with mismatched nonce.\n");
602 hprintf("HTTP/1.1 404 Security check failed\r\n");
603 hprintf("Content-Type: text/plain\r\n\r\n");
604 wprintf("Security check failed.\r\n");
606 goto SKIP_ALL_THIS_CRAP;
611 * If we're not connected to a Citadel server, try to hook up the
614 if (!WCC->connected) {
616 goto SKIP_ALL_THIS_CRAP;
621 * If we're not logged in, but we have authentication data (either from
622 * a cookie or from http-auth), try logging in to Citadel using that.
624 if ((!WCC->logged_in)
625 && (StrLength(WCC->Hdr->c_username) > 0)
626 && (StrLength(WCC->Hdr->c_password) > 0))
629 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
630 StrBuf_ServGetln(Buf);
631 if (GetServerStatus(Buf, NULL) == 3) {
632 serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
633 StrBuf_ServGetln(Buf);
634 if (GetServerStatus(Buf, NULL) == 2) {
635 become_logged_in(WCC->Hdr->c_username,
636 WCC->Hdr->c_password, Buf);
638 /* Should only display when password is wrong */
639 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
640 authorization_required();
642 goto SKIP_ALL_THIS_CRAP;
647 xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
648 (WCC->Hdr->HR.eReqType != ePOST) &&
649 (WCC->Hdr->HR.eReqType != eHEAD);
652 * If a 'gotofirst' parameter has been specified, attempt to goto that room
653 * prior to doing anything else.
655 if (havebstr("gotofirst")) {
657 ret = gotoroom(sbstr("gotofirst")); /* do quietly to avoid session output! */
658 if ((ret/100) != 2) {
659 lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
660 bstr("gotofirst"), ret);
665 * If we aren't in any room yet, but we have cookie data telling us where we're
666 * supposed to be, and 'gotofirst' was not specified, then go there.
668 else if ( (StrLength(WCC->wc_roomname) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
671 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
672 ChrPtr(WCC->wc_roomname),
673 ChrPtr(WCC->Hdr->c_roomname)
675 ret = gotoroom(WCC->Hdr->c_roomname); /* do quietly to avoid session output! */
676 if ((ret/100) != 2) {
677 lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
678 ChrPtr(WCC->Hdr->c_roomname), ret);
682 if (WCC->Hdr->HR.Handler != NULL) {
683 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
687 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
688 begin_ajax_response();
689 WCC->Hdr->HR.Handler->F();
690 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
694 /* When all else fais, display the main menu. */
697 * ordinary browser users get a nice login screen, DAV etc. requsets
698 * are given a 401 so they can handle it appropriate.
700 if (!WCC->logged_in) {
702 authorization_required();
707 * Toplevel dav requests? or just a flat browser request?
724 * Replacement for sleep() that uses select() in order to avoid SIGALRM
726 void sleeeeeeeeeep(int seconds)
732 select(0, NULL, NULL, NULL, &tv);
736 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
740 return ((!IsEmptyStr(WCC->ImportantMessage)) ||
741 (StrLength(WCC->ImportantMsg) > 0));
746 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
751 if (!IsEmptyStr(WCC->ImportantMessage)) {
752 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
753 WCC->ImportantMessage[0] = '\0';
755 else if (StrLength(WCC->ImportantMsg) > 0) {
756 StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
757 FlushStrBuf(WCC->ImportantMsg);
762 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
767 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
770 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
772 StrBufAppendBuf(Target,
776 extern char static_local_dir[PATH_MAX];
784 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
785 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
786 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX|LOGCHATTY);
787 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
788 WebcitAddUrlHandler(HKEY("webcit"), blank_page, URLNAMESPACE);
790 WebcitAddUrlHandler(HKEY("401"), authorization_required, ANONYMOUS|COOKIEUNNEEDED);
791 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
792 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
793 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
794 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
796 snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
797 if (!access(dir, R_OK)) {
798 lprintf(9, "Using local Stylesheet [%s]\n", dir);
799 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
802 lprintf(9, "Didn't find site local Stylesheet [%s]\n", dir);
807 ServerStartModule_WEBCIT
810 HandlerHash = NewHash(1, NULL);
815 ServerShutdownModule_WEBCIT
818 FreeStrBuf(&csslocal);
819 DeleteHash(&HandlerHash);
825 SessionNewModule_WEBCIT
828 sess->ImportantMsg = NewStrBuf();
829 sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
830 sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
834 SessionDetachModule_WEBCIT
837 DeleteHash(&sess->Hdr->urlstrings);// TODO?
838 if (sess->upload_length > 0) {
839 FreeStrBuf(&sess->upload);
840 sess->upload_length = 0;
842 FreeStrBuf(&sess->trailing_javascript);
844 if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
846 FreeStrBuf(&sess->WBuf);
847 sess->WBuf = NewStrBuf();
850 FlushStrBuf(sess->WBuf);
851 FlushStrBuf(sess->HBuf);
855 SessionDestroyModule_WEBCIT
858 FreeStrBuf(&sess->WBuf);
859 FreeStrBuf(&sess->HBuf);
860 FreeStrBuf(&sess->ImportantMsg);