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.
11 #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,
30 WebcitHandler *NewHandler;
32 if (HandlerHash == NULL)
33 HandlerHash = NewHash(1, NULL);
35 NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
37 NewHandler->Flags = Flags;
38 Put(HandlerHash, UrlString, UrlSLen, NewHandler, NULL);
42 * remove escaped strings from i.e. the url string (like %20 for blanks)
44 long unescape_input(char *buf)
53 while ((buflen > 0) && (isspace(buf[buflen - 1]))){
63 /* don't let % chars through, rather truncate the input. */
73 sscanf(hex, "%02x", &b);
77 memmove(&buf[a + 1], &buf[a + 3], len);
87 void free_url(void *U)
89 urlcontent *u = (urlcontent*) U;
95 * Extract variables from the URL.
97 void addurls(char *url, long ulen)
99 char *aptr, *bptr, *eptr;
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);
113 while ((up < eptr) && (!IsEmptyStr(up))) {
115 while ((aptr < eptr) && (*aptr != '\0') && (*aptr != '='))
122 while ((bptr < eptr) && (*bptr != '\0')
123 && (*bptr != '&') && (*bptr != '?') && (*bptr != ' ')) {
127 u = (urlcontent *) malloc(sizeof(urlcontent));
129 keylen = safestrncpy(u->url_key, up, sizeof u->url_key);
131 lprintf(1, "URLkey to long! [%s]", up);
135 Put(WCC->urlstrings, u->url_key, keylen, u, free_url);
137 u->url_data = malloc(len + 2);
138 safestrncpy(u->url_data, aptr, len + 2);
139 u->url_data_size = unescape_input(u->url_data);
140 u->url_data[u->url_data_size] = '\0';
143 #ifdef DEBUG_URLSTRINGS
144 lprintf(9, "%s = [%ld] %s\n", u->url_key, u->url_data_size, u->url_data);
151 * free urlstring memory
155 DeleteHash(&WC->urlstrings);
159 * Diagnostic function to display the contents of all variables
164 struct wcsession *WCC = WC;
171 Cursor = GetNewHashPos ();
172 while (GetNextHashPos(WCC->urlstrings, Cursor, &HKLen, &HKey, &U)) {
174 wprintf("%38s = %s\n", u->url_key, u->url_data);
179 * Return the value of a variable supplied to the current web page (from the url or a form)
182 const char *XBstr(char *key, size_t keylen, size_t *len)
186 if ((WC->urlstrings != NULL) &&
187 GetHash(WC->urlstrings, key, keylen, &U)) {
188 *len = ((urlcontent *)U)->url_data_size;
189 return ((urlcontent *)U)->url_data;
197 const char *XBSTR(char *key, size_t *len)
201 if ((WC->urlstrings != NULL) &&
202 GetHash(WC->urlstrings, key, strlen (key), &U)){
203 *len = ((urlcontent *)U)->url_data_size;
204 return ((urlcontent *)U)->url_data;
213 const char *BSTR(char *key)
217 if ((WC->urlstrings != NULL) &&
218 GetHash(WC->urlstrings, key, strlen (key), &U))
219 return ((urlcontent *)U)->url_data;
224 const char *Bstr(char *key, size_t keylen)
228 if ((WC->urlstrings != NULL) &&
229 GetHash(WC->urlstrings, key, keylen, &U))
230 return ((urlcontent *)U)->url_data;
235 long LBstr(char *key, size_t keylen)
239 if ((WC->urlstrings != NULL) &&
240 GetHash(WC->urlstrings, key, keylen, &U))
241 return atol(((urlcontent *)U)->url_data);
246 long LBSTR(char *key)
250 if ((WC->urlstrings != NULL) &&
251 GetHash(WC->urlstrings, key, strlen(key), &U))
252 return atol(((urlcontent *)U)->url_data);
257 int IBstr(char *key, size_t keylen)
261 if ((WC->urlstrings != NULL) &&
262 GetHash(WC->urlstrings, key, keylen, &U))
263 return atoi(((urlcontent *)U)->url_data);
272 if ((WC->urlstrings != NULL) &&
273 GetHash(WC->urlstrings, key, strlen(key), &U))
274 return atoi(((urlcontent *)U)->url_data);
279 int HaveBstr(char *key, size_t keylen)
283 if ((WC->urlstrings != NULL) &&
284 GetHash(WC->urlstrings, key, keylen, &U))
285 return ((urlcontent *)U)->url_data_size != 0;
290 int HAVEBSTR(char *key)
294 if ((WC->urlstrings != NULL) &&
295 GetHash(WC->urlstrings, key, strlen(key), &U))
296 return ((urlcontent *)U)->url_data_size != 0;
302 int YesBstr(char *key, size_t keylen)
306 if ((WC->urlstrings != NULL) &&
307 GetHash(WC->urlstrings, key, keylen, &U))
308 return strcmp( ((urlcontent *)U)->url_data, "yes") == 0;
313 int YESBSTR(char *key)
317 if ((WC->urlstrings != NULL) &&
318 GetHash(WC->urlstrings, key, strlen(key), &U))
319 return strcmp( ((urlcontent *)U)->url_data, "yes") == 0;
325 * web-printing funcion. uses our vsnprintf wrapper
327 void wprintf(const char *format,...)
332 va_start(arg_ptr, format);
333 vsnprintf(wbuf, sizeof wbuf, format, arg_ptr);
336 client_write(wbuf, strlen(wbuf));
341 * wrap up an HTTP session, closes tags, etc.
343 * print_standard_html_footer should be set to:
344 * 0 to transmit only,
345 * 1 to append the main menu and closing tags,
346 * 2 to append the closing tags only.
348 void wDumpContent(int print_standard_html_footer)
350 if (print_standard_html_footer) {
351 wprintf("</div>\n"); /* end of "text" div */
352 do_template("trailing");
355 /* If we've been saving it all up for one big output burst,
356 * go ahead and do that now.
363 * Copy a string, escaping characters which have meaning in HTML.
365 * target target buffer
366 * strbuf source buffer
367 * nbsp If nonzero, spaces are converted to non-breaking spaces.
368 * nolinebreaks if set, linebreaks are removed from the string.
370 long stresc(char *target, long tSize, char *strbuf, int nbsp, int nolinebreaks)
372 char *aptr, *bptr, *eptr;
377 eptr = target + tSize - 6; // our biggest unit to put in...
379 while ((bptr < eptr) && !IsEmptyStr(aptr) ){
381 memcpy(bptr, "<", 4);
384 else if (*aptr == '>') {
385 memcpy(bptr, ">", 4);
388 else if (*aptr == '&') {
389 memcpy(bptr, "&", 5);
392 else if (*aptr == '\"') {
393 memcpy(bptr, """, 6);
396 else if (*aptr == '\'') {
397 memcpy(bptr, "'", 5);
400 else if (*aptr == LB) {
404 else if (*aptr == RB) {
408 else if (*aptr == QU) {
412 else if ((*aptr == 32) && (nbsp == 1)) {
413 memcpy(bptr, " ", 6);
416 else if ((*aptr == '\n') && (nolinebreaks)) {
417 *bptr='\0'; /* nothing */
419 else if ((*aptr == '\r') && (nolinebreaks)) {
420 *bptr='\0'; /* nothing */
429 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
431 return (bptr - target);
434 void escputs1(char *strbuf, int nbsp, int nolinebreaks)
439 if (strbuf == NULL) return;
440 Siz = (3 * strlen(strbuf)) + SIZ ;
442 stresc(buf, Siz, strbuf, nbsp, nolinebreaks);
448 * static wrapper for ecsputs1
450 void escputs(char *strbuf)
452 escputs1(strbuf, 0, 0);
457 * urlescape buffer and print it to the client
459 void urlescputs(char *strbuf)
463 urlesc(outbuf, SIZ, strbuf);
464 wprintf("%s", outbuf);
469 * Copy a string, escaping characters for JavaScript strings.
471 void jsesc(char *target, size_t tlen, char *strbuf)
480 len = strlen (strbuf);
482 tend = target + tlen;
486 while (!IsEmptyStr(sptr) &&
492 else if (*sptr == '>')
494 else if (*sptr == '\'') {
500 else if (*sptr == '"') {
510 else if (*sptr == '&') {
527 * escape and print javascript
529 void jsescputs(char *strbuf)
533 jsesc(outbuf, SIZ, strbuf);
534 wprintf("%s", outbuf);
538 * Copy a string, escaping characters for message text hold
540 void msgesc(char *target, size_t tlen, char *strbuf)
549 len = strlen (strbuf);
551 tend = target + tlen;
555 while (!IsEmptyStr(sptr) &&
561 else if (*sptr == '\r')
563 else if (*sptr == '\'') {
580 * print a string to the client after cleaning it with msgesc() and stresc()
582 void msgescputs1( char *strbuf)
588 if (strbuf == NULL) return;
589 buflen = 3 * strlen(strbuf) + SIZ;
590 outbuf = malloc( buflen);
591 outbuf2 = malloc( buflen);
592 msgesc(outbuf, buflen, strbuf);
593 stresc(outbuf2, buflen, outbuf, 0, 0);
594 wprintf("%s", outbuf2);
600 * print a string to the client after cleaning it with msgesc()
602 void msgescputs(char *strbuf) {
606 if (strbuf == NULL) return;
607 len = (3 * strlen(strbuf)) + SIZ;
608 outbuf = malloc(len);
609 msgesc(outbuf, len, strbuf);
610 wprintf("%s", outbuf);
618 * Output HTTP headers and leading HTML for a page
620 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
621 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
623 int do_room_banner, /* 0=no, 1=yes,
624 * 2 = I'm going to embed my own, so don't open the
625 * <div id="content"> either.
628 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
629 int suppress_check, /* 1 = suppress check for instant messages */
630 int cache /* 1 = allow browser to cache this page */
635 wprintf("HTTP/1.1 200 OK\n");
636 http_datestring(httpnow, sizeof httpnow, time(NULL));
638 if (do_httpheaders) {
639 wprintf("Content-type: text/html; charset=utf-8\r\n"
641 "Connection: close\r\n",
642 PACKAGE_STRING, serv_info.serv_software
647 char httpTomorow[128];
649 http_datestring(httpTomorow, sizeof httpTomorow,
650 time(NULL) + 60 * 60 * 24 * 2);
652 wprintf("Pragma: public\r\n"
653 "Cache-Control: max-age=3600, must-revalidate\r\n"
654 "Last-modified: %s\r\n"
661 wprintf("Pragma: no-cache\r\n"
662 "Cache-Control: no-store\r\n"
667 stuff_to_cookie(cookie, 1024, WC->wc_session, WC->wc_username,
668 WC->wc_password, WC->wc_roomname);
671 wprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
673 wprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
674 if (server_cookie != NULL) {
675 wprintf("%s\n", server_cookie);
681 if (!access("static.local/webcit.css", R_OK)) {
682 svprintf(HKEY("CSSLOCAL"), WCS_STRING,
683 "<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"
693 /* check for ImportantMessages (these display in a div overlaying the main screen) */
694 if (!IsEmptyStr(WC->ImportantMessage)) {
695 wprintf("<div id=\"important_message\">\n"
696 "<span class=\"imsg\">");
697 escputs(WC->ImportantMessage);
698 wprintf("</span><br />\n"
700 "<script type=\"text/javascript\">\n"
701 " setTimeout('hide_imsg_popup()', 5000); \n"
703 WC->ImportantMessage[0] = 0;
706 if ( (WC->logged_in) && (!unset_cookies) ) {
707 wprintf("<div id=\"iconbar\">");
708 do_selected_iconbar();
709 /** check for instant messages (these display in a new window) */
714 if (do_room_banner == 1) {
715 wprintf("<div id=\"banner\">\n");
716 embed_room_banner(NULL, navbar_default);
721 if (do_room_banner == 1) {
722 wprintf("<div id=\"content\">\n");
728 * Generic function to do an HTTP redirect. Easy and fun.
730 void http_redirect(const char *whichpage) {
731 wprintf("HTTP/1.1 302 Moved Temporarily\n");
732 wprintf("Location: %s\r\n", whichpage);
733 wprintf("URI: %s\r\n", whichpage);
734 wprintf("Content-type: text/html; charset=utf-8\r\n\r\n");
735 wprintf("<html><body>");
736 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
737 wprintf("</body></html>\n");
743 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
745 void http_transmit_thing(char *thing, size_t length, const char *content_type,
748 output_headers(0, 0, 0, 0, 0, is_static);
750 wprintf("Content-type: %s\r\n"
752 "Connection: close\r\n",
757 /* If we can send the data out compressed, please do so. */
759 char *compressed_data = NULL;
760 size_t compressed_len;
762 compressed_len = ((length * 101) / 100) + 100;
763 compressed_data = malloc(compressed_len);
765 if (compress_gzip((Bytef *) compressed_data,
768 (uLongf) length, Z_BEST_SPEED) == Z_OK) {
769 wprintf("Content-encoding: gzip\r\n"
770 "Content-length: %ld\r\n"
772 (long) compressed_len
774 client_write(compressed_data, (size_t)compressed_len);
775 free(compressed_data);
781 /* No compression ... just send it out as-is */
782 wprintf("Content-length: %ld\r\n"
786 client_write(thing, (size_t)length);
790 * print menu box like used in the floor view or admin interface.
791 * This function takes pair of strings as va_args,
792 * Title Title string of the box
793 * Class CSS Class for the box
794 * nLines How many string pairs should we print? (URL, UrlText)
795 * ... Pairs of URL Strings and their Names
797 void print_menu_box(char* Title, char *Class, int nLines, ...)
802 svput("BOXTITLE", WCS_STRING, Title);
803 do_template("beginbox");
805 wprintf("<ul class=\"%s\">", Class);
807 va_start(arg_list, nLines);
808 for (i = 0; i < nLines; ++i)
810 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
811 wprintf((char *) va_arg(arg_list, char *));
812 wprintf("</a></li>\n");
816 wprintf("</a></li>\n");
820 do_template("endbox");
825 * dump out static pages from disk
827 void output_static(char *what)
835 const char *content_type;
838 fp = fopen(what, "rb");
840 lprintf(9, "output_static('%s') -- NOT FOUND --\n", what);
841 wprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
842 wprintf("Content-Type: text/plain\r\n");
844 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
847 content_type = GuessMimeByFilename(what, len);
849 if (fstat(fileno(fp), &statbuf) == -1) {
850 lprintf(9, "output_static('%s') -- FSTAT FAILED --\n", what);
851 wprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
852 wprintf("Content-Type: text/plain\r\n");
854 wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
859 bytes = statbuf.st_size;
860 if ((bigbuffer = malloc(bytes + 2)) == NULL) {
861 lprintf(9, "output_static('%s') -- MALLOC FAILED (%s) --\n", what, strerror(errno));
862 wprintf("HTTP/1.1 500 internal server error\r\n");
863 wprintf("Content-Type: text/plain\r\n");
867 while (count < bytes) {
868 if ((res = fread(bigbuffer + count, 1, bytes - count, fp)) == 0) {
869 lprintf(9, "output_static('%s') -- FREAD FAILED (%s) %zu bytes of %zu --\n", what, strerror(errno), bytes - count, bytes);
870 wprintf("HTTP/1.1 500 internal server error \r\n");
871 wprintf("Content-Type: text/plain\r\n");
880 lprintf(9, "output_static('%s') %s\n", what, content_type);
881 http_transmit_thing(bigbuffer, (size_t)bytes, content_type, 1);
884 if (yesbstr("force_close_session")) {
885 end_webcit_session();
890 * When the browser requests an image file from the Citadel server,
891 * this function is called to transmit it.
896 char *xferbuf = NULL;
898 const char *MimeType;
900 serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
901 serv_getln(buf, sizeof buf);
903 bytes = extract_long(&buf[4], 0);
904 xferbuf = malloc(bytes + 2);
906 /** Read it from the server */
907 read_server_binary(xferbuf, bytes);
909 serv_getln(buf, sizeof buf);
911 MimeType = GuessMimeType (xferbuf, bytes);
912 /** Write it to the browser */
913 if (!IsEmptyStr(MimeType))
915 http_transmit_thing(xferbuf,
922 /* hm... unknown mimetype? fallback to blank gif */
928 * Instead of an ugly 404, send a 1x1 transparent GIF
929 * when there's no such image on the server.
932 snprintf (blank_gif, SIZ, "%s%s", static_dirs[0], "/blank.gif");
933 output_static(blank_gif);
937 * Extract an embedded photo from a vCard for display on the client
939 void display_vcard_photo_img(void)
947 const char *contentType;
949 msgnum = StrTol(WC->UrlFragment1);
951 vcard = load_mimepart(msgnum,"1");
952 v = vcard_load(vcard);
954 photosrc = vcard_get_prop(v, "PHOTO", 1,0,0);
955 xferbuf = malloc(strlen(photosrc));
956 if (xferbuf == NULL) {
957 lprintf(5, "xferbuf malloc failed\n");
960 memset(xferbuf, 1, SIZ);
961 decoded = CtdlDecodeBase64(
965 contentType = GuessMimeType(xferbuf, decoded);
966 http_transmit_thing(xferbuf, decoded, contentType, 0);
973 * Generic function to output an arbitrary MIME part from an arbitrary
974 * message number on the server.
976 * msgnum Number of the item on the citadel server
977 * partnum The MIME part to be output
978 * force_download Nonzero to force set the Content-Type: header to "application/octet-stream"
980 void mimepart(const char *msgnum, const char *partnum, int force_download)
984 char content_type[256];
985 char *content = NULL;
987 serv_printf("OPNA %s|%s", msgnum, partnum);
988 serv_getln(buf, sizeof buf);
990 bytes = extract_long(&buf[4], 0);
991 content = malloc(bytes + 2);
992 if (force_download) {
993 strcpy(content_type, "application/octet-stream");
996 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
998 output_headers(0, 0, 0, 0, 0, 0);
999 read_server_binary(content, bytes);
1001 serv_getln(buf, sizeof buf);
1002 http_transmit_thing(content, bytes, content_type, 0);
1005 wprintf("HTTP/1.1 404 %s\n", &buf[4]);
1006 output_headers(0, 0, 0, 0, 0, 0);
1007 wprintf("Content-Type: text/plain\r\n");
1009 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
1016 * Read any MIME part of a message, from the server, into memory.
1018 char *load_mimepart(long msgnum, char *partnum)
1022 char content_type[SIZ];
1025 serv_printf("DLAT %ld|%s", msgnum, partnum);
1026 serv_getln(buf, sizeof buf);
1027 if (buf[0] == '6') {
1028 bytes = extract_long(&buf[4], 0);
1029 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1031 content = malloc(bytes + 2);
1032 serv_read(content, bytes);
1034 content[bytes] = 0; /* null terminate for good measure */
1045 * Convenience functions to display a page containing only a string
1047 * titlebarcolor color of the titlebar of the frame
1048 * titlebarmsg text to display in the title bar
1049 * messagetext body of the box
1051 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
1053 wprintf("HTTP/1.1 200 OK\n");
1054 output_headers(1, 1, 2, 0, 0, 0);
1055 wprintf("<div id=\"banner\">\n");
1056 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
1057 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
1058 wprintf("</td></tr></table>\n");
1059 wprintf("</div>\n<div id=\"content\">\n");
1060 escputs(messagetext);
1062 wprintf("<hr />\n");
1068 * Display a blank page.
1070 void blank_page(void) {
1071 output_headers(1, 1, 0, 0, 0, 0);
1077 * A template has been requested
1079 void url_do_template(void) {
1080 do_template(bstr("template"));
1086 * Offer to make any page the user's "start page."
1088 void offer_start_page(void) {
1089 wprintf("<a href=\"change_start_page?startpage=");
1090 urlescputs(WC->this_page);
1092 wprintf(_("Make this my start page"));
1095 wprintf("<br/><a href=\"rss?room=");
1096 urlescputs(WC->wc_roomname);
1097 wprintf("\" title=\"RSS 2.0 feed for ");
1098 escputs(WC->wc_roomname);
1099 wprintf("\"><img alt=\"RSS\" border=\"0\" src=\"static/xml_button.gif\"/></a>\n");
1105 * Change the user's start page
1107 void change_start_page(void) {
1109 if (bstr("startpage") == NULL) {
1110 safestrncpy(WC->ImportantMessage,
1111 _("You no longer have a start page selected."),
1112 sizeof WC->ImportantMessage);
1113 display_main_menu();
1117 set_preference("startpage", NewStrBufPlain(bstr("startpage"), -1), 1);
1119 output_headers(1, 1, 0, 0, 0, 0);
1120 do_template("newstartpage");
1127 * convenience function to indicate success
1129 void display_success(char *successmessage)
1131 convenience_page("007700", "OK", successmessage);
1136 * Authorization required page
1137 * This is probably temporary and should be revisited
1139 void authorization_required(const char *message)
1141 wprintf("HTTP/1.1 401 Authorization Required\r\n");
1142 wprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", serv_info.serv_humannode);
1143 wprintf("Content-Type: text/html\r\n\r\n");
1145 wprintf(_("Authorization Required"));
1146 wprintf("</h1>\r\n");
1147 wprintf(_("The resource you requested requires a valid username and password. "
1148 "You could not be logged in: %s\n"), message);
1153 * This function is called by the MIME parser to handle data uploaded by
1154 * the browser. Form data, uploaded files, and the data from HTTP PUT
1155 * operations (such as those found in GroupDAV) all arrive this way.
1157 * name Name of the item being uploaded
1158 * filename Filename of the item being uploaded
1159 * partnum MIME part identifier (not needed)
1160 * disp MIME content disposition (not needed)
1161 * content The actual data
1162 * cbtype MIME content-type
1163 * cbcharset Character set
1164 * length Content length
1165 * encoding MIME encoding type (not needed)
1166 * userdata Not used here
1168 void upload_handler(char *name, char *filename, char *partnum, char *disp,
1169 void *content, char *cbtype, char *cbcharset,
1170 size_t length, char *encoding, void *userdata)
1173 #ifdef DEBUG_URLSTRINGS
1174 lprintf(9, "upload_handler() name=%s, type=%s, len=%d\n", name, cbtype, length);
1176 if (WC->urlstrings == NULL)
1177 WC->urlstrings = NewHash(1, NULL);
1180 if ( (length > 0) && (IsEmptyStr(cbtype)) ) {
1181 u = (urlcontent *) malloc(sizeof(urlcontent));
1183 safestrncpy(u->url_key, name, sizeof(u->url_key));
1184 u->url_data = malloc(length + 1);
1185 u->url_data_size = length;
1186 memcpy(u->url_data, content, length);
1187 u->url_data[length] = 0;
1188 Put(WC->urlstrings, u->url_key, strlen(u->url_key), u, free_url);
1189 #ifdef DEBUG_URLSTRINGS
1190 lprintf(9, "Key: <%s> len: [%ld] Data: <%s>\n", u->url_key, u->url_data_size, u->url_data);
1194 /** Uploaded files */
1195 if ( (length > 0) && (!IsEmptyStr(cbtype)) ) {
1196 WC->upload = malloc(length);
1197 if (WC->upload != NULL) {
1198 WC->upload_length = length;
1199 safestrncpy(WC->upload_filename, filename,
1200 sizeof(WC->upload_filename));
1201 safestrncpy(WC->upload_content_type, cbtype,
1202 sizeof(WC->upload_content_type));
1203 memcpy(WC->upload, content, length);
1206 lprintf(3, "malloc() failed: %s\n", strerror(errno));
1213 * Convenience functions to wrap around asynchronous ajax responses
1215 void begin_ajax_response(void) {
1216 output_headers(0, 0, 0, 0, 0, 0);
1218 wprintf("Content-type: text/html; charset=UTF-8\r\n"
1220 "Connection: close\r\n"
1221 "Pragma: no-cache\r\n"
1222 "Cache-Control: no-cache\r\n"
1230 * print ajax response footer
1232 void end_ajax_response(void) {
1238 * Wraps a Citadel server command in an AJAX transaction.
1240 void ajax_servcmd(void)
1243 char gcontent[1024];
1247 begin_ajax_response();
1249 serv_printf("%s", bstr("g_cmd"));
1250 serv_getln(buf, sizeof buf);
1251 wprintf("%s\n", buf);
1253 if (buf[0] == '8') {
1254 serv_printf("\n\n000");
1256 if ((buf[0] == '1') || (buf[0] == '8')) {
1257 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
1258 wprintf("%s\n", gcontent);
1262 if (buf[0] == '4') {
1263 text_to_server(bstr("g_input"));
1266 if (buf[0] == '6') {
1267 len = atol(&buf[4]);
1269 serv_read(junk, len);
1272 if (buf[0] == '7') {
1273 len = atol(&buf[4]);
1275 memset(junk, 0, len);
1276 serv_write(junk, len);
1280 end_ajax_response();
1283 * This is kind of an ugly hack, but this is the only place it can go.
1284 * If the command was GEXP, then the instant messenger window must be
1285 * running, so reset the "last_pager_check" watchdog timer so
1286 * that page_popup() doesn't try to open it a second time.
1288 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
1289 WC->last_pager_check = time(NULL);
1295 * Helper function for the asynchronous check to see if we need
1296 * to open the instant messenger window.
1298 void seconds_since_last_gexp(void)
1302 begin_ajax_response();
1303 if ( (time(NULL) - WC->last_pager_check) < 30) {
1308 serv_getln(buf, sizeof buf);
1309 if (buf[3] == '*') {
1316 end_ajax_response();
1320 * \brief Detects a 'mobile' user agent
1322 int is_mobile_ua(char *user_agent) {
1323 if (strstr(user_agent,"iPhone OS") != NULL) {
1325 } else if (strstr(user_agent,"Windows CE") != NULL) {
1327 } else if (strstr(user_agent,"SymbianOS") != NULL) {
1335 * Entry point for WebCit transaction
1337 void session_loop(struct httprequest *req)
1345 char request_method[128];
1346 char pathname[1024];
1347 int a, b, nBackDots, nEmpty;
1348 int ContentLength = 0;
1349 char ContentType[512];
1350 char *content = NULL;
1351 char *content_end = NULL;
1352 struct httprequest *hptr;
1353 char browser_host[256];
1354 char user_agent[256];
1360 * We stuff these with the values coming from the client cookies,
1361 * so we can use them to reconnect a timed out session if we have to.
1363 char c_username[SIZ];
1364 char c_password[SIZ];
1365 char c_roomname[SIZ];
1366 char c_httpauth_string[SIZ];
1367 char c_httpauth_user[SIZ];
1368 char c_httpauth_pass[SIZ];
1370 struct wcsession *WCC = WC;
1372 safestrncpy(c_username, "", sizeof c_username);
1373 safestrncpy(c_password, "", sizeof c_password);
1374 safestrncpy(c_roomname, "", sizeof c_roomname);
1375 safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
1376 safestrncpy(c_httpauth_user, DEFAULT_HTTPAUTH_USER, sizeof c_httpauth_user);
1377 safestrncpy(c_httpauth_pass, DEFAULT_HTTPAUTH_PASS, sizeof c_httpauth_pass);
1378 strcpy(browser_host, "");
1380 WCC->upload_length = 0;
1385 if (hptr == NULL) return;
1387 safestrncpy(cmd, hptr->line, sizeof cmd);
1389 extract_token(request_method, cmd, 0, ' ', sizeof request_method);
1390 extract_token(pathname, cmd, 1, ' ', sizeof pathname);
1392 /** Figure out the action */
1394 sizes[0] = sizeof action;
1397 index[a] = arg[a-1];
1398 sizes[a] = sizeof arg[a-1];
1400 //// index[9] = &foo; todo
1403 for ( a = 0; a < 9; ++a)
1405 extract_token(index[a], pathname, a + 1, '/', sizes[a]);
1406 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
1407 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
1408 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
1409 if ((index[a][0] == '.') && (index[a][1] == '.'))
1411 if (index[a][0] == '\0')
1415 while (hptr != NULL) {
1416 safestrncpy(buf, hptr->line, sizeof buf);
1417 /* lprintf(9, "HTTP HEADER: %s\n", buf); */
1420 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
1421 safestrncpy(cookie, &buf[15], sizeof cookie);
1422 cookie_to_stuff(cookie, NULL,
1423 c_username, sizeof c_username,
1424 c_password, sizeof c_password,
1425 c_roomname, sizeof c_roomname);
1427 else if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
1428 CtdlDecodeBase64(c_httpauth_string, &buf[21], strlen(&buf[21]));
1429 extract_token(c_httpauth_user, c_httpauth_string, 0, ':', sizeof c_httpauth_user);
1430 extract_token(c_httpauth_pass, c_httpauth_string, 1, ':', sizeof c_httpauth_pass);
1432 else if (!strncasecmp(buf, "Content-length: ", 16)) {
1433 ContentLength = atoi(&buf[16]);
1435 else if (!strncasecmp(buf, "Content-type: ", 14)) {
1436 safestrncpy(ContentType, &buf[14], sizeof ContentType);
1438 else if (!strncasecmp(buf, "User-agent: ", 12)) {
1439 safestrncpy(user_agent, &buf[12], sizeof user_agent);
1440 if (is_mobile_ua(&buf[12])) {
1444 else if (!strncasecmp(buf, "X-Forwarded-Host: ", 18)) {
1446 safestrncpy(WCC->http_host, &buf[18], sizeof WCC->http_host);
1449 else if (!strncasecmp(buf, "Host: ", 6)) {
1450 if (IsEmptyStr(WCC->http_host)) {
1451 safestrncpy(WCC->http_host, &buf[6], sizeof WCC->http_host);
1454 else if (!strncasecmp(buf, "X-Forwarded-For: ", 17)) {
1455 safestrncpy(browser_host, &buf[17], sizeof browser_host);
1456 while (num_tokens(browser_host, ',') > 1) {
1457 remove_token(browser_host, 0, ',');
1459 striplt(browser_host);
1463 if (ContentLength > 0) {
1466 BuffSize = ContentLength + SIZ;
1467 content = malloc(BuffSize);
1468 memset(content, 0, BuffSize);
1469 snprintf(content, BuffSize, "Content-type: %s\n"
1470 "Content-length: %d\n\n",
1471 ContentType, ContentLength);
1472 body_start = strlen(content);
1474 /** Read the entire input data at once. */
1475 client_read(WCC->http_sock, &content[body_start], ContentLength);
1477 if (!strncasecmp(ContentType, "application/x-www-form-urlencoded", 33)) {
1478 addurls(&content[body_start], ContentLength);
1479 } else if (!strncasecmp(ContentType, "multipart", 9)) {
1480 content_end = content + ContentLength + body_start;
1481 mime_parser(content, content_end, *upload_handler, NULL, NULL, NULL, 0);
1487 /* make a note of where we are in case the user wants to save it */
1488 safestrncpy(WCC->this_page, cmd, sizeof(WCC->this_page));
1489 remove_token(WCC->this_page, 2, ' ');
1490 remove_token(WCC->this_page, 0, ' ');
1492 /* If there are variables in the URL, we must grab them now */
1494 for (a = 0; a < len; ++a) {
1495 if ((cmd[a] == '?') || (cmd[a] == '&')) {
1496 for (b = a; b < len; ++b) {
1497 if (isspace(cmd[b])){
1502 addurls(&cmd[a + 1], len - a);
1508 /* If it's a "force 404" situation then display the error and bail. */
1509 if (!strcmp(action, "404")) {
1510 wprintf("HTTP/1.1 404 Not found\r\n");
1511 wprintf("Content-Type: text/plain\r\n");
1513 wprintf("Not found\r\n");
1514 goto SKIP_ALL_THIS_CRAP;
1517 /* Static content can be sent without connecting to Citadel. */
1519 for (a=0; a<ndirs; ++a) {
1520 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
1528 snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
1529 static_dirs[n_static],
1530 index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
1531 for (a=0; a<8; ++a) {
1532 if (buf[strlen(buf)-1] == '/') {
1533 buf[strlen(buf)-1] = 0;
1536 for (a = 0; a < strlen(buf); ++a) {
1537 if (isspace(buf[a])) {
1545 lprintf(9, "Suspicious request. Ignoring.");
1546 wprintf("HTTP/1.1 404 Security check failed\r\n");
1547 wprintf("Content-Type: text/plain\r\n");
1549 wprintf("You have sent a malformed or invalid request.\r\n");
1551 goto SKIP_ALL_THIS_CRAP; /* Don't try to connect */
1554 /* If the client sent a nonce that is incorrect, kill the request. */
1555 if (strlen(bstr("nonce")) > 0) {
1556 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
1557 bstr("nonce"), WCC->nonce);
1558 if (ibstr("nonce") != WCC->nonce) {
1559 lprintf(9, "Ignoring request with mismatched nonce.\n");
1560 wprintf("HTTP/1.1 404 Security check failed\r\n");
1561 wprintf("Content-Type: text/plain\r\n");
1563 wprintf("Security check failed.\r\n");
1564 goto SKIP_ALL_THIS_CRAP;
1569 * If we're not connected to a Citadel server, try to hook up the
1572 if (!WCC->connected) {
1573 if (!strcasecmp(ctdlhost, "uds")) {
1574 /* unix domain socket */
1575 snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
1576 WCC->serv_sock = uds_connectsock(buf);
1580 WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
1583 if (WCC->serv_sock < 0) {
1585 goto SKIP_ALL_THIS_CRAP;
1589 serv_getln(buf, sizeof buf); /** get the server welcome message */
1592 * From what host is our user connecting? Go with
1593 * the host at the other end of the HTTP socket,
1594 * unless we are following X-Forwarded-For: headers
1595 * and such a header has already turned up something.
1597 if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
1598 locate_host(browser_host, WCC->http_sock);
1601 get_serv_info(browser_host, user_agent);
1602 if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
1603 wprintf(_("You are connected to a Citadel "
1604 "server running Citadel %d.%02d. \n"
1605 "In order to run this version of WebCit "
1606 "you must also have Citadel %d.%02d or"
1608 serv_info.serv_rev_level / 100,
1609 serv_info.serv_rev_level % 100,
1610 MINIMUM_CIT_VERSION / 100,
1611 MINIMUM_CIT_VERSION % 100
1613 end_webcit_session();
1614 goto SKIP_ALL_THIS_CRAP;
1620 * Functions which can be performed without logging in
1622 if (!strcasecmp(action, "listsub")) {
1624 goto SKIP_ALL_THIS_CRAP;
1626 if (!strcasecmp(action, "freebusy")) {
1628 goto SKIP_ALL_THIS_CRAP;
1632 * If we're not logged in, but we have HTTP Authentication data,
1633 * try logging in to Citadel using that.
1635 if ((!WCC->logged_in)
1636 && (strlen(c_httpauth_user) > 0)
1637 && (strlen(c_httpauth_pass) > 0)) {
1638 serv_printf("USER %s", c_httpauth_user);
1639 serv_getln(buf, sizeof buf);
1640 if (buf[0] == '3') {
1641 serv_printf("PASS %s", c_httpauth_pass);
1642 serv_getln(buf, sizeof buf);
1643 if (buf[0] == '2') {
1644 become_logged_in(c_httpauth_user,
1645 c_httpauth_pass, buf);
1646 safestrncpy(WCC->httpauth_user, c_httpauth_user, sizeof WCC->httpauth_user);
1647 safestrncpy(WCC->httpauth_pass, c_httpauth_pass, sizeof WCC->httpauth_pass);
1649 /* Should only display when password is wrong */
1650 authorization_required(&buf[4]);
1651 goto SKIP_ALL_THIS_CRAP;
1656 /* This needs to run early */
1658 if (!strcasecmp(action, "rss")) {
1659 display_rss(bstr("room"), request_method);
1660 goto SKIP_ALL_THIS_CRAP;
1665 * The GroupDAV stuff relies on HTTP authentication instead of
1666 * our session's authentication.
1668 if (!strncasecmp(action, "groupdav", 8)) {
1669 groupdav_main(req, ContentType, /* do GroupDAV methods */
1670 ContentLength, content+body_start);
1671 if (!WCC->logged_in) {
1672 WCC->killthis = 1; /* If not logged in, don't */
1673 } /* keep the session active */
1674 goto SKIP_ALL_THIS_CRAP;
1679 * Automatically send requests with any method other than GET or
1680 * POST to the GroupDAV code as well.
1682 if ((strcasecmp(request_method, "GET")) && (strcasecmp(request_method, "POST"))) {
1683 groupdav_main(req, ContentType, /** do GroupDAV methods */
1684 ContentLength, content+body_start);
1685 if (!WCC->logged_in) {
1686 WCC->killthis = 1; /** If not logged in, don't */
1687 } /** keep the session active */
1688 goto SKIP_ALL_THIS_CRAP;
1692 * If we're not logged in, but we have username and password cookies
1693 * supplied by the browser, try using them to log in.
1695 if ((!WCC->logged_in)
1696 && (!IsEmptyStr(c_username))
1697 && (!IsEmptyStr(c_password))) {
1698 serv_printf("USER %s", c_username);
1699 serv_getln(buf, sizeof buf);
1700 if (buf[0] == '3') {
1701 serv_printf("PASS %s", c_password);
1702 serv_getln(buf, sizeof buf);
1703 if (buf[0] == '2') {
1704 become_logged_in(c_username, c_password, buf);
1709 * If we don't have a current room, but a cookie specifying the
1710 * current room is supplied, make an effort to go there.
1712 if ((IsEmptyStr(WCC->wc_roomname)) && (!IsEmptyStr(c_roomname))) {
1713 serv_printf("GOTO %s", c_roomname);
1714 serv_getln(buf, sizeof buf);
1715 if (buf[0] == '2') {
1716 safestrncpy(WCC->wc_roomname, c_roomname, sizeof WCC->wc_roomname);
1720 if (!strcasecmp(action, "image")) {
1722 } else if (!strcasecmp(action, "display_mime_icon")) {
1723 display_mime_icon();
1727 WebcitHandler *Handler;
1729 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
1730 Handler = (WebcitHandler*) vHandler;
1731 if (Handler != NULL) {
1732 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
1733 display_login(NULL);
1736 if((Handler->Flags & NEED_URL)) {
1737 if (WCC->UrlFragment1 == NULL)
1738 WCC->UrlFragment1 = NewStrBuf();
1739 if (WCC->UrlFragment2 == NULL)
1740 WCC->UrlFragment2 = NewStrBuf();
1741 StrBufPrintf(WCC->UrlFragment1, "%s", index[1]);
1742 StrBufPrintf(WCC->UrlFragment2, "%s", index[2]);
1744 if ((Handler->Flags & AJAX) != 0)
1745 begin_ajax_response();
1747 if ((Handler->Flags & AJAX) != 0)
1748 end_ajax_response();
1751 /* When all else fais, display the main menu. */
1753 if (!WCC->logged_in)
1754 display_login(NULL);
1756 display_main_menu();
1761 if (content != NULL) {
1766 if (WCC->upload_length > 0) {
1768 WCC->upload_length = 0;
1774 * Replacement for sleep() that uses select() in order to avoid SIGALRM
1776 void sleeeeeeeeeep(int seconds)
1780 tv.tv_sec = seconds;
1782 select(0, NULL, NULL, NULL, &tv);
1785 void diagnostics(void)
1787 output_headers(1, 1, 1, 0, 0, 0);
1788 wprintf("Session: %d<hr />\n", WC->wc_session);
1789 wprintf("Command: <br /><PRE>\n");
1790 escputs(WC->UrlFragment1);
1791 wprintf("<br />\n");
1792 escputs(WC->UrlFragment2);
1793 wprintf("</PRE><hr />\n");
1794 wprintf("Variables: <br /><PRE>\n");
1796 wprintf("</PRE><hr />\n");
1800 void view_mimepart(void) {
1801 mimepart(ChrPtr(WC->UrlFragment1),
1802 ChrPtr(WC->UrlFragment2),
1806 void download_mimepart(void) {
1807 mimepart(ChrPtr(WC->UrlFragment1),
1808 ChrPtr(WC->UrlFragment2),
1816 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1817 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1818 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1819 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1820 WebcitAddUrlHandler(HKEY("change_start_page"), change_start_page, 0);
1821 WebcitAddUrlHandler(HKEY("toggle_self_service"), toggle_self_service, 0);
1822 WebcitAddUrlHandler(HKEY("vcardphoto"), display_vcard_photo_img, NEED_URL);
1823 WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1824 WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1825 WebcitAddUrlHandler(HKEY("diagnostics"), diagnostics, NEED_URL);