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.
413 * Copy a string, escaping characters which have meaning in HTML.
415 * target target buffer
416 * strbuf source buffer
417 * nbsp If nonzero, spaces are converted to non-breaking spaces.
418 * nolinebreaks if set, linebreaks are removed from the string.
420 long stresc(char *target, long tSize, char *strbuf, int nbsp, int nolinebreaks)
422 char *aptr, *bptr, *eptr;
427 eptr = target + tSize - 6; // our biggest unit to put in...
429 while ((bptr < eptr) && !IsEmptyStr(aptr) ){
431 memcpy(bptr, "<", 4);
434 else if (*aptr == '>') {
435 memcpy(bptr, ">", 4);
438 else if (*aptr == '&') {
439 memcpy(bptr, "&", 5);
442 else if (*aptr == '\"') {
443 memcpy(bptr, """, 6);
446 else if (*aptr == '\'') {
447 memcpy(bptr, "'", 5);
450 else if (*aptr == LB) {
454 else if (*aptr == RB) {
458 else if (*aptr == QU) {
462 else if ((*aptr == 32) && (nbsp == 1)) {
463 memcpy(bptr, " ", 6);
466 else if ((*aptr == '\n') && (nolinebreaks)) {
467 *bptr='\0'; /* nothing */
469 else if ((*aptr == '\r') && (nolinebreaks)) {
470 *bptr='\0'; /* nothing */
479 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
481 return (bptr - target);
484 void escputs1(char *strbuf, int nbsp, int nolinebreaks)
489 if (strbuf == NULL) return;
490 Siz = (3 * strlen(strbuf)) + SIZ ;
492 stresc(buf, Siz, strbuf, nbsp, nolinebreaks);
498 * static wrapper for ecsputs1
500 void escputs(char *strbuf)
502 escputs1(strbuf, 0, 0);
507 * urlescape buffer and print it to the client
509 void urlescputs(char *strbuf)
513 urlesc(outbuf, SIZ, strbuf);
514 wprintf("%s", outbuf);
517 * urlescape buffer and print it as header
519 void hurlescputs(char *strbuf) {
522 urlesc(outbuf, SIZ, strbuf);
523 hprintf("%s", outbuf);
528 * Copy a string, escaping characters for JavaScript strings.
530 void jsesc(char *target, size_t tlen, char *strbuf)
539 len = strlen (strbuf);
541 tend = target + tlen;
545 while (!IsEmptyStr(sptr) &&
551 else if (*sptr == '>')
553 else if (*sptr == '\'') {
559 else if (*sptr == '"') {
569 else if (*sptr == '&') {
586 * escape and print javascript
588 void jsescputs(char *strbuf)
592 jsesc(outbuf, SIZ, strbuf);
593 wprintf("%s", outbuf);
597 * Copy a string, escaping characters for message text hold
599 void msgesc(char *target, size_t tlen, char *strbuf)
608 len = strlen (strbuf);
610 tend = target + tlen;
614 while (!IsEmptyStr(sptr) &&
620 else if (*sptr == '\r')
622 else if (*sptr == '\'') {
639 * print a string to the client after cleaning it with msgesc() and stresc()
641 void msgescputs1( char *strbuf)
647 if (strbuf == NULL) return;
648 buflen = 3 * strlen(strbuf) + SIZ;
649 outbuf = malloc( buflen);
650 outbuf2 = malloc( buflen);
651 msgesc(outbuf, buflen, strbuf);
652 stresc(outbuf2, buflen, outbuf, 0, 0);
653 wprintf("%s", outbuf2);
659 * print a string to the client after cleaning it with msgesc()
661 void msgescputs(char *strbuf) {
665 if (strbuf == NULL) return;
666 len = (3 * strlen(strbuf)) + SIZ;
667 outbuf = malloc(len);
668 msgesc(outbuf, len, strbuf);
669 wprintf("%s", outbuf);
677 * Output HTTP headers and leading HTML for a page
679 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
680 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
682 int do_room_banner, /* 0=no, 1=yes,
683 * 2 = I'm going to embed my own, so don't open the
684 * <div id="content"> either.
687 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
688 int suppress_check, /* 1 = suppress check for instant messages */
689 int cache /* 1 = allow browser to cache this page */
694 hprintf("HTTP/1.1 200 OK\n");
695 http_datestring(httpnow, sizeof httpnow, time(NULL));
697 if (do_httpheaders) {
698 hprintf("Content-type: text/html; charset=utf-8\r\n"
700 "Connection: close\r\n",
701 PACKAGE_STRING, serv_info.serv_software
706 char httpTomorow[128];
708 http_datestring(httpTomorow, sizeof httpTomorow,
709 time(NULL) + 60 * 60 * 24 * 2);
711 hprintf("Pragma: public\r\n"
712 "Cache-Control: max-age=3600, must-revalidate\r\n"
713 "Last-modified: %s\r\n"
720 hprintf("Pragma: no-cache\r\n"
721 "Cache-Control: no-store\r\n"
726 stuff_to_cookie(cookie, 1024, WC->wc_session, WC->wc_username,
727 WC->wc_password, WC->wc_roomname);
730 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
732 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
733 if (server_cookie != NULL) {
734 hprintf("%s\n", server_cookie);
740 if (!access("static.local/webcit.css", R_OK)) {
741 svprintf(HKEY("CSSLOCAL"), WCS_STRING,
742 "<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"
745 do_template("head", NULL);
752 /* check for ImportantMessages (these display in a div overlaying the main screen) */
753 if (!IsEmptyStr(WC->ImportantMessage)) {
754 wprintf("<div id=\"important_message\">\n"
755 "<span class=\"imsg\">");
756 escputs(WC->ImportantMessage);
757 wprintf("</span><br />\n"
759 "<script type=\"text/javascript\">\n"
760 " setTimeout('hide_imsg_popup()', 5000); \n"
762 WC->ImportantMessage[0] = 0;
765 if ( (WC->logged_in) && (!unset_cookies) ) {
766 wprintf("<div id=\"iconbar\">");
767 do_selected_iconbar();
768 /** check for instant messages (these display in a new window) */
773 if (do_room_banner == 1) {
774 wprintf("<div id=\"banner\">\n");
775 embed_room_banner(NULL, navbar_default);
780 if (do_room_banner == 1) {
781 wprintf("<div id=\"content\">\n");
787 * Generic function to do an HTTP redirect. Easy and fun.
789 void http_redirect(const char *whichpage) {
790 hprintf("HTTP/1.1 302 Moved Temporarily\n");
791 hprintf("Location: %s\r\n", whichpage);
792 hprintf("URI: %s\r\n", whichpage);
793 hprintf("Content-type: text/html; charset=utf-8\r\n");
794 wprintf("<html><body>");
795 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
796 wprintf("</body></html>\n");
803 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
805 void http_transmit_thing(const char *content_type,
808 output_headers(0, 0, 0, 0, 0, is_static);
810 hprintf("Content-type: %s\r\n"
812 "Connection: close\r\n",
820 * print menu box like used in the floor view or admin interface.
821 * This function takes pair of strings as va_args,
822 * Title Title string of the box
823 * Class CSS Class for the box
824 * nLines How many string pairs should we print? (URL, UrlText)
825 * ... Pairs of URL Strings and their Names
827 void print_menu_box(char* Title, char *Class, int nLines, ...)
832 svput("BOXTITLE", WCS_STRING, Title);
833 do_template("beginbox", NULL);
835 wprintf("<ul class=\"%s\">", Class);
837 va_start(arg_list, nLines);
838 for (i = 0; i < nLines; ++i)
840 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
841 wprintf((char *) va_arg(arg_list, char *));
842 wprintf("</a></li>\n");
846 wprintf("</a></li>\n");
850 do_template("endbox", NULL);
855 * dump out static pages from disk
857 void output_static(char *what)
863 const char *content_type;
867 fd = open(what, O_RDONLY);
869 lprintf(9, "output_static('%s') -- NOT FOUND --\n", what);
870 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
871 hprintf("Content-Type: text/plain\r\n");
872 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
876 content_type = GuessMimeByFilename(what, len);
878 if (fstat(fd, &statbuf) == -1) {
879 lprintf(9, "output_static('%s') -- FSTAT FAILED --\n", what);
880 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
881 hprintf("Content-Type: text/plain\r\n");
882 wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
888 bytes = statbuf.st_size;
890 if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
892 if (fd > 0) close(fd);
893 lprintf(9, "output_static('%s') -- FREAD FAILED (%s) --\n", what, strerror(errno));
894 hprintf("HTTP/1.1 500 internal server error \r\n");
895 hprintf("Content-Type: text/plain\r\n");
902 lprintf(9, "output_static('%s') %s\n", what, content_type);
903 http_transmit_thing(content_type, 1);
905 if (yesbstr("force_close_session")) {
906 end_webcit_session();
911 * When the browser requests an image file from the Citadel server,
912 * this function is called to transmit it.
916 struct wcsession *WCC = WC;
919 const char *MimeType;
921 serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
922 serv_getln(buf, sizeof buf);
924 bytes = extract_long(&buf[4], 0);
926 /** Read it from the server */
928 if (read_server_binary(WCC->WBuf, bytes) > 0) {
930 serv_getln(buf, sizeof buf);
932 MimeType = GuessMimeType (ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
933 /** Write it to the browser */
934 if (!IsEmptyStr(MimeType))
936 http_transmit_thing(MimeType, 0);
940 /* hm... unknown mimetype? fallback to blank gif */
945 * Instead of an ugly 404, send a 1x1 transparent GIF
946 * when there's no such image on the server.
949 snprintf (blank_gif, SIZ, "%s%s", static_dirs[0], "/blank.gif");
950 output_static(blank_gif);
954 * Extract an embedded photo from a vCard for display on the client
956 void display_vcard_photo_img(void)
962 const char *contentType;
963 struct wcsession *WCC = WC;
965 msgnum = StrTol(WCC->UrlFragment1);
967 vcard = load_mimepart(msgnum,"1");
968 v = vcard_load(vcard);
970 photosrc = vcard_get_prop(v, "PHOTO", 1,0,0);
971 FlushStrBuf(WCC->WBuf);
972 StrBufAppendBufPlain(WCC->WBuf, photosrc, -1, 0);
973 if (StrBufDecodeBase64(WCC->WBuf) <= 0) {
974 FlushStrBuf(WCC->WBuf);
976 hprintf("HTTP/1.1 500 %s\n","Unable to get photo");
977 output_headers(0, 0, 0, 0, 0, 0);
978 hprintf("Content-Type: text/plain\r\n");
979 wprintf(_("Could Not decode vcard photo\n"));
983 contentType = GuessMimeType(ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
984 http_transmit_thing(contentType, 0);
990 * Generic function to output an arbitrary MIME part from an arbitrary
991 * message number on the server.
993 * msgnum Number of the item on the citadel server
994 * partnum The MIME part to be output
995 * force_download Nonzero to force set the Content-Type: header to "application/octet-stream"
997 void mimepart(const char *msgnum, const char *partnum, int force_download)
1001 char content_type[256];
1002 char *content = NULL;
1004 serv_printf("OPNA %s|%s", msgnum, partnum);
1005 serv_getln(buf, sizeof buf);
1006 if (buf[0] == '2') {
1007 bytes = extract_long(&buf[4], 0);
1008 content = malloc(bytes + 2);
1009 if (force_download) {
1010 strcpy(content_type, "application/octet-stream");
1013 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1015 output_headers(0, 0, 0, 0, 0, 0);
1017 read_server_binary(WC->WBuf, bytes);
1019 serv_getln(buf, sizeof buf);
1020 http_transmit_thing(content_type, 0);
1022 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
1023 output_headers(0, 0, 0, 0, 0, 0);
1024 hprintf("Content-Type: text/plain\r\n");
1025 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
1033 * Read any MIME part of a message, from the server, into memory.
1035 char *load_mimepart(long msgnum, char *partnum)
1039 char content_type[SIZ];
1042 serv_printf("DLAT %ld|%s", msgnum, partnum);
1043 serv_getln(buf, sizeof buf);
1044 if (buf[0] == '6') {
1045 bytes = extract_long(&buf[4], 0);
1046 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1048 content = malloc(bytes + 2);
1049 serv_read(content, bytes);
1051 content[bytes] = 0; /* null terminate for good measure */
1062 * Convenience functions to display a page containing only a string
1064 * titlebarcolor color of the titlebar of the frame
1065 * titlebarmsg text to display in the title bar
1066 * messagetext body of the box
1068 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
1070 hprintf("HTTP/1.1 200 OK\n");
1071 output_headers(1, 1, 2, 0, 0, 0);
1072 wprintf("<div id=\"banner\">\n");
1073 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
1074 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
1075 wprintf("</td></tr></table>\n");
1076 wprintf("</div>\n<div id=\"content\">\n");
1077 escputs(messagetext);
1079 wprintf("<hr />\n");
1085 * Display a blank page.
1087 void blank_page(void) {
1088 output_headers(1, 1, 0, 0, 0, 0);
1094 * A template has been requested
1096 void url_do_template(void) {
1097 const StrBuf *Tmpl = sbstr("template");
1099 DoTemplate(ChrPtr(Tmpl), StrLength(Tmpl), NULL, NULL);
1106 * Offer to make any page the user's "start page."
1108 void offer_start_page(void) {
1109 wprintf("<a href=\"change_start_page?startpage=");
1110 urlescputs(WC->this_page);
1112 wprintf(_("Make this my start page"));
1115 wprintf("<br/><a href=\"rss?room=");
1116 urlescputs(WC->wc_roomname);
1117 wprintf("\" title=\"RSS 2.0 feed for ");
1118 escputs(WC->wc_roomname);
1119 wprintf("\"><img alt=\"RSS\" border=\"0\" src=\"static/xml_button.gif\"/></a>\n");
1125 * Change the user's start page
1127 void change_start_page(void) {
1129 if (bstr("startpage") == NULL) {
1130 safestrncpy(WC->ImportantMessage,
1131 _("You no longer have a start page selected."),
1132 sizeof WC->ImportantMessage);
1133 display_main_menu();
1137 set_preference("startpage", NewStrBufPlain(bstr("startpage"), -1), 1);
1139 output_headers(1, 1, 0, 0, 0, 0);
1140 do_template("newstartpage", NULL);
1147 * convenience function to indicate success
1149 void display_success(char *successmessage)
1151 convenience_page("007700", "OK", successmessage);
1156 * Authorization required page
1157 * This is probably temporary and should be revisited
1159 void authorization_required(const char *message)
1161 hprintf("HTTP/1.1 401 Authorization Required\r\n");
1162 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", serv_info.serv_humannode);
1163 hprintf("Content-Type: text/html\r\n");
1165 wprintf(_("Authorization Required"));
1166 wprintf("</h1>\r\n");
1167 wprintf(_("The resource you requested requires a valid username and password. "
1168 "You could not be logged in: %s\n"), message);
1174 * This function is called by the MIME parser to handle data uploaded by
1175 * the browser. Form data, uploaded files, and the data from HTTP PUT
1176 * operations (such as those found in GroupDAV) all arrive this way.
1178 * name Name of the item being uploaded
1179 * filename Filename of the item being uploaded
1180 * partnum MIME part identifier (not needed)
1181 * disp MIME content disposition (not needed)
1182 * content The actual data
1183 * cbtype MIME content-type
1184 * cbcharset Character set
1185 * length Content length
1186 * encoding MIME encoding type (not needed)
1187 * userdata Not used here
1189 void upload_handler(char *name, char *filename, char *partnum, char *disp,
1190 void *content, char *cbtype, char *cbcharset,
1191 size_t length, char *encoding, void *userdata)
1194 #ifdef DEBUG_URLSTRINGS
1195 lprintf(9, "upload_handler() name=%s, type=%s, len=%d\n", name, cbtype, length);
1197 if (WC->urlstrings == NULL)
1198 WC->urlstrings = NewHash(1, NULL);
1201 if ( (length > 0) && (IsEmptyStr(cbtype)) ) {
1202 u = (urlcontent *) malloc(sizeof(urlcontent));
1204 safestrncpy(u->url_key, name, sizeof(u->url_key));
1205 u->url_data = NewStrBufPlain(content, length);
1207 Put(WC->urlstrings, u->url_key, strlen(u->url_key), u, free_url);
1208 #ifdef DEBUG_URLSTRINGS
1209 lprintf(9, "Key: <%s> len: [%ld] Data: <%s>\n", u->url_key, u->url_data_size, u->url_data);
1213 /** Uploaded files */
1214 if ( (length > 0) && (!IsEmptyStr(cbtype)) ) {
1215 WC->upload = malloc(length);
1216 if (WC->upload != NULL) {
1217 WC->upload_length = length;
1218 safestrncpy(WC->upload_filename, filename,
1219 sizeof(WC->upload_filename));
1220 safestrncpy(WC->upload_content_type, cbtype,
1221 sizeof(WC->upload_content_type));
1222 memcpy(WC->upload, content, length);
1225 lprintf(3, "malloc() failed: %s\n", strerror(errno));
1232 * Convenience functions to wrap around asynchronous ajax responses
1234 void begin_ajax_response(void) {
1235 output_headers(0, 0, 0, 0, 0, 0);
1237 hprintf("Content-type: text/html; charset=UTF-8\r\n"
1239 "Connection: close\r\n"
1240 "Pragma: no-cache\r\n"
1241 "Cache-Control: no-cache\r\n"
1249 * print ajax response footer
1251 void end_ajax_response(void) {
1252 ///hprintf("\r\n");///// todo: is this right?
1257 * Wraps a Citadel server command in an AJAX transaction.
1259 void ajax_servcmd(void)
1262 char gcontent[1024];
1266 begin_ajax_response();
1268 serv_printf("%s", bstr("g_cmd"));
1269 serv_getln(buf, sizeof buf);
1270 wprintf("%s\n", buf);
1272 if (buf[0] == '8') {
1273 serv_printf("\n\n000");
1275 if ((buf[0] == '1') || (buf[0] == '8')) {
1276 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
1277 wprintf("%s\n", gcontent);
1281 if (buf[0] == '4') {
1282 text_to_server(bstr("g_input"));
1285 if (buf[0] == '6') {
1286 len = atol(&buf[4]);
1288 serv_read(junk, len);
1291 if (buf[0] == '7') {
1292 len = atol(&buf[4]);
1294 memset(junk, 0, len);
1295 serv_write(junk, len);
1299 end_ajax_response();
1302 * This is kind of an ugly hack, but this is the only place it can go.
1303 * If the command was GEXP, then the instant messenger window must be
1304 * running, so reset the "last_pager_check" watchdog timer so
1305 * that page_popup() doesn't try to open it a second time.
1307 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
1308 WC->last_pager_check = time(NULL);
1314 * Helper function for the asynchronous check to see if we need
1315 * to open the instant messenger window.
1317 void seconds_since_last_gexp(void)
1321 begin_ajax_response();
1322 if ( (time(NULL) - WC->last_pager_check) < 30) {
1327 serv_getln(buf, sizeof buf);
1328 if (buf[3] == '*') {
1335 end_ajax_response();
1339 * \brief Detects a 'mobile' user agent
1341 int is_mobile_ua(char *user_agent) {
1342 if (strstr(user_agent,"iPhone OS") != NULL) {
1344 } else if (strstr(user_agent,"Windows CE") != NULL) {
1346 } else if (strstr(user_agent,"SymbianOS") != NULL) {
1348 } else if (strstr(user_agent, "Opera Mobi") != NULL) {
1350 } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
1351 // For some reason a new install of Opera 9.51beta decided to spoof.
1359 * Entry point for WebCit transaction
1361 void session_loop(struct httprequest *req)
1369 char request_method[128];
1370 char pathname[1024];
1371 int a, b, nBackDots, nEmpty;
1372 int ContentLength = 0;
1373 char ContentType[512];
1374 char *content = NULL;
1375 char *content_end = NULL;
1376 struct httprequest *hptr;
1377 char browser_host[256];
1378 char user_agent[256];
1384 * We stuff these with the values coming from the client cookies,
1385 * so we can use them to reconnect a timed out session if we have to.
1387 char c_username[SIZ];
1388 char c_password[SIZ];
1389 char c_roomname[SIZ];
1390 char c_httpauth_string[SIZ];
1391 char c_httpauth_user[SIZ];
1392 char c_httpauth_pass[SIZ];
1394 struct wcsession *WCC;
1396 safestrncpy(c_username, "", sizeof c_username);
1397 safestrncpy(c_password, "", sizeof c_password);
1398 safestrncpy(c_roomname, "", sizeof c_roomname);
1399 safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
1400 safestrncpy(c_httpauth_user, DEFAULT_HTTPAUTH_USER, sizeof c_httpauth_user);
1401 safestrncpy(c_httpauth_pass, DEFAULT_HTTPAUTH_PASS, sizeof c_httpauth_pass);
1402 strcpy(browser_host, "");
1405 if (WCC->WBuf == NULL)
1406 WC->WBuf = NewStrBufPlain(NULL, 32768);
1407 FlushStrBuf(WCC->WBuf);
1409 if (WCC->HBuf == NULL)
1410 WCC->HBuf = NewStrBuf();
1411 FlushStrBuf(WCC->HBuf);
1413 WCC->upload_length = 0;
1418 if (hptr == NULL) return;
1420 safestrncpy(cmd, hptr->line, sizeof cmd);
1422 extract_token(request_method, cmd, 0, ' ', sizeof request_method);
1423 extract_token(pathname, cmd, 1, ' ', sizeof pathname);
1425 /** Figure out the action */
1427 sizes[0] = sizeof action;
1430 index[a] = arg[a-1];
1431 sizes[a] = sizeof arg[a-1];
1433 //// index[9] = &foo; todo
1436 for ( a = 0; a < 9; ++a)
1438 extract_token(index[a], pathname, a + 1, '/', sizes[a]);
1439 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
1440 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
1441 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
1442 if ((index[a][0] == '.') && (index[a][1] == '.'))
1444 if (index[a][0] == '\0')
1448 while (hptr != NULL) {
1449 safestrncpy(buf, hptr->line, sizeof buf);
1450 /* lprintf(9, "HTTP HEADER: %s\n", buf); */
1453 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
1454 safestrncpy(cookie, &buf[15], sizeof cookie);
1455 cookie_to_stuff(cookie, NULL,
1456 c_username, sizeof c_username,
1457 c_password, sizeof c_password,
1458 c_roomname, sizeof c_roomname);
1460 else if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
1461 CtdlDecodeBase64(c_httpauth_string, &buf[21], strlen(&buf[21]));
1462 extract_token(c_httpauth_user, c_httpauth_string, 0, ':', sizeof c_httpauth_user);
1463 extract_token(c_httpauth_pass, c_httpauth_string, 1, ':', sizeof c_httpauth_pass);
1465 else if (!strncasecmp(buf, "Content-length: ", 16)) {
1466 ContentLength = atoi(&buf[16]);
1468 else if (!strncasecmp(buf, "Content-type: ", 14)) {
1469 safestrncpy(ContentType, &buf[14], sizeof ContentType);
1471 else if (!strncasecmp(buf, "User-agent: ", 12)) {
1472 safestrncpy(user_agent, &buf[12], sizeof user_agent);
1474 if (is_mobile_ua(&buf[12])) {
1479 else if (!strncasecmp(buf, "X-Forwarded-Host: ", 18)) {
1481 safestrncpy(WCC->http_host, &buf[18], sizeof WCC->http_host);
1484 else if (!strncasecmp(buf, "Host: ", 6)) {
1485 if (IsEmptyStr(WCC->http_host)) {
1486 safestrncpy(WCC->http_host, &buf[6], sizeof WCC->http_host);
1489 else if (!strncasecmp(buf, "X-Forwarded-For: ", 17)) {
1490 safestrncpy(browser_host, &buf[17], sizeof browser_host);
1491 while (num_tokens(browser_host, ',') > 1) {
1492 remove_token(browser_host, 0, ',');
1494 striplt(browser_host);
1498 if (ContentLength > 0) {
1501 BuffSize = ContentLength + SIZ;
1502 content = malloc(BuffSize);
1503 memset(content, 0, BuffSize);
1504 hprintf("Content-type: %s\n"
1505 "Content-length: %d\n\n",
1506 ContentType, ContentLength);
1507 body_start = strlen(content);
1509 /** Read the entire input data at once. */
1510 client_read(WCC->http_sock, &content[body_start], ContentLength);
1512 if (!strncasecmp(ContentType, "application/x-www-form-urlencoded", 33)) {
1515 Content = _NewConstStrBuf(&content[body_start],ContentLength);
1517 FreeStrBuf(&Content);
1518 } else if (!strncasecmp(ContentType, "multipart", 9)) {
1519 content_end = content + ContentLength + body_start;
1520 mime_parser(content, content_end, *upload_handler, NULL, NULL, NULL, 0);
1526 /* make a note of where we are in case the user wants to save it */
1527 safestrncpy(WCC->this_page, cmd, sizeof(WCC->this_page));
1528 remove_token(WCC->this_page, 2, ' ');
1529 remove_token(WCC->this_page, 0, ' ');
1531 /* If there are variables in the URL, we must grab them now */
1533 for (a = 0; a < len; ++a) {
1534 if ((cmd[a] == '?') || (cmd[a] == '&')) {
1536 for (b = a; b < len; ++b) {
1537 if (isspace(cmd[b])){
1542 //cmd[len - a] = '\0';
1543 Params = _NewConstStrBuf(&cmd[a + 1], len - a);
1550 /* If it's a "force 404" situation then display the error and bail. */
1551 if (!strcmp(action, "404")) {
1552 hprintf("HTTP/1.1 404 Not found\r\n");
1553 hprintf("Content-Type: text/plain\r\n");
1554 wprintf("Not found\r\n");
1556 goto SKIP_ALL_THIS_CRAP;
1559 /* Static content can be sent without connecting to Citadel. */
1561 for (a=0; a<ndirs; ++a) {
1562 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
1570 snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
1571 static_dirs[n_static],
1572 index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
1573 for (a=0; a<8; ++a) {
1574 if (buf[strlen(buf)-1] == '/') {
1575 buf[strlen(buf)-1] = 0;
1578 for (a = 0; a < strlen(buf); ++a) {
1579 if (isspace(buf[a])) {
1587 lprintf(9, "Suspicious request. Ignoring.");
1588 hprintf("HTTP/1.1 404 Security check failed\r\n");
1589 hprintf("Content-Type: text/plain\r\n");
1590 wprintf("You have sent a malformed or invalid request.\r\n");
1593 goto SKIP_ALL_THIS_CRAP; /* Don't try to connect */
1596 /* If the client sent a nonce that is incorrect, kill the request. */
1597 if (strlen(bstr("nonce")) > 0) {
1598 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
1599 bstr("nonce"), WCC->nonce);
1600 if (ibstr("nonce") != WCC->nonce) {
1601 lprintf(9, "Ignoring request with mismatched nonce.\n");
1602 hprintf("HTTP/1.1 404 Security check failed\r\n");
1603 hprintf("Content-Type: text/plain\r\n");
1604 wprintf("Security check failed.\r\n");
1606 goto SKIP_ALL_THIS_CRAP;
1611 * If we're not connected to a Citadel server, try to hook up the
1614 if (!WCC->connected) {
1615 if (!strcasecmp(ctdlhost, "uds")) {
1616 /* unix domain socket */
1617 snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
1618 WCC->serv_sock = uds_connectsock(buf);
1622 WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
1625 if (WCC->serv_sock < 0) {
1627 goto SKIP_ALL_THIS_CRAP;
1631 serv_getln(buf, sizeof buf); /** get the server welcome message */
1634 * From what host is our user connecting? Go with
1635 * the host at the other end of the HTTP socket,
1636 * unless we are following X-Forwarded-For: headers
1637 * and such a header has already turned up something.
1639 if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
1640 locate_host(browser_host, WCC->http_sock);
1643 get_serv_info(browser_host, user_agent);
1644 if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
1645 wprintf(_("You are connected to a Citadel "
1646 "server running Citadel %d.%02d. \n"
1647 "In order to run this version of WebCit "
1648 "you must also have Citadel %d.%02d or"
1650 serv_info.serv_rev_level / 100,
1651 serv_info.serv_rev_level % 100,
1652 MINIMUM_CIT_VERSION / 100,
1653 MINIMUM_CIT_VERSION % 100
1655 end_webcit_session();
1656 goto SKIP_ALL_THIS_CRAP;
1660 ////////todo: restorte language in this case
1662 * Functions which can be performed without logging in
1664 if (!strcasecmp(action, "listsub")) {
1666 goto SKIP_ALL_THIS_CRAP;
1668 if (!strcasecmp(action, "freebusy")) {
1670 goto SKIP_ALL_THIS_CRAP;
1674 * If we're not logged in, but we have HTTP Authentication data,
1675 * try logging in to Citadel using that.
1677 if ((!WCC->logged_in)
1678 && (strlen(c_httpauth_user) > 0)
1679 && (strlen(c_httpauth_pass) > 0)) {
1680 serv_printf("USER %s", c_httpauth_user);
1681 serv_getln(buf, sizeof buf);
1682 if (buf[0] == '3') {
1683 serv_printf("PASS %s", c_httpauth_pass);
1684 serv_getln(buf, sizeof buf);
1685 if (buf[0] == '2') {
1686 become_logged_in(c_httpauth_user,
1687 c_httpauth_pass, buf);
1688 safestrncpy(WCC->httpauth_user, c_httpauth_user, sizeof WCC->httpauth_user);
1689 safestrncpy(WCC->httpauth_pass, c_httpauth_pass, sizeof WCC->httpauth_pass);
1691 /* Should only display when password is wrong */
1692 authorization_required(&buf[4]);
1693 goto SKIP_ALL_THIS_CRAP;
1698 /* This needs to run early */
1700 if (!strcasecmp(action, "rss")) {
1701 display_rss(bstr("room"), request_method);
1702 goto SKIP_ALL_THIS_CRAP;
1707 * The GroupDAV stuff relies on HTTP authentication instead of
1708 * our session's authentication.
1710 if (!strncasecmp(action, "groupdav", 8)) {
1711 groupdav_main(req, ContentType, /* do GroupDAV methods */
1712 ContentLength, content+body_start);
1713 if (!WCC->logged_in) {
1714 WCC->killthis = 1; /* If not logged in, don't */
1715 } /* keep the session active */
1716 goto SKIP_ALL_THIS_CRAP;
1721 * Automatically send requests with any method other than GET or
1722 * POST to the GroupDAV code as well.
1724 if ((strcasecmp(request_method, "GET")) && (strcasecmp(request_method, "POST"))) {
1725 groupdav_main(req, ContentType, /** do GroupDAV methods */
1726 ContentLength, content+body_start);
1727 if (!WCC->logged_in) {
1728 WCC->killthis = 1; /** If not logged in, don't */
1729 } /** keep the session active */
1730 goto SKIP_ALL_THIS_CRAP;
1734 * If we're not logged in, but we have username and password cookies
1735 * supplied by the browser, try using them to log in.
1737 if ((!WCC->logged_in)
1738 && (!IsEmptyStr(c_username))
1739 && (!IsEmptyStr(c_password))) {
1740 serv_printf("USER %s", c_username);
1741 serv_getln(buf, sizeof buf);
1742 if (buf[0] == '3') {
1743 serv_printf("PASS %s", c_password);
1744 serv_getln(buf, sizeof buf);
1745 if (buf[0] == '2') {
1747 become_logged_in(c_username, c_password, buf);
1748 if (get_preference("language", &Lang)) {
1749 set_selected_language(ChrPtr(Lang));
1750 go_selected_language(); /* set locale */
1756 * If we don't have a current room, but a cookie specifying the
1757 * current room is supplied, make an effort to go there.
1759 if ((IsEmptyStr(WCC->wc_roomname)) && (!IsEmptyStr(c_roomname))) {
1760 serv_printf("GOTO %s", c_roomname);
1761 serv_getln(buf, sizeof buf);
1762 if (buf[0] == '2') {
1763 safestrncpy(WCC->wc_roomname, c_roomname, sizeof WCC->wc_roomname);
1767 if (!strcasecmp(action, "image")) {
1769 } else if (!strcasecmp(action, "display_mime_icon")) {
1770 display_mime_icon();
1774 WebcitHandler *Handler;
1776 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
1777 Handler = (WebcitHandler*) vHandler;
1778 if (Handler != NULL) {
1779 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
1780 display_login(NULL);
1783 if((Handler->Flags & NEED_URL)) {
1784 if (WCC->UrlFragment1 == NULL)
1785 WCC->UrlFragment1 = NewStrBuf();
1786 if (WCC->UrlFragment2 == NULL)
1787 WCC->UrlFragment2 = NewStrBuf();
1788 StrBufPrintf(WCC->UrlFragment1, "%s", index[1]);
1789 StrBufPrintf(WCC->UrlFragment2, "%s", index[2]);
1791 if ((Handler->Flags & AJAX) != 0)
1792 begin_ajax_response();
1794 if ((Handler->Flags & AJAX) != 0)
1795 end_ajax_response();
1798 /* When all else fais, display the main menu. */
1800 if (!WCC->logged_in)
1801 display_login(NULL);
1803 display_main_menu();
1808 if (content != NULL) {
1813 if (WCC->upload_length > 0) {
1815 WCC->upload_length = 0;
1821 * Replacement for sleep() that uses select() in order to avoid SIGALRM
1823 void sleeeeeeeeeep(int seconds)
1827 tv.tv_sec = seconds;
1829 select(0, NULL, NULL, NULL, &tv);
1832 void diagnostics(void)
1834 output_headers(1, 1, 1, 0, 0, 0);
1835 wprintf("Session: %d<hr />\n", WC->wc_session);
1836 wprintf("Command: <br /><PRE>\n");
1837 escputs(WC->UrlFragment1);
1838 wprintf("<br />\n");
1839 escputs(WC->UrlFragment2);
1840 wprintf("</PRE><hr />\n");
1841 wprintf("Variables: <br /><PRE>\n");
1843 wprintf("</PRE><hr />\n");
1847 void view_mimepart(void) {
1848 mimepart(ChrPtr(WC->UrlFragment1),
1849 ChrPtr(WC->UrlFragment2),
1853 void download_mimepart(void) {
1854 mimepart(ChrPtr(WC->UrlFragment1),
1855 ChrPtr(WC->UrlFragment2),
1863 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1864 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1865 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1866 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1867 WebcitAddUrlHandler(HKEY("change_start_page"), change_start_page, 0);
1868 WebcitAddUrlHandler(HKEY("toggle_self_service"), toggle_self_service, 0);
1869 WebcitAddUrlHandler(HKEY("vcardphoto"), display_vcard_photo_img, NEED_URL);
1870 WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1871 WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1872 WebcitAddUrlHandler(HKEY("diagnostics"), diagnostics, NEED_URL);