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");
245 wprintf("<html><body>");
246 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
247 wprintf("</body></html>\n");
254 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
256 void http_transmit_thing(const char *content_type,
260 lprintf(9, "http_transmit_thing(%s)%s\n",
262 ((is_static > 0) ? " (static)" : "")
265 output_headers(0, 0, 0, 0, 0, is_static);
267 hprintf("Content-type: %s\r\n"
269 "Connection: close\r\n",
277 * print menu box like used in the floor view or admin interface.
278 * This function takes pair of strings as va_args,
279 * Title Title string of the box
280 * Class CSS Class for the box
281 * nLines How many string pairs should we print? (URL, UrlText)
282 * ... Pairs of URL Strings and their Names
284 void print_menu_box(char* Title, char *Class, int nLines, ...)
289 svput("BOXTITLE", WCS_STRING, Title);
290 do_template("beginboxx", NULL);
292 wprintf("<ul class=\"%s\">", Class);
294 va_start(arg_list, nLines);
295 for (i = 0; i < nLines; ++i)
297 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
298 wprintf((char *) va_arg(arg_list, char *));
299 wprintf("</a></li>\n");
303 wprintf("</a></li>\n");
307 do_template("endbox", NULL);
313 * Convenience functions to display a page containing only a string
315 * titlebarcolor color of the titlebar of the frame
316 * titlebarmsg text to display in the title bar
317 * messagetext body of the box
319 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
321 hprintf("HTTP/1.1 200 OK\n");
322 output_headers(1, 1, 2, 0, 0, 0);
323 wprintf("<div id=\"banner\">\n");
324 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
325 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
326 wprintf("</td></tr></table>\n");
327 wprintf("</div>\n<div id=\"content\">\n");
328 escputs(messagetext);
336 * Display a blank page.
338 void blank_page(void) {
339 output_headers(1, 1, 0, 0, 0, 0);
345 * A template has been requested
347 void url_do_template(void) {
348 const StrBuf *MimeType;
349 const StrBuf *Tmpl = sbstr("template");
351 MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
352 http_transmit_thing(ChrPtr(MimeType), 0);
358 * convenience function to indicate success
360 void display_success(char *successmessage)
362 convenience_page("007700", "OK", successmessage);
367 * Authorization required page
368 * This is probably temporary and should be revisited
370 void authorization_required(void)
373 const char *message = "";
375 hprintf("HTTP/1.1 401 Authorization Required\r\n");
377 "Server: %s / %s\r\n"
378 "Connection: close\r\n",
379 PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
381 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
382 hprintf("Content-Type: text/html\r\n");
385 wprintf(_("Authorization Required"));
386 wprintf("</h1>\r\n");
389 if (WCC->ImportantMsg != NULL)
390 message = ChrPtr(WCC->ImportantMsg);
391 else if (WCC->ImportantMessage != NULL)
392 message = WCC->ImportantMessage;
394 wprintf(_("The resource you requested requires a valid username and password. "
395 "You could not be logged in: %s\n"), message);
397 end_webcit_session();
401 * Convenience functions to wrap around asynchronous ajax responses
403 void begin_ajax_response(void) {
406 FlushStrBuf(WCC->HBuf);
407 output_headers(0, 0, 0, 0, 0, 0);
409 hprintf("Content-type: text/html; charset=UTF-8\r\n"
411 "Connection: close\r\n"
418 * print ajax response footer
420 void end_ajax_response(void) {
427 * Wraps a Citadel server command in an AJAX transaction.
429 void ajax_servcmd(void)
437 begin_ajax_response();
439 serv_puts(bstr("g_cmd"));
440 StrBuf_ServGetln(Buf);
441 StrBufAppendBuf(WCC->WBuf, Buf, 0);
442 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
444 switch (GetServerStatus(Buf, NULL)) {
446 serv_puts("\n\n000");
447 if ( (StrLength(Buf)==3) &&
448 !strcmp(ChrPtr(Buf), "000")) {
449 StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
454 StrBuf_ServGetln(Buf);
455 if ( (StrLength(Buf)==3) &&
456 !strcmp(ChrPtr(Buf), "000")) {
459 StrBufAppendBuf(WCC->WBuf, Buf, 0);
460 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
464 text_to_server(bstr("g_input"));
468 len = atol(&ChrPtr(Buf)[4]);
469 StrBuf_ServGetBLOBBuffered(Buf, len);
472 len = atol(&ChrPtr(Buf)[4]);
474 memset(junk, 0, len);
475 serv_write(junk, len);
482 * This is kind of an ugly hack, but this is the only place it can go.
483 * If the command was GEXP, then the instant messenger window must be
484 * running, so reset the "last_pager_check" watchdog timer so
485 * that page_popup() doesn't try to open it a second time.
487 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
488 WCC->last_pager_check = time(NULL);
495 * Helper function for the asynchronous check to see if we need
496 * to open the instant messenger window.
498 void seconds_since_last_gexp(void)
502 if ( (time(NULL) - WC->last_pager_check) < 30) {
508 serv_getln(buf, sizeof buf);
520 void ReadPostData(void)
522 const char *content_end = NULL;
525 StrBuf *content = NULL;
527 content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
529 StrBufPrintf(content,
531 "Content-length: %ld\n\n",
532 ChrPtr(WCC->Hdr->HR.ContentType),
533 WCC->Hdr->HR.ContentLength);
535 hprintf("Content-type: %s\n"
536 "Content-length: %d\n\n",
537 ContentType, ContentLength);
539 body_start = StrLength(content);
541 /** Read the entire input data at once. */
542 client_read_to(WCC->Hdr, content,
543 WCC->Hdr->HR.ContentLength,
546 if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33)) {
547 StrBufCutLeft(content, body_start);
548 ParseURLParams(content);
549 } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
550 content_end = ChrPtr(content) +
551 WCC->Hdr->HR.ContentLength +
553 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
554 } else if (WCC->Hdr->HR.ContentLength > 0) {
555 WCC->upload = content;
558 FreeStrBuf(&content);
563 * Entry point for WebCit transaction
565 void session_loop(void)
572 * We stuff these with the values coming from the client cookies,
573 * so we can use them to reconnect a timed out session if we have to.
582 WCC->upload_length = 0;
585 WCC->trailing_javascript = NewStrBuf();
586 WCC->Hdr->nWildfireHeaders = 0;
587 if (WCC->Hdr->HR.Handler != NULL)
588 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
590 if (WCC->Hdr->HR.ContentLength > 0) {
594 /* If there are variables in the URL, we must grab them now */
595 if (WCC->Hdr->PlainArgs != NULL)
596 ParseURLParams(WCC->Hdr->PlainArgs);
598 /* If the client sent a nonce that is incorrect, kill the request. */
599 if (havebstr("nonce")) {
600 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
601 bstr("nonce"), WCC->nonce);
602 if (ibstr("nonce") != WCC->nonce) {
603 lprintf(9, "Ignoring request with mismatched nonce.\n");
604 hprintf("HTTP/1.1 404 Security check failed\r\n");
605 hprintf("Content-Type: text/plain\r\n\r\n");
607 wprintf("Security check failed.\r\n");
609 goto SKIP_ALL_THIS_CRAP;
614 * If we're not connected to a Citadel server, try to hook up the
617 if (!WCC->connected) {
619 goto SKIP_ALL_THIS_CRAP;
624 * If we're not logged in, but we have authentication data (either from
625 * a cookie or from http-auth), try logging in to Citadel using that.
627 if ((!WCC->logged_in)
628 && (StrLength(WCC->Hdr->c_username) > 0)
629 && (StrLength(WCC->Hdr->c_password) > 0))
632 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
633 StrBuf_ServGetln(Buf);
634 if (GetServerStatus(Buf, NULL) == 3) {
635 serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
636 StrBuf_ServGetln(Buf);
637 if (GetServerStatus(Buf, NULL) == 2) {
638 become_logged_in(WCC->Hdr->c_username,
639 WCC->Hdr->c_password, Buf);
641 /* Should only display when password is wrong */
642 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
643 authorization_required();
645 goto SKIP_ALL_THIS_CRAP;
650 xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
651 (WCC->Hdr->HR.eReqType != ePOST) &&
652 (WCC->Hdr->HR.eReqType != eHEAD);
655 * If a 'gotofirst' parameter has been specified, attempt to goto that room
656 * prior to doing anything else.
658 if (havebstr("gotofirst")) {
660 ret = gotoroom(sbstr("gotofirst")); /* do quietly to avoid session output! */
661 if ((ret/100) != 2) {
662 lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
663 bstr("gotofirst"), ret);
668 * If we aren't in any room yet, but we have cookie data telling us where we're
669 * supposed to be, and 'gotofirst' was not specified, then go there.
671 else if ( (StrLength(WCC->wc_roomname) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
674 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
675 ChrPtr(WCC->wc_roomname),
676 ChrPtr(WCC->Hdr->c_roomname)
678 ret = gotoroom(WCC->Hdr->c_roomname); /* do quietly to avoid session output! */
679 if ((ret/100) != 2) {
680 lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
681 ChrPtr(WCC->Hdr->c_roomname), ret);
685 if (WCC->Hdr->HR.Handler != NULL) {
686 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
690 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
691 begin_ajax_response();
692 WCC->Hdr->HR.Handler->F();
693 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
697 /* When all else fais, display the main menu. */
700 * ordinary browser users get a nice login screen, DAV etc. requsets
701 * are given a 401 so they can handle it appropriate.
703 if (!WCC->logged_in) {
705 authorization_required();
710 * Toplevel dav requests? or just a flat browser request?
727 * Replacement for sleep() that uses select() in order to avoid SIGALRM
729 void sleeeeeeeeeep(int seconds)
735 select(0, NULL, NULL, NULL, &tv);
739 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
743 return ((!IsEmptyStr(WCC->ImportantMessage)) ||
744 (StrLength(WCC->ImportantMsg) > 0));
749 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
754 if (!IsEmptyStr(WCC->ImportantMessage)) {
755 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
756 WCC->ImportantMessage[0] = '\0';
758 else if (StrLength(WCC->ImportantMsg) > 0) {
759 StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
760 FlushStrBuf(WCC->ImportantMsg);
765 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
770 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
773 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
775 StrBufAppendBuf(Target,
779 extern char static_local_dir[PATH_MAX];
787 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
788 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
789 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX|LOGCHATTY);
790 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
791 WebcitAddUrlHandler(HKEY("webcit"), blank_page, URLNAMESPACE);
793 WebcitAddUrlHandler(HKEY("401"), authorization_required, ANONYMOUS|COOKIEUNNEEDED);
794 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
795 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
796 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
797 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
799 snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
800 if (!access(dir, R_OK)) {
801 lprintf(9, "Using local Stylesheet [%s]\n", dir);
802 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
805 lprintf(9, "No Site-local Stylesheet [%s] installed. \n", dir);
810 ServerStartModule_WEBCIT
813 HandlerHash = NewHash(1, NULL);
818 ServerShutdownModule_WEBCIT
821 FreeStrBuf(&csslocal);
822 DeleteHash(&HandlerHash);
828 SessionNewModule_WEBCIT
831 sess->ImportantMsg = NewStrBuf();
832 sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
833 sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
837 SessionDetachModule_WEBCIT
840 DeleteHash(&sess->Hdr->urlstrings);// TODO?
841 if (sess->upload_length > 0) {
842 FreeStrBuf(&sess->upload);
843 sess->upload_length = 0;
845 FreeStrBuf(&sess->trailing_javascript);
847 if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
849 FreeStrBuf(&sess->WBuf);
850 sess->WBuf = NewStrBuf();
853 FlushStrBuf(sess->WBuf);
854 FlushStrBuf(sess->HBuf);
858 SessionDestroyModule_WEBCIT
861 FreeStrBuf(&sess->WBuf);
862 FreeStrBuf(&sess->HBuf);
863 FreeStrBuf(&sess->ImportantMsg);