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, long UrlSLen,
35 const char *DisplayName, long dslen,
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 NewHandler->DisplayName = NewStrBufPlain(DisplayName, dslen);
46 StrBufShrinkToFit(NewHandler->DisplayName, 1);
47 Put(HandlerHash, UrlString, UrlSLen, NewHandler, DeleteWebcitHandler);
52 * web-printing funcion. uses our vsnprintf wrapper
54 void wc_printf(const char *format,...)
59 if (WCC->WBuf == NULL)
60 WCC->WBuf = NewStrBuf();
62 va_start(arg_ptr, format);
63 StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
68 * http-header-printing funcion. uses our vsnprintf wrapper
70 void hprintf(const char *format,...)
75 va_start(arg_ptr, format);
76 StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
83 * wrap up an HTTP session, closes tags, etc.
85 * print_standard_html_footer should be set to:
86 * 0 - to transmit only,
87 * nonzero - to append the closing tags
89 void wDumpContent(int print_standard_html_footer)
91 if (print_standard_html_footer) {
92 wc_printf("</div> <!-- end of 'content' div -->\n");
93 do_template("trailing", NULL);
96 /* If we've been saving it all up for one big output burst,
97 * go ahead and do that now.
106 * Output HTTP headers and leading HTML for a page
108 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
109 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
111 int do_room_banner, /* 0=no, 1=yes,
112 * 2 = I'm going to embed my own, so don't open the
113 * <div id="content"> either.
116 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
117 int suppress_check, /* 1 = suppress check for instant messages */
118 int cache /* 1 = allow browser to cache this page */
124 hprintf("HTTP/1.1 200 OK\n");
125 http_datestring(httpnow, sizeof httpnow, time(NULL));
127 if (do_httpheaders) {
128 if (WCC->serv_info != NULL)
129 hprintf("Content-type: text/html; charset=utf-8\r\n"
131 "Connection: close\r\n",
133 ChrPtr(WCC->serv_info->serv_software));
135 hprintf("Content-type: text/html; charset=utf-8\r\n"
136 "Server: %s / [n/a]\n"
137 "Connection: close\r\n",
142 char httpTomorow[128];
144 http_datestring(httpTomorow, sizeof httpTomorow,
145 time(NULL) + 60 * 60 * 24 * 2);
147 hprintf("Pragma: public\r\n"
148 "Cache-Control: max-age=3600, must-revalidate\r\n"
149 "Last-modified: %s\r\n"
156 hprintf("Pragma: no-cache\r\n"
157 "Cache-Control: no-store\r\n"
164 stuff_to_cookie(cookie, 1024,
169 get_selected_language()
173 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
175 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
176 if (server_cookie != NULL) {
177 hprintf("%s\n", server_cookie);
184 do_template("head", NULL);
186 /* check for ImportantMessages (these display in a div overlaying the main screen) */
187 if (!IsEmptyStr(WCC->ImportantMessage)) {
188 wc_printf("<div id=\"important_message\">\n"
189 "<span class=\"imsg\">");
190 StrEscAppend(WCC->WBuf, NULL, WCC->ImportantMessage, 0, 0);
191 wc_printf("</span><br />\n"
194 StrBufAppendBufPlain(WCC->trailing_javascript,
195 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
198 WCC->ImportantMessage[0] = 0;
200 else if (StrLength(WCC->ImportantMsg) > 0) {
201 wc_printf("<div id=\"important_message\">\n"
202 "<span class=\"imsg\">");
203 StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
204 wc_printf("</span><br />\n"
207 StrBufAppendBufPlain(WCC->trailing_javascript,
208 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
211 FlushStrBuf(WCC->ImportantMsg);
213 if ( (WCC->logged_in) && (!unset_cookies) ) {
214 DoTemplate(HKEY("paging"), NULL, &NoCtx);
217 if (do_room_banner == 1) {
218 wc_printf("<div id=\"banner\">\n");
219 embed_room_banner(NULL, navbar_default);
220 wc_printf("</div>\n");
224 if (do_room_banner == 1) {
225 wc_printf("<div id=\"content\">\n");
229 void output_custom_content_header(const char *ctype) {
230 hprintf("HTTP/1.1 200 OK\r\n");
231 hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
232 hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
233 hprintf("Connection: close\r\n");
238 * Generic function to do an HTTP redirect. Easy and fun.
240 void http_redirect(const char *whichpage) {
241 hprintf("HTTP/1.1 302 Moved Temporarily\n");
242 hprintf("Location: %s\r\n", whichpage);
243 hprintf("URI: %s\r\n", whichpage);
244 hprintf("Content-type: text/html; charset=utf-8\r\n");
246 wc_printf("<html><body>");
247 wc_printf("Go <a href=\"%s\">here</A>.", whichpage);
248 wc_printf("</body></html>\n");
255 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
257 void http_transmit_thing(const char *content_type,
261 lprintf(9, "http_transmit_thing(%s)%s\n",
263 ((is_static > 0) ? " (static)" : "")
266 output_headers(0, 0, 0, 0, 0, is_static);
268 hprintf("Content-type: %s\r\n"
270 "Connection: close\r\n",
279 * Convenience functions to display a page containing only a string
281 * titlebarcolor color of the titlebar of the frame
282 * titlebarmsg text to display in the title bar
283 * messagetext body of the box
285 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
287 hprintf("HTTP/1.1 200 OK\n");
288 output_headers(1, 1, 2, 0, 0, 0);
289 wc_printf("<div id=\"banner\">\n");
290 wc_printf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
291 wc_printf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
292 wc_printf("</td></tr></table>\n");
293 wc_printf("</div>\n<div id=\"content\">\n");
294 escputs(messagetext);
296 wc_printf("<hr />\n");
302 * Display a blank page.
304 void blank_page(void) {
305 output_headers(1, 1, 0, 0, 0, 0);
311 * A template has been requested
313 void url_do_template(void) {
314 const StrBuf *MimeType;
315 const StrBuf *Tmpl = sbstr("template");
317 MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
318 http_transmit_thing(ChrPtr(MimeType), 0);
324 * convenience function to indicate success
326 void display_success(char *successmessage)
328 convenience_page("007700", "OK", successmessage);
333 * Authorization required page
334 * This is probably temporary and should be revisited
336 void authorization_required(void)
339 const char *message = "";
341 hprintf("HTTP/1.1 401 Authorization Required\r\n");
343 "Server: %s / %s\r\n"
344 "Connection: close\r\n",
345 PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
347 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
348 hprintf("Content-Type: text/html\r\n");
351 wc_printf(_("Authorization Required"));
352 wc_printf("</h1>\r\n");
355 if (WCC->ImportantMsg != NULL)
356 message = ChrPtr(WCC->ImportantMsg);
357 else if (WCC->ImportantMessage != NULL)
358 message = WCC->ImportantMessage;
360 wc_printf(_("The resource you requested requires a valid username and password. "
361 "You could not be logged in: %s\n"), message);
363 end_webcit_session();
367 * Convenience functions to wrap around asynchronous ajax responses
369 void begin_ajax_response(void) {
372 FlushStrBuf(WCC->HBuf);
373 output_headers(0, 0, 0, 0, 0, 0);
375 hprintf("Content-type: text/html; charset=UTF-8\r\n"
377 "Connection: close\r\n"
384 * print ajax response footer
386 void end_ajax_response(void) {
393 * Wraps a Citadel server command in an AJAX transaction.
395 void ajax_servcmd(void)
403 begin_ajax_response();
405 serv_puts(bstr("g_cmd"));
406 StrBuf_ServGetln(Buf);
407 StrBufAppendBuf(WCC->WBuf, Buf, 0);
408 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
410 switch (GetServerStatus(Buf, NULL)) {
412 serv_puts("\n\n000");
413 if ( (StrLength(Buf)==3) &&
414 !strcmp(ChrPtr(Buf), "000")) {
415 StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
420 StrBuf_ServGetln(Buf);
421 if ( (StrLength(Buf)==3) &&
422 !strcmp(ChrPtr(Buf), "000")) {
425 StrBufAppendBuf(WCC->WBuf, Buf, 0);
426 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
430 text_to_server(bstr("g_input"));
434 len = atol(&ChrPtr(Buf)[4]);
435 StrBuf_ServGetBLOBBuffered(Buf, len);
438 len = atol(&ChrPtr(Buf)[4]);
440 memset(junk, 0, len);
441 serv_write(junk, len);
448 * This is kind of an ugly hack, but this is the only place it can go.
449 * If the command was GEXP, then the instant messenger window must be
450 * running, so reset the "last_pager_check" watchdog timer so
451 * that page_popup() doesn't try to open it a second time.
453 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
454 WCC->last_pager_check = time(NULL);
461 * Helper function for the asynchronous check to see if we need
462 * to open the instant messenger window.
464 void seconds_since_last_gexp(void)
468 if ( (time(NULL) - WC->last_pager_check) < 30) {
474 serv_getln(buf, sizeof buf);
486 void ReadPostData(void)
490 StrBuf *content = NULL;
492 content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
494 StrBufPrintf(content,
496 "Content-length: %ld\n\n",
497 ChrPtr(WCC->Hdr->HR.ContentType),
498 WCC->Hdr->HR.ContentLength);
500 hprintf("Content-type: %s\n"
501 "Content-length: %d\n\n",
502 ContentType, ContentLength);
504 body_start = StrLength(content);
506 /** Read the entire input data at once. */
507 client_read_to(WCC->Hdr, content,
508 WCC->Hdr->HR.ContentLength,
511 if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33)) {
512 StrBufCutLeft(content, body_start);
513 ParseURLParams(content);
514 } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
519 len = StrLength(content);
520 Buf = SmashStrBuf(&content);
522 mime_parser(Buf, BufEnd, *upload_handler, NULL, NULL, NULL, 0);
524 } else if (WCC->Hdr->HR.ContentLength > 0) {
525 WCC->upload = content;
526 WCC->upload_length = StrLength(WCC->upload);
529 FreeStrBuf(&content);
533 void ParseREST_URL(void)
536 StrBuf *pFloor = NULL;
539 const char *pCh = NULL;
543 WCC->Directory = NewHash(1, Flathash);
546 while (StrBufExtract_NextToken(WCC->Hdr->HR.ReqLine,
547 Buf, &pCh, '/') >= 0)
549 Put(WCC->Directory, IKEY(i), Buf, HFreeStrBuf);
557 else if (pFloor != NULL)
559 Floors = GetFloorListHash(NULL, NULL);
563 if (GetHash(Floors, SKEY(pFloor), &vFloor))
564 WCC->CurrentFloor = (floor*) vFloor;
573 * Entry point for WebCit transaction
575 void session_loop(void)
582 * We stuff these with the values coming from the client cookies,
583 * so we can use them to reconnect a timed out session if we have to.
592 WCC->upload_length = 0;
595 WCC->trailing_javascript = NewStrBuf();
596 WCC->Hdr->nWildfireHeaders = 0;
597 if (WCC->Hdr->HR.Handler != NULL)
598 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
600 if (WCC->Hdr->HR.ContentLength > 0) {
604 /* If there are variables in the URL, we must grab them now */
605 if (WCC->Hdr->PlainArgs != NULL)
606 ParseURLParams(WCC->Hdr->PlainArgs);
608 /* If the client sent a nonce that is incorrect, kill the request. */
609 if (havebstr("nonce")) {
610 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
611 bstr("nonce"), WCC->nonce);
612 if (ibstr("nonce") != WCC->nonce) {
613 lprintf(9, "Ignoring request with mismatched nonce.\n");
614 hprintf("HTTP/1.1 404 Security check failed\r\n");
615 hprintf("Content-Type: text/plain\r\n");
617 wc_printf("Security check failed.\r\n");
619 goto SKIP_ALL_THIS_CRAP;
624 * If we're not connected to a Citadel server, try to hook up the
627 if (!WCC->connected) {
629 goto SKIP_ALL_THIS_CRAP;
634 * If we're not logged in, but we have authentication data (either from
635 * a cookie or from http-auth), try logging in to Citadel using that.
637 if ((!WCC->logged_in)
638 && (StrLength(WCC->Hdr->c_username) > 0)
639 && (StrLength(WCC->Hdr->c_password) > 0))
642 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
643 StrBuf_ServGetln(Buf);
644 if (GetServerStatus(Buf, NULL) == 3) {
645 serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
646 StrBuf_ServGetln(Buf);
647 if (GetServerStatus(Buf, NULL) == 2) {
648 become_logged_in(WCC->Hdr->c_username,
649 WCC->Hdr->c_password, Buf);
651 /* Should only display when password is wrong */
652 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
653 authorization_required();
655 goto SKIP_ALL_THIS_CRAP;
660 xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
661 (WCC->Hdr->HR.eReqType != ePOST) &&
662 (WCC->Hdr->HR.eReqType != eHEAD);
665 * If a 'gotofirst' parameter has been specified, attempt to goto that room
666 * prior to doing anything else.
668 if (havebstr("gotofirst")) {
670 ret = gotoroom(sbstr("gotofirst")); /* do quietly to avoid session output! */
671 if ((ret/100) != 2) {
672 lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
673 bstr("gotofirst"), ret);
678 * If we aren't in any room yet, but we have cookie data telling us where we're
679 * supposed to be, and 'gotofirst' was not specified, then go there.
681 else if ( (StrLength(WCC->wc_roomname) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
684 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
685 ChrPtr(WCC->wc_roomname),
686 ChrPtr(WCC->Hdr->c_roomname)
688 ret = gotoroom(WCC->Hdr->c_roomname); /* do quietly to avoid session output! */
689 if ((ret/100) != 2) {
690 lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
691 ChrPtr(WCC->Hdr->c_roomname), ret);
695 if (WCC->Hdr->HR.Handler != NULL) {
696 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
701 if ((WCC->Hdr->HR.Handler->Flags & PARSE_REST_URL) != 0)
704 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
705 begin_ajax_response();
706 WCC->Hdr->HR.Handler->F();
707 if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
711 /* When all else fais, display the main menu. */
714 * ordinary browser users get a nice login screen, DAV etc. requsets
715 * are given a 401 so they can handle it appropriate.
717 if (!WCC->logged_in) {
719 authorization_required();
724 * Toplevel dav requests? or just a flat browser request?
741 * Replacement for sleep() that uses select() in order to avoid SIGALRM
743 void sleeeeeeeeeep(int seconds)
749 select(0, NULL, NULL, NULL, &tv);
753 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
757 return ((!IsEmptyStr(WCC->ImportantMessage)) ||
758 (StrLength(WCC->ImportantMsg) > 0));
763 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
768 if (!IsEmptyStr(WCC->ImportantMessage)) {
769 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
770 WCC->ImportantMessage[0] = '\0';
772 else if (StrLength(WCC->ImportantMsg) > 0) {
773 StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
774 FlushStrBuf(WCC->ImportantMsg);
779 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
784 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
787 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
789 StrBufAppendBuf(Target,
793 extern char static_local_dir[PATH_MAX];
801 WebcitAddUrlHandler(HKEY("blank"), "", 0, blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
802 WebcitAddUrlHandler(HKEY("do_template"), "", 0, url_do_template, ANONYMOUS);
803 WebcitAddUrlHandler(HKEY("sslg"), "", 0, seconds_since_last_gexp, AJAX|LOGCHATTY);
804 WebcitAddUrlHandler(HKEY("ajax_servcmd"), "", 0, ajax_servcmd, 0);
805 WebcitAddUrlHandler(HKEY("webcit"), "", 0, blank_page, URLNAMESPACE);
807 WebcitAddUrlHandler(HKEY("401"), "", 0, authorization_required, ANONYMOUS|COOKIEUNNEEDED);
808 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
809 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, NULL, CTX_NONE);
810 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, NULL, CTX_NONE);
811 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, NULL, CTX_NONE);
813 snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
814 if (!access(dir, R_OK)) {
815 lprintf(9, "Using local Stylesheet [%s]\n", dir);
816 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\" />"));
819 lprintf(9, "No Site-local Stylesheet [%s] installed. \n", dir);
824 ServerStartModule_WEBCIT
827 HandlerHash = NewHash(1, NULL);
832 ServerShutdownModule_WEBCIT
835 FreeStrBuf(&csslocal);
836 DeleteHash(&HandlerHash);
842 SessionNewModule_WEBCIT
845 sess->ImportantMsg = NewStrBuf();
846 sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
847 sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
851 SessionDetachModule_WEBCIT
854 DeleteHash(&sess->Directory);
856 FreeStrBuf(&sess->upload);
857 sess->upload_length = 0;
859 FreeStrBuf(&sess->trailing_javascript);
861 if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
863 FreeStrBuf(&sess->WBuf);
864 sess->WBuf = NewStrBuf();
867 FlushStrBuf(sess->WBuf);
868 FlushStrBuf(sess->HBuf);
872 SessionDestroyModule_WEBCIT
875 FreeStrBuf(&sess->WBuf);
876 FreeStrBuf(&sess->HBuf);
877 FreeStrBuf(&sess->ImportantMsg);