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",
154 StrLength(u->url_data),
155 ChrPtr(u->url_data));
162 * free urlstring memory
166 DeleteHash(&WC->urlstrings);
170 * Diagnostic function to display the contents of all variables
175 struct wcsession *WCC = WC;
182 Cursor = GetNewHashPos ();
183 while (GetNextHashPos(WCC->urlstrings, Cursor, &HKLen, &HKey, &U)) {
185 wprintf("%38s = %s\n", u->url_key, ChrPtr(u->url_data));
190 * Return the value of a variable supplied to the current web page (from the url or a form)
193 const char *XBstr(const char *key, size_t keylen, size_t *len)
197 if ((WC->urlstrings != NULL) &&
198 GetHash(WC->urlstrings, key, keylen, &U)) {
199 *len = StrLength(((urlcontent *)U)->url_data);
200 return ChrPtr(((urlcontent *)U)->url_data);
208 const char *XBSTR(const char *key, size_t *len)
212 if ((WC->urlstrings != NULL) &&
213 GetHash(WC->urlstrings, key, strlen (key), &U)){
214 *len = StrLength(((urlcontent *)U)->url_data);
215 return ChrPtr(((urlcontent *)U)->url_data);
224 const char *BSTR(const char *key)
228 if ((WC->urlstrings != NULL) &&
229 GetHash(WC->urlstrings, key, strlen (key), &U))
230 return ChrPtr(((urlcontent *)U)->url_data);
235 const char *Bstr(const char *key, size_t keylen)
239 if ((WC->urlstrings != NULL) &&
240 GetHash(WC->urlstrings, key, keylen, &U))
241 return ChrPtr(((urlcontent *)U)->url_data);
246 const StrBuf *SBSTR(const char *key)
250 if ((WC->urlstrings != NULL) &&
251 GetHash(WC->urlstrings, key, strlen (key), &U))
252 return ((urlcontent *)U)->url_data;
257 const StrBuf *SBstr(const char *key, size_t keylen)
261 if ((WC->urlstrings != NULL) &&
262 GetHash(WC->urlstrings, key, keylen, &U))
263 return ((urlcontent *)U)->url_data;
268 long LBstr(const char *key, size_t keylen)
272 if ((WC->urlstrings != NULL) &&
273 GetHash(WC->urlstrings, key, keylen, &U))
274 return StrTol(((urlcontent *)U)->url_data);
279 long LBSTR(const char *key)
283 if ((WC->urlstrings != NULL) &&
284 GetHash(WC->urlstrings, key, strlen(key), &U))
285 return StrTol(((urlcontent *)U)->url_data);
290 int IBstr(const char *key, size_t keylen)
294 if ((WC->urlstrings != NULL) &&
295 GetHash(WC->urlstrings, key, keylen, &U))
296 return StrTol(((urlcontent *)U)->url_data);
301 int IBSTR(const char *key)
305 if ((WC->urlstrings != NULL) &&
306 GetHash(WC->urlstrings, key, strlen(key), &U))
307 return StrToi(((urlcontent *)U)->url_data);
312 int HaveBstr(const char *key, size_t keylen)
316 if ((WC->urlstrings != NULL) &&
317 GetHash(WC->urlstrings, key, keylen, &U))
318 return (StrLength(((urlcontent *)U)->url_data) != 0);
323 int HAVEBSTR(const char *key)
327 if ((WC->urlstrings != NULL) &&
328 GetHash(WC->urlstrings, key, strlen(key), &U))
329 return (StrLength(((urlcontent *)U)->url_data) != 0);
335 int YesBstr(const char *key, size_t keylen)
339 if ((WC->urlstrings != NULL) &&
340 GetHash(WC->urlstrings, key, keylen, &U))
341 return strcmp( ChrPtr(((urlcontent *)U)->url_data), "yes") == 0;
346 int YESBSTR(const char *key)
350 if ((WC->urlstrings != NULL) &&
351 GetHash(WC->urlstrings, key, strlen(key), &U))
352 return strcmp( ChrPtr(((urlcontent *)U)->url_data), "yes") == 0;
358 * web-printing funcion. uses our vsnprintf wrapper
360 void wprintf(const char *format,...)
362 struct wcsession *WCC = WC;
365 if (WCC->WBuf == NULL)
366 WCC->WBuf = NewStrBuf();
368 va_start(arg_ptr, format);
369 StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
372 /// if (StrLength(WCC-WBuf) > 2048)
373 ///client_write(wbuf, strlen(wbuf));
377 * http-header-printing funcion. uses our vsnprintf wrapper
379 void hprintf(const char *format,...)
381 struct wcsession *WCC = WC;
384 va_start(arg_ptr, format);
385 StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
388 /// if (StrLength(WCC-WBuf) > 2048)
389 ///client_write(wbuf, strlen(wbuf));
394 * wrap up an HTTP session, closes tags, etc.
396 * print_standard_html_footer should be set to:
397 * 0 to transmit only,
398 * 1 to append the main menu and closing tags,
399 * 2 to append the closing tags only.
401 void wDumpContent(int print_standard_html_footer)
403 if (print_standard_html_footer) {
404 wprintf("</div>\n"); /* end of "text" div */
405 do_template("trailing", NULL);
408 /* If we've been saving it all up for one big output burst,
409 * go ahead and do that now.
417 * Copy a string, escaping characters which have meaning in HTML.
419 * target target buffer
420 * strbuf source buffer
421 * nbsp If nonzero, spaces are converted to non-breaking spaces.
422 * nolinebreaks if set, linebreaks are removed from the string.
424 long stresc(char *target, long tSize, char *strbuf, int nbsp, int nolinebreaks)
426 char *aptr, *bptr, *eptr;
431 eptr = target + tSize - 6; // our biggest unit to put in...
434 while ((bptr < eptr) && !IsEmptyStr(aptr) ){
436 memcpy(bptr, "<", 4);
439 else if (*aptr == '>') {
440 memcpy(bptr, ">", 4);
443 else if (*aptr == '&') {
444 memcpy(bptr, "&", 5);
447 else if (*aptr == '\"') {
448 memcpy(bptr, """, 6);
451 else if (*aptr == '\'') {
452 memcpy(bptr, "'", 5);
455 else if (*aptr == LB) {
459 else if (*aptr == RB) {
463 else if (*aptr == QU) {
467 else if ((*aptr == 32) && (nbsp == 1)) {
468 memcpy(bptr, " ", 6);
471 else if ((*aptr == '\n') && (nolinebreaks)) {
472 *bptr='\0'; /* nothing */
474 else if ((*aptr == '\r') && (nolinebreaks)) {
475 *bptr='\0'; /* nothing */
484 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
486 return (bptr - target);
490 void escputs1(char *strbuf, int nbsp, int nolinebreaks)
492 StrEscAppend(WC->WBuf, NULL, strbuf, nbsp, nolinebreaks);
495 void StrEscputs1(const StrBuf *strbuf, int nbsp, int nolinebreaks)
497 StrEscAppend(WC->WBuf, strbuf, NULL, nbsp, nolinebreaks);
501 * static wrapper for ecsputs1
503 void escputs(char *strbuf)
505 escputs1(strbuf, 0, 0);
510 * static wrapper for ecsputs1
512 void StrEscPuts(const StrBuf *strbuf)
514 StrEscputs1(strbuf, 0, 0);
519 * urlescape buffer and print it to the client
521 void urlescputs(const char *strbuf)
523 StrBufUrlescAppend(WC->WBuf, NULL, strbuf);
527 * urlescape buffer and print it to the client
529 void UrlescPutStrBuf(const StrBuf *strbuf)
531 StrBufUrlescAppend(WC->WBuf, strbuf, NULL);
535 * urlescape buffer and print it as header
537 void hurlescputs(const char *strbuf)
539 StrBufUrlescAppend(WC->HBuf, NULL, strbuf);
544 * Copy a string, escaping characters for JavaScript strings.
546 void jsesc(char *target, size_t tlen, char *strbuf)
555 len = strlen (strbuf);
557 tend = target + tlen;
561 while (!IsEmptyStr(sptr) &&
567 else if (*sptr == '>')
569 else if (*sptr == '\'') {
575 else if (*sptr == '"') {
585 else if (*sptr == '&') {
602 * escape and print javascript
604 void jsescputs(char *strbuf)
608 jsesc(outbuf, SIZ, strbuf);
609 wprintf("%s", outbuf);
613 * print a string to the client after cleaning it with msgesc() and stresc()
615 void msgescputs1( char *strbuf)
619 if ((strbuf == NULL) || IsEmptyStr(strbuf))
621 OutBuf = NewStrBuf();
622 StrMsgEscAppend(OutBuf, NULL, strbuf);
623 StrEscAppend(WC->WBuf, OutBuf, NULL, 0, 0);
628 * print a string to the client after cleaning it with msgesc()
630 void msgescputs(char *strbuf) {
631 if ((strbuf != NULL) && !IsEmptyStr(strbuf))
632 StrMsgEscAppend(WC->WBuf, NULL, strbuf);
639 * Output HTTP headers and leading HTML for a page
641 void output_headers( int do_httpheaders, /* 1 = output HTTP headers */
642 int do_htmlhead, /* 1 = output HTML <head> section and <body> opener */
644 int do_room_banner, /* 0=no, 1=yes,
645 * 2 = I'm going to embed my own, so don't open the
646 * <div id="content"> either.
649 int unset_cookies, /* 1 = session is terminating, so unset the cookies */
650 int suppress_check, /* 1 = suppress check for instant messages */
651 int cache /* 1 = allow browser to cache this page */
656 hprintf("HTTP/1.1 200 OK\n");
657 http_datestring(httpnow, sizeof httpnow, time(NULL));
659 if (do_httpheaders) {
660 hprintf("Content-type: text/html; charset=utf-8\r\n"
662 "Connection: close\r\n",
663 PACKAGE_STRING, serv_info.serv_software
668 char httpTomorow[128];
670 http_datestring(httpTomorow, sizeof httpTomorow,
671 time(NULL) + 60 * 60 * 24 * 2);
673 hprintf("Pragma: public\r\n"
674 "Cache-Control: max-age=3600, must-revalidate\r\n"
675 "Last-modified: %s\r\n"
682 hprintf("Pragma: no-cache\r\n"
683 "Cache-Control: no-store\r\n"
688 stuff_to_cookie(cookie, 1024, WC->wc_session, WC->wc_username,
689 WC->wc_password, WC->wc_roomname);
692 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
694 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
695 if (server_cookie != NULL) {
696 hprintf("%s\n", server_cookie);
702 if (!access("static.local/webcit.css", R_OK)) {
703 svprintf(HKEY("CSSLOCAL"), WCS_STRING,
704 "<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"
707 do_template("head", NULL);
714 /* check for ImportantMessages (these display in a div overlaying the main screen) */
715 if (!IsEmptyStr(WC->ImportantMessage)) {
716 wprintf("<div id=\"important_message\">\n"
717 "<span class=\"imsg\">");
718 escputs(WC->ImportantMessage);
719 wprintf("</span><br />\n"
721 "<script type=\"text/javascript\">\n"
722 " setTimeout('hide_imsg_popup()', 5000); \n"
724 WC->ImportantMessage[0] = 0;
727 if ( (WC->logged_in) && (!unset_cookies) ) {
728 wprintf("<div id=\"iconbar\">");
729 do_selected_iconbar();
730 /** check for instant messages (these display in a new window) */
735 if (do_room_banner == 1) {
736 wprintf("<div id=\"banner\">\n");
737 embed_room_banner(NULL, navbar_default);
742 if (do_room_banner == 1) {
743 wprintf("<div id=\"content\">\n");
749 * Generic function to do an HTTP redirect. Easy and fun.
751 void http_redirect(const char *whichpage) {
752 hprintf("HTTP/1.1 302 Moved Temporarily\n");
753 hprintf("Location: %s\r\n", whichpage);
754 hprintf("URI: %s\r\n", whichpage);
755 hprintf("Content-type: text/html; charset=utf-8\r\n");
756 wprintf("<html><body>");
757 wprintf("Go <a href=\"%s\">here</A>.", whichpage);
758 wprintf("</body></html>\n");
765 * Output a piece of content to the web browser using conformant HTTP and MIME semantics
767 void http_transmit_thing(const char *content_type,
770 output_headers(0, 0, 0, 0, 0, is_static);
772 hprintf("Content-type: %s\r\n"
774 "Connection: close\r\n",
782 * print menu box like used in the floor view or admin interface.
783 * This function takes pair of strings as va_args,
784 * Title Title string of the box
785 * Class CSS Class for the box
786 * nLines How many string pairs should we print? (URL, UrlText)
787 * ... Pairs of URL Strings and their Names
789 void print_menu_box(char* Title, char *Class, int nLines, ...)
794 svput("BOXTITLE", WCS_STRING, Title);
795 do_template("beginbox", NULL);
797 wprintf("<ul class=\"%s\">", Class);
799 va_start(arg_list, nLines);
800 for (i = 0; i < nLines; ++i)
802 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
803 wprintf((char *) va_arg(arg_list, char *));
804 wprintf("</a></li>\n");
808 wprintf("</a></li>\n");
812 do_template("endbox", NULL);
817 * dump out static pages from disk
819 void output_static(char *what)
825 const char *content_type;
829 fd = open(what, O_RDONLY);
831 lprintf(9, "output_static('%s') -- NOT FOUND --\n", what);
832 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
833 hprintf("Content-Type: text/plain\r\n");
834 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
838 content_type = GuessMimeByFilename(what, len);
840 if (fstat(fd, &statbuf) == -1) {
841 lprintf(9, "output_static('%s') -- FSTAT FAILED --\n", what);
842 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
843 hprintf("Content-Type: text/plain\r\n");
844 wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
850 bytes = statbuf.st_size;
852 if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
854 if (fd > 0) close(fd);
855 lprintf(9, "output_static('%s') -- FREAD FAILED (%s) --\n", what, strerror(errno));
856 hprintf("HTTP/1.1 500 internal server error \r\n");
857 hprintf("Content-Type: text/plain\r\n");
865 lprintf(9, "output_static('%s') %s\n", what, content_type);
867 http_transmit_thing(content_type, 1);
869 if (yesbstr("force_close_session")) {
870 end_webcit_session();
875 * When the browser requests an image file from the Citadel server,
876 * this function is called to transmit it.
880 struct wcsession *WCC = WC;
883 const char *MimeType;
885 serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
886 serv_getln(buf, sizeof buf);
888 bytes = extract_long(&buf[4], 0);
890 /** Read it from the server */
892 if (read_server_binary(WCC->WBuf, bytes) > 0) {
894 serv_getln(buf, sizeof buf);
896 MimeType = GuessMimeType (ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
897 /** Write it to the browser */
898 if (!IsEmptyStr(MimeType))
900 http_transmit_thing(MimeType, 0);
904 /* hm... unknown mimetype? fallback to blank gif */
909 * Instead of an ugly 404, send a 1x1 transparent GIF
910 * when there's no such image on the server.
913 snprintf (blank_gif, SIZ, "%s%s", static_dirs[0], "/blank.gif");
914 output_static(blank_gif);
918 * Extract an embedded photo from a vCard for display on the client
920 void display_vcard_photo_img(void)
926 const char *contentType;
927 struct wcsession *WCC = WC;
929 msgnum = StrTol(WCC->UrlFragment1);
931 vcard = load_mimepart(msgnum,"1");
932 v = vcard_load(vcard);
934 photosrc = vcard_get_prop(v, "PHOTO", 1,0,0);
935 FlushStrBuf(WCC->WBuf);
936 StrBufAppendBufPlain(WCC->WBuf, photosrc, -1, 0);
937 if (StrBufDecodeBase64(WCC->WBuf) <= 0) {
938 FlushStrBuf(WCC->WBuf);
940 hprintf("HTTP/1.1 500 %s\n","Unable to get photo");
941 output_headers(0, 0, 0, 0, 0, 0);
942 hprintf("Content-Type: text/plain\r\n");
943 wprintf(_("Could Not decode vcard photo\n"));
947 contentType = GuessMimeType(ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
948 http_transmit_thing(contentType, 0);
954 * Generic function to output an arbitrary MIME part from an arbitrary
955 * message number on the server.
957 * msgnum Number of the item on the citadel server
958 * partnum The MIME part to be output
959 * force_download Nonzero to force set the Content-Type: header to "application/octet-stream"
961 void mimepart(const char *msgnum, const char *partnum, int force_download)
965 char content_type[256];
967 serv_printf("OPNA %s|%s", msgnum, partnum);
968 serv_getln(buf, sizeof buf);
970 bytes = extract_long(&buf[4], 0);
971 if (force_download) {
972 strcpy(content_type, "application/octet-stream");
975 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
977 output_headers(0, 0, 0, 0, 0, 0);
979 read_server_binary(WC->WBuf, bytes);
981 serv_getln(buf, sizeof buf);
982 http_transmit_thing(content_type, 0);
984 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
985 output_headers(0, 0, 0, 0, 0, 0);
986 hprintf("Content-Type: text/plain\r\n");
987 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
994 * Read any MIME part of a message, from the server, into memory.
996 char *load_mimepart(long msgnum, char *partnum)
1000 char content_type[SIZ];
1003 serv_printf("DLAT %ld|%s", msgnum, partnum);
1004 serv_getln(buf, sizeof buf);
1005 if (buf[0] == '6') {
1006 bytes = extract_long(&buf[4], 0);
1007 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1009 content = malloc(bytes + 2);
1010 serv_read(content, bytes);
1012 content[bytes] = 0; /* null terminate for good measure */
1022 * Convenience functions to display a page containing only a string
1024 * titlebarcolor color of the titlebar of the frame
1025 * titlebarmsg text to display in the title bar
1026 * messagetext body of the box
1028 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
1030 hprintf("HTTP/1.1 200 OK\n");
1031 output_headers(1, 1, 2, 0, 0, 0);
1032 wprintf("<div id=\"banner\">\n");
1033 wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
1034 wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
1035 wprintf("</td></tr></table>\n");
1036 wprintf("</div>\n<div id=\"content\">\n");
1037 escputs(messagetext);
1039 wprintf("<hr />\n");
1045 * Display a blank page.
1047 void blank_page(void) {
1048 output_headers(1, 1, 0, 0, 0, 0);
1054 * A template has been requested
1056 void url_do_template(void) {
1057 const StrBuf *Tmpl = sbstr("template");
1059 output_headers(1, 0, 0, 0, 1, 0);
1060 DoTemplate(ChrPtr(Tmpl), StrLength(Tmpl), NULL, NULL);
1067 * Offer to make any page the user's "start page."
1069 void offer_start_page(void) {
1070 wprintf("<a href=\"change_start_page?startpage=");
1071 urlescputs(WC->this_page);
1073 wprintf(_("Make this my start page"));
1076 wprintf("<br/><a href=\"rss?room=");
1077 urlescputs(WC->wc_roomname);
1078 wprintf("\" title=\"RSS 2.0 feed for ");
1079 escputs(WC->wc_roomname);
1080 wprintf("\"><img alt=\"RSS\" border=\"0\" src=\"static/xml_button.gif\"/></a>\n");
1086 * Change the user's start page
1088 void change_start_page(void) {
1090 if (bstr("startpage") == NULL) {
1091 safestrncpy(WC->ImportantMessage,
1092 _("You no longer have a start page selected."),
1093 sizeof WC->ImportantMessage);
1094 display_main_menu();
1098 set_preference("startpage", NewStrBufPlain(bstr("startpage"), -1), 1);
1100 output_headers(1, 1, 0, 0, 0, 0);
1101 do_template("newstartpage", NULL);
1108 * convenience function to indicate success
1110 void display_success(char *successmessage)
1112 convenience_page("007700", "OK", successmessage);
1117 * Authorization required page
1118 * This is probably temporary and should be revisited
1120 void authorization_required(const char *message)
1122 hprintf("HTTP/1.1 401 Authorization Required\r\n");
1123 hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", serv_info.serv_humannode);
1124 hprintf("Content-Type: text/html\r\n");
1126 wprintf(_("Authorization Required"));
1127 wprintf("</h1>\r\n");
1128 wprintf(_("The resource you requested requires a valid username and password. "
1129 "You could not be logged in: %s\n"), message);
1135 * This function is called by the MIME parser to handle data uploaded by
1136 * the browser. Form data, uploaded files, and the data from HTTP PUT
1137 * operations (such as those found in GroupDAV) all arrive this way.
1139 * name Name of the item being uploaded
1140 * filename Filename of the item being uploaded
1141 * partnum MIME part identifier (not needed)
1142 * disp MIME content disposition (not needed)
1143 * content The actual data
1144 * cbtype MIME content-type
1145 * cbcharset Character set
1146 * length Content length
1147 * encoding MIME encoding type (not needed)
1148 * userdata Not used here
1150 void upload_handler(char *name, char *filename, char *partnum, char *disp,
1151 void *content, char *cbtype, char *cbcharset,
1152 size_t length, char *encoding, void *userdata)
1155 #ifdef DEBUG_URLSTRINGS
1156 lprintf(9, "upload_handler() name=%s, type=%s, len=%d\n", name, cbtype, length);
1158 if (WC->urlstrings == NULL)
1159 WC->urlstrings = NewHash(1, NULL);
1162 if ( (length > 0) && (IsEmptyStr(cbtype)) ) {
1163 u = (urlcontent *) malloc(sizeof(urlcontent));
1165 safestrncpy(u->url_key, name, sizeof(u->url_key));
1166 u->url_data = NewStrBufPlain(content, length);
1168 Put(WC->urlstrings, u->url_key, strlen(u->url_key), u, free_url);
1169 #ifdef DEBUG_URLSTRINGS
1170 lprintf(9, "Key: <%s> len: [%ld] Data: <%s>\n",
1172 StrLength(u->url_data),
1173 ChrPtr(u->url_data));
1177 /** Uploaded files */
1178 if ( (length > 0) && (!IsEmptyStr(cbtype)) ) {
1179 WC->upload = malloc(length);
1180 if (WC->upload != NULL) {
1181 WC->upload_length = length;
1182 safestrncpy(WC->upload_filename, filename,
1183 sizeof(WC->upload_filename));
1184 safestrncpy(WC->upload_content_type, cbtype,
1185 sizeof(WC->upload_content_type));
1186 memcpy(WC->upload, content, length);
1189 lprintf(3, "malloc() failed: %s\n", strerror(errno));
1196 * Convenience functions to wrap around asynchronous ajax responses
1198 void begin_ajax_response(void) {
1199 struct wcsession *WCC = WC;
1201 FlushStrBuf(WCC->HBuf);
1202 output_headers(0, 0, 0, 0, 0, 0);
1204 hprintf("Content-type: text/html; charset=UTF-8\r\n"
1206 "Connection: close\r\n"
1213 * print ajax response footer
1215 void end_ajax_response(void) {
1216 ///hprintf("\r\n");///// todo: is this right?
1221 * Wraps a Citadel server command in an AJAX transaction.
1223 void ajax_servcmd(void)
1226 char gcontent[1024];
1230 begin_ajax_response();
1232 serv_printf("%s", bstr("g_cmd"));
1233 serv_getln(buf, sizeof buf);
1234 wprintf("%s\n", buf);
1236 if (buf[0] == '8') {
1237 serv_printf("\n\n000");
1239 if ((buf[0] == '1') || (buf[0] == '8')) {
1240 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
1241 wprintf("%s\n", gcontent);
1245 if (buf[0] == '4') {
1246 text_to_server(bstr("g_input"));
1249 if (buf[0] == '6') {
1250 len = atol(&buf[4]);
1252 serv_read(junk, len);
1255 if (buf[0] == '7') {
1256 len = atol(&buf[4]);
1258 memset(junk, 0, len);
1259 serv_write(junk, len);
1263 end_ajax_response();
1266 * This is kind of an ugly hack, but this is the only place it can go.
1267 * If the command was GEXP, then the instant messenger window must be
1268 * running, so reset the "last_pager_check" watchdog timer so
1269 * that page_popup() doesn't try to open it a second time.
1271 if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
1272 WC->last_pager_check = time(NULL);
1278 * Helper function for the asynchronous check to see if we need
1279 * to open the instant messenger window.
1281 void seconds_since_last_gexp(void)
1285 if ( (time(NULL) - WC->last_pager_check) < 30) {
1290 serv_getln(buf, sizeof buf);
1291 if (buf[3] == '*') {
1301 * \brief Detects a 'mobile' user agent
1303 int is_mobile_ua(char *user_agent) {
1304 if (strstr(user_agent,"iPhone OS") != NULL) {
1306 } else if (strstr(user_agent,"Windows CE") != NULL) {
1308 } else if (strstr(user_agent,"SymbianOS") != NULL) {
1310 } else if (strstr(user_agent, "Opera Mobi") != NULL) {
1312 } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
1313 // For some reason a new install of Opera 9.51beta decided to spoof.
1321 * Entry point for WebCit transaction
1323 void session_loop(struct httprequest *req)
1331 char request_method[128];
1332 char pathname[1024];
1333 int a, b, nBackDots, nEmpty;
1334 int ContentLength = 0;
1335 char ContentType[512];
1336 char *content = NULL;
1337 char *content_end = NULL;
1338 struct httprequest *hptr;
1339 char browser_host[256];
1340 char user_agent[256];
1346 * We stuff these with the values coming from the client cookies,
1347 * so we can use them to reconnect a timed out session if we have to.
1349 char c_username[SIZ];
1350 char c_password[SIZ];
1351 char c_roomname[SIZ];
1352 char c_httpauth_string[SIZ];
1353 char c_httpauth_user[SIZ];
1354 char c_httpauth_pass[SIZ];
1356 struct wcsession *WCC;
1358 safestrncpy(c_username, "", sizeof c_username);
1359 safestrncpy(c_password, "", sizeof c_password);
1360 safestrncpy(c_roomname, "", sizeof c_roomname);
1361 safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
1362 safestrncpy(c_httpauth_user, DEFAULT_HTTPAUTH_USER, sizeof c_httpauth_user);
1363 safestrncpy(c_httpauth_pass, DEFAULT_HTTPAUTH_PASS, sizeof c_httpauth_pass);
1364 strcpy(browser_host, "");
1367 if (WCC->WBuf == NULL)
1368 WC->WBuf = NewStrBufPlain(NULL, 32768);
1369 FlushStrBuf(WCC->WBuf);
1371 if (WCC->HBuf == NULL)
1372 WCC->HBuf = NewStrBuf();
1373 FlushStrBuf(WCC->HBuf);
1375 WCC->upload_length = 0;
1380 if (hptr == NULL) return;
1382 safestrncpy(cmd, hptr->line, sizeof cmd);
1384 extract_token(request_method, cmd, 0, ' ', sizeof request_method);
1385 extract_token(pathname, cmd, 1, ' ', sizeof pathname);
1387 /** Figure out the action */
1389 sizes[0] = sizeof action;
1392 index[a] = arg[a-1];
1393 sizes[a] = sizeof arg[a-1];
1395 //// index[9] = &foo; todo
1398 for ( a = 0; a < 9; ++a)
1400 extract_token(index[a], pathname, a + 1, '/', sizes[a]);
1401 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
1402 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
1403 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
1404 if ((index[a][0] == '.') && (index[a][1] == '.'))
1406 if (index[a][0] == '\0')
1410 while (hptr != NULL) {
1411 safestrncpy(buf, hptr->line, sizeof buf);
1412 /* lprintf(9, "HTTP HEADER: %s\n", buf); */
1415 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
1416 safestrncpy(cookie, &buf[15], sizeof cookie);
1417 cookie_to_stuff(cookie, NULL,
1418 c_username, sizeof c_username,
1419 c_password, sizeof c_password,
1420 c_roomname, sizeof c_roomname);
1422 else if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
1423 CtdlDecodeBase64(c_httpauth_string, &buf[21], strlen(&buf[21]));
1424 extract_token(c_httpauth_user, c_httpauth_string, 0, ':', sizeof c_httpauth_user);
1425 extract_token(c_httpauth_pass, c_httpauth_string, 1, ':', sizeof c_httpauth_pass);
1427 else if (!strncasecmp(buf, "Content-length: ", 16)) {
1428 ContentLength = atoi(&buf[16]);
1430 else if (!strncasecmp(buf, "Content-type: ", 14)) {
1431 safestrncpy(ContentType, &buf[14], sizeof ContentType);
1433 else if (!strncasecmp(buf, "User-agent: ", 12)) {
1434 safestrncpy(user_agent, &buf[12], sizeof user_agent);
1436 if (is_mobile_ua(&buf[12])) {
1441 else if (!strncasecmp(buf, "X-Forwarded-Host: ", 18)) {
1443 safestrncpy(WCC->http_host, &buf[18], sizeof WCC->http_host);
1446 else if (!strncasecmp(buf, "Host: ", 6)) {
1447 if (IsEmptyStr(WCC->http_host)) {
1448 safestrncpy(WCC->http_host, &buf[6], sizeof WCC->http_host);
1451 else if (!strncasecmp(buf, "X-Forwarded-For: ", 17)) {
1452 safestrncpy(browser_host, &buf[17], sizeof browser_host);
1453 while (num_tokens(browser_host, ',') > 1) {
1454 remove_token(browser_host, 0, ',');
1456 striplt(browser_host);
1460 if (ContentLength > 0) {
1463 BuffSize = ContentLength + SIZ;
1464 content = malloc(BuffSize);
1465 memset(content, 0, BuffSize);
1466 snprintf(content, BuffSize, "Content-type: %s\n"
1467 "Content-length: %d\n\n",
1468 ContentType, ContentLength);
1470 hprintf("Content-type: %s\n"
1471 "Content-length: %d\n\n",
1472 ContentType, ContentLength);
1474 body_start = strlen(content);
1476 /** Read the entire input data at once. */
1477 client_read(&WCC->http_sock, &content[body_start], ContentLength);
1479 if (!strncasecmp(ContentType, "application/x-www-form-urlencoded", 33)) {
1482 Content = _NewConstStrBuf(&content[body_start],ContentLength);
1484 FreeStrBuf(&Content);
1485 } else if (!strncasecmp(ContentType, "multipart", 9)) {
1486 content_end = content + ContentLength + body_start;
1487 mime_parser(content, content_end, *upload_handler, NULL, NULL, NULL, 0);
1493 /* make a note of where we are in case the user wants to save it */
1494 safestrncpy(WCC->this_page, cmd, sizeof(WCC->this_page));
1495 remove_token(WCC->this_page, 2, ' ');
1496 remove_token(WCC->this_page, 0, ' ');
1498 /* If there are variables in the URL, we must grab them now */
1500 for (a = 0; a < len; ++a) {
1501 if ((cmd[a] == '?') || (cmd[a] == '&')) {
1503 for (b = a; b < len; ++b) {
1504 if (isspace(cmd[b])){
1509 //cmd[len - a] = '\0';
1510 Params = _NewConstStrBuf(&cmd[a + 1], len - a);
1512 FreeStrBuf(&Params);
1518 /* If it's a "force 404" situation then display the error and bail. */
1519 if (!strcmp(action, "404")) {
1520 hprintf("HTTP/1.1 404 Not found\r\n");
1521 hprintf("Content-Type: text/plain\r\n");
1522 wprintf("Not found\r\n");
1524 goto SKIP_ALL_THIS_CRAP;
1527 /* Static content can be sent without connecting to Citadel. */
1529 for (a=0; a<ndirs; ++a) {
1530 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
1538 snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
1539 static_dirs[n_static],
1540 index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
1541 for (a=0; a<8; ++a) {
1542 if (buf[strlen(buf)-1] == '/') {
1543 buf[strlen(buf)-1] = 0;
1546 for (a = 0; a < strlen(buf); ++a) {
1547 if (isspace(buf[a])) {
1555 lprintf(9, "Suspicious request. Ignoring.");
1556 hprintf("HTTP/1.1 404 Security check failed\r\n");
1557 hprintf("Content-Type: text/plain\r\n");
1558 wprintf("You have sent a malformed or invalid request.\r\n");
1561 goto SKIP_ALL_THIS_CRAP; /* Don't try to connect */
1564 /* If the client sent a nonce that is incorrect, kill the request. */
1565 if (strlen(bstr("nonce")) > 0) {
1566 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n",
1567 bstr("nonce"), WCC->nonce);
1568 if (ibstr("nonce") != WCC->nonce) {
1569 lprintf(9, "Ignoring request with mismatched nonce.\n");
1570 hprintf("HTTP/1.1 404 Security check failed\r\n");
1571 hprintf("Content-Type: text/plain\r\n");
1572 wprintf("Security check failed.\r\n");
1574 goto SKIP_ALL_THIS_CRAP;
1579 * If we're not connected to a Citadel server, try to hook up the
1582 if (!WCC->connected) {
1583 if (!strcasecmp(ctdlhost, "uds")) {
1584 /* unix domain socket */
1585 snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
1586 WCC->serv_sock = uds_connectsock(buf);
1590 WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
1593 if (WCC->serv_sock < 0) {
1595 goto SKIP_ALL_THIS_CRAP;
1599 serv_getln(buf, sizeof buf); /** get the server welcome message */
1602 * From what host is our user connecting? Go with
1603 * the host at the other end of the HTTP socket,
1604 * unless we are following X-Forwarded-For: headers
1605 * and such a header has already turned up something.
1607 if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
1608 locate_host(browser_host, WCC->http_sock);
1611 get_serv_info(browser_host, user_agent);
1612 if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
1613 wprintf(_("You are connected to a Citadel "
1614 "server running Citadel %d.%02d. \n"
1615 "In order to run this version of WebCit "
1616 "you must also have Citadel %d.%02d or"
1618 serv_info.serv_rev_level / 100,
1619 serv_info.serv_rev_level % 100,
1620 MINIMUM_CIT_VERSION / 100,
1621 MINIMUM_CIT_VERSION % 100
1623 end_webcit_session();
1624 goto SKIP_ALL_THIS_CRAP;
1628 ////////todo: restorte language in this case
1630 * Functions which can be performed without logging in
1632 if (!strcasecmp(action, "listsub")) {
1634 goto SKIP_ALL_THIS_CRAP;
1636 if (!strcasecmp(action, "freebusy")) {
1638 goto SKIP_ALL_THIS_CRAP;
1642 * If we're not logged in, but we have HTTP Authentication data,
1643 * try logging in to Citadel using that.
1645 if ((!WCC->logged_in)
1646 && (strlen(c_httpauth_user) > 0)
1647 && (strlen(c_httpauth_pass) > 0)) {
1648 serv_printf("USER %s", c_httpauth_user);
1649 serv_getln(buf, sizeof buf);
1650 if (buf[0] == '3') {
1651 serv_printf("PASS %s", c_httpauth_pass);
1652 serv_getln(buf, sizeof buf);
1653 if (buf[0] == '2') {
1654 become_logged_in(c_httpauth_user,
1655 c_httpauth_pass, buf);
1656 safestrncpy(WCC->httpauth_user, c_httpauth_user, sizeof WCC->httpauth_user);
1657 safestrncpy(WCC->httpauth_pass, c_httpauth_pass, sizeof WCC->httpauth_pass);
1659 /* Should only display when password is wrong */
1660 authorization_required(&buf[4]);
1661 goto SKIP_ALL_THIS_CRAP;
1666 /* This needs to run early */
1668 if (!strcasecmp(action, "rss")) {
1669 display_rss(bstr("room"), request_method);
1670 goto SKIP_ALL_THIS_CRAP;
1675 * The GroupDAV stuff relies on HTTP authentication instead of
1676 * our session's authentication.
1678 if (!strncasecmp(action, "groupdav", 8)) {
1679 groupdav_main(req, ContentType, /* do GroupDAV methods */
1680 ContentLength, content+body_start);
1681 if (!WCC->logged_in) {
1682 WCC->killthis = 1; /* If not logged in, don't */
1683 } /* keep the session active */
1684 goto SKIP_ALL_THIS_CRAP;
1689 * Automatically send requests with any method other than GET or
1690 * POST to the GroupDAV code as well.
1692 if ((strcasecmp(request_method, "GET")) && (strcasecmp(request_method, "POST"))) {
1693 groupdav_main(req, ContentType, /** do GroupDAV methods */
1694 ContentLength, content+body_start);
1695 if (!WCC->logged_in) {
1696 WCC->killthis = 1; /** If not logged in, don't */
1697 } /** keep the session active */
1698 goto SKIP_ALL_THIS_CRAP;
1702 * If we're not logged in, but we have username and password cookies
1703 * supplied by the browser, try using them to log in.
1705 if ((!WCC->logged_in)
1706 && (!IsEmptyStr(c_username))
1707 && (!IsEmptyStr(c_password))) {
1708 serv_printf("USER %s", c_username);
1709 serv_getln(buf, sizeof buf);
1710 if (buf[0] == '3') {
1711 serv_printf("PASS %s", c_password);
1712 serv_getln(buf, sizeof buf);
1713 if (buf[0] == '2') {
1715 become_logged_in(c_username, c_password, buf);
1716 if (get_preference("language", &Lang)) {
1717 set_selected_language(ChrPtr(Lang));
1718 go_selected_language(); /* set locale */
1724 * If we don't have a current room, but a cookie specifying the
1725 * current room is supplied, make an effort to go there.
1727 if ((IsEmptyStr(WCC->wc_roomname)) && (!IsEmptyStr(c_roomname))) {
1728 serv_printf("GOTO %s", c_roomname);
1729 serv_getln(buf, sizeof buf);
1730 if (buf[0] == '2') {
1731 safestrncpy(WCC->wc_roomname, c_roomname, sizeof WCC->wc_roomname);
1735 if (!strcasecmp(action, "image")) {
1737 } else if (!strcasecmp(action, "display_mime_icon")) {
1738 display_mime_icon();
1742 WebcitHandler *Handler;
1744 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
1745 Handler = (WebcitHandler*) vHandler;
1746 if (Handler != NULL) {
1747 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
1748 display_login(NULL);
1751 if((Handler->Flags & NEED_URL)) {
1752 if (WCC->UrlFragment1 == NULL)
1753 WCC->UrlFragment1 = NewStrBuf();
1754 if (WCC->UrlFragment2 == NULL)
1755 WCC->UrlFragment2 = NewStrBuf();
1756 StrBufPrintf(WCC->UrlFragment1, "%s", index[1]);
1757 StrBufPrintf(WCC->UrlFragment2, "%s", index[2]);
1759 if ((Handler->Flags & AJAX) != 0)
1760 begin_ajax_response();
1762 if ((Handler->Flags & AJAX) != 0)
1763 end_ajax_response();
1766 /* When all else fais, display the main menu. */
1768 if (!WCC->logged_in)
1769 display_login(NULL);
1771 display_main_menu();
1776 if (content != NULL) {
1781 if (WCC->upload_length > 0) {
1783 WCC->upload_length = 0;
1789 * Replacement for sleep() that uses select() in order to avoid SIGALRM
1791 void sleeeeeeeeeep(int seconds)
1795 tv.tv_sec = seconds;
1797 select(0, NULL, NULL, NULL, &tv);
1800 void diagnostics(void)
1802 output_headers(1, 1, 1, 0, 0, 0);
1803 wprintf("Session: %d<hr />\n", WC->wc_session);
1804 wprintf("Command: <br /><PRE>\n");
1805 StrEscPuts(WC->UrlFragment1);
1806 wprintf("<br />\n");
1807 StrEscPuts(WC->UrlFragment2);
1808 wprintf("</PRE><hr />\n");
1809 wprintf("Variables: <br /><PRE>\n");
1811 wprintf("</PRE><hr />\n");
1815 void view_mimepart(void) {
1816 mimepart(ChrPtr(WC->UrlFragment1),
1817 ChrPtr(WC->UrlFragment2),
1821 void download_mimepart(void) {
1822 mimepart(ChrPtr(WC->UrlFragment1),
1823 ChrPtr(WC->UrlFragment2),
1828 int ConditionalImportantMesage(WCTemplateToken *Tokens, void *Context)
1830 struct wcsession *WCC = WC;
1832 return (!IsEmptyStr(WCC->ImportantMessage));
1837 void tmplput_importantmessage(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1839 struct wcsession *WCC = WC;
1842 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
1843 WCC->ImportantMessage[0] = '\0';
1847 void tmplput_offer_start_page(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1853 int ConditionalBstr(WCTemplateToken *Tokens, void *Context)
1855 if(Tokens->nParameters == 1)
1856 return HaveBstr(Tokens->Params[0]->Start,
1857 Tokens->Params[0]->len);
1859 return strcmp(Bstr(Tokens->Params[0]->Start,
1860 Tokens->Params[0]->len),
1861 Tokens->Params[1]->Start) == 0;
1864 void tmplput_bstr(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1866 StrBufAppendBuf(Target,
1867 SBstr(Tokens->Params[0]->Start,
1868 Tokens->Params[0]->len), 0);
1875 WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1876 WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1877 WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1878 WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1879 WebcitAddUrlHandler(HKEY("change_start_page"), change_start_page, 0);
1880 WebcitAddUrlHandler(HKEY("toggle_self_service"), toggle_self_service, 0);
1881 WebcitAddUrlHandler(HKEY("vcardphoto"), display_vcard_photo_img, NEED_URL);
1882 WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1883 WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1884 WebcitAddUrlHandler(HKEY("diagnostics"), diagnostics, NEED_URL);
1885 RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage);
1886 RegisterConditional(HKEY("COND:BSTR"), 1, ConditionalBstr);
1887 RegisterNamespace("BSTR", 1, 2, tmplput_bstr);
1888 RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage);
1889 RegisterNamespace("OFFERSTARTPAGE", 0, 0, tmplput_offer_start_page);