* Added another conditional for presence/absence of Subject: header
[citadel.git] / webcit / webcit.c
blob3904d043199465dc1ed46c2fee4b220423972526
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 char cookie[1024];
112 char httpnow[128];
114 hprintf("HTTP/1.1 200 OK\n");
115 http_datestring(httpnow, sizeof httpnow, time(NULL));
117 if (do_httpheaders) {
118 hprintf("Content-type: text/html; charset=utf-8\r\n"
119 "Server: %s / %s\n"
120 "Connection: close\r\n",
121 PACKAGE_STRING,
122 ChrPtr(serv_info.serv_software)
126 if (cache) {
127 char httpTomorow[128];
129 http_datestring(httpTomorow, sizeof httpTomorow,
130 time(NULL) + 60 * 60 * 24 * 2);
132 hprintf("Pragma: public\r\n"
133 "Cache-Control: max-age=3600, must-revalidate\r\n"
134 "Last-modified: %s\r\n"
135 "Expires: %s\r\n",
136 httpnow,
137 httpTomorow
140 else {
141 hprintf("Pragma: no-cache\r\n"
142 "Cache-Control: no-store\r\n"
143 "Expires: -1\r\n"
147 stuff_to_cookie(cookie, 1024,
148 WC->wc_session, WC->wc_username,
149 WC->wc_password, WC->wc_roomname);
151 if (unset_cookies) {
152 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
153 } else {
154 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
155 if (server_cookie != NULL) {
156 hprintf("%s\n", server_cookie);
160 if (do_htmlhead) {
161 begin_burst();
162 do_template("head", NULL);
164 /* check for ImportantMessages (these display in a div overlaying the main screen) */
165 if (!IsEmptyStr(WC->ImportantMessage)) {
166 wprintf("<div id=\"important_message\">\n"
167 "<span class=\"imsg\">");
168 escputs(WC->ImportantMessage);
169 wprintf("</span><br />\n"
170 "</div>\n"
171 "<script type=\"text/javascript\">\n"
172 " setTimeout('hide_imsg_popup()', 5000); \n"
173 "</script>\n");
174 WC->ImportantMessage[0] = 0;
177 if ( (WC->logged_in) && (!unset_cookies) ) {
178 //DoTemplate(HKEY("iconbar"), NULL, &NoCtx);
179 page_popup();
182 if (do_room_banner == 1) {
183 wprintf("<div id=\"banner\">\n");
184 embed_room_banner(NULL, navbar_default);
185 wprintf("</div>\n");
189 if (do_room_banner == 1) {
190 wprintf("<div id=\"content\">\n");
194 void output_custom_content_header(const char *ctype) {
195 hprintf("HTTP/1.1 200 OK\r\n");
196 hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
197 hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(serv_info.serv_software));
198 hprintf("Connection: close\r\n");
203 * Generic function to do an HTTP redirect. Easy and fun.
205 void http_redirect(const char *whichpage) {
206 hprintf("HTTP/1.1 302 Moved Temporarily\n");
207 hprintf("Location: %s\r\n", whichpage);
208 hprintf("URI: %s\r\n", whichpage);
209 hprintf("Content-type: text/html; charset=utf-8\r\n");
210 wprintf("<html><body>");
211 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
212 wprintf("</body></html>\n");
213 end_burst();
219 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
221 void http_transmit_thing(const char *content_type,
222 int is_static) {
224 #ifndef TECH_PREVIEW
225 lprintf(9, "http_transmit_thing(%s)%s\n",
226 content_type,
227 (is_static ? " (static)" : "")
229 #endif
230 output_headers(0, 0, 0, 0, 0, is_static);
232 hprintf("Content-type: %s\r\n"
233 "Server: %s\r\n"
234 "Connection: close\r\n",
235 content_type,
236 PACKAGE_STRING);
238 end_burst();
242 * print menu box like used in the floor view or admin interface.
243 * This function takes pair of strings as va_args,
244 * Title Title string of the box
245 * Class CSS Class for the box
246 * nLines How many string pairs should we print? (URL, UrlText)
247 * ... Pairs of URL Strings and their Names
249 void print_menu_box(char* Title, char *Class, int nLines, ...)
251 va_list arg_list;
252 long i;
254 svput("BOXTITLE", WCS_STRING, Title);
255 do_template("beginboxx", NULL);
257 wprintf("<ul class=\"%s\">", Class);
259 va_start(arg_list, nLines);
260 for (i = 0; i < nLines; ++i)
262 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
263 wprintf((char *) va_arg(arg_list, char *));
264 wprintf("</a></li>\n");
266 va_end (arg_list);
268 wprintf("</a></li>\n");
270 wprintf("</ul>");
272 do_template("endbox", NULL);
277 * dump out static pages from disk
279 void output_static(char *what)
281 int fd;
282 struct stat statbuf;
283 off_t bytes;
284 off_t count = 0;
285 const char *content_type;
286 int len;
287 const char *Err;
289 fd = open(what, O_RDONLY);
290 if (fd <= 0) {
291 lprintf(9, "output_static('%s') -- NOT FOUND --\n", what);
292 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
293 hprintf("Content-Type: text/plain\r\n");
294 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
295 end_burst();
296 } else {
297 len = strlen (what);
298 content_type = GuessMimeByFilename(what, len);
300 if (fstat(fd, &statbuf) == -1) {
301 lprintf(9, "output_static('%s') -- FSTAT FAILED --\n", what);
302 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
303 hprintf("Content-Type: text/plain\r\n");
304 wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
305 end_burst();
306 return;
309 count = 0;
310 bytes = statbuf.st_size;
312 if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
314 if (fd > 0) close(fd);
315 lprintf(9, "output_static('%s') -- FREAD FAILED (%s) --\n", what, strerror(errno));
316 hprintf("HTTP/1.1 500 internal server error \r\n");
317 hprintf("Content-Type: text/plain\r\n");
318 end_burst();
319 return;
323 close(fd);
324 #ifndef TECH_PREVIEW
325 lprintf(9, "output_static('%s') %s\n", what, content_type);
326 #endif
327 http_transmit_thing(content_type, 1);
329 if (yesbstr("force_close_session")) {
330 end_webcit_session();
336 * Convenience functions to display a page containing only a string
338 * titlebarcolor color of the titlebar of the frame
339 * titlebarmsg text to display in the title bar
340 * messagetext body of the box
342 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
344 hprintf("HTTP/1.1 200 OK\n");
345 output_headers(1, 1, 2, 0, 0, 0);
346 wprintf("<div id=\"banner\">\n");
347 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
348 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
349 wprintf("</td></tr></table>\n");
350 wprintf("</div>\n<div id=\"content\">\n");
351 escputs(messagetext);
353 wprintf("<hr />\n");
354 wDumpContent(1);
359 * Display a blank page.
361 void blank_page(void) {
362 output_headers(1, 1, 0, 0, 0, 0);
363 wDumpContent(2);
368 * A template has been requested
370 void url_do_template(void) {
371 const StrBuf *MimeType;
372 const StrBuf *Tmpl = sbstr("template");
373 begin_burst();
374 output_headers(0, 0, 0, 0, 1, 0);
375 MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
376 http_transmit_thing(ChrPtr(MimeType), 0);
382 * convenience function to indicate success
384 void display_success(char *successmessage)
386 convenience_page("007700", "OK", successmessage);
391 * Authorization required page
392 * This is probably temporary and should be revisited
394 void authorization_required(const char *message)
396 hprintf("HTTP/1.1 401 Authorization Required\r\n");
397 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(serv_info.serv_humannode));
398 hprintf("Content-Type: text/html\r\n");
399 wprintf("<h1>");
400 wprintf(_("Authorization Required"));
401 wprintf("</h1>\r\n");
402 wprintf(_("The resource you requested requires a valid username and password. "
403 "You could not be logged in: %s\n"), message);
404 wDumpContent(0);
409 * Convenience functions to wrap around asynchronous ajax responses
411 void begin_ajax_response(void) {
412 wcsession *WCC = WC;
414 FlushStrBuf(WCC->HBuf);
415 output_headers(0, 0, 0, 0, 0, 0);
417 hprintf("Content-type: text/html; charset=UTF-8\r\n"
418 "Server: %s\r\n"
419 "Connection: close\r\n"
421 PACKAGE_STRING);
422 begin_burst();
426 * print ajax response footer
428 void end_ajax_response(void) {
429 wDumpContent(0);
433 * Wraps a Citadel server command in an AJAX transaction.
435 void ajax_servcmd(void)
437 char buf[1024];
438 char gcontent[1024];
439 char *junk;
440 size_t len;
442 begin_ajax_response();
444 serv_printf("%s", bstr("g_cmd"));
445 serv_getln(buf, sizeof buf);
446 wprintf("%s\n", buf);
448 if (buf[0] == '8') {
449 serv_printf("\n\n000");
451 if ((buf[0] == '1') || (buf[0] == '8')) {
452 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
453 wprintf("%s\n", gcontent);
455 wprintf("000");
457 if (buf[0] == '4') {
458 text_to_server(bstr("g_input"));
459 serv_puts("000");
461 if (buf[0] == '6') {
462 len = atol(&buf[4]);
463 junk = malloc(len);
464 serv_read(junk, len);
465 free(junk);
467 if (buf[0] == '7') {
468 len = atol(&buf[4]);
469 junk = malloc(len);
470 memset(junk, 0, len);
471 serv_write(junk, len);
472 free(junk);
475 end_ajax_response();
478 * This is kind of an ugly hack, but this is the only place it can go.
479 * If the command was GEXP, then the instant messenger window must be
480 * running, so reset the "last_pager_check" watchdog timer so
481 * that page_popup() doesn't try to open it a second time.
483 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
484 WC->last_pager_check = time(NULL);
490 * Helper function for the asynchronous check to see if we need
491 * to open the instant messenger window.
493 void seconds_since_last_gexp(void)
495 char buf[256];
497 if ( (time(NULL) - WC->last_pager_check) < 30) {
498 wprintf("NO\n");
500 else {
501 memset(buf, 0, 5);
502 serv_puts("NOOP");
503 serv_getln(buf, sizeof buf);
504 if (buf[3] == '*') {
505 wprintf("YES");
507 else {
508 wprintf("NO");
514 * \brief Detects a 'mobile' user agent
516 int is_mobile_ua(char *user_agent) {
517 if (strstr(user_agent,"iPhone OS") != NULL) {
518 return 1;
519 } else if (strstr(user_agent,"Windows CE") != NULL) {
520 return 1;
521 } else if (strstr(user_agent,"SymbianOS") != NULL) {
522 return 1;
523 } else if (strstr(user_agent, "Opera Mobi") != NULL) {
524 return 1;
525 } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
526 /* For some reason a new install of Opera 9.51beta decided to spoof. */
527 return 1;
529 return 0;
534 * Entry point for WebCit transaction
536 void session_loop(HashList *HTTPHeaders, StrBuf *ReqLine, StrBuf *request_method, StrBuf *ReadBuf)
538 StrBuf *Buf;
539 const char *pch, *pchs, *pche;
540 void *vLine;
541 char action[1024];
542 char arg[8][128];
543 size_t sizes[10];
544 char *index[10];
545 char buf[SIZ];
546 int a, nBackDots, nEmpty;
547 int ContentLength = 0;
548 StrBuf *ContentType = NULL;
549 StrBuf *UrlLine = NULL;
550 StrBuf *content = NULL;
551 const char *content_end = NULL;
552 StrBuf *browser_host = NULL;
553 char user_agent[256];
554 int body_start = 0;
555 int is_static = 0;
556 int n_static = 0;
557 int len = 0;
558 void *vHandler;
559 WebcitHandler *Handler;
562 * We stuff these with the values coming from the client cookies,
563 * so we can use them to reconnect a timed out session if we have to.
565 StrBuf *c_username;
566 StrBuf *c_password;
567 StrBuf *c_roomname;
568 char c_httpauth_string[SIZ];
569 StrBuf *c_httpauth_user;
570 StrBuf *c_httpauth_pass;
571 wcsession *WCC;
573 Buf = NewStrBuf();
574 c_username = NewStrBuf();
575 c_password = NewStrBuf();
576 c_roomname = NewStrBuf();
577 safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
578 c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
579 c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
581 WCC= WC;
582 if (WCC->WBuf == NULL)
583 WC->WBuf = NewStrBufPlain(NULL, 32768);
584 FlushStrBuf(WCC->WBuf);
586 if (WCC->HBuf == NULL)
587 WCC->HBuf = NewStrBuf();
588 FlushStrBuf(WCC->HBuf);
590 WCC->upload_length = 0;
591 WCC->upload = NULL;
592 WCC->is_mobile = 0;
593 WCC->trailing_javascript = NewStrBuf();
594 WCC->nWildfireHeaders = 0;
596 /** Figure out the action */
597 index[0] = action;
598 sizes[0] = sizeof action;
599 for (a=1; a<9; a++)
601 index[a] = arg[a-1];
602 sizes[a] = sizeof arg[a-1];
604 /*/// index[9] = &foo; todo */
605 nBackDots = 0;
606 nEmpty = 0;
607 for ( a = 0; a < 9; ++a)
609 extract_token(index[a], ChrPtr(ReqLine), a + 1, '/', sizes[a]);
610 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
611 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
612 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
613 if ((index[a][0] == '.') && (index[a][1] == '.'))
614 nBackDots++;
615 if (index[a][0] == '\0')
616 nEmpty++;
620 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
621 (vLine != NULL)){
622 cookie_to_stuff((StrBuf *)vLine, NULL,
623 c_username,
624 c_password,
625 c_roomname);
627 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
628 (vLine!=NULL)) {
629 /* TODO: wrap base64 in strbuf */
630 CtdlDecodeBase64(c_httpauth_string, ChrPtr((StrBuf*)vLine), StrLength((StrBuf*)vLine));
631 FlushStrBuf(Buf);
632 StrBufAppendBufPlain(Buf, c_httpauth_string, -1, 0);
633 StrBufExtract_token(c_httpauth_user, Buf, 0, ':');
634 StrBufExtract_token(c_httpauth_pass, Buf, 1, ':');
636 if (GetHash(HTTPHeaders, HKEY("CONTENT-LENGTH"), &vLine) &&
637 (vLine!=NULL)) {
638 ContentLength = StrToi((StrBuf*)vLine);
640 if (GetHash(HTTPHeaders, HKEY("CONTENT-TYPE"), &vLine) &&
641 (vLine!=NULL)) {
642 ContentType = (StrBuf*)vLine;
644 if (GetHash(HTTPHeaders, HKEY("USER-AGENT"), &vLine) &&
645 (vLine!=NULL)) {
646 safestrncpy(user_agent, ChrPtr((StrBuf*)vLine), sizeof user_agent);
647 #ifdef TECH_PREVIEW
648 if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {
649 WCC->is_mobile = 1;
651 else {
652 WCC->is_mobile = 0;
654 #endif
656 if ((follow_xff) &&
657 GetHash(HTTPHeaders, HKEY("X-FORWARDED-HOST"), &vLine) &&
658 (vLine != NULL)) {
659 WCC->http_host = (StrBuf*)vLine;
661 if ((StrLength(WCC->http_host) == 0) &&
662 GetHash(HTTPHeaders, HKEY("HOST"), &vLine) &&
663 (vLine!=NULL)) {
664 WCC->http_host = (StrBuf*)vLine;
667 if (GetHash(HTTPHeaders, HKEY("X-FORWARDED-FOR"), &vLine) &&
668 (vLine!=NULL)) {
669 browser_host = (StrBuf*) vLine;
671 while (StrBufNum_tokens(browser_host, ',') > 1) {
672 StrBufRemove_token(browser_host, 0, ',');
674 StrBufTrim(browser_host);
677 if (ContentLength > 0) {
678 content = NewStrBuf();
679 StrBufPrintf(content, "Content-type: %s\n"
680 "Content-length: %d\n\n",
681 ChrPtr(ContentType), ContentLength);
683 hprintf("Content-type: %s\n"
684 "Content-length: %d\n\n",
685 ContentType, ContentLength);
687 body_start = StrLength(content);
689 /** Read the entire input data at once. */
690 client_read(&WCC->http_sock, content, ReadBuf, ContentLength + body_start);
692 if (!strncasecmp(ChrPtr(ContentType), "application/x-www-form-urlencoded", 33)) {
693 StrBufCutLeft(content, body_start);
694 ParseURLParams(content);
695 } else if (!strncasecmp(ChrPtr(ContentType), "multipart", 9)) {
696 content_end = ChrPtr(content) + ContentLength + body_start;
697 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
699 } else {
700 content = NULL;
703 /* make a note of where we are in case the user wants to save it */
704 WCC->this_page = NewStrBufDup(ReqLine);
705 StrBufRemove_token(WCC->this_page, 2, ' ');
706 StrBufRemove_token(WCC->this_page, 0, ' ');
708 /* If there are variables in the URL, we must grab them now */
709 UrlLine = NewStrBufDup(ReqLine);
710 len = StrLength(UrlLine);
711 pch = pchs = ChrPtr(UrlLine);
712 pche = pchs + len;
713 while (pch < pche) {
714 if ((*pch == '?') || (*pch == '&')) {
715 StrBufCutLeft(UrlLine, pch - pchs + 1);
716 ParseURLParams(UrlLine);
717 break;
719 pch ++;
721 FreeStrBuf(&UrlLine);
723 /* If it's a "force 404" situation then display the error and bail. */
724 if (!strcmp(action, "404")) {
725 hprintf("HTTP/1.1 404 Not found\r\n");
726 hprintf("Content-Type: text/plain\r\n");
727 wprintf("Not found\r\n");
728 end_burst();
729 goto SKIP_ALL_THIS_CRAP;
732 /* Static content can be sent without connecting to Citadel. */
733 is_static = 0;
734 for (a=0; a<ndirs && ! is_static; ++a) {
735 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
736 is_static = 1;
737 n_static = a;
740 if (is_static) {
741 if (nBackDots < 2)
743 snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
744 static_dirs[n_static],
745 index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
746 for (a=0; a<8; ++a) {
747 if (buf[strlen(buf)-1] == '/') {
748 buf[strlen(buf)-1] = 0;
751 for (a = 0; a < strlen(buf); ++a) {
752 if (isspace(buf[a])) {
753 buf[a] = 0;
756 output_static(buf);
758 else
760 lprintf(9, "Suspicious request. Ignoring.");
761 hprintf("HTTP/1.1 404 Security check failed\r\n");
762 hprintf("Content-Type: text/plain\r\n\r\n");
763 wprintf("You have sent a malformed or invalid request.\r\n");
764 end_burst();
766 goto SKIP_ALL_THIS_CRAP; /* Don't try to connect */
769 /* If the client sent a nonce that is incorrect, kill the request. */
770 if (strlen(bstr("nonce")) > 0) {
771 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
772 bstr("nonce"), WCC->nonce);
773 if (ibstr("nonce") != WCC->nonce) {
774 lprintf(9, "Ignoring request with mismatched nonce.\n");
775 hprintf("HTTP/1.1 404 Security check failed\r\n");
776 hprintf("Content-Type: text/plain\r\n\r\n");
777 wprintf("Security check failed.\r\n");
778 end_burst();
779 goto SKIP_ALL_THIS_CRAP;
784 * If we're not connected to a Citadel server, try to hook up the
785 * connection now.
787 if (!WCC->connected) {
788 if (!strcasecmp(ctdlhost, "uds")) {
789 /* unix domain socket */
790 snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
791 WCC->serv_sock = uds_connectsock(buf);
793 else {
794 /* tcp socket */
795 WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
798 if (WCC->serv_sock < 0) {
799 do_logout();
800 goto SKIP_ALL_THIS_CRAP;
802 else {
803 WCC->connected = 1;
804 serv_getln(buf, sizeof buf); /* get the server greeting */
806 /* Are there too many users already logged in? */
807 if (!strncmp(buf, "571", 3)) {
808 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."));
809 end_burst();
810 end_webcit_session();
811 goto SKIP_ALL_THIS_CRAP;
815 * From what host is our user connecting? Go with
816 * the host at the other end of the HTTP socket,
817 * unless we are following X-Forwarded-For: headers
818 * and such a header has already turned up something.
820 if ( (!follow_xff) || (StrLength(browser_host) == 0) ) {
821 if (browser_host == NULL) {
822 browser_host = NewStrBuf();
823 Put(HTTPHeaders, HKEY("FreeMeWithTheOtherHeaders"),
824 browser_host, HFreeStrBuf);
826 locate_host(browser_host, WCC->http_sock);
829 get_serv_info(browser_host, user_agent);
830 if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
831 begin_burst();
832 wprintf(_("You are connected to a Citadel "
833 "server running Citadel %d.%02d. \n"
834 "In order to run this version of WebCit "
835 "you must also have Citadel %d.%02d or"
836 " newer.\n\n\n"),
837 serv_info.serv_rev_level / 100,
838 serv_info.serv_rev_level % 100,
839 MINIMUM_CIT_VERSION / 100,
840 MINIMUM_CIT_VERSION % 100
842 end_burst();
843 end_webcit_session();
844 goto SKIP_ALL_THIS_CRAP;
848 /*///////todo: restore language in this case */
850 * Functions which can be performed without logging in
852 if (!strcasecmp(action, "listsub")) {
853 do_listsub();
854 goto SKIP_ALL_THIS_CRAP;
856 if (!strcasecmp(action, "freebusy")) {
857 do_freebusy(ChrPtr(ReqLine));
858 goto SKIP_ALL_THIS_CRAP;
862 * If we're not logged in, but we have HTTP Authentication data,
863 * try logging in to Citadel using that.
865 if ((!WCC->logged_in)
866 && (StrLength(c_httpauth_user) > 0)
867 && (StrLength(c_httpauth_pass) > 0))
869 FlushStrBuf(Buf);
870 serv_printf("USER %s", ChrPtr(c_httpauth_user));
871 StrBuf_ServGetln(Buf);
872 if (GetServerStatus(Buf, NULL) == 3) {
873 serv_printf("PASS %s", ChrPtr(c_httpauth_pass));
874 StrBuf_ServGetln(Buf);
875 if (GetServerStatus(Buf, NULL) == 2) {
876 become_logged_in(c_httpauth_user,
877 c_httpauth_pass, Buf);
878 if (WCC->httpauth_user == NULL)
879 WCC->httpauth_user = NewStrBufDup(c_httpauth_user);
880 else {
881 FlushStrBuf(WCC->httpauth_user);
882 StrBufAppendBuf(WCC->httpauth_user, c_httpauth_user, 0);
884 if (WCC->httpauth_pass == NULL)
885 WCC->httpauth_pass = NewStrBufDup(c_httpauth_pass);
886 else {
887 FlushStrBuf(WCC->httpauth_pass);
888 StrBufAppendBuf(WCC->httpauth_pass, c_httpauth_pass, 0);
890 } else {
891 /* Should only display when password is wrong */
892 authorization_required(&buf[4]);
893 FreeStrBuf(&Buf);
894 goto SKIP_ALL_THIS_CRAP;
899 /* This needs to run early */
900 #ifdef TECH_PREVIEW
901 if (!strcasecmp(action, "rss")) {
902 display_rss(sbstr("room"), request_method);
903 goto SKIP_ALL_THIS_CRAP;
905 #endif
908 * The GroupDAV stuff relies on HTTP authentication instead of
909 * our session's authentication.
911 if (!strncasecmp(action, "groupdav", 8)) {
912 groupdav_main(HTTPHeaders,
913 ReqLine, request_method,
914 ContentType, /* do GroupDAV methods */
915 ContentLength, content, body_start);
916 if (!WCC->logged_in) {
917 WCC->killthis = 1; /* If not logged in, don't */
918 } /* keep the session active */
919 goto SKIP_ALL_THIS_CRAP;
924 * Automatically send requests with any method other than GET or
925 * POST to the GroupDAV code as well.
927 if ((strcasecmp(ChrPtr(request_method), "GET")) && (strcasecmp(ChrPtr(request_method), "POST"))) {
928 groupdav_main(HTTPHeaders, ReqLine,
929 request_method, ContentType, /** do GroupDAV methods */
930 ContentLength, content, body_start);
931 if (!WCC->logged_in) {
932 WCC->killthis = 1; /** If not logged in, don't */
933 } /** keep the session active */
934 goto SKIP_ALL_THIS_CRAP;
938 * If we're not logged in, but we have username and password cookies
939 * supplied by the browser, try using them to log in.
941 if ((!WCC->logged_in)
942 && (StrLength(c_username)>0)
943 && (StrLength(c_password)>0)) {
944 serv_printf("USER %s", ChrPtr(c_username));
945 StrBuf_ServGetln(Buf);
946 if (GetServerStatus(Buf, NULL) == 3) {
947 serv_printf("PASS %s", ChrPtr(c_password));
948 StrBuf_ServGetln(Buf);
949 if (GetServerStatus(Buf, NULL) == 2) {
950 StrBuf *Lang;
951 become_logged_in(c_username, c_password, Buf);
952 if (get_preference("language", &Lang)) {
953 set_selected_language(ChrPtr(Lang));
954 go_selected_language(); /* set locale */
956 get_preference("default_header_charset", &WCC->DefaultCharset);
962 * If a 'gotofirst' parameter has been specified, attempt to goto that room
963 * prior to doing anything else.
965 if (havebstr("gotofirst")) {
966 gotoroom(sbstr("gotofirst")); /* do this quietly to avoid session output! */
970 * If we don't have a current room, but a cookie specifying the
971 * current room is supplied, make an effort to go there.
973 if ((StrLength(WCC->wc_roomname) == 0) && (StrLength(c_roomname) > 0)) {
974 serv_printf("GOTO %s", ChrPtr(c_roomname));
975 StrBuf_ServGetln(Buf);
976 if (GetServerStatus(Buf, NULL) == 2) {
977 if (WCC->wc_roomname == NULL) {
978 WCC->wc_roomname = NewStrBufDup(c_roomname);
980 else {
981 FlushStrBuf(WCC->wc_roomname);
982 StrBufAppendBuf(WCC->wc_roomname, c_roomname, 0);
987 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
988 Handler = (WebcitHandler*) vHandler;
989 if (Handler != NULL) {
990 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
991 display_login(NULL);
993 else {
994 if((Handler->Flags & NEED_URL)) {
995 if (WCC->UrlFragment1 == NULL)
996 WCC->UrlFragment1 = NewStrBuf();
997 if (WCC->UrlFragment2 == NULL)
998 WCC->UrlFragment2 = NewStrBuf();
999 if (WCC->UrlFragment3 == NULL)
1000 WCC->UrlFragment3 = NewStrBuf();
1001 StrBufPrintf(WCC->UrlFragment1, "%s", index[0]);
1002 StrBufPrintf(WCC->UrlFragment2, "%s", index[1]);
1003 StrBufPrintf(WCC->UrlFragment3, "%s", index[2]);
1005 if ((Handler->Flags & AJAX) != 0)
1006 begin_ajax_response();
1007 Handler->F();
1008 if ((Handler->Flags & AJAX) != 0)
1009 end_ajax_response();
1012 /* When all else fais, display the main menu. */
1013 else {
1014 if (!WCC->logged_in)
1015 display_login(NULL);
1016 else
1017 display_main_menu();
1020 SKIP_ALL_THIS_CRAP:
1021 if (WCC->SavePrefsToServer) {
1022 save_preferences();
1023 WCC->SavePrefsToServer = 0;
1025 FreeStrBuf(&Buf);
1026 FreeStrBuf(&c_username);
1027 FreeStrBuf(&c_password);
1028 FreeStrBuf(&c_roomname);
1029 FreeStrBuf(&c_httpauth_user);
1030 FreeStrBuf(&c_httpauth_pass);
1031 FreeStrBuf(&WCC->this_page);
1032 fflush(stdout);
1033 if (content != NULL) {
1034 FreeStrBuf(&content);
1035 content = NULL;
1037 DeleteHash(&WCC->urlstrings);
1038 if (WCC->upload_length > 0) {
1039 free(WCC->upload);
1040 WCC->upload_length = 0;
1042 FreeStrBuf(&WCC->trailing_javascript);
1043 WCC->http_host = NULL;
1048 * Replacement for sleep() that uses select() in order to avoid SIGALRM
1050 void sleeeeeeeeeep(int seconds)
1052 struct timeval tv;
1054 tv.tv_sec = seconds;
1055 tv.tv_usec = 0;
1056 select(0, NULL, NULL, NULL, &tv);
1060 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
1062 wcsession *WCC = WC;
1063 if (WCC != NULL)
1064 return (!IsEmptyStr(WCC->ImportantMessage));
1065 else
1066 return 0;
1069 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
1071 wcsession *WCC = WC;
1073 if (WCC != NULL) {
1075 StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType,
1076 WCC->ImportantMessage, 0);
1078 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
1079 WCC->ImportantMessage[0] = '\0';
1083 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
1085 wcsession *WCC = WC;
1087 if (WCC != NULL)
1088 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
1091 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
1093 extern StrBuf *csslocal;
1094 StrBufAppendBuf(Target,
1095 csslocal, 0);
1101 void
1102 InitModule_WEBCIT
1103 (void)
1105 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1106 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1107 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1108 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1110 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
1111 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
1112 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
1113 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);