* implement paging hooks in a templated way so it can be called from them.
[citadel.git] / webcit / webcit.c
1 /*
2  * $Id$
3  *
4  * This is the main transaction loop of the web service.  It maintains a
5  * persistent session to the Citadel server, handling HTTP WebCit requests as
6  * they arrive and presenting a user interface.
7  */
8 #define SHOW_ME_VAPPEND_PRINTF
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include "webcit.h"
12 #include "groupdav.h"
13 #include "webserver.h"
14
15
16 /*
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.  :)
20  */
21 static char *unset = "; expires=28-May-1971 18:10:00 GMT";
22 StrBuf *csslocal = NULL;
23 HashList *HandlerHash = NULL;
24
25
26 void DeleteWebcitHandler(void *vHandler)
27 {
28         WebcitHandler *Handler = (WebcitHandler*) vHandler;
29         FreeStrBuf(&Handler->Name);
30         free (Handler);
31
32 }
33
34 void WebcitAddUrlHandler(const char * UrlString, 
35                          long UrlSLen, 
36                          WebcitHandlerFunc F, 
37                          long Flags)
38 {
39         WebcitHandler *NewHandler;      
40         NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
41         NewHandler->F = F;
42         NewHandler->Flags = Flags;
43         NewHandler->Name = NewStrBufPlain(UrlString, UrlSLen);
44         StrBufShrinkToFit(NewHandler->Name, 1);
45         Put(HandlerHash, UrlString, UrlSLen, NewHandler, DeleteWebcitHandler);
46 }
47
48
49 /*
50  * web-printing funcion. uses our vsnprintf wrapper
51  */
52 void wprintf(const char *format,...)
53 {
54         wcsession *WCC = WC;
55         va_list arg_ptr;
56
57         if (WCC->WBuf == NULL)
58                 WCC->WBuf = NewStrBuf();
59
60         va_start(arg_ptr, format);
61         StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
62         va_end(arg_ptr);
63 }
64
65 /*
66  * http-header-printing funcion. uses our vsnprintf wrapper
67  */
68 void hprintf(const char *format,...)
69 {
70         wcsession *WCC = WC;
71         va_list arg_ptr;
72
73         va_start(arg_ptr, format);
74         StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
75         va_end(arg_ptr);
76 }
77
78
79
80 /*
81  * wrap up an HTTP session, closes tags, etc.
82  *
83  * print_standard_html_footer should be set to:
84  * 0            - to transmit only,
85  * nonzero      - to append the closing tags
86  */
87 void wDumpContent(int print_standard_html_footer)
88 {
89         if (print_standard_html_footer) {
90                 wprintf("</div> <!-- end of 'content' div -->\n");
91                 do_template("trailing", NULL);
92         }
93
94         /* If we've been saving it all up for one big output burst,
95          * go ahead and do that now.
96          */
97         end_burst();
98 }
99
100
101  
102
103 /*
104  * Output HTTP headers and leading HTML for a page
105  */
106 void output_headers(    int do_httpheaders,     /* 1 = output HTTP headers                          */
107                         int do_htmlhead,        /* 1 = output HTML <head> section and <body> opener */
108
109                         int do_room_banner,     /* 0=no, 1=yes,                                     
110                                                  * 2 = I'm going to embed my own, so don't open the 
111                                                  *     <div id="content"> either.                   
112                                                  */
113
114                         int unset_cookies,      /* 1 = session is terminating, so unset the cookies */
115                         int suppress_check,     /* 1 = suppress check for instant messages          */
116                         int cache               /* 1 = allow browser to cache this page             */
117 ) {
118         wcsession *WCC = WC;
119         char cookie[1024];
120         char httpnow[128];
121
122         hprintf("HTTP/1.1 200 OK\n");
123         http_datestring(httpnow, sizeof httpnow, time(NULL));
124
125         if (do_httpheaders) {
126                 if (WCC->serv_info != NULL)
127                         hprintf("Content-type: text/html; charset=utf-8\r\n"
128                                 "Server: %s / %s\n"
129                                 "Connection: close\r\n",
130                                 PACKAGE_STRING, 
131                                 ChrPtr(WCC->serv_info->serv_software));
132                 else
133                         hprintf("Content-type: text/html; charset=utf-8\r\n"
134                                 "Server: %s / [n/a]\n"
135                                 "Connection: close\r\n",
136                                 PACKAGE_STRING);
137         }
138
139         if (cache > 0) {
140                 char httpTomorow[128];
141
142                 http_datestring(httpTomorow, sizeof httpTomorow, 
143                                 time(NULL) + 60 * 60 * 24 * 2);
144
145                 hprintf("Pragma: public\r\n"
146                         "Cache-Control: max-age=3600, must-revalidate\r\n"
147                         "Last-modified: %s\r\n"
148                         "Expires: %s\r\n",
149                         httpnow,
150                         httpTomorow
151                 );
152         }
153         else {
154                 hprintf("Pragma: no-cache\r\n"
155                         "Cache-Control: no-store\r\n"
156                         "Expires: -1\r\n"
157                 );
158         }
159
160         if (cache < 2) {
161
162                 stuff_to_cookie(cookie, 1024, 
163                                 WCC->wc_session,
164                                 WCC->wc_username,
165                                 WCC->wc_password,
166                                 WCC->wc_roomname,
167                                 get_selected_language()
168                         );
169                 
170                 if (unset_cookies) {
171                         hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
172                 } else {
173                         hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
174                         if (server_cookie != NULL) {
175                                 hprintf("%s\n", server_cookie);
176                         }
177                 }
178         }
179
180         if (do_htmlhead) {
181                 begin_burst();
182                 do_template("head", NULL);
183
184                 /* check for ImportantMessages (these display in a div overlaying the main screen) */
185                 if (!IsEmptyStr(WCC->ImportantMessage)) {
186                         wprintf("<div id=\"important_message\">\n"
187                                 "<span class=\"imsg\">");
188                         StrEscAppend(WCC->WBuf, NULL, WCC->ImportantMessage, 0, 0);
189                         wprintf("</span><br />\n"
190                                 "</div>\n"
191                         );
192                         StrBufAppendBufPlain(WCC->trailing_javascript,
193                                              HKEY("setTimeout('hide_imsg_popup()', 5000);       \n"), 
194                                              0
195                         );
196                         WCC->ImportantMessage[0] = 0;
197                 }
198                 else if (StrLength(WCC->ImportantMsg) > 0) {
199                         wprintf("<div id=\"important_message\">\n"
200                                 "<span class=\"imsg\">");
201                         StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
202                         wprintf("</span><br />\n"
203                                 "</div>\n"
204                         );
205                         StrBufAppendBufPlain(WCC->trailing_javascript,
206                                              HKEY("setTimeout('hide_imsg_popup()', 5000);       \n"),
207                                              0
208                         );
209                         FlushStrBuf(WCC->ImportantMsg);
210                 }
211                 if ( (WCC->logged_in) && (!unset_cookies) ) {
212                         DoTemplate(HKEY("paging"), NULL, &NoCtx);
213                 }
214
215                 if (do_room_banner == 1) {
216                         wprintf("<div id=\"banner\">\n");
217                         embed_room_banner(NULL, navbar_default);
218                         wprintf("</div>\n");
219                 }
220         }
221
222         if (do_room_banner == 1) {
223                 wprintf("<div id=\"content\">\n");
224         }
225 }
226
227 void output_custom_content_header(const char *ctype) {
228   hprintf("HTTP/1.1 200 OK\r\n");
229   hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
230   hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
231   hprintf("Connection: close\r\n");
232 }
233
234
235 /*
236  * Generic function to do an HTTP redirect.  Easy and fun.
237  */
238 void http_redirect(const char *whichpage) {
239         hprintf("HTTP/1.1 302 Moved Temporarily\n");
240         hprintf("Location: %s\r\n", whichpage);
241         hprintf("URI: %s\r\n", whichpage);
242         hprintf("Content-type: text/html; charset=utf-8\r\n");
243         begin_burst();
244         wprintf("<html><body>");
245         wprintf("Go <a href=\"%s\">here</A>.", whichpage);
246         wprintf("</body></html>\n");
247         end_burst();
248 }
249
250
251
252 /*
253  * Output a piece of content to the web browser using conformant HTTP and MIME semantics
254  */
255 void http_transmit_thing(const char *content_type,
256                          int is_static) {
257
258 #ifndef TECH_PREVIEW
259         lprintf(9, "http_transmit_thing(%s)%s\n",
260                 content_type,
261                 ((is_static > 0) ? " (static)" : "")
262         );
263 #endif
264         output_headers(0, 0, 0, 0, 0, is_static);
265
266         hprintf("Content-type: %s\r\n"
267                 "Server: %s\r\n"
268                 "Connection: close\r\n",
269                 content_type,
270                 PACKAGE_STRING);
271
272         end_burst();
273 }
274
275 /*
276  * print menu box like used in the floor view or admin interface.
277  * This function takes pair of strings as va_args, 
278  * Title        Title string of the box
279  * Class        CSS Class for the box
280  * nLines       How many string pairs should we print? (URL, UrlText)
281  * ...          Pairs of URL Strings and their Names
282  */
283 void print_menu_box(char* Title, char *Class, int nLines, ...)
284 {
285         va_list arg_list;
286         long i;
287         
288         svput("BOXTITLE", WCS_STRING, Title);
289         do_template("beginboxx", NULL);
290         
291         wprintf("<ul class=\"%s\">", Class);
292         
293         va_start(arg_list, nLines);
294         for (i = 0; i < nLines; ++i)
295         { 
296                 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
297                 wprintf((char *) va_arg(arg_list, char *));
298                 wprintf("</a></li>\n");
299         }
300         va_end (arg_list);
301         
302         wprintf("</a></li>\n");
303         
304         wprintf("</ul>");
305         
306         do_template("endbox", NULL);
307 }
308
309
310
311 /*
312  * Convenience functions to display a page containing only a string
313  *
314  * titlebarcolor        color of the titlebar of the frame
315  * titlebarmsg          text to display in the title bar
316  * messagetext          body of the box
317  */
318 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
319 {
320         hprintf("HTTP/1.1 200 OK\n");
321         output_headers(1, 1, 2, 0, 0, 0);
322         wprintf("<div id=\"banner\">\n");
323         wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
324         wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
325         wprintf("</td></tr></table>\n");
326         wprintf("</div>\n<div id=\"content\">\n");
327         escputs(messagetext);
328
329         wprintf("<hr />\n");
330         wDumpContent(1);
331 }
332
333
334 /*
335  * Display a blank page.
336  */
337 void blank_page(void) {
338         output_headers(1, 1, 0, 0, 0, 0);
339         wDumpContent(2);
340 }
341
342
343 /*
344  * A template has been requested
345  */
346 void url_do_template(void) {
347         const StrBuf *MimeType;
348         const StrBuf *Tmpl = sbstr("template");
349         begin_burst();
350         MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
351         http_transmit_thing(ChrPtr(MimeType), 0);
352 }
353
354
355
356 /*
357  * convenience function to indicate success
358  */
359 void display_success(char *successmessage)
360 {
361         convenience_page("007700", "OK", successmessage);
362 }
363
364
365 /*
366  * Authorization required page 
367  * This is probably temporary and should be revisited 
368  */
369 void authorization_required(void)
370 {
371         wcsession *WCC = WC;
372         const char *message = "";
373
374         hprintf("HTTP/1.1 401 Authorization Required\r\n");
375         hprintf(
376                 "Server: %s / %s\r\n"
377                 "Connection: close\r\n",
378                 PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
379         );
380         hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
381         hprintf("Content-Type: text/html\r\n");
382         begin_burst();
383         wprintf("<h1>");
384         wprintf(_("Authorization Required"));
385         wprintf("</h1>\r\n");
386         
387
388         if (WCC->ImportantMsg != NULL)
389                 message = ChrPtr(WCC->ImportantMsg);
390         else if (WCC->ImportantMessage != NULL)
391                 message = WCC->ImportantMessage;
392
393         wprintf(_("The resource you requested requires a valid username and password. "
394                 "You could not be logged in: %s\n"), message);
395         wDumpContent(0);
396         end_webcit_session();
397 }
398
399 /*
400  * Convenience functions to wrap around asynchronous ajax responses
401  */
402 void begin_ajax_response(void) {
403         wcsession *WCC = WC;
404
405         FlushStrBuf(WCC->HBuf);
406         output_headers(0, 0, 0, 0, 0, 0);
407
408         hprintf("Content-type: text/html; charset=UTF-8\r\n"
409                 "Server: %s\r\n"
410                 "Connection: close\r\n"
411                 ,
412                 PACKAGE_STRING);
413         begin_burst();
414 }
415
416 /*
417  * print ajax response footer 
418  */
419 void end_ajax_response(void) {
420         wDumpContent(0);
421 }
422
423
424
425 /*
426  * Wraps a Citadel server command in an AJAX transaction.
427  */
428 void ajax_servcmd(void)
429 {
430         wcsession *WCC = WC;
431         int Done = 0;
432         StrBuf *Buf;
433         char *junk;
434         size_t len;
435
436         begin_ajax_response();
437         Buf = NewStrBuf();
438         serv_puts(bstr("g_cmd"));
439         StrBuf_ServGetln(Buf);
440         StrBufAppendBuf(WCC->WBuf, Buf, 0);
441         StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
442         
443         switch (GetServerStatus(Buf, NULL)) {
444         case 8:
445                 serv_puts("\n\n000");
446                 if ( (StrLength(Buf)==3) && 
447                      !strcmp(ChrPtr(Buf), "000")) {
448                         StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
449                         break;
450                 }
451         case 1:
452                 while (!Done) {
453                         StrBuf_ServGetln(Buf);
454                         if ( (StrLength(Buf)==3) && 
455                              !strcmp(ChrPtr(Buf), "000")) {
456                                 Done = 1;
457                         }
458                         StrBufAppendBuf(WCC->WBuf, Buf, 0);
459                         StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
460                 }
461                 break;
462         case 4:
463                 text_to_server(bstr("g_input"));
464                 serv_puts("000");
465                 break;
466         case 6:
467                 len = atol(&ChrPtr(Buf)[4]);
468                 StrBuf_ServGetBLOBBuffered(Buf, len);
469                 break;
470         case 7:
471                 len = atol(&ChrPtr(Buf)[4]);
472                 junk = malloc(len);
473                 memset(junk, 0, len);
474                 serv_write(junk, len);
475                 free(junk);
476         }
477         
478         end_ajax_response();
479         
480         /*
481          * This is kind of an ugly hack, but this is the only place it can go.
482          * If the command was GEXP, then the instant messenger window must be
483          * running, so reset the "last_pager_check" watchdog timer so
484          * that page_popup() doesn't try to open it a second time.
485          */
486         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
487                 WCC->last_pager_check = time(NULL);
488         }
489         FreeStrBuf(&Buf);
490 }
491
492
493 /*
494  * Helper function for the asynchronous check to see if we need
495  * to open the instant messenger window.
496  */
497 void seconds_since_last_gexp(void)
498 {
499         char buf[256];
500
501         if ( (time(NULL) - WC->last_pager_check) < 30) {
502                 wprintf("NO\n");
503         }
504         else {
505                 memset(buf, 0, 5);
506                 serv_puts("NOOP");
507                 serv_getln(buf, sizeof buf);
508                 if (buf[3] == '*') {
509                         wprintf("YES");
510                 }
511                 else {
512                         wprintf("NO");
513                 }
514         }
515 }
516
517
518
519 void ReadPostData(void)
520 {
521         const char *content_end = NULL;
522         int body_start = 0;
523         wcsession *WCC = WC;
524         StrBuf *content = NULL;
525         
526         content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
527
528         StrBufPrintf(content, 
529                      "Content-type: %s\n"
530                      "Content-length: %ld\n\n",
531                      ChrPtr(WCC->Hdr->HR.ContentType), 
532                              WCC->Hdr->HR.ContentLength);
533 /*
534   hprintf("Content-type: %s\n"
535   "Content-length: %d\n\n",
536   ContentType, ContentLength);
537 */
538         body_start = StrLength(content);
539
540         /** Read the entire input data at once. */
541         client_read_to(WCC->Hdr, content, 
542                        WCC->Hdr->HR.ContentLength,
543                        SLEEPING);
544         
545         if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33)) {
546                 StrBufCutLeft(content, body_start);
547                 ParseURLParams(content);
548         } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
549                 content_end = ChrPtr(content) + 
550                         WCC->Hdr->HR.ContentLength + 
551                         body_start;
552                 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
553         } else if (WCC->Hdr->HR.ContentLength > 0) {
554                 WCC->upload = content;
555                 content = NULL;
556         }
557         FreeStrBuf(&content);
558 }
559
560
561 /*
562  * Entry point for WebCit transaction
563  */
564 void session_loop(void)
565 {
566         int Flags = 0;
567         int xhttp;
568         StrBuf *Buf;
569         
570         /*
571          * We stuff these with the values coming from the client cookies,
572          * so we can use them to reconnect a timed out session if we have to.
573          */
574         wcsession *WCC;
575
576         
577         Buf = NewStrBuf();
578
579         WCC= WC;
580
581         WCC->upload_length = 0;
582         WCC->upload = NULL;
583         WCC->is_mobile = 0;
584         WCC->trailing_javascript = NewStrBuf();
585         WCC->Hdr->nWildfireHeaders = 0;
586         if (WCC->Hdr->HR.Handler != NULL)
587                 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
588
589         if (WCC->Hdr->HR.ContentLength > 0) {
590                 ReadPostData();
591         }
592
593         /* If there are variables in the URL, we must grab them now */
594         if (WCC->Hdr->PlainArgs != NULL)
595                 ParseURLParams(WCC->Hdr->PlainArgs);
596
597         /* If the client sent a nonce that is incorrect, kill the request. */
598         if (havebstr("nonce")) {
599                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
600                         bstr("nonce"), WCC->nonce);
601                 if (ibstr("nonce") != WCC->nonce) {
602                         lprintf(9, "Ignoring request with mismatched nonce.\n");
603                         hprintf("HTTP/1.1 404 Security check failed\r\n");
604                         hprintf("Content-Type: text/plain\r\n\r\n");
605                         begin_burst();
606                         wprintf("Security check failed.\r\n");
607                         end_burst();
608                         goto SKIP_ALL_THIS_CRAP;
609                 }
610         }
611
612         /*
613          * If we're not connected to a Citadel server, try to hook up the
614          * connection now.
615          */
616         if (!WCC->connected) {
617                 if (GetConnected ())
618                         goto SKIP_ALL_THIS_CRAP;
619         }
620
621
622         /*
623          * If we're not logged in, but we have authentication data (either from
624          * a cookie or from http-auth), try logging in to Citadel using that.
625          */
626         if ((!WCC->logged_in)
627             && (StrLength(WCC->Hdr->c_username) > 0)
628             && (StrLength(WCC->Hdr->c_password) > 0))
629         {
630                 FlushStrBuf(Buf);
631                 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
632                 StrBuf_ServGetln(Buf);
633                 if (GetServerStatus(Buf, NULL) == 3) {
634                         serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
635                         StrBuf_ServGetln(Buf);
636                         if (GetServerStatus(Buf, NULL) == 2) {
637                                 become_logged_in(WCC->Hdr->c_username,
638                                                  WCC->Hdr->c_password, Buf);
639                         } else {
640                                 /* Should only display when password is wrong */
641                                 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
642                                 authorization_required();
643                                 FreeStrBuf(&Buf);
644                                 goto SKIP_ALL_THIS_CRAP;
645                         }
646                 }
647         }
648
649         xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
650                 (WCC->Hdr->HR.eReqType != ePOST) &&
651                 (WCC->Hdr->HR.eReqType != eHEAD);
652
653         /*
654          * If a 'gotofirst' parameter has been specified, attempt to goto that room
655          * prior to doing anything else.
656          */
657         if (havebstr("gotofirst")) {
658                 int ret;
659                 ret = gotoroom(sbstr("gotofirst"));     /* do quietly to avoid session output! */
660                 if ((ret/100) != 2) {
661                         lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
662                                 bstr("gotofirst"), ret);
663                 }
664         }
665
666         /*
667          * If we aren't in any room yet, but we have cookie data telling us where we're
668          * supposed to be, and 'gotofirst' was not specified, then go there.
669          */
670         else if ( (StrLength(WCC->wc_roomname) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
671                 int ret;
672
673                 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
674                         ChrPtr(WCC->wc_roomname),
675                         ChrPtr(WCC->Hdr->c_roomname)
676                 );
677                 ret = gotoroom(WCC->Hdr->c_roomname);   /* do quietly to avoid session output! */
678                 if ((ret/100) != 2) {
679                         lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
680                                 ChrPtr(WCC->Hdr->c_roomname), ret);
681                 }
682         }
683
684         if (WCC->Hdr->HR.Handler != NULL) {
685                 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
686                         display_login(NULL);
687                 }
688                 else {
689                         if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
690                                 begin_ajax_response();
691                         WCC->Hdr->HR.Handler->F();
692                         if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
693                                 end_ajax_response();
694                 }
695         }
696         /* When all else fais, display the main menu. */
697         else {
698                 /* 
699                  * ordinary browser users get a nice login screen, DAV etc. requsets
700                  * are given a 401 so they can handle it appropriate.
701                  */
702                 if (!WCC->logged_in)  {
703                         if (xhttp)
704                                 authorization_required();
705                         else 
706                                 display_login(NULL);
707                 }
708                 /*
709                  * Toplevel dav requests? or just a flat browser request? 
710                  */
711                 else {
712                         if (xhttp)
713                                 groupdav_main();
714                         else
715                                 display_main_menu();
716                 }
717         }
718
719 SKIP_ALL_THIS_CRAP:
720         FreeStrBuf(&Buf);
721         fflush(stdout);
722 }
723
724
725 /*
726  * Replacement for sleep() that uses select() in order to avoid SIGALRM
727  */
728 void sleeeeeeeeeep(int seconds)
729 {
730         struct timeval tv;
731
732         tv.tv_sec = seconds;
733         tv.tv_usec = 0;
734         select(0, NULL, NULL, NULL, &tv);
735 }
736
737
738 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
739 {
740         wcsession *WCC = WC;
741         if (WCC != NULL)
742                 return ((!IsEmptyStr(WCC->ImportantMessage)) || 
743                         (StrLength(WCC->ImportantMsg) > 0));
744         else
745                 return 0;
746 }
747
748 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
749 {
750         wcsession *WCC = WC;
751         
752         if (WCC != NULL) {
753                 if (!IsEmptyStr(WCC->ImportantMessage)) {
754                         StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
755                         WCC->ImportantMessage[0] = '\0';
756                 }
757                 else if (StrLength(WCC->ImportantMsg) > 0) {
758                         StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
759                         FlushStrBuf(WCC->ImportantMsg);
760                 }
761         }
762 }
763
764 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
765 {
766         wcsession *WCC = WC;
767
768         if (WCC != NULL)
769                 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
770 }
771
772 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
773 {
774         StrBufAppendBuf(Target, 
775                         csslocal, 0);
776 }
777
778 extern char static_local_dir[PATH_MAX];
779
780
781 void 
782 InitModule_WEBCIT
783 (void)
784 {
785         char dir[SIZ];
786         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
787         WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
788         WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX|LOGCHATTY);
789         WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
790         WebcitAddUrlHandler(HKEY("webcit"), blank_page, URLNAMESPACE);
791
792         WebcitAddUrlHandler(HKEY("401"), authorization_required, ANONYMOUS|COOKIEUNNEEDED);
793         RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
794         RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
795         RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
796         RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
797
798         snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
799         if (!access(dir, R_OK)) {
800                 lprintf(9, "Using local Stylesheet [%s]\n", dir);
801                 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
802         }
803         else
804                 lprintf(9, "No Site-local Stylesheet [%s] installed. \n", dir);
805
806 }
807
808 void
809 ServerStartModule_WEBCIT
810 (void)
811 {
812         HandlerHash = NewHash(1, NULL);
813 }
814
815
816 void 
817 ServerShutdownModule_WEBCIT
818 (void)
819 {
820         FreeStrBuf(&csslocal);
821         DeleteHash(&HandlerHash);
822 }
823
824
825
826 void
827 SessionNewModule_WEBCIT
828 (wcsession *sess)
829 {
830         sess->ImportantMsg = NewStrBuf();
831         sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
832         sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
833 }
834
835 void
836 SessionDetachModule_WEBCIT
837 (wcsession *sess)
838 {
839         DeleteHash(&sess->Hdr->urlstrings);// TODO?
840         if (sess->upload_length > 0) {
841                 FreeStrBuf(&sess->upload);
842                 sess->upload_length = 0;
843         }
844         FreeStrBuf(&sess->trailing_javascript);
845
846         if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
847         {
848                 FreeStrBuf(&sess->WBuf);
849                 sess->WBuf = NewStrBuf();
850         }
851         else
852                 FlushStrBuf(sess->WBuf);
853         FlushStrBuf(sess->HBuf);
854 }
855
856 void 
857 SessionDestroyModule_WEBCIT
858 (wcsession *sess)
859 {
860         FreeStrBuf(&sess->WBuf);
861         FreeStrBuf(&sess->HBuf);
862         FreeStrBuf(&sess->ImportantMsg);
863 }
864