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;
25 void WebcitAddUrlHandler(const char * UrlString,
30 WebcitHandler *NewHandler;
31 NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
33 NewHandler->Flags = Flags;
34 Put(HandlerHash, UrlString, UrlSLen, NewHandler, NULL);
39 * web-printing funcion. uses our vsnprintf wrapper
41 void wprintf(const char *format,...)
46 if (WCC->WBuf == NULL)
47 WCC->WBuf = NewStrBuf();
49 va_start(arg_ptr, format);
50 StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
55 * http-header-printing funcion. uses our vsnprintf wrapper
57 void hprintf(const char *format,...)
62 va_start(arg_ptr, format);
63 StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
70 * wrap up an HTTP session, closes tags, etc.
72 * print_standard_html_footer should be set to:
73 * 0 - to transmit only,
74 * nonzero - to append the closing tags
76 void wDumpContent(int print_standard_html_footer)
78 if (print_standard_html_footer) {
79 wprintf("</div> <!-- end of 'content' div -->\n");
80 do_template("trailing", NULL);
83 /* If we've been saving it all up for one big output burst,
84 * go ahead and do that now.
93 * Output HTTP headers and leading HTML for a page
95 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
96 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
98 int do_room_banner, /* 0=no, 1=yes,
99 * 2 = I'm going to embed my own, so don't open the
100 * <div id="content"> either.
103 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
104 int suppress_check, /* 1 = suppress check for instant messages */
105 int cache /* 1 = allow browser to cache this page */
111 hprintf("HTTP/1.1 200 OK\n");
112 http_datestring(httpnow, sizeof httpnow, time(NULL));
114 if (do_httpheaders) {
115 if (WCC->serv_info != NULL)
116 hprintf("Content-type: text/html; charset=utf-8\r\n"
118 "Connection: close\r\n",
120 ChrPtr(WCC->serv_info->serv_software));
122 hprintf("Content-type: text/html; charset=utf-8\r\n"
123 "Server: %s / [n/a]\n"
124 "Connection: close\r\n",
129 char httpTomorow[128];
131 http_datestring(httpTomorow, sizeof httpTomorow,
132 time(NULL) + 60 * 60 * 24 * 2);
134 hprintf("Pragma: public\r\n"
135 "Cache-Control: max-age=3600, must-revalidate\r\n"
136 "Last-modified: %s\r\n"
143 hprintf("Pragma: no-cache\r\n"
144 "Cache-Control: no-store\r\n"
149 stuff_to_cookie(cookie, 1024,
150 WCC->wc_session, WCC->wc_username,
151 WCC->wc_password, WCC->wc_roomname);
154 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
156 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
157 if (server_cookie != NULL) {
158 hprintf("%s\n", server_cookie);
164 do_template("head", NULL);
166 /* check for ImportantMessages (these display in a div overlaying the main screen) */
167 if (!IsEmptyStr(WCC->ImportantMessage)) {
168 wprintf("<div id=\"important_message\">\n"
169 "<span class=\"imsg\">");
170 StrEscAppend(WCC->WBuf, NULL, WCC->ImportantMessage, 0, 0);
171 wprintf("</span><br />\n"
174 StrBufAppendBufPlain(WCC->trailing_javascript,
175 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
178 WCC->ImportantMessage[0] = 0;
180 else if (StrLength(WCC->ImportantMsg) > 0) {
181 wprintf("<div id=\"important_message\">\n"
182 "<span class=\"imsg\">");
183 StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
184 wprintf("</span><br />\n"
187 StrBufAppendBufPlain(WCC->trailing_javascript,
188 HKEY("setTimeout('hide_imsg_popup()', 5000); \n"),
191 FlushStrBuf(WCC->ImportantMsg);
193 if ( (WCC->logged_in) && (!unset_cookies) ) {
194 /*DoTemplate(HKEY("iconbar"), NULL, &NoCtx);*/
198 if (do_room_banner == 1) {
199 wprintf("<div id=\"banner\">\n");
200 embed_room_banner(NULL, navbar_default);
205 if (do_room_banner == 1) {
206 wprintf("<div id=\"content\">\n");
210 void output_custom_content_header(const char *ctype) {
211 hprintf("HTTP/1.1 200 OK\r\n");
212 hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
213 hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
214 hprintf("Connection: close\r\n");
219 * Generic function to do an HTTP redirect. Easy and fun.
221 void http_redirect(const char *whichpage) {
222 hprintf("HTTP/1.1 302 Moved Temporarily\n");
223 hprintf("Location: %s\r\n", whichpage);
224 hprintf("URI: %s\r\n", whichpage);
225 hprintf("Content-type: text/html; charset=utf-8\r\n");
226 wprintf("<html><body>");
227 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
228 wprintf("</body></html>\n");
235 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
237 void http_transmit_thing(const char *content_type,
241 lprintf(9, "http_transmit_thing(%s)%s\n",
243 (is_static ? " (static)" : "")
246 output_headers(0, 0, 0, 0, 0, is_static);
248 hprintf("Content-type: %s\r\n"
250 "Connection: close\r\n",
258 * print menu box like used in the floor view or admin interface.
259 * This function takes pair of strings as va_args,
260 * Title Title string of the box
261 * Class CSS Class for the box
262 * nLines How many string pairs should we print? (URL, UrlText)
263 * ... Pairs of URL Strings and their Names
265 void print_menu_box(char* Title, char *Class, int nLines, ...)
270 svput("BOXTITLE", WCS_STRING, Title);
271 do_template("beginboxx", NULL);
273 wprintf("<ul class=\"%s\">", Class);
275 va_start(arg_list, nLines);
276 for (i = 0; i < nLines; ++i)
278 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
279 wprintf((char *) va_arg(arg_list, char *));
280 wprintf("</a></li>\n");
284 wprintf("</a></li>\n");
288 do_template("endbox", NULL);
294 * Convenience functions to display a page containing only a string
296 * titlebarcolor color of the titlebar of the frame
297 * titlebarmsg text to display in the title bar
298 * messagetext body of the box
300 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
302 hprintf("HTTP/1.1 200 OK\n");
303 output_headers(1, 1, 2, 0, 0, 0);
304 wprintf("<div id=\"banner\">\n");
305 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
306 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
307 wprintf("</td></tr></table>\n");
308 wprintf("</div>\n<div id=\"content\">\n");
309 escputs(messagetext);
317 * Display a blank page.
319 void blank_page(void) {
320 output_headers(1, 1, 0, 0, 0, 0);
326 * A template has been requested
328 void url_do_template(void) {
329 const StrBuf *MimeType;
330 const StrBuf *Tmpl = sbstr("template");
332 MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
333 http_transmit_thing(ChrPtr(MimeType), 0);
339 * convenience function to indicate success
341 void display_success(char *successmessage)
343 convenience_page("007700", "OK", successmessage);
348 * Authorization required page
349 * This is probably temporary and should be revisited
351 void authorization_required(const char *message)
353 hprintf("HTTP/1.1 401 Authorization Required\r\n");
354 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
355 hprintf("Content-Type: text/html\r\n");
357 wprintf(_("Authorization Required"));
358 wprintf("</h1>\r\n");
359 wprintf(_("The resource you requested requires a valid username and password. "
360 "You could not be logged in: %s\n"), message);
366 * Convenience functions to wrap around asynchronous ajax responses
368 void begin_ajax_response(void) {
371 FlushStrBuf(WCC->HBuf);
372 output_headers(0, 0, 0, 0, 0, 0);
374 hprintf("Content-type: text/html; charset=UTF-8\r\n"
376 "Connection: close\r\n"
383 * print ajax response footer
385 void end_ajax_response(void) {
389 /* If it's a "force 404" situation then display the error and bail. */
392 hprintf("HTTP/1.1 404 Not found\r\n");
393 hprintf("Content-Type: text/plain\r\n");
394 wprintf("Not found\r\n");
400 * Wraps a Citadel server command in an AJAX transaction.
402 void ajax_servcmd(void)
410 begin_ajax_response();
412 serv_puts(bstr("g_cmd"));
413 StrBuf_ServGetln(Buf);
414 StrBufAppendBuf(WCC->WBuf, Buf, 0);
415 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
417 switch (GetServerStatus(Buf, NULL)) {
419 serv_puts("\n\n000");
420 if ( (StrLength(Buf)==3) &&
421 !strcmp(ChrPtr(Buf), "000")) {
422 StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
427 StrBuf_ServGetln(Buf);
428 if ( (StrLength(Buf)==3) &&
429 !strcmp(ChrPtr(Buf), "000")) {
432 StrBufAppendBuf(WCC->WBuf, Buf, 0);
433 StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
437 text_to_server(bstr("g_input"));
441 len = atol(&ChrPtr(Buf)[4]);
442 StrBuf_ServGetBLOBBuffered(Buf, len);
445 len = atol(&ChrPtr(Buf)[4]);
447 memset(junk, 0, len);
448 serv_write(junk, len);
455 * This is kind of an ugly hack, but this is the only place it can go.
456 * If the command was GEXP, then the instant messenger window must be
457 * running, so reset the "last_pager_check" watchdog timer so
458 * that page_popup() doesn't try to open it a second time.
460 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
461 WCC->last_pager_check = time(NULL);
468 * Helper function for the asynchronous check to see if we need
469 * to open the instant messenger window.
471 void seconds_since_last_gexp(void)
475 if ( (time(NULL) - WC->last_pager_check) < 30) {
481 serv_getln(buf, sizeof buf);
493 void ReadPostData(void)
495 const char *content_end = NULL;
498 StrBuf *content = NULL;
500 content = NewStrBuf();
502 StrBufPrintf(content,
504 "Content-length: %ld\n\n",
505 ChrPtr(WCC->Hdr->ContentType),
506 WCC->Hdr->ContentLength);
508 hprintf("Content-type: %s\n"
509 "Content-length: %d\n\n",
510 ContentType, ContentLength);
512 body_start = StrLength(content);
514 /** Read the entire input data at once. */
515 client_read_to(&WCC->Hdr->http_sock,
517 WCC->Hdr->ReadBuf, &WCC->Hdr->Pos,
518 WCC->Hdr->ContentLength,
521 if (!strncasecmp(ChrPtr(WCC->Hdr->ContentType), "application/x-www-form-urlencoded", 33)) {
522 StrBufCutLeft(content, body_start);
523 ParseURLParams(content);
524 } else if (!strncasecmp(ChrPtr(WCC->Hdr->ContentType), "multipart", 9)) {
525 content_end = ChrPtr(content) +
526 WCC->Hdr->ContentLength +
528 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
530 FreeStrBuf(&content);
535 * Entry point for WebCit transaction
537 void session_loop(void)
546 * We stuff these with the values coming from the client cookies,
547 * so we can use them to reconnect a timed out session if we have to.
556 WCC->upload_length = 0;
559 WCC->trailing_javascript = NewStrBuf();
560 WCC->Hdr->nWildfireHeaders = 0;
561 if (WCC->Hdr->Handler != NULL)
562 Flags = WCC->Hdr->Handler->Flags; /* so we can temporarily add our own... */
564 if (WCC->Hdr->ContentLength > 0) {
568 /* If there are variables in the URL, we must grab them now */
569 if (WCC->Hdr->PlainArgs != NULL)
570 ParseURLParams(WCC->Hdr->PlainArgs);
572 /* If the client sent a nonce that is incorrect, kill the request. */
573 if (havebstr("nonce")) {
574 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
575 bstr("nonce"), WCC->nonce);
576 if (ibstr("nonce") != WCC->nonce) {
577 lprintf(9, "Ignoring request with mismatched nonce.\n");
578 hprintf("HTTP/1.1 404 Security check failed\r\n");
579 hprintf("Content-Type: text/plain\r\n\r\n");
580 wprintf("Security check failed.\r\n");
582 goto SKIP_ALL_THIS_CRAP;
587 * If we're not connected to a Citadel server, try to hook up the
590 if (!WCC->connected) {
592 goto SKIP_ALL_THIS_CRAP;
597 * If we're not logged in, but we have HTTP Authentication data,
598 * try logging in to Citadel using that.
600 if ((!WCC->logged_in)
601 && (StrLength(WCC->Hdr->c_username) > 0)
602 && (StrLength(WCC->Hdr->c_password) > 0))
605 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
606 StrBuf_ServGetln(Buf);
607 if (GetServerStatus(Buf, NULL) == 3) {
608 serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
609 StrBuf_ServGetln(Buf);
610 if (GetServerStatus(Buf, NULL) == 2) {
611 become_logged_in(WCC->Hdr->c_username,
612 WCC->Hdr->c_password, Buf);
614 /* Should only display when password is wrong */
615 authorization_required(&buf[4]);
617 goto SKIP_ALL_THIS_CRAP;
622 xhttp = (WCC->Hdr->eReqType != eGET) &&
623 (WCC->Hdr->eReqType != ePOST) &&
624 (WCC->Hdr->eReqType != eHEAD);
627 * If we're not logged in, but we have username and password cookies
628 * supplied by the browser, try using them to log in.
630 if ((!WCC->logged_in)
631 && (StrLength(WCC->Hdr->c_username)>0)
632 && (StrLength(WCC->Hdr->c_password)>0)) {
633 ReEstablish_Session();
637 * If a 'gotofirst' parameter has been specified, attempt to goto that room
638 * prior to doing anything else.
640 if (havebstr("gotofirst")) {
642 ret = gotoroom(sbstr("gotofirst")); /* do this quietly to avoid session output! */
644 lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n", bstr("gotofirst"), ret);
647 if (WCC->Hdr->Handler != NULL) {
648 if (!WCC->logged_in && ((WCC->Hdr->Handler->Flags & ANONYMOUS) == 0)) {
652 if ((WCC->Hdr->Handler->Flags & AJAX) != 0)
653 begin_ajax_response();
654 WCC->Hdr->Handler->F();
655 if ((WCC->Hdr->Handler->Flags & AJAX) != 0)
659 /* When all else fais, display the main menu. */
668 if (WCC->SavePrefsToServer) {
670 WCC->SavePrefsToServer = 0;
674 WCC->Hdr->http_host = NULL;
679 * Replacement for sleep() that uses select() in order to avoid SIGALRM
681 void sleeeeeeeeeep(int seconds)
687 select(0, NULL, NULL, NULL, &tv);
691 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
695 return ((!IsEmptyStr(WCC->ImportantMessage)) ||
696 (StrLength(WCC->ImportantMsg) > 0));
701 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
706 if (!IsEmptyStr(WCC->ImportantMessage)) {
707 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
708 WCC->ImportantMessage[0] = '\0';
710 else if (StrLength(WCC->ImportantMsg) > 0) {
711 StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
712 FlushStrBuf(WCC->ImportantMsg);
717 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
722 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
725 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
727 StrBufAppendBuf(Target,
731 extern char static_local_dir[PATH_MAX];
739 WebcitAddUrlHandler(HKEY("404"), do_404, ANONYMOUS|COOKIEUNNEEDED);
740 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
743 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
744 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
745 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX|LOGCHATTY);
746 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
748 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
749 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
750 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
751 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
753 snprintf(dir, SIZ, "%s/static.local/webcit.css", static_local_dir);
754 if (!access(dir, R_OK)) {
755 lprintf(9, "Using local Stylesheet [%s]\n", dir);
756 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
759 lprintf(9, "Didn't find site local Stylesheet [%s]\n", dir);
764 ServerStartModule_WEBCIT
767 HandlerHash = NewHash(1, NULL);
772 ServerShutdownModule_WEBCIT
775 FreeStrBuf(&csslocal);
776 DeleteHash(&HandlerHash);
782 SessionNewModule_WEBCIT
785 sess->ImportantMsg = NewStrBuf();
786 sess->WBuf = NewStrBuf();
787 sess->HBuf = NewStrBuf();
791 SessionDetachModule_WEBCIT
794 DeleteHash(&sess->Hdr->urlstrings);// TODO?
795 if (sess->upload_length > 0) {
797 sess->upload_length = 0;
799 FreeStrBuf(&sess->trailing_javascript);
801 if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
803 FreeStrBuf(&sess->WBuf);
804 sess->WBuf = NewStrBuf();
807 FlushStrBuf(sess->WBuf);
808 FlushStrBuf(sess->HBuf);
812 SessionDestroyModule_WEBCIT
815 FreeStrBuf(&sess->WBuf);
816 FreeStrBuf(&sess->HBuf);
817 FreeStrBuf(&sess->ImportantMsg);