* Re-added tiny_mce, this time with the language packs
[citadel.git] / webcit / webcit.c
blobeaf4d30b735522bce9a94ece3cf1739dc18bddb2
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 *Tmpl = sbstr("template");
372 begin_burst();
373 output_headers(1, 0, 0, 0, 1, 0);
374 DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
375 end_burst();
381 * convenience function to indicate success
383 void display_success(char *successmessage)
385 convenience_page("007700", "OK", successmessage);
390 * Authorization required page
391 * This is probably temporary and should be revisited
393 void authorization_required(const char *message)
395 hprintf("HTTP/1.1 401 Authorization Required\r\n");
396 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(serv_info.serv_humannode));
397 hprintf("Content-Type: text/html\r\n");
398 wprintf("<h1>");
399 wprintf(_("Authorization Required"));
400 wprintf("</h1>\r\n");
401 wprintf(_("The resource you requested requires a valid username and password. "
402 "You could not be logged in: %s\n"), message);
403 wDumpContent(0);
408 * Convenience functions to wrap around asynchronous ajax responses
410 void begin_ajax_response(void) {
411 wcsession *WCC = WC;
413 FlushStrBuf(WCC->HBuf);
414 output_headers(0, 0, 0, 0, 0, 0);
416 hprintf("Content-type: text/html; charset=UTF-8\r\n"
417 "Server: %s\r\n"
418 "Connection: close\r\n"
420 PACKAGE_STRING);
421 begin_burst();
425 * print ajax response footer
427 void end_ajax_response(void) {
428 wDumpContent(0);
432 * Wraps a Citadel server command in an AJAX transaction.
434 void ajax_servcmd(void)
436 char buf[1024];
437 char gcontent[1024];
438 char *junk;
439 size_t len;
441 begin_ajax_response();
443 serv_printf("%s", bstr("g_cmd"));
444 serv_getln(buf, sizeof buf);
445 wprintf("%s\n", buf);
447 if (buf[0] == '8') {
448 serv_printf("\n\n000");
450 if ((buf[0] == '1') || (buf[0] == '8')) {
451 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
452 wprintf("%s\n", gcontent);
454 wprintf("000");
456 if (buf[0] == '4') {
457 text_to_server(bstr("g_input"));
458 serv_puts("000");
460 if (buf[0] == '6') {
461 len = atol(&buf[4]);
462 junk = malloc(len);
463 serv_read(junk, len);
464 free(junk);
466 if (buf[0] == '7') {
467 len = atol(&buf[4]);
468 junk = malloc(len);
469 memset(junk, 0, len);
470 serv_write(junk, len);
471 free(junk);
474 end_ajax_response();
477 * This is kind of an ugly hack, but this is the only place it can go.
478 * If the command was GEXP, then the instant messenger window must be
479 * running, so reset the "last_pager_check" watchdog timer so
480 * that page_popup() doesn't try to open it a second time.
482 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
483 WC->last_pager_check = time(NULL);
489 * Helper function for the asynchronous check to see if we need
490 * to open the instant messenger window.
492 void seconds_since_last_gexp(void)
494 char buf[256];
496 if ( (time(NULL) - WC->last_pager_check) < 30) {
497 wprintf("NO\n");
499 else {
500 memset(buf, 0, 5);
501 serv_puts("NOOP");
502 serv_getln(buf, sizeof buf);
503 if (buf[3] == '*') {
504 wprintf("YES");
506 else {
507 wprintf("NO");
513 * \brief Detects a 'mobile' user agent
515 int is_mobile_ua(char *user_agent) {
516 if (strstr(user_agent,"iPhone OS") != NULL) {
517 return 1;
518 } else if (strstr(user_agent,"Windows CE") != NULL) {
519 return 1;
520 } else if (strstr(user_agent,"SymbianOS") != NULL) {
521 return 1;
522 } else if (strstr(user_agent, "Opera Mobi") != NULL) {
523 return 1;
524 } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
525 /* For some reason a new install of Opera 9.51beta decided to spoof. */
526 return 1;
528 return 0;
533 * Entry point for WebCit transaction
535 void session_loop(HashList *HTTPHeaders, StrBuf *ReqLine, StrBuf *request_method, StrBuf *ReadBuf)
537 StrBuf *Buf;
538 const char *pch, *pchs, *pche;
539 void *vLine;
540 char action[1024];
541 char arg[8][128];
542 size_t sizes[10];
543 char *index[10];
544 char buf[SIZ];
545 int a, nBackDots, nEmpty;
546 int ContentLength = 0;
547 StrBuf *ContentType = NULL;
548 StrBuf *UrlLine = NULL;
549 StrBuf *content = NULL;
550 const char *content_end = NULL;
551 StrBuf *browser_host = NULL;
552 char user_agent[256];
553 int body_start = 0;
554 int is_static = 0;
555 int n_static = 0;
556 int len = 0;
557 void *vHandler;
558 WebcitHandler *Handler;
561 * We stuff these with the values coming from the client cookies,
562 * so we can use them to reconnect a timed out session if we have to.
564 StrBuf *c_username;
565 StrBuf *c_password;
566 StrBuf *c_roomname;
567 char c_httpauth_string[SIZ];
568 StrBuf *c_httpauth_user;
569 StrBuf *c_httpauth_pass;
570 wcsession *WCC;
572 Buf = NewStrBuf();
573 c_username = NewStrBuf();
574 c_password = NewStrBuf();
575 c_roomname = NewStrBuf();
576 safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
577 c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
578 c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
580 WCC= WC;
581 if (WCC->WBuf == NULL)
582 WC->WBuf = NewStrBufPlain(NULL, 32768);
583 FlushStrBuf(WCC->WBuf);
585 if (WCC->HBuf == NULL)
586 WCC->HBuf = NewStrBuf();
587 FlushStrBuf(WCC->HBuf);
589 WCC->upload_length = 0;
590 WCC->upload = NULL;
591 WCC->is_mobile = 0;
592 WCC->trailing_javascript = NewStrBuf();
593 WCC->nWildfireHeaders = 0;
595 /** Figure out the action */
596 index[0] = action;
597 sizes[0] = sizeof action;
598 for (a=1; a<9; a++)
600 index[a] = arg[a-1];
601 sizes[a] = sizeof arg[a-1];
603 /*/// index[9] = &foo; todo */
604 nBackDots = 0;
605 nEmpty = 0;
606 for ( a = 0; a < 9; ++a)
608 extract_token(index[a], ChrPtr(ReqLine), a + 1, '/', sizes[a]);
609 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
610 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
611 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
612 if ((index[a][0] == '.') && (index[a][1] == '.'))
613 nBackDots++;
614 if (index[a][0] == '\0')
615 nEmpty++;
619 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
620 (vLine != NULL)){
621 cookie_to_stuff((StrBuf *)vLine, NULL,
622 c_username,
623 c_password,
624 c_roomname);
626 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
627 (vLine!=NULL)) {
628 /* TODO: wrap base64 in strbuf */
629 CtdlDecodeBase64(c_httpauth_string, ChrPtr((StrBuf*)vLine), StrLength((StrBuf*)vLine));
630 FlushStrBuf(Buf);
631 StrBufAppendBufPlain(Buf, c_httpauth_string, -1, 0);
632 StrBufExtract_token(c_httpauth_user, Buf, 0, ':');
633 StrBufExtract_token(c_httpauth_pass, Buf, 1, ':');
635 if (GetHash(HTTPHeaders, HKEY("CONTENT-LENGTH"), &vLine) &&
636 (vLine!=NULL)) {
637 ContentLength = StrToi((StrBuf*)vLine);
639 if (GetHash(HTTPHeaders, HKEY("CONTENT-TYPE"), &vLine) &&
640 (vLine!=NULL)) {
641 ContentType = (StrBuf*)vLine;
643 if (GetHash(HTTPHeaders, HKEY("USER-AGENT"), &vLine) &&
644 (vLine!=NULL)) {
645 safestrncpy(user_agent, ChrPtr((StrBuf*)vLine), sizeof user_agent);
646 #ifdef TECH_PREVIEW
647 if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {
648 WCC->is_mobile = 1;
650 else {
651 WCC->is_mobile = 0;
653 #endif
655 if ((follow_xff) &&
656 GetHash(HTTPHeaders, HKEY("X-FORWARDED-HOST"), &vLine) &&
657 (vLine != NULL)) {
658 WCC->http_host = (StrBuf*)vLine;
660 if ((StrLength(WCC->http_host) == 0) &&
661 GetHash(HTTPHeaders, HKEY("HOST"), &vLine) &&
662 (vLine!=NULL)) {
663 WCC->http_host = (StrBuf*)vLine;
666 if (GetHash(HTTPHeaders, HKEY("X-FORWARDED-FOR"), &vLine) &&
667 (vLine!=NULL)) {
668 browser_host = (StrBuf*) vLine;
670 while (StrBufNum_tokens(browser_host, ',') > 1) {
671 StrBufRemove_token(browser_host, 0, ',');
673 StrBufTrim(browser_host);
676 if (ContentLength > 0) {
677 content = NewStrBuf();
678 StrBufPrintf(content, "Content-type: %s\n"
679 "Content-length: %d\n\n",
680 ChrPtr(ContentType), ContentLength);
682 hprintf("Content-type: %s\n"
683 "Content-length: %d\n\n",
684 ContentType, ContentLength);
686 body_start = StrLength(content);
688 /** Read the entire input data at once. */
689 client_read(&WCC->http_sock, content, ReadBuf, ContentLength + body_start);
691 if (!strncasecmp(ChrPtr(ContentType), "application/x-www-form-urlencoded", 33)) {
692 StrBufCutLeft(content, body_start);
693 ParseURLParams(content);
694 } else if (!strncasecmp(ChrPtr(ContentType), "multipart", 9)) {
695 content_end = ChrPtr(content) + ContentLength + body_start;
696 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
698 } else {
699 content = NULL;
702 /* make a note of where we are in case the user wants to save it */
703 WCC->this_page = NewStrBufDup(ReqLine);
704 StrBufRemove_token(WCC->this_page, 2, ' ');
705 StrBufRemove_token(WCC->this_page, 0, ' ');
707 /* If there are variables in the URL, we must grab them now */
708 UrlLine = NewStrBufDup(ReqLine);
709 len = StrLength(UrlLine);
710 pch = pchs = ChrPtr(UrlLine);
711 pche = pchs + len;
712 while (pch < pche) {
713 if ((*pch == '?') || (*pch == '&')) {
714 StrBufCutLeft(UrlLine, pch - pchs + 1);
715 ParseURLParams(UrlLine);
716 break;
718 pch ++;
720 FreeStrBuf(&UrlLine);
722 /* If it's a "force 404" situation then display the error and bail. */
723 if (!strcmp(action, "404")) {
724 hprintf("HTTP/1.1 404 Not found\r\n");
725 hprintf("Content-Type: text/plain\r\n");
726 wprintf("Not found\r\n");
727 end_burst();
728 goto SKIP_ALL_THIS_CRAP;
731 /* Static content can be sent without connecting to Citadel. */
732 is_static = 0;
733 for (a=0; a<ndirs && ! is_static; ++a) {
734 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
735 is_static = 1;
736 n_static = a;
739 if (is_static) {
740 if (nBackDots < 2)
742 snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
743 static_dirs[n_static],
744 index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
745 for (a=0; a<8; ++a) {
746 if (buf[strlen(buf)-1] == '/') {
747 buf[strlen(buf)-1] = 0;
750 for (a = 0; a < strlen(buf); ++a) {
751 if (isspace(buf[a])) {
752 buf[a] = 0;
755 output_static(buf);
757 else
759 lprintf(9, "Suspicious request. Ignoring.");
760 hprintf("HTTP/1.1 404 Security check failed\r\n");
761 hprintf("Content-Type: text/plain\r\n\r\n");
762 wprintf("You have sent a malformed or invalid request.\r\n");
763 end_burst();
765 goto SKIP_ALL_THIS_CRAP; /* Don't try to connect */
768 /* If the client sent a nonce that is incorrect, kill the request. */
769 if (strlen(bstr("nonce")) > 0) {
770 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
771 bstr("nonce"), WCC->nonce);
772 if (ibstr("nonce") != WCC->nonce) {
773 lprintf(9, "Ignoring request with mismatched nonce.\n");
774 hprintf("HTTP/1.1 404 Security check failed\r\n");
775 hprintf("Content-Type: text/plain\r\n\r\n");
776 wprintf("Security check failed.\r\n");
777 end_burst();
778 goto SKIP_ALL_THIS_CRAP;
783 * If we're not connected to a Citadel server, try to hook up the
784 * connection now.
786 if (!WCC->connected) {
787 if (!strcasecmp(ctdlhost, "uds")) {
788 /* unix domain socket */
789 snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
790 WCC->serv_sock = uds_connectsock(buf);
792 else {
793 /* tcp socket */
794 WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
797 if (WCC->serv_sock < 0) {
798 do_logout();
799 goto SKIP_ALL_THIS_CRAP;
801 else {
802 WCC->connected = 1;
803 serv_getln(buf, sizeof buf); /* get the server greeting */
805 /* Are there too many users already logged in? */
806 if (!strncmp(buf, "571", 3)) {
807 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."));
808 end_burst();
809 end_webcit_session();
810 goto SKIP_ALL_THIS_CRAP;
814 * From what host is our user connecting? Go with
815 * the host at the other end of the HTTP socket,
816 * unless we are following X-Forwarded-For: headers
817 * and such a header has already turned up something.
819 if ( (!follow_xff) || (StrLength(browser_host) == 0) ) {
820 if (browser_host == NULL) {
821 browser_host = NewStrBuf();
822 Put(HTTPHeaders, HKEY("FreeMeWithTheOtherHeaders"),
823 browser_host, HFreeStrBuf);
825 locate_host(browser_host, WCC->http_sock);
828 get_serv_info(browser_host, user_agent);
829 if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
830 begin_burst();
831 wprintf(_("You are connected to a Citadel "
832 "server running Citadel %d.%02d. \n"
833 "In order to run this version of WebCit "
834 "you must also have Citadel %d.%02d or"
835 " newer.\n\n\n"),
836 serv_info.serv_rev_level / 100,
837 serv_info.serv_rev_level % 100,
838 MINIMUM_CIT_VERSION / 100,
839 MINIMUM_CIT_VERSION % 100
841 end_burst();
842 end_webcit_session();
843 goto SKIP_ALL_THIS_CRAP;
847 /*///////todo: restore language in this case */
849 * Functions which can be performed without logging in
851 if (!strcasecmp(action, "listsub")) {
852 do_listsub();
853 goto SKIP_ALL_THIS_CRAP;
855 if (!strcasecmp(action, "freebusy")) {
856 do_freebusy(ChrPtr(ReqLine));
857 goto SKIP_ALL_THIS_CRAP;
861 * If we're not logged in, but we have HTTP Authentication data,
862 * try logging in to Citadel using that.
864 if ((!WCC->logged_in)
865 && (StrLength(c_httpauth_user) > 0)
866 && (StrLength(c_httpauth_pass) > 0))
868 FlushStrBuf(Buf);
869 serv_printf("USER %s", ChrPtr(c_httpauth_user));
870 StrBuf_ServGetln(Buf);
871 if (GetServerStatus(Buf, NULL) == 3) {
872 serv_printf("PASS %s", ChrPtr(c_httpauth_pass));
873 StrBuf_ServGetln(Buf);
874 if (GetServerStatus(Buf, NULL) == 2) {
875 become_logged_in(c_httpauth_user,
876 c_httpauth_pass, Buf);
877 if (WCC->httpauth_user == NULL)
878 WCC->httpauth_user = NewStrBufDup(c_httpauth_user);
879 else {
880 FlushStrBuf(WCC->httpauth_user);
881 StrBufAppendBuf(WCC->httpauth_user, c_httpauth_user, 0);
883 if (WCC->httpauth_pass == NULL)
884 WCC->httpauth_pass = NewStrBufDup(c_httpauth_pass);
885 else {
886 FlushStrBuf(WCC->httpauth_pass);
887 StrBufAppendBuf(WCC->httpauth_pass, c_httpauth_pass, 0);
889 } else {
890 /* Should only display when password is wrong */
891 authorization_required(&buf[4]);
892 FreeStrBuf(&Buf);
893 goto SKIP_ALL_THIS_CRAP;
898 /* This needs to run early */
899 #ifdef TECH_PREVIEW
900 if (!strcasecmp(action, "rss")) {
901 display_rss(sbstr("room"), request_method);
902 goto SKIP_ALL_THIS_CRAP;
904 #endif
907 * The GroupDAV stuff relies on HTTP authentication instead of
908 * our session's authentication.
910 if (!strncasecmp(action, "groupdav", 8)) {
911 groupdav_main(HTTPHeaders,
912 ReqLine, request_method,
913 ContentType, /* do GroupDAV methods */
914 ContentLength, content, body_start);
915 if (!WCC->logged_in) {
916 WCC->killthis = 1; /* If not logged in, don't */
917 } /* keep the session active */
918 goto SKIP_ALL_THIS_CRAP;
923 * Automatically send requests with any method other than GET or
924 * POST to the GroupDAV code as well.
926 if ((strcasecmp(ChrPtr(request_method), "GET")) && (strcasecmp(ChrPtr(request_method), "POST"))) {
927 groupdav_main(HTTPHeaders, ReqLine,
928 request_method, ContentType, /** do GroupDAV methods */
929 ContentLength, content, body_start);
930 if (!WCC->logged_in) {
931 WCC->killthis = 1; /** If not logged in, don't */
932 } /** keep the session active */
933 goto SKIP_ALL_THIS_CRAP;
937 * If we're not logged in, but we have username and password cookies
938 * supplied by the browser, try using them to log in.
940 if ((!WCC->logged_in)
941 && (StrLength(c_username)>0)
942 && (StrLength(c_password)>0)) {
943 serv_printf("USER %s", ChrPtr(c_username));
944 StrBuf_ServGetln(Buf);
945 if (GetServerStatus(Buf, NULL) == 3) {
946 serv_printf("PASS %s", ChrPtr(c_password));
947 StrBuf_ServGetln(Buf);
948 if (GetServerStatus(Buf, NULL) == 2) {
949 StrBuf *Lang;
950 become_logged_in(c_username, c_password, Buf);
951 if (get_preference("language", &Lang)) {
952 set_selected_language(ChrPtr(Lang));
953 go_selected_language(); /* set locale */
955 get_preference("default_header_charset", &WCC->DefaultCharset);
961 * If a 'gotofirst' parameter has been specified, attempt to goto that room
962 * prior to doing anything else.
964 if (havebstr("gotofirst")) {
965 gotoroom(sbstr("gotofirst")); /* do this quietly to avoid session output! */
969 * If we don't have a current room, but a cookie specifying the
970 * current room is supplied, make an effort to go there.
972 if ((StrLength(WCC->wc_roomname) == 0) && (StrLength(c_roomname) > 0)) {
973 serv_printf("GOTO %s", ChrPtr(c_roomname));
974 StrBuf_ServGetln(Buf);
975 if (GetServerStatus(Buf, NULL) == 2) {
976 if (WCC->wc_roomname == NULL) {
977 WCC->wc_roomname = NewStrBufDup(c_roomname);
979 else {
980 FlushStrBuf(WCC->wc_roomname);
981 StrBufAppendBuf(WCC->wc_roomname, c_roomname, 0);
986 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
987 Handler = (WebcitHandler*) vHandler;
988 if (Handler != NULL) {
989 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
990 display_login(NULL);
992 else {
993 if((Handler->Flags & NEED_URL)) {
994 if (WCC->UrlFragment1 == NULL)
995 WCC->UrlFragment1 = NewStrBuf();
996 if (WCC->UrlFragment2 == NULL)
997 WCC->UrlFragment2 = NewStrBuf();
998 if (WCC->UrlFragment3 == NULL)
999 WCC->UrlFragment3 = NewStrBuf();
1000 StrBufPrintf(WCC->UrlFragment1, "%s", index[0]);
1001 StrBufPrintf(WCC->UrlFragment2, "%s", index[1]);
1002 StrBufPrintf(WCC->UrlFragment3, "%s", index[2]);
1004 if ((Handler->Flags & AJAX) != 0)
1005 begin_ajax_response();
1006 Handler->F();
1007 if ((Handler->Flags & AJAX) != 0)
1008 end_ajax_response();
1011 /* When all else fais, display the main menu. */
1012 else {
1013 if (!WCC->logged_in)
1014 display_login(NULL);
1015 else
1016 display_main_menu();
1019 SKIP_ALL_THIS_CRAP:
1020 if (WCC->SavePrefsToServer) {
1021 save_preferences();
1022 WCC->SavePrefsToServer = 0;
1024 FreeStrBuf(&Buf);
1025 FreeStrBuf(&c_username);
1026 FreeStrBuf(&c_password);
1027 FreeStrBuf(&c_roomname);
1028 FreeStrBuf(&c_httpauth_user);
1029 FreeStrBuf(&c_httpauth_pass);
1030 FreeStrBuf(&WCC->this_page);
1031 fflush(stdout);
1032 if (content != NULL) {
1033 FreeStrBuf(&content);
1034 content = NULL;
1036 DeleteHash(&WCC->urlstrings);
1037 if (WCC->upload_length > 0) {
1038 free(WCC->upload);
1039 WCC->upload_length = 0;
1041 FreeStrBuf(&WCC->trailing_javascript);
1042 WCC->http_host = NULL;
1047 * Replacement for sleep() that uses select() in order to avoid SIGALRM
1049 void sleeeeeeeeeep(int seconds)
1051 struct timeval tv;
1053 tv.tv_sec = seconds;
1054 tv.tv_usec = 0;
1055 select(0, NULL, NULL, NULL, &tv);
1059 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
1061 wcsession *WCC = WC;
1062 if (WCC != NULL)
1063 return (!IsEmptyStr(WCC->ImportantMessage));
1064 else
1065 return 0;
1068 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
1070 wcsession *WCC = WC;
1072 if (WCC != NULL) {
1074 StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType,
1075 WCC->ImportantMessage, 0);
1077 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
1078 WCC->ImportantMessage[0] = '\0';
1082 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
1084 wcsession *WCC = WC;
1086 if (WCC != NULL)
1087 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
1090 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
1092 extern StrBuf *csslocal;
1093 StrBufAppendBuf(Target,
1094 csslocal, 0);
1100 void
1101 InitModule_WEBCIT
1102 (void)
1104 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1105 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1106 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1107 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1109 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
1110 RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
1111 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
1112 RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);