* Attempting to add a smart host in webcit was instead adding it as an RBL host....
[citadel.git] / webcit / webcit.c
blobfdde5ef53de869668d7f243aefc24c420198f9d9
1 /*
2 * $Id$
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.
7 */
8 #define SHOW_ME_VAPPEND_PRINTF
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include "webcit.h"
12 #include "groupdav.h"
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";
23 HashList *HandlerHash = NULL;
25 void WebcitAddUrlHandler(const char * UrlString,
26 long UrlSLen,
27 WebcitHandlerFunc F,
28 long Flags)
30 WebcitHandler *NewHandler;
32 if (HandlerHash == NULL)
33 HandlerHash = NewHash(1, NULL);
35 NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
36 NewHandler->F = F;
37 NewHandler->Flags = Flags;
38 Put(HandlerHash, UrlString, UrlSLen, NewHandler, NULL);
43 * web-printing funcion. uses our vsnprintf wrapper
45 void wprintf(const char *format,...)
47 wcsession *WCC = WC;
48 va_list arg_ptr;
50 if (WCC->WBuf == NULL)
51 WCC->WBuf = NewStrBuf();
53 va_start(arg_ptr, format);
54 StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
55 va_end(arg_ptr);
59 * http-header-printing funcion. uses our vsnprintf wrapper
61 void hprintf(const char *format,...)
63 wcsession *WCC = WC;
64 va_list arg_ptr;
66 va_start(arg_ptr, format);
67 StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
68 va_end(arg_ptr);
74 * wrap up an HTTP session, closes tags, etc.
76 * print_standard_html_footer should be set to:
77 * 0 - to transmit only,
78 * nonzero - to append the closing tags
80 void wDumpContent(int print_standard_html_footer)
82 if (print_standard_html_footer) {
83 wprintf("</div> <!-- end of 'content' div -->\n");
84 do_template("trailing", NULL);
87 /* If we've been saving it all up for one big output burst,
88 * go ahead and do that now.
90 end_burst();
97 * Output HTTP headers and leading HTML for a page
99 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
100 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
102 int do_room_banner, /* 0=no, 1=yes,
103 * 2 = I'm going to embed my own, so don't open the
104 * <div id="content"> either.
107 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
108 int suppress_check, /* 1 = suppress check for instant messages */
109 int cache /* 1 = allow browser to cache this page */
111 wcsession *WCC = WC;
112 char cookie[1024];
113 char httpnow[128];
115 hprintf("HTTP/1.1 200 OK\n");
116 http_datestring(httpnow, sizeof httpnow, time(NULL));
118 if (do_httpheaders) {
119 if (WCC->serv_info != NULL)
120 hprintf("Content-type: text/html; charset=utf-8\r\n"
121 "Server: %s / %s\n"
122 "Connection: close\r\n",
123 PACKAGE_STRING,
124 ChrPtr(WCC->serv_info->serv_software));
125 else
126 hprintf("Content-type: text/html; charset=utf-8\r\n"
127 "Server: %s / [n/a]\n"
128 "Connection: close\r\n",
129 PACKAGE_STRING);
132 if (cache) {
133 char httpTomorow[128];
135 http_datestring(httpTomorow, sizeof httpTomorow,
136 time(NULL) + 60 * 60 * 24 * 2);
138 hprintf("Pragma: public\r\n"
139 "Cache-Control: max-age=3600, must-revalidate\r\n"
140 "Last-modified: %s\r\n"
141 "Expires: %s\r\n",
142 httpnow,
143 httpTomorow
146 else {
147 hprintf("Pragma: no-cache\r\n"
148 "Cache-Control: no-store\r\n"
149 "Expires: -1\r\n"
153 stuff_to_cookie(cookie, 1024,
154 WCC->wc_session, WCC->wc_username,
155 WCC->wc_password, WCC->wc_roomname);
157 if (unset_cookies) {
158 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
159 } else {
160 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
161 if (server_cookie != NULL) {
162 hprintf("%s\n", server_cookie);
166 if (do_htmlhead) {
167 begin_burst();
168 do_template("head", NULL);
170 /* check for ImportantMessages (these display in a div overlaying the main screen) */
171 if (!IsEmptyStr(WC->ImportantMessage)) {
172 wprintf("<div id=\"important_message\">\n"
173 "<span class=\"imsg\">");
174 escputs(WC->ImportantMessage);
175 wprintf("</span><br />\n"
176 "</div>\n"
178 StrBufAppendPrintf(WCC->trailing_javascript,
179 "setTimeout('hide_imsg_popup()', 5000); \n"
181 WCC->ImportantMessage[0] = 0;
184 if ( (WCC->logged_in) && (!unset_cookies) ) {
185 //DoTemplate(HKEY("iconbar"), NULL, &NoCtx);
186 page_popup();
189 if (do_room_banner == 1) {
190 wprintf("<div id=\"banner\">\n");
191 embed_room_banner(NULL, navbar_default);
192 wprintf("</div>\n");
196 if (do_room_banner == 1) {
197 wprintf("<div id=\"content\">\n");
201 void output_custom_content_header(const char *ctype) {
202 hprintf("HTTP/1.1 200 OK\r\n");
203 hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
204 hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
205 hprintf("Connection: close\r\n");
210 * Generic function to do an HTTP redirect. Easy and fun.
212 void http_redirect(const char *whichpage) {
213 hprintf("HTTP/1.1 302 Moved Temporarily\n");
214 hprintf("Location: %s\r\n", whichpage);
215 hprintf("URI: %s\r\n", whichpage);
216 hprintf("Content-type: text/html; charset=utf-8\r\n");
217 wprintf("<html><body>");
218 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
219 wprintf("</body></html>\n");
220 end_burst();
226 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
228 void http_transmit_thing(const char *content_type,
229 int is_static) {
231 #ifndef TECH_PREVIEW
232 lprintf(9, "http_transmit_thing(%s)%s\n",
233 content_type,
234 (is_static ? " (static)" : "")
236 #endif
237 output_headers(0, 0, 0, 0, 0, is_static);
239 hprintf("Content-type: %s\r\n"
240 "Server: %s\r\n"
241 "Connection: close\r\n",
242 content_type,
243 PACKAGE_STRING);
245 end_burst();
249 * print menu box like used in the floor view or admin interface.
250 * This function takes pair of strings as va_args,
251 * Title Title string of the box
252 * Class CSS Class for the box
253 * nLines How many string pairs should we print? (URL, UrlText)
254 * ... Pairs of URL Strings and their Names
256 void print_menu_box(char* Title, char *Class, int nLines, ...)
258 va_list arg_list;
259 long i;
261 svput("BOXTITLE", WCS_STRING, Title);
262 do_template("beginboxx", NULL);
264 wprintf("<ul class=\"%s\">", Class);
266 va_start(arg_list, nLines);
267 for (i = 0; i < nLines; ++i)
269 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
270 wprintf((char *) va_arg(arg_list, char *));
271 wprintf("</a></li>\n");
273 va_end (arg_list);
275 wprintf("</a></li>\n");
277 wprintf("</ul>");
279 do_template("endbox", NULL);
284 * dump out static pages from disk
286 void output_static(char *what)
288 int fd;
289 struct stat statbuf;
290 off_t bytes;
291 off_t count = 0;
292 const char *content_type;
293 int len;
294 const char *Err;
296 fd = open(what, O_RDONLY);
297 if (fd <= 0) {
298 lprintf(9, "output_static('%s') -- NOT FOUND --\n", what);
299 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
300 hprintf("Content-Type: text/plain\r\n");
301 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
302 end_burst();
303 } else {
304 len = strlen (what);
305 content_type = GuessMimeByFilename(what, len);
307 if (fstat(fd, &statbuf) == -1) {
308 lprintf(9, "output_static('%s') -- FSTAT FAILED --\n", what);
309 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
310 hprintf("Content-Type: text/plain\r\n");
311 wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
312 end_burst();
313 return;
316 count = 0;
317 bytes = statbuf.st_size;
319 if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
321 if (fd > 0) close(fd);
322 lprintf(9, "output_static('%s') -- FREAD FAILED (%s) --\n", what, strerror(errno));
323 hprintf("HTTP/1.1 500 internal server error \r\n");
324 hprintf("Content-Type: text/plain\r\n");
325 end_burst();
326 return;
330 close(fd);
331 #ifndef TECH_PREVIEW
332 lprintf(9, "output_static('%s') %s\n", what, content_type);
333 #endif
334 http_transmit_thing(content_type, 1);
336 if (yesbstr("force_close_session")) {
337 end_webcit_session();
343 * Convenience functions to display a page containing only a string
345 * titlebarcolor color of the titlebar of the frame
346 * titlebarmsg text to display in the title bar
347 * messagetext body of the box
349 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
351 hprintf("HTTP/1.1 200 OK\n");
352 output_headers(1, 1, 2, 0, 0, 0);
353 wprintf("<div id=\"banner\">\n");
354 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
355 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
356 wprintf("</td></tr></table>\n");
357 wprintf("</div>\n<div id=\"content\">\n");
358 escputs(messagetext);
360 wprintf("<hr />\n");
361 wDumpContent(1);
366 * Display a blank page.
368 void blank_page(void) {
369 output_headers(1, 1, 0, 0, 0, 0);
370 wDumpContent(2);
375 * A template has been requested
377 void url_do_template(void) {
378 const StrBuf *MimeType;
379 const StrBuf *Tmpl = sbstr("template");
380 begin_burst();
381 output_headers(0, 0, 0, 0, 1, 0);
382 MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
383 http_transmit_thing(ChrPtr(MimeType), 0);
389 * convenience function to indicate success
391 void display_success(char *successmessage)
393 convenience_page("007700", "OK", successmessage);
398 * Authorization required page
399 * This is probably temporary and should be revisited
401 void authorization_required(const char *message)
403 hprintf("HTTP/1.1 401 Authorization Required\r\n");
404 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
405 hprintf("Content-Type: text/html\r\n");
406 wprintf("<h1>");
407 wprintf(_("Authorization Required"));
408 wprintf("</h1>\r\n");
409 wprintf(_("The resource you requested requires a valid username and password. "
410 "You could not be logged in: %s\n"), message);
411 wDumpContent(0);
416 * Convenience functions to wrap around asynchronous ajax responses
418 void begin_ajax_response(void) {
419 wcsession *WCC = WC;
421 FlushStrBuf(WCC->HBuf);
422 output_headers(0, 0, 0, 0, 0, 0);
424 hprintf("Content-type: text/html; charset=UTF-8\r\n"
425 "Server: %s\r\n"
426 "Connection: close\r\n"
428 PACKAGE_STRING);
429 begin_burst();
433 * print ajax response footer
435 void end_ajax_response(void) {
436 wDumpContent(0);
440 * Wraps a Citadel server command in an AJAX transaction.
442 void ajax_servcmd(void)
444 char buf[1024];
445 char gcontent[1024];
446 char *junk;
447 size_t len;
449 begin_ajax_response();
451 serv_printf("%s", bstr("g_cmd"));
452 serv_getln(buf, sizeof buf);
453 wprintf("%s\n", buf);
455 if (buf[0] == '8') {
456 serv_printf("\n\n000");
458 if ((buf[0] == '1') || (buf[0] == '8')) {
459 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
460 wprintf("%s\n", gcontent);
462 wprintf("000");
464 if (buf[0] == '4') {
465 text_to_server(bstr("g_input"));
466 serv_puts("000");
468 if (buf[0] == '6') {
469 len = atol(&buf[4]);
470 junk = malloc(len);
471 serv_read(junk, len);
472 free(junk);
474 if (buf[0] == '7') {
475 len = atol(&buf[4]);
476 junk = malloc(len);
477 memset(junk, 0, len);
478 serv_write(junk, len);
479 free(junk);
482 end_ajax_response();
485 * This is kind of an ugly hack, but this is the only place it can go.
486 * If the command was GEXP, then the instant messenger window must be
487 * running, so reset the "last_pager_check" watchdog timer so
488 * that page_popup() doesn't try to open it a second time.
490 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
491 WC->last_pager_check = time(NULL);
497 * Helper function for the asynchronous check to see if we need
498 * to open the instant messenger window.
500 void seconds_since_last_gexp(void)
502 char buf[256];
504 if ( (time(NULL) - WC->last_pager_check) < 30) {
505 wprintf("NO\n");
507 else {
508 memset(buf, 0, 5);
509 serv_puts("NOOP");
510 serv_getln(buf, sizeof buf);
511 if (buf[3] == '*') {
512 wprintf("YES");
514 else {
515 wprintf("NO");
521 * \brief Detects a 'mobile' user agent
523 int is_mobile_ua(char *user_agent) {
524 if (strstr(user_agent,"iPhone OS") != NULL) {
525 return 1;
526 } else if (strstr(user_agent,"Windows CE") != NULL) {
527 return 1;
528 } else if (strstr(user_agent,"SymbianOS") != NULL) {
529 return 1;
530 } else if (strstr(user_agent, "Opera Mobi") != NULL) {
531 return 1;
532 } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
533 /* For some reason a new install of Opera 9.51beta decided to spoof. */
534 return 1;
536 return 0;
541 * Entry point for WebCit transaction
543 void session_loop(HashList *HTTPHeaders, StrBuf *ReqLine, StrBuf *request_method, StrBuf *ReadBuf)
545 StrBuf *Buf;
546 const char *pch, *pchs, *pche;
547 void *vLine;
548 char action[1024];
549 char arg[8][128];
550 size_t sizes[10];
551 char *index[10];
552 char buf[SIZ];
553 int a, nBackDots, nEmpty;
554 int ContentLength = 0;
555 StrBuf *ContentType = NULL;
556 StrBuf *UrlLine = NULL;
557 StrBuf *content = NULL;
558 const char *content_end = NULL;
559 StrBuf *browser_host = NULL;
560 char user_agent[256];
561 int body_start = 0;
562 int is_static = 0;
563 int n_static = 0;
564 int len = 0;
565 void *vHandler;
566 WebcitHandler *Handler;
569 * We stuff these with the values coming from the client cookies,
570 * so we can use them to reconnect a timed out session if we have to.
572 StrBuf *c_username;
573 StrBuf *c_password;
574 StrBuf *c_roomname;
575 char c_httpauth_string[SIZ];
576 StrBuf *c_httpauth_user;
577 StrBuf *c_httpauth_pass;
578 wcsession *WCC;
580 Buf = NewStrBuf();
581 c_username = NewStrBuf();
582 c_password = NewStrBuf();
583 c_roomname = NewStrBuf();
584 safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
585 c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
586 c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
588 WCC= WC;
589 if (WCC->WBuf == NULL)
590 WC->WBuf = NewStrBufPlain(NULL, 32768);
591 FlushStrBuf(WCC->WBuf);
593 if (WCC->HBuf == NULL)
594 WCC->HBuf = NewStrBuf();
595 FlushStrBuf(WCC->HBuf);
597 WCC->upload_length = 0;
598 WCC->upload = NULL;
599 WCC->is_mobile = 0;
600 WCC->trailing_javascript = NewStrBuf();
601 WCC->nWildfireHeaders = 0;
603 /** Figure out the action */
604 index[0] = action;
605 sizes[0] = sizeof action;
606 for (a=1; a<9; a++)
608 index[a] = arg[a-1];
609 sizes[a] = sizeof arg[a-1];
611 nBackDots = 0;
612 nEmpty = 0;
613 for ( a = 0; a < 9; ++a)
615 extract_token(index[a], ChrPtr(ReqLine), a + 1, '/', sizes[a]);
616 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
617 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
618 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
619 if ((index[a][0] == '.') && (index[a][1] == '.'))
620 nBackDots++;
621 if (index[a][0] == '\0')
622 nEmpty++;
626 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
627 (vLine != NULL)){
628 cookie_to_stuff((StrBuf *)vLine, NULL,
629 c_username,
630 c_password,
631 c_roomname);
633 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
634 (vLine!=NULL)) {
635 StrBufDecodeBase64((StrBuf*)vLine);
636 StrBufExtract_token(c_httpauth_user, (StrBuf*)vLine, 0, ':');
637 StrBufExtract_token(c_httpauth_pass, (StrBuf*)vLine, 1, ':');
639 if (GetHash(HTTPHeaders, HKEY("CONTENT-LENGTH"), &vLine) &&
640 (vLine!=NULL)) {
641 ContentLength = StrToi((StrBuf*)vLine);
643 if (GetHash(HTTPHeaders, HKEY("CONTENT-TYPE"), &vLine) &&
644 (vLine!=NULL)) {
645 ContentType = (StrBuf*)vLine;
647 if (GetHash(HTTPHeaders, HKEY("USER-AGENT"), &vLine) &&
648 (vLine!=NULL)) {
649 safestrncpy(user_agent, ChrPtr((StrBuf*)vLine), sizeof user_agent);
650 #ifdef TECH_PREVIEW
651 if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {
652 WCC->is_mobile = 1;
654 else {
655 WCC->is_mobile = 0;
657 #endif
659 if ((follow_xff) &&
660 GetHash(HTTPHeaders, HKEY("X-FORWARDED-HOST"), &vLine) &&
661 (vLine != NULL)) {
662 WCC->http_host = (StrBuf*)vLine;
664 if ((StrLength(WCC->http_host) == 0) &&
665 GetHash(HTTPHeaders, HKEY("HOST"), &vLine) &&
666 (vLine!=NULL)) {
667 WCC->http_host = (StrBuf*)vLine;
670 if (GetHash(HTTPHeaders, HKEY("X-FORWARDED-FOR"), &vLine) &&
671 (vLine!=NULL)) {
672 browser_host = (StrBuf*) vLine;
674 while (StrBufNum_tokens(browser_host, ',') > 1) {
675 StrBufRemove_token(browser_host, 0, ',');
677 StrBufTrim(browser_host);
680 if (ContentLength > 0) {
681 content = NewStrBuf();
682 StrBufPrintf(content, "Content-type: %s\n"
683 "Content-length: %d\n\n",
684 ChrPtr(ContentType), ContentLength);
686 hprintf("Content-type: %s\n"
687 "Content-length: %d\n\n",
688 ContentType, ContentLength);
690 body_start = StrLength(content);
692 /** Read the entire input data at once. */
693 client_read(&WCC->http_sock, content, ReadBuf, ContentLength + body_start);
695 if (!strncasecmp(ChrPtr(ContentType), "application/x-www-form-urlencoded", 33)) {
696 StrBufCutLeft(content, body_start);
697 ParseURLParams(content);
698 } else if (!strncasecmp(ChrPtr(ContentType), "multipart", 9)) {
699 content_end = ChrPtr(content) + ContentLength + body_start;
700 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
702 } else {
703 content = NULL;
706 /* make a note of where we are in case the user wants to save it */
707 WCC->this_page = NewStrBufDup(ReqLine);
708 StrBufRemove_token(WCC->this_page, 2, ' ');
709 StrBufRemove_token(WCC->this_page, 0, ' ');
711 /* If there are variables in the URL, we must grab them now */
712 UrlLine = NewStrBufDup(ReqLine);
713 len = StrLength(UrlLine);
714 pch = pchs = ChrPtr(UrlLine);
715 pche = pchs + len;
716 while (pch < pche) {
717 if ((*pch == '?') || (*pch == '&')) {
718 StrBufCutLeft(UrlLine, pch - pchs + 1);
719 ParseURLParams(UrlLine);
720 break;
722 pch ++;
724 FreeStrBuf(&UrlLine);
726 /* If it's a "force 404" situation then display the error and bail. */
727 if (!strcmp(action, "404")) {
728 hprintf("HTTP/1.1 404 Not found\r\n");
729 hprintf("Content-Type: text/plain\r\n");
730 wprintf("Not found\r\n");
731 end_burst();
732 goto SKIP_ALL_THIS_CRAP;
735 /* Static content can be sent without connecting to Citadel. */
736 is_static = 0;
737 for (a=0; a<ndirs && ! is_static; ++a) {
738 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
739 is_static = 1;
740 n_static = a;
743 if (is_static) {
744 if (nBackDots < 2)
746 snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
747 static_dirs[n_static],
748 index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
749 for (a=0; a<8; ++a) {
750 if (buf[strlen(buf)-1] == '/') {
751 buf[strlen(buf)-1] = 0;
754 for (a = 0; a < strlen(buf); ++a) {
755 if (isspace(buf[a])) {
756 buf[a] = 0;
759 output_static(buf);
761 else
763 lprintf(9, "Suspicious request. Ignoring.");
764 hprintf("HTTP/1.1 404 Security check failed\r\n");
765 hprintf("Content-Type: text/plain\r\n\r\n");
766 wprintf("You have sent a malformed or invalid request.\r\n");
767 end_burst();
769 goto SKIP_ALL_THIS_CRAP; /* Don't try to connect */
772 /* If the client sent a nonce that is incorrect, kill the request. */
773 if (strlen(bstr("nonce")) > 0) {
774 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
775 bstr("nonce"), WCC->nonce);
776 if (ibstr("nonce") != WCC->nonce) {
777 lprintf(9, "Ignoring request with mismatched nonce.\n");
778 hprintf("HTTP/1.1 404 Security check failed\r\n");
779 hprintf("Content-Type: text/plain\r\n\r\n");
780 wprintf("Security check failed.\r\n");
781 end_burst();
782 goto SKIP_ALL_THIS_CRAP;
787 * If we're not connected to a Citadel server, try to hook up the
788 * connection now.
790 if (!WCC->connected) {
791 if (WCC->ReadBuf == NULL)
792 WCC->ReadBuf = NewStrBuf();
793 if (!strcasecmp(ctdlhost, "uds")) {
794 /* unix domain socket */
795 snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
796 WCC->serv_sock = uds_connectsock(buf);
798 else {
799 /* tcp socket */
800 WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
803 if (WCC->serv_sock < 0) {
804 do_logout();
805 FreeStrBuf(&WCC->ReadBuf);
806 goto SKIP_ALL_THIS_CRAP;
808 else {
809 WCC->connected = 1;
810 serv_getln(buf, sizeof buf); /* get the server greeting */
812 /* Are there too many users already logged in? */
813 if (!strncmp(buf, "571", 3)) {
814 wprintf(_("This server is already serving its maximum number of users and cannot accept any additional logins at this time. Please try again later or contact your system administrator."));
815 end_burst();
816 end_webcit_session();
817 goto SKIP_ALL_THIS_CRAP;
821 * From what host is our user connecting? Go with
822 * the host at the other end of the HTTP socket,
823 * unless we are following X-Forwarded-For: headers
824 * and such a header has already turned up something.
826 if ( (!follow_xff) || (StrLength(browser_host) == 0) ) {
827 if (browser_host == NULL) {
828 browser_host = NewStrBuf();
829 Put(HTTPHeaders, HKEY("FreeMeWithTheOtherHeaders"),
830 browser_host, HFreeStrBuf);
832 locate_host(browser_host, WCC->http_sock);
834 if (WCC->serv_info == NULL)
835 WCC->serv_info = get_serv_info(browser_host, user_agent);
836 if (WCC->serv_info->serv_rev_level < MINIMUM_CIT_VERSION) {
837 begin_burst();
838 wprintf(_("You are connected to a Citadel "
839 "server running Citadel %d.%02d. \n"
840 "In order to run this version of WebCit "
841 "you must also have Citadel %d.%02d or"
842 " newer.\n\n\n"),
843 WCC->serv_info->serv_rev_level / 100,
844 WCC->serv_info->serv_rev_level % 100,
845 MINIMUM_CIT_VERSION / 100,
846 MINIMUM_CIT_VERSION % 100
848 end_burst();
849 end_webcit_session();
850 goto SKIP_ALL_THIS_CRAP;
856 * Functions which can be performed without logging in
858 if (!strcasecmp(action, "listsub")) {
859 do_listsub();
860 goto SKIP_ALL_THIS_CRAP;
862 if (!strcasecmp(action, "freebusy")) {
863 do_freebusy(ChrPtr(ReqLine));
864 goto SKIP_ALL_THIS_CRAP;
868 * If we're not logged in, but we have HTTP Authentication data,
869 * try logging in to Citadel using that.
871 if ((!WCC->logged_in)
872 && (StrLength(c_httpauth_user) > 0)
873 && (StrLength(c_httpauth_pass) > 0))
875 FlushStrBuf(Buf);
876 serv_printf("USER %s", ChrPtr(c_httpauth_user));
877 StrBuf_ServGetln(Buf);
878 if (GetServerStatus(Buf, NULL) == 3) {
879 serv_printf("PASS %s", ChrPtr(c_httpauth_pass));
880 StrBuf_ServGetln(Buf);
881 if (GetServerStatus(Buf, NULL) == 2) {
882 become_logged_in(c_httpauth_user,
883 c_httpauth_pass, Buf);
884 if (WCC->httpauth_user == NULL)
885 WCC->httpauth_user = NewStrBufDup(c_httpauth_user);
886 else {
887 FlushStrBuf(WCC->httpauth_user);
888 StrBufAppendBuf(WCC->httpauth_user, c_httpauth_user, 0);
890 if (WCC->httpauth_pass == NULL)
891 WCC->httpauth_pass = NewStrBufDup(c_httpauth_pass);
892 else {
893 FlushStrBuf(WCC->httpauth_pass);
894 StrBufAppendBuf(WCC->httpauth_pass, c_httpauth_pass, 0);
896 } else {
897 /* Should only display when password is wrong */
898 authorization_required(&buf[4]);
899 FreeStrBuf(&Buf);
900 goto SKIP_ALL_THIS_CRAP;
905 /* This needs to run early */
906 #ifdef TECH_PREVIEW
907 if (!strcasecmp(action, "rss")) {
908 display_rss(sbstr("room"), request_method);
909 goto SKIP_ALL_THIS_CRAP;
911 #endif
914 * The GroupDAV stuff relies on HTTP authentication instead of
915 * our session's authentication.
917 if (!strncasecmp(action, "groupdav", 8)) {
918 groupdav_main(HTTPHeaders,
919 ReqLine, request_method,
920 ContentType, /* do GroupDAV methods */
921 ContentLength, content, body_start);
922 if (!WCC->logged_in) {
923 WCC->killthis = 1; /* If not logged in, don't */
924 } /* keep the session active */
925 goto SKIP_ALL_THIS_CRAP;
930 * Automatically send requests with any method other than GET or
931 * POST to the GroupDAV code as well.
933 if ((strcasecmp(ChrPtr(request_method), "GET")) && (strcasecmp(ChrPtr(request_method), "POST"))) {
934 groupdav_main(HTTPHeaders, ReqLine,
935 request_method, ContentType, /** do GroupDAV methods */
936 ContentLength, content, body_start);
937 if (!WCC->logged_in) {
938 WCC->killthis = 1; /** If not logged in, don't */
939 } /** keep the session active */
940 goto SKIP_ALL_THIS_CRAP;
944 * If we're not logged in, but we have username and password cookies
945 * supplied by the browser, try using them to log in.
947 if ((!WCC->logged_in)
948 && (StrLength(c_username)>0)
949 && (StrLength(c_password)>0)) {
950 serv_printf("USER %s", ChrPtr(c_username));
951 StrBuf_ServGetln(Buf);
952 if (GetServerStatus(Buf, NULL) == 3) {
953 serv_printf("PASS %s", ChrPtr(c_password));
954 StrBuf_ServGetln(Buf);
955 if (GetServerStatus(Buf, NULL) == 2) {
956 become_logged_in(c_username, c_password, Buf);
957 get_preference("default_header_charset", &WCC->DefaultCharset);
963 * If a 'gotofirst' parameter has been specified, attempt to goto that room
964 * prior to doing anything else.
966 if (havebstr("gotofirst")) {
967 gotoroom(sbstr("gotofirst")); /* do this quietly to avoid session output! */
971 * If we don't have a current room, but a cookie specifying the
972 * current room is supplied, make an effort to go there.
974 if ((StrLength(WCC->wc_roomname) == 0) && (StrLength(c_roomname) > 0)) {
975 serv_printf("GOTO %s", ChrPtr(c_roomname));
976 StrBuf_ServGetln(Buf);
977 if (GetServerStatus(Buf, NULL) == 2) {
978 if (WCC->wc_roomname == NULL) {
979 WCC->wc_roomname = NewStrBufDup(c_roomname);
981 else {
982 FlushStrBuf(WCC->wc_roomname);
983 StrBufAppendBuf(WCC->wc_roomname, c_roomname, 0);
988 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
989 Handler = (WebcitHandler*) vHandler;
990 if (Handler != NULL) {
991 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
992 display_login(NULL);
994 else {
995 if((Handler->Flags & NEED_URL)) {
996 if (WCC->UrlFragment1 == NULL)
997 WCC->UrlFragment1 = NewStrBuf();
998 if (WCC->UrlFragment2 == NULL)
999 WCC->UrlFragment2 = NewStrBuf();
1000 if (WCC->UrlFragment3 == NULL)
1001 WCC->UrlFragment3 = NewStrBuf();
1002 if (WCC->UrlFragment4 == NULL)
1003 WCC->UrlFragment4 = NewStrBuf();
1004 StrBufPlain(WCC->UrlFragment1, index[0], -1);
1005 StrBufPlain(WCC->UrlFragment2, index[1], -1);
1006 StrBufPlain(WCC->UrlFragment3, index[2], -1);
1007 StrBufPlain(WCC->UrlFragment4, index[3], -1);
1009 if ((Handler->Flags & AJAX) != 0)
1010 begin_ajax_response();
1011 Handler->F();
1012 if ((Handler->Flags & AJAX) != 0)
1013 end_ajax_response();
1016 /* When all else fais, display the main menu. */
1017 else {
1018 if (!WCC->logged_in)
1019 display_login(NULL);
1020 else
1021 display_main_menu();
1024 SKIP_ALL_THIS_CRAP:
1025 if (WCC->SavePrefsToServer) {
1026 save_preferences();
1027 WCC->SavePrefsToServer = 0;
1029 FreeStrBuf(&Buf);
1030 FreeStrBuf(&c_username);
1031 FreeStrBuf(&c_password);
1032 FreeStrBuf(&c_roomname);
1033 FreeStrBuf(&c_httpauth_user);
1034 FreeStrBuf(&c_httpauth_pass);
1035 FreeStrBuf(&WCC->this_page);
1036 fflush(stdout);
1037 if (content != NULL) {
1038 FreeStrBuf(&content);
1039 content = NULL;
1041 DeleteHash(&WCC->urlstrings);
1042 if (WCC->upload_length > 0) {
1043 free(WCC->upload);
1044 WCC->upload_length = 0;
1046 FreeStrBuf(&WCC->trailing_javascript);
1047 WCC->http_host = NULL;
1052 * Replacement for sleep() that uses select() in order to avoid SIGALRM
1054 void sleeeeeeeeeep(int seconds)
1056 struct timeval tv;
1058 tv.tv_sec = seconds;
1059 tv.tv_usec = 0;
1060 select(0, NULL, NULL, NULL, &tv);
1064 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
1066 wcsession *WCC = WC;
1067 if (WCC != NULL)
1068 return (!IsEmptyStr(WCC->ImportantMessage));
1069 else
1070 return 0;
1073 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
1075 wcsession *WCC = WC;
1077 if (WCC != NULL) {
1079 StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType,
1080 WCC->ImportantMessage, 0);
1082 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
1083 WCC->ImportantMessage[0] = '\0';
1087 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
1089 wcsession *WCC = WC;
1091 if (WCC != NULL)
1092 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
1095 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
1097 extern StrBuf *csslocal;
1098 StrBufAppendBuf(Target,
1099 csslocal, 0);
1105 void
1106 InitModule_WEBCIT
1107 (void)
1109 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1110 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1111 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1112 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1114 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
1115 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
1116 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
1117 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);