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.
9 #define SHOW_ME_VAPPEND_PRINTF
12 #include "webserver.h"
18 * String to unset the cookie.
19 * Any date "in the past" will work, so I chose my birthday, right down to
20 * the exact minute. :)
22 static char *unset = "; expires=28-May-1971 18:10:00 GMT";
24 HashList *HandlerHash = NULL;
26 void WebcitAddUrlHandler(const char * UrlString,
31 WebcitHandler *NewHandler;
33 if (HandlerHash == NULL)
34 HandlerHash = NewHash(1, NULL);
36 NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
38 NewHandler->Flags = Flags;
39 Put(HandlerHash, UrlString, UrlSLen, NewHandler, NULL);
43 * remove escaped strings from i.e. the url string (like %20 for blanks)
45 long unescape_input(char *buf)
54 while ((buflen > 0) && (isspace(buf[buflen - 1]))){
64 /* don't let % chars through, rather truncate the input. */
74 sscanf(hex, "%02x", &b);
78 memmove(&buf[a + 1], &buf[a + 3], len);
88 void free_url(void *U)
90 urlcontent *u = (urlcontent*) U;
91 FreeStrBuf(&u->url_data);
96 * Extract variables from the URL.
98 void addurls(StrBuf *url)
100 const char *aptr, *bptr, *eptr, *up;
104 struct wcsession *WCC = WC;
106 if (WCC->urlstrings == NULL)
107 WCC->urlstrings = NewHash(1, NULL);
108 // buf = (char*) malloc (ulen + 1);
109 // memcpy(buf, url, ulen);
110 /// buf[ulen] = '\0';
111 eptr = ChrPtr(url) + StrLength(url);
113 while ((up < eptr) && (!IsEmptyStr(up))) {
115 while ((aptr < eptr) && (*aptr != '\0') && (*aptr != '='))
124 while ((bptr < eptr) && (*bptr != '\0')
125 && (*bptr != '&') && (*bptr != '?') && (*bptr != ' ')) {
129 keylen = aptr - up - 1; /* -1 -> '=' */
130 if(keylen > sizeof(u->url_key)) {
131 lprintf(1, "URLkey to long! [%s]", up);
135 u = (urlcontent *) malloc(sizeof(urlcontent));
136 memcpy(u->url_key, up, keylen);
137 u->url_key[keylen] = '\0';
139 lprintf(1, "URLkey to long! [%s]", up);
144 Put(WCC->urlstrings, u->url_key, keylen, u, free_url);
146 u->url_data = NewStrBufPlain(aptr, len);
147 StrBufUnescape(u->url_data, 1);
151 #ifdef DEBUG_URLSTRINGS
152 lprintf(9, "%s = [%ld] %s\n", u->url_key, u->url_data_size, ChrPtr(u->url_data));
159 * free urlstring memory
163 DeleteHash(&WC->urlstrings);
167 * Diagnostic function to display the contents of all variables
172 struct wcsession *WCC = WC;
179 Cursor = GetNewHashPos ();
180 while (GetNextHashPos(WCC->urlstrings, Cursor, &HKLen, &HKey, &U)) {
182 wprintf("%38s = %s\n", u->url_key, ChrPtr(u->url_data));
187 * Return the value of a variable supplied to the current web page (from the url or a form)
190 const char *XBstr(char *key, size_t keylen, size_t *len)
194 if ((WC->urlstrings != NULL) &&
195 GetHash(WC->urlstrings, key, keylen, &U)) {
196 *len = StrLength(((urlcontent *)U)->url_data);
197 return ChrPtr(((urlcontent *)U)->url_data);
205 const char *XBSTR(char *key, size_t *len)
209 if ((WC->urlstrings != NULL) &&
210 GetHash(WC->urlstrings, key, strlen (key), &U)){
211 *len = StrLength(((urlcontent *)U)->url_data);
212 return ChrPtr(((urlcontent *)U)->url_data);
221 const char *BSTR(char *key)
225 if ((WC->urlstrings != NULL) &&
226 GetHash(WC->urlstrings, key, strlen (key), &U))
227 return ChrPtr(((urlcontent *)U)->url_data);
232 const char *Bstr(char *key, size_t keylen)
236 if ((WC->urlstrings != NULL) &&
237 GetHash(WC->urlstrings, key, keylen, &U))
238 return ChrPtr(((urlcontent *)U)->url_data);
243 const StrBuf *SBSTR(const char *key)
247 if ((WC->urlstrings != NULL) &&
248 GetHash(WC->urlstrings, key, strlen (key), &U))
249 return ((urlcontent *)U)->url_data;
254 const StrBuf *SBstr(const char *key, size_t keylen)
258 if ((WC->urlstrings != NULL) &&
259 GetHash(WC->urlstrings, key, keylen, &U))
260 return ((urlcontent *)U)->url_data;
265 long LBstr(char *key, size_t keylen)
269 if ((WC->urlstrings != NULL) &&
270 GetHash(WC->urlstrings, key, keylen, &U))
271 return StrTol(((urlcontent *)U)->url_data);
276 long LBSTR(char *key)
280 if ((WC->urlstrings != NULL) &&
281 GetHash(WC->urlstrings, key, strlen(key), &U))
282 return StrTol(((urlcontent *)U)->url_data);
287 int IBstr(char *key, size_t keylen)
291 if ((WC->urlstrings != NULL) &&
292 GetHash(WC->urlstrings, key, keylen, &U))
293 return StrTol(((urlcontent *)U)->url_data);
302 if ((WC->urlstrings != NULL) &&
303 GetHash(WC->urlstrings, key, strlen(key), &U))
304 return StrToi(((urlcontent *)U)->url_data);
309 int HaveBstr(char *key, size_t keylen)
313 if ((WC->urlstrings != NULL) &&
314 GetHash(WC->urlstrings, key, keylen, &U))
315 return (StrLength(((urlcontent *)U)->url_data) != 0);
320 int HAVEBSTR(char *key)
324 if ((WC->urlstrings != NULL) &&
325 GetHash(WC->urlstrings, key, strlen(key), &U))
326 return (StrLength(((urlcontent *)U)->url_data) != 0);
332 int YesBstr(char *key, size_t keylen)
336 if ((WC->urlstrings != NULL) &&
337 GetHash(WC->urlstrings, key, keylen, &U))
338 return strcmp( ChrPtr(((urlcontent *)U)->url_data), "yes") == 0;
343 int YESBSTR(char *key)
347 if ((WC->urlstrings != NULL) &&
348 GetHash(WC->urlstrings, key, strlen(key), &U))
349 return strcmp( ChrPtr(((urlcontent *)U)->url_data), "yes") == 0;
355 * web-printing funcion. uses our vsnprintf wrapper
357 void wprintf(const char *format,...)
359 struct wcsession *WCC = WC;
362 if (WCC->WBuf == NULL)
363 WCC->WBuf = NewStrBuf();
365 va_start(arg_ptr, format);
366 StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
369 /// if (StrLength(WCC-WBuf) > 2048)
370 ///client_write(wbuf, strlen(wbuf));
374 * http-header-printing funcion. uses our vsnprintf wrapper
376 void hprintf(const char *format,...)
378 struct wcsession *WCC = WC;
381 va_start(arg_ptr, format);
382 StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
385 /// if (StrLength(WCC-WBuf) > 2048)
386 ///client_write(wbuf, strlen(wbuf));
391 * wrap up an HTTP session, closes tags, etc.
393 * print_standard_html_footer should be set to:
394 * 0 to transmit only,
395 * 1 to append the main menu and closing tags,
396 * 2 to append the closing tags only.
398 void wDumpContent(int print_standard_html_footer)
400 if (print_standard_html_footer) {
401 wprintf("</div>\n"); /* end of "text" div */
402 do_template("trailing", NULL);
405 /* If we've been saving it all up for one big output burst,
406 * go ahead and do that now.
414 * Copy a string, escaping characters which have meaning in HTML.
416 * target target buffer
417 * strbuf source buffer
418 * nbsp If nonzero, spaces are converted to non-breaking spaces.
419 * nolinebreaks if set, linebreaks are removed from the string.
421 long stresc(char *target, long tSize, char *strbuf, int nbsp, int nolinebreaks)
423 char *aptr, *bptr, *eptr;
428 eptr = target + tSize - 6; // our biggest unit to put in...
431 while ((bptr < eptr) && !IsEmptyStr(aptr) ){
433 memcpy(bptr, "<", 4);
436 else if (*aptr == '>') {
437 memcpy(bptr, ">", 4);
440 else if (*aptr == '&') {
441 memcpy(bptr, "&", 5);
444 else if (*aptr == '\"') {
445 memcpy(bptr, """, 6);
448 else if (*aptr == '\'') {
449 memcpy(bptr, "'", 5);
452 else if (*aptr == LB) {
456 else if (*aptr == RB) {
460 else if (*aptr == QU) {
464 else if ((*aptr == 32) && (nbsp == 1)) {
465 memcpy(bptr, " ", 6);
468 else if ((*aptr == '\n') && (nolinebreaks)) {
469 *bptr='\0'; /* nothing */
471 else if ((*aptr == '\r') && (nolinebreaks)) {
472 *bptr='\0'; /* nothing */
481 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
483 return (bptr - target);
487 void escputs1(char *strbuf, int nbsp, int nolinebreaks)
489 StrEscAppend(WC->WBuf, NULL, strbuf, nbsp, nolinebreaks);
492 void StrEscputs1(const StrBuf *strbuf, int nbsp, int nolinebreaks)
494 StrEscAppend(WC->WBuf, strbuf, NULL, nbsp, nolinebreaks);
498 * static wrapper for ecsputs1
500 void escputs(char *strbuf)
502 escputs1(strbuf, 0, 0);
507 * static wrapper for ecsputs1
509 void StrEscPuts(const StrBuf *strbuf)
511 StrEscputs1(strbuf, 0, 0);
516 * urlescape buffer and print it to the client
518 void urlescputs(const char *strbuf)
520 StrBufUrlescAppend(WC->WBuf, NULL, strbuf);
524 * urlescape buffer and print it to the client
526 void UrlescPutStrBuf(const StrBuf *strbuf)
528 StrBufUrlescAppend(WC->WBuf, strbuf, NULL);
532 * urlescape buffer and print it as header
534 void hurlescputs(const char *strbuf)
536 StrBufUrlescAppend(WC->HBuf, NULL, strbuf);
541 * Copy a string, escaping characters for JavaScript strings.
543 void jsesc(char *target, size_t tlen, char *strbuf)
552 len = strlen (strbuf);
554 tend = target + tlen;
558 while (!IsEmptyStr(sptr) &&
564 else if (*sptr == '>')
566 else if (*sptr == '\'') {
572 else if (*sptr == '"') {
582 else if (*sptr == '&') {
599 * escape and print javascript
601 void jsescputs(char *strbuf)
605 jsesc(outbuf, SIZ, strbuf);
606 wprintf("%s", outbuf);
610 * print a string to the client after cleaning it with msgesc() and stresc()
612 void msgescputs1( char *strbuf)
614 StrBuf *OutBuf = NewStrBuf();
616 if ((strbuf == NULL) || IsEmptyStr(strbuf))
618 StrMsgEscAppend(OutBuf, NULL, strbuf);
619 StrEscAppend(WC->WBuf, OutBuf, NULL, 0, 0);
623 * print a string to the client after cleaning it with msgesc()
625 void msgescputs(char *strbuf) {
626 if ((strbuf != NULL) && !IsEmptyStr(strbuf))
627 StrMsgEscAppend(WC->WBuf, NULL, strbuf);
634 * Output HTTP headers and leading HTML for a page
636 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
637 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
639 int do_room_banner, /* 0=no, 1=yes,
640 * 2 = I'm going to embed my own, so don't open the
641 * <div id="content"> either.
644 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
645 int suppress_check, /* 1 = suppress check for instant messages */
646 int cache /* 1 = allow browser to cache this page */
651 hprintf("HTTP/1.1 200 OK\n");
652 http_datestring(httpnow, sizeof httpnow, time(NULL));
654 if (do_httpheaders) {
655 hprintf("Content-type: text/html; charset=utf-8\r\n"
657 "Connection: close\r\n",
658 PACKAGE_STRING, serv_info.serv_software
663 char httpTomorow[128];
665 http_datestring(httpTomorow, sizeof httpTomorow,
666 time(NULL) + 60 * 60 * 24 * 2);
668 hprintf("Pragma: public\r\n"
669 "Cache-Control: max-age=3600, must-revalidate\r\n"
670 "Last-modified: %s\r\n"
677 hprintf("Pragma: no-cache\r\n"
678 "Cache-Control: no-store\r\n"
683 stuff_to_cookie(cookie, 1024, WC->wc_session, WC->wc_username,
684 WC->wc_password, WC->wc_roomname);
687 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
689 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
690 if (server_cookie != NULL) {
691 hprintf("%s\n", server_cookie);
697 if (!access("static.local/webcit.css", R_OK)) {
698 svprintf(HKEY("CSSLOCAL"), WCS_STRING,
699 "<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"
702 do_template("head", NULL);
709 /* check for ImportantMessages (these display in a div overlaying the main screen) */
710 if (!IsEmptyStr(WC->ImportantMessage)) {
711 wprintf("<div id=\"important_message\">\n"
712 "<span class=\"imsg\">");
713 escputs(WC->ImportantMessage);
714 wprintf("</span><br />\n"
716 "<script type=\"text/javascript\">\n"
717 " setTimeout('hide_imsg_popup()', 5000); \n"
719 WC->ImportantMessage[0] = 0;
722 if ( (WC->logged_in) && (!unset_cookies) ) {
723 wprintf("<div id=\"iconbar\">");
724 do_selected_iconbar();
725 /** check for instant messages (these display in a new window) */
730 if (do_room_banner == 1) {
731 wprintf("<div id=\"banner\">\n");
732 embed_room_banner(NULL, navbar_default);
737 if (do_room_banner == 1) {
738 wprintf("<div id=\"content\">\n");
744 * Generic function to do an HTTP redirect. Easy and fun.
746 void http_redirect(const char *whichpage) {
747 hprintf("HTTP/1.1 302 Moved Temporarily\n");
748 hprintf("Location: %s\r\n", whichpage);
749 hprintf("URI: %s\r\n", whichpage);
750 hprintf("Content-type: text/html; charset=utf-8\r\n");
751 wprintf("<html><body>");
752 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
753 wprintf("</body></html>\n");
760 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
762 void http_transmit_thing(const char *content_type,
765 output_headers(0, 0, 0, 0, 0, is_static);
767 hprintf("Content-type: %s\r\n"
769 "Connection: close\r\n",
777 * print menu box like used in the floor view or admin interface.
778 * This function takes pair of strings as va_args,
779 * Title Title string of the box
780 * Class CSS Class for the box
781 * nLines How many string pairs should we print? (URL, UrlText)
782 * ... Pairs of URL Strings and their Names
784 void print_menu_box(char* Title, char *Class, int nLines, ...)
789 svput("BOXTITLE", WCS_STRING, Title);
790 do_template("beginbox", NULL);
792 wprintf("<ul class=\"%s\">", Class);
794 va_start(arg_list, nLines);
795 for (i = 0; i < nLines; ++i)
797 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
798 wprintf((char *) va_arg(arg_list, char *));
799 wprintf("</a></li>\n");
803 wprintf("</a></li>\n");
807 do_template("endbox", NULL);
812 * dump out static pages from disk
814 void output_static(char *what)
820 const char *content_type;
824 fd = open(what, O_RDONLY);
826 lprintf(9, "output_static('%s') -- NOT FOUND --\n", what);
827 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
828 hprintf("Content-Type: text/plain\r\n");
829 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
833 content_type = GuessMimeByFilename(what, len);
835 if (fstat(fd, &statbuf) == -1) {
836 lprintf(9, "output_static('%s') -- FSTAT FAILED --\n", what);
837 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
838 hprintf("Content-Type: text/plain\r\n");
839 wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
845 bytes = statbuf.st_size;
847 if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
849 if (fd > 0) close(fd);
850 lprintf(9, "output_static('%s') -- FREAD FAILED (%s) --\n", what, strerror(errno));
851 hprintf("HTTP/1.1 500 internal server error \r\n");
852 hprintf("Content-Type: text/plain\r\n");
859 lprintf(9, "output_static('%s') %s\n", what, content_type);
860 http_transmit_thing(content_type, 1);
862 if (yesbstr("force_close_session")) {
863 end_webcit_session();
868 * When the browser requests an image file from the Citadel server,
869 * this function is called to transmit it.
873 struct wcsession *WCC = WC;
876 const char *MimeType;
878 serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
879 serv_getln(buf, sizeof buf);
881 bytes = extract_long(&buf[4], 0);
883 /** Read it from the server */
885 if (read_server_binary(WCC->WBuf, bytes) > 0) {
887 serv_getln(buf, sizeof buf);
889 MimeType = GuessMimeType (ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
890 /** Write it to the browser */
891 if (!IsEmptyStr(MimeType))
893 http_transmit_thing(MimeType, 0);
897 /* hm... unknown mimetype? fallback to blank gif */
902 * Instead of an ugly 404, send a 1x1 transparent GIF
903 * when there's no such image on the server.
906 snprintf (blank_gif, SIZ, "%s%s", static_dirs[0], "/blank.gif");
907 output_static(blank_gif);
911 * Extract an embedded photo from a vCard for display on the client
913 void display_vcard_photo_img(void)
919 const char *contentType;
920 struct wcsession *WCC = WC;
922 msgnum = StrTol(WCC->UrlFragment1);
924 vcard = load_mimepart(msgnum,"1");
925 v = vcard_load(vcard);
927 photosrc = vcard_get_prop(v, "PHOTO", 1,0,0);
928 FlushStrBuf(WCC->WBuf);
929 StrBufAppendBufPlain(WCC->WBuf, photosrc, -1, 0);
930 if (StrBufDecodeBase64(WCC->WBuf) <= 0) {
931 FlushStrBuf(WCC->WBuf);
933 hprintf("HTTP/1.1 500 %s\n","Unable to get photo");
934 output_headers(0, 0, 0, 0, 0, 0);
935 hprintf("Content-Type: text/plain\r\n");
936 wprintf(_("Could Not decode vcard photo\n"));
940 contentType = GuessMimeType(ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
941 http_transmit_thing(contentType, 0);
947 * Generic function to output an arbitrary MIME part from an arbitrary
948 * message number on the server.
950 * msgnum Number of the item on the citadel server
951 * partnum The MIME part to be output
952 * force_download Nonzero to force set the Content-Type: header to "application/octet-stream"
954 void mimepart(const char *msgnum, const char *partnum, int force_download)
958 char content_type[256];
959 char *content = NULL;
961 serv_printf("OPNA %s|%s", msgnum, partnum);
962 serv_getln(buf, sizeof buf);
964 bytes = extract_long(&buf[4], 0);
965 content = malloc(bytes + 2);
966 if (force_download) {
967 strcpy(content_type, "application/octet-stream");
970 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
972 output_headers(0, 0, 0, 0, 0, 0);
974 read_server_binary(WC->WBuf, bytes);
976 serv_getln(buf, sizeof buf);
977 http_transmit_thing(content_type, 0);
979 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
980 output_headers(0, 0, 0, 0, 0, 0);
981 hprintf("Content-Type: text/plain\r\n");
982 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
990 * Read any MIME part of a message, from the server, into memory.
992 char *load_mimepart(long msgnum, char *partnum)
996 char content_type[SIZ];
999 serv_printf("DLAT %ld|%s", msgnum, partnum);
1000 serv_getln(buf, sizeof buf);
1001 if (buf[0] == '6') {
1002 bytes = extract_long(&buf[4], 0);
1003 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1005 content = malloc(bytes + 2);
1006 serv_read(content, bytes);
1008 content[bytes] = 0; /* null terminate for good measure */
1019 * Convenience functions to display a page containing only a string
1021 * titlebarcolor color of the titlebar of the frame
1022 * titlebarmsg text to display in the title bar
1023 * messagetext body of the box
1025 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
1027 hprintf("HTTP/1.1 200 OK\n");
1028 output_headers(1, 1, 2, 0, 0, 0);
1029 wprintf("<div id=\"banner\">\n");
1030 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
1031 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
1032 wprintf("</td></tr></table>\n");
1033 wprintf("</div>\n<div id=\"content\">\n");
1034 escputs(messagetext);
1036 wprintf("<hr />\n");
1042 * Display a blank page.
1044 void blank_page(void) {
1045 output_headers(1, 1, 0, 0, 0, 0);
1051 * A template has been requested
1053 void url_do_template(void) {
1054 const StrBuf *Tmpl = sbstr("template");
1056 output_headers(1, 0, 0, 0, 1, 0);
1057 DoTemplate(ChrPtr(Tmpl), StrLength(Tmpl), NULL, NULL);
1064 * Offer to make any page the user's "start page."
1066 void offer_start_page(void) {
1067 wprintf("<a href=\"change_start_page?startpage=");
1068 urlescputs(WC->this_page);
1070 wprintf(_("Make this my start page"));
1073 wprintf("<br/><a href=\"rss?room=");
1074 urlescputs(WC->wc_roomname);
1075 wprintf("\" title=\"RSS 2.0 feed for ");
1076 escputs(WC->wc_roomname);
1077 wprintf("\"><img alt=\"RSS\" border=\"0\" src=\"static/xml_button.gif\"/></a>\n");
1083 * Change the user's start page
1085 void change_start_page(void) {
1087 if (bstr("startpage") == NULL) {
1088 safestrncpy(WC->ImportantMessage,
1089 _("You no longer have a start page selected."),
1090 sizeof WC->ImportantMessage);
1091 display_main_menu();
1095 set_preference("startpage", NewStrBufPlain(bstr("startpage"), -1), 1);
1097 output_headers(1, 1, 0, 0, 0, 0);
1098 do_template("newstartpage", NULL);
1105 * convenience function to indicate success
1107 void display_success(char *successmessage)
1109 convenience_page("007700", "OK", successmessage);
1114 * Authorization required page
1115 * This is probably temporary and should be revisited
1117 void authorization_required(const char *message)
1119 hprintf("HTTP/1.1 401 Authorization Required\r\n");
1120 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", serv_info.serv_humannode);
1121 hprintf("Content-Type: text/html\r\n");
1123 wprintf(_("Authorization Required"));
1124 wprintf("</h1>\r\n");
1125 wprintf(_("The resource you requested requires a valid username and password. "
1126 "You could not be logged in: %s\n"), message);
1132 * This function is called by the MIME parser to handle data uploaded by
1133 * the browser. Form data, uploaded files, and the data from HTTP PUT
1134 * operations (such as those found in GroupDAV) all arrive this way.
1136 * name Name of the item being uploaded
1137 * filename Filename of the item being uploaded
1138 * partnum MIME part identifier (not needed)
1139 * disp MIME content disposition (not needed)
1140 * content The actual data
1141 * cbtype MIME content-type
1142 * cbcharset Character set
1143 * length Content length
1144 * encoding MIME encoding type (not needed)
1145 * userdata Not used here
1147 void upload_handler(char *name, char *filename, char *partnum, char *disp,
1148 void *content, char *cbtype, char *cbcharset,
1149 size_t length, char *encoding, void *userdata)
1152 #ifdef DEBUG_URLSTRINGS
1153 lprintf(9, "upload_handler() name=%s, type=%s, len=%d\n", name, cbtype, length);
1155 if (WC->urlstrings == NULL)
1156 WC->urlstrings = NewHash(1, NULL);
1159 if ( (length > 0) && (IsEmptyStr(cbtype)) ) {
1160 u = (urlcontent *) malloc(sizeof(urlcontent));
1162 safestrncpy(u->url_key, name, sizeof(u->url_key));
1163 u->url_data = NewStrBufPlain(content, length);
1165 Put(WC->urlstrings, u->url_key, strlen(u->url_key), u, free_url);
1166 #ifdef DEBUG_URLSTRINGS
1167 lprintf(9, "Key: <%s> len: [%ld] Data: <%s>\n", u->url_key, u->url_data_size, u->url_data);
1171 /** Uploaded files */
1172 if ( (length > 0) && (!IsEmptyStr(cbtype)) ) {
1173 WC->upload = malloc(length);
1174 if (WC->upload != NULL) {
1175 WC->upload_length = length;
1176 safestrncpy(WC->upload_filename, filename,
1177 sizeof(WC->upload_filename));
1178 safestrncpy(WC->upload_content_type, cbtype,
1179 sizeof(WC->upload_content_type));
1180 memcpy(WC->upload, content, length);
1183 lprintf(3, "malloc() failed: %s\n", strerror(errno));
1190 * Convenience functions to wrap around asynchronous ajax responses
1192 void begin_ajax_response(void) {
1193 output_headers(0, 0, 0, 0, 0, 0);
1195 hprintf("Content-type: text/html; charset=UTF-8\r\n"
1197 "Connection: close\r\n"
1198 "Pragma: no-cache\r\n"
1199 "Cache-Control: no-cache\r\n"
1207 * print ajax response footer
1209 void end_ajax_response(void) {
1210 ///hprintf("\r\n");///// todo: is this right?
1215 * Wraps a Citadel server command in an AJAX transaction.
1217 void ajax_servcmd(void)
1220 char gcontent[1024];
1224 begin_ajax_response();
1226 serv_printf("%s", bstr("g_cmd"));
1227 serv_getln(buf, sizeof buf);
1228 wprintf("%s\n", buf);
1230 if (buf[0] == '8') {
1231 serv_printf("\n\n000");
1233 if ((buf[0] == '1') || (buf[0] == '8')) {
1234 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
1235 wprintf("%s\n", gcontent);
1239 if (buf[0] == '4') {
1240 text_to_server(bstr("g_input"));
1243 if (buf[0] == '6') {
1244 len = atol(&buf[4]);
1246 serv_read(junk, len);
1249 if (buf[0] == '7') {
1250 len = atol(&buf[4]);
1252 memset(junk, 0, len);
1253 serv_write(junk, len);
1257 end_ajax_response();
1260 * This is kind of an ugly hack, but this is the only place it can go.
1261 * If the command was GEXP, then the instant messenger window must be
1262 * running, so reset the "last_pager_check" watchdog timer so
1263 * that page_popup() doesn't try to open it a second time.
1265 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
1266 WC->last_pager_check = time(NULL);
1272 * Helper function for the asynchronous check to see if we need
1273 * to open the instant messenger window.
1275 void seconds_since_last_gexp(void)
1279 begin_ajax_response();
1280 if ( (time(NULL) - WC->last_pager_check) < 30) {
1285 serv_getln(buf, sizeof buf);
1286 if (buf[3] == '*') {
1293 end_ajax_response();
1297 * \brief Detects a 'mobile' user agent
1299 int is_mobile_ua(char *user_agent) {
1300 if (strstr(user_agent,"iPhone OS") != NULL) {
1302 } else if (strstr(user_agent,"Windows CE") != NULL) {
1304 } else if (strstr(user_agent,"SymbianOS") != NULL) {
1306 } else if (strstr(user_agent, "Opera Mobi") != NULL) {
1308 } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
1309 // For some reason a new install of Opera 9.51beta decided to spoof.
1317 * Entry point for WebCit transaction
1319 void session_loop(struct httprequest *req)
1327 char request_method[128];
1328 char pathname[1024];
1329 int a, b, nBackDots, nEmpty;
1330 int ContentLength = 0;
1331 char ContentType[512];
1332 char *content = NULL;
1333 char *content_end = NULL;
1334 struct httprequest *hptr;
1335 char browser_host[256];
1336 char user_agent[256];
1342 * We stuff these with the values coming from the client cookies,
1343 * so we can use them to reconnect a timed out session if we have to.
1345 char c_username[SIZ];
1346 char c_password[SIZ];
1347 char c_roomname[SIZ];
1348 char c_httpauth_string[SIZ];
1349 char c_httpauth_user[SIZ];
1350 char c_httpauth_pass[SIZ];
1352 struct wcsession *WCC;
1354 safestrncpy(c_username, "", sizeof c_username);
1355 safestrncpy(c_password, "", sizeof c_password);
1356 safestrncpy(c_roomname, "", sizeof c_roomname);
1357 safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
1358 safestrncpy(c_httpauth_user, DEFAULT_HTTPAUTH_USER, sizeof c_httpauth_user);
1359 safestrncpy(c_httpauth_pass, DEFAULT_HTTPAUTH_PASS, sizeof c_httpauth_pass);
1360 strcpy(browser_host, "");
1363 if (WCC->WBuf == NULL)
1364 WC->WBuf = NewStrBufPlain(NULL, 32768);
1365 FlushStrBuf(WCC->WBuf);
1367 if (WCC->HBuf == NULL)
1368 WCC->HBuf = NewStrBuf();
1369 FlushStrBuf(WCC->HBuf);
1371 WCC->upload_length = 0;
1376 if (hptr == NULL) return;
1378 safestrncpy(cmd, hptr->line, sizeof cmd);
1380 extract_token(request_method, cmd, 0, ' ', sizeof request_method);
1381 extract_token(pathname, cmd, 1, ' ', sizeof pathname);
1383 /** Figure out the action */
1385 sizes[0] = sizeof action;
1388 index[a] = arg[a-1];
1389 sizes[a] = sizeof arg[a-1];
1391 //// index[9] = &foo; todo
1394 for ( a = 0; a < 9; ++a)
1396 extract_token(index[a], pathname, a + 1, '/', sizes[a]);
1397 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
1398 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
1399 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
1400 if ((index[a][0] == '.') && (index[a][1] == '.'))
1402 if (index[a][0] == '\0')
1406 while (hptr != NULL) {
1407 safestrncpy(buf, hptr->line, sizeof buf);
1408 /* lprintf(9, "HTTP HEADER: %s\n", buf); */
1411 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
1412 safestrncpy(cookie, &buf[15], sizeof cookie);
1413 cookie_to_stuff(cookie, NULL,
1414 c_username, sizeof c_username,
1415 c_password, sizeof c_password,
1416 c_roomname, sizeof c_roomname);
1418 else if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
1419 CtdlDecodeBase64(c_httpauth_string, &buf[21], strlen(&buf[21]));
1420 extract_token(c_httpauth_user, c_httpauth_string, 0, ':', sizeof c_httpauth_user);
1421 extract_token(c_httpauth_pass, c_httpauth_string, 1, ':', sizeof c_httpauth_pass);
1423 else if (!strncasecmp(buf, "Content-length: ", 16)) {
1424 ContentLength = atoi(&buf[16]);
1426 else if (!strncasecmp(buf, "Content-type: ", 14)) {
1427 safestrncpy(ContentType, &buf[14], sizeof ContentType);
1429 else if (!strncasecmp(buf, "User-agent: ", 12)) {
1430 safestrncpy(user_agent, &buf[12], sizeof user_agent);
1432 if (is_mobile_ua(&buf[12])) {
1437 else if (!strncasecmp(buf, "X-Forwarded-Host: ", 18)) {
1439 safestrncpy(WCC->http_host, &buf[18], sizeof WCC->http_host);
1442 else if (!strncasecmp(buf, "Host: ", 6)) {
1443 if (IsEmptyStr(WCC->http_host)) {
1444 safestrncpy(WCC->http_host, &buf[6], sizeof WCC->http_host);
1447 else if (!strncasecmp(buf, "X-Forwarded-For: ", 17)) {
1448 safestrncpy(browser_host, &buf[17], sizeof browser_host);
1449 while (num_tokens(browser_host, ',') > 1) {
1450 remove_token(browser_host, 0, ',');
1452 striplt(browser_host);
1456 if (ContentLength > 0) {
1459 BuffSize = ContentLength + SIZ;
1460 content = malloc(BuffSize);
1461 memset(content, 0, BuffSize);
1462 snprintf(content, BuffSize, "Content-type: %s\n"
1463 "Content-length: %d\n\n",
1464 ContentType, ContentLength);
1466 hprintf("Content-type: %s\n"
1467 "Content-length: %d\n\n",
1468 ContentType, ContentLength);
1470 body_start = strlen(content);
1472 /** Read the entire input data at once. */
1473 client_read(WCC->http_sock, &content[body_start], ContentLength);
1475 if (!strncasecmp(ContentType, "application/x-www-form-urlencoded", 33)) {
1478 Content = _NewConstStrBuf(&content[body_start],ContentLength);
1480 FreeStrBuf(&Content);
1481 } else if (!strncasecmp(ContentType, "multipart", 9)) {
1482 content_end = content + ContentLength + body_start;
1483 mime_parser(content, content_end, *upload_handler, NULL, NULL, NULL, 0);
1489 /* make a note of where we are in case the user wants to save it */
1490 safestrncpy(WCC->this_page, cmd, sizeof(WCC->this_page));
1491 remove_token(WCC->this_page, 2, ' ');
1492 remove_token(WCC->this_page, 0, ' ');
1494 /* If there are variables in the URL, we must grab them now */
1496 for (a = 0; a < len; ++a) {
1497 if ((cmd[a] == '?') || (cmd[a] == '&')) {
1499 for (b = a; b < len; ++b) {
1500 if (isspace(cmd[b])){
1505 //cmd[len - a] = '\0';
1506 Params = _NewConstStrBuf(&cmd[a + 1], len - a);
1513 /* If it's a "force 404" situation then display the error and bail. */
1514 if (!strcmp(action, "404")) {
1515 hprintf("HTTP/1.1 404 Not found\r\n");
1516 hprintf("Content-Type: text/plain\r\n");
1517 wprintf("Not found\r\n");
1519 goto SKIP_ALL_THIS_CRAP;
1522 /* Static content can be sent without connecting to Citadel. */
1524 for (a=0; a<ndirs; ++a) {
1525 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
1533 snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
1534 static_dirs[n_static],
1535 index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
1536 for (a=0; a<8; ++a) {
1537 if (buf[strlen(buf)-1] == '/') {
1538 buf[strlen(buf)-1] = 0;
1541 for (a = 0; a < strlen(buf); ++a) {
1542 if (isspace(buf[a])) {
1550 lprintf(9, "Suspicious request. Ignoring.");
1551 hprintf("HTTP/1.1 404 Security check failed\r\n");
1552 hprintf("Content-Type: text/plain\r\n");
1553 wprintf("You have sent a malformed or invalid request.\r\n");
1556 goto SKIP_ALL_THIS_CRAP; /* Don't try to connect */
1559 /* If the client sent a nonce that is incorrect, kill the request. */
1560 if (strlen(bstr("nonce")) > 0) {
1561 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
1562 bstr("nonce"), WCC->nonce);
1563 if (ibstr("nonce") != WCC->nonce) {
1564 lprintf(9, "Ignoring request with mismatched nonce.\n");
1565 hprintf("HTTP/1.1 404 Security check failed\r\n");
1566 hprintf("Content-Type: text/plain\r\n");
1567 wprintf("Security check failed.\r\n");
1569 goto SKIP_ALL_THIS_CRAP;
1574 * If we're not connected to a Citadel server, try to hook up the
1577 if (!WCC->connected) {
1578 if (!strcasecmp(ctdlhost, "uds")) {
1579 /* unix domain socket */
1580 snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
1581 WCC->serv_sock = uds_connectsock(buf);
1585 WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
1588 if (WCC->serv_sock < 0) {
1590 goto SKIP_ALL_THIS_CRAP;
1594 serv_getln(buf, sizeof buf); /** get the server welcome message */
1597 * From what host is our user connecting? Go with
1598 * the host at the other end of the HTTP socket,
1599 * unless we are following X-Forwarded-For: headers
1600 * and such a header has already turned up something.
1602 if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
1603 locate_host(browser_host, WCC->http_sock);
1606 get_serv_info(browser_host, user_agent);
1607 if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
1608 wprintf(_("You are connected to a Citadel "
1609 "server running Citadel %d.%02d. \n"
1610 "In order to run this version of WebCit "
1611 "you must also have Citadel %d.%02d or"
1613 serv_info.serv_rev_level / 100,
1614 serv_info.serv_rev_level % 100,
1615 MINIMUM_CIT_VERSION / 100,
1616 MINIMUM_CIT_VERSION % 100
1618 end_webcit_session();
1619 goto SKIP_ALL_THIS_CRAP;
1623 ////////todo: restorte language in this case
1625 * Functions which can be performed without logging in
1627 if (!strcasecmp(action, "listsub")) {
1629 goto SKIP_ALL_THIS_CRAP;
1631 if (!strcasecmp(action, "freebusy")) {
1633 goto SKIP_ALL_THIS_CRAP;
1637 * If we're not logged in, but we have HTTP Authentication data,
1638 * try logging in to Citadel using that.
1640 if ((!WCC->logged_in)
1641 && (strlen(c_httpauth_user) > 0)
1642 && (strlen(c_httpauth_pass) > 0)) {
1643 serv_printf("USER %s", c_httpauth_user);
1644 serv_getln(buf, sizeof buf);
1645 if (buf[0] == '3') {
1646 serv_printf("PASS %s", c_httpauth_pass);
1647 serv_getln(buf, sizeof buf);
1648 if (buf[0] == '2') {
1649 become_logged_in(c_httpauth_user,
1650 c_httpauth_pass, buf);
1651 safestrncpy(WCC->httpauth_user, c_httpauth_user, sizeof WCC->httpauth_user);
1652 safestrncpy(WCC->httpauth_pass, c_httpauth_pass, sizeof WCC->httpauth_pass);
1654 /* Should only display when password is wrong */
1655 authorization_required(&buf[4]);
1656 goto SKIP_ALL_THIS_CRAP;
1661 /* This needs to run early */
1663 if (!strcasecmp(action, "rss")) {
1664 display_rss(bstr("room"), request_method);
1665 goto SKIP_ALL_THIS_CRAP;
1670 * The GroupDAV stuff relies on HTTP authentication instead of
1671 * our session's authentication.
1673 if (!strncasecmp(action, "groupdav", 8)) {
1674 groupdav_main(req, ContentType, /* do GroupDAV methods */
1675 ContentLength, content+body_start);
1676 if (!WCC->logged_in) {
1677 WCC->killthis = 1; /* If not logged in, don't */
1678 } /* keep the session active */
1679 goto SKIP_ALL_THIS_CRAP;
1684 * Automatically send requests with any method other than GET or
1685 * POST to the GroupDAV code as well.
1687 if ((strcasecmp(request_method, "GET")) && (strcasecmp(request_method, "POST"))) {
1688 groupdav_main(req, ContentType, /** do GroupDAV methods */
1689 ContentLength, content+body_start);
1690 if (!WCC->logged_in) {
1691 WCC->killthis = 1; /** If not logged in, don't */
1692 } /** keep the session active */
1693 goto SKIP_ALL_THIS_CRAP;
1697 * If we're not logged in, but we have username and password cookies
1698 * supplied by the browser, try using them to log in.
1700 if ((!WCC->logged_in)
1701 && (!IsEmptyStr(c_username))
1702 && (!IsEmptyStr(c_password))) {
1703 serv_printf("USER %s", c_username);
1704 serv_getln(buf, sizeof buf);
1705 if (buf[0] == '3') {
1706 serv_printf("PASS %s", c_password);
1707 serv_getln(buf, sizeof buf);
1708 if (buf[0] == '2') {
1710 become_logged_in(c_username, c_password, buf);
1711 if (get_preference("language", &Lang)) {
1712 set_selected_language(ChrPtr(Lang));
1713 go_selected_language(); /* set locale */
1719 * If we don't have a current room, but a cookie specifying the
1720 * current room is supplied, make an effort to go there.
1722 if ((IsEmptyStr(WCC->wc_roomname)) && (!IsEmptyStr(c_roomname))) {
1723 serv_printf("GOTO %s", c_roomname);
1724 serv_getln(buf, sizeof buf);
1725 if (buf[0] == '2') {
1726 safestrncpy(WCC->wc_roomname, c_roomname, sizeof WCC->wc_roomname);
1730 if (!strcasecmp(action, "image")) {
1732 } else if (!strcasecmp(action, "display_mime_icon")) {
1733 display_mime_icon();
1737 WebcitHandler *Handler;
1739 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
1740 Handler = (WebcitHandler*) vHandler;
1741 if (Handler != NULL) {
1742 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
1743 display_login(NULL);
1746 if((Handler->Flags & NEED_URL)) {
1747 if (WCC->UrlFragment1 == NULL)
1748 WCC->UrlFragment1 = NewStrBuf();
1749 if (WCC->UrlFragment2 == NULL)
1750 WCC->UrlFragment2 = NewStrBuf();
1751 StrBufPrintf(WCC->UrlFragment1, "%s", index[1]);
1752 StrBufPrintf(WCC->UrlFragment2, "%s", index[2]);
1754 if ((Handler->Flags & AJAX) != 0)
1755 begin_ajax_response();
1757 if ((Handler->Flags & AJAX) != 0)
1758 end_ajax_response();
1761 /* When all else fais, display the main menu. */
1763 if (!WCC->logged_in)
1764 display_login(NULL);
1766 display_main_menu();
1771 if (content != NULL) {
1776 if (WCC->upload_length > 0) {
1778 WCC->upload_length = 0;
1784 * Replacement for sleep() that uses select() in order to avoid SIGALRM
1786 void sleeeeeeeeeep(int seconds)
1790 tv.tv_sec = seconds;
1792 select(0, NULL, NULL, NULL, &tv);
1795 void diagnostics(void)
1797 output_headers(1, 1, 1, 0, 0, 0);
1798 wprintf("Session: %d<hr />\n", WC->wc_session);
1799 wprintf("Command: <br /><PRE>\n");
1800 escputs(WC->UrlFragment1);
1801 wprintf("<br />\n");
1802 escputs(WC->UrlFragment2);
1803 wprintf("</PRE><hr />\n");
1804 wprintf("Variables: <br /><PRE>\n");
1806 wprintf("</PRE><hr />\n");
1810 void view_mimepart(void) {
1811 mimepart(ChrPtr(WC->UrlFragment1),
1812 ChrPtr(WC->UrlFragment2),
1816 void download_mimepart(void) {
1817 mimepart(ChrPtr(WC->UrlFragment1),
1818 ChrPtr(WC->UrlFragment2),
1826 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1827 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1828 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1829 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1830 WebcitAddUrlHandler(HKEY("change_start_page"), change_start_page, 0);
1831 WebcitAddUrlHandler(HKEY("toggle_self_service"), toggle_self_service, 0);
1832 WebcitAddUrlHandler(HKEY("vcardphoto"), display_vcard_photo_img, NEED_URL);
1833 WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1834 WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1835 WebcitAddUrlHandler(HKEY("diagnostics"), diagnostics, NEED_URL);