* rework login screen to utilize more modern templating
[citadel.git] / webcit / webcit.h
1
2 /* $Id$ */
3
4 #include "sysdep.h"
5
6
7 #include <sys/select.h>
8
9 #include <ctype.h>
10 #include <stdlib.h>
11 #ifdef HAVE_UNISTD_H
12 #include <unistd.h>
13 #endif
14 #include <stdio.h>
15 #ifdef HAVE_FCNTL_H
16 #include <fcntl.h>
17 #endif
18 #include <signal.h>
19 #include <sys/types.h>
20 #include <sys/wait.h>
21 #include <sys/socket.h>
22 #ifdef HAVE_SYS_TIME_H
23 #include <sys/time.h>
24 #endif
25 #include <sys/stat.h>
26 #ifdef HAVE_LIMITS_H
27 #include <limits.h>
28 #endif
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <sys/un.h>
32 #include <netdb.h>
33 #include <sys/poll.h>
34 #include <string.h>
35 #include <pwd.h>
36 #include <errno.h>
37 #include <stdarg.h>
38 #include <pthread.h>
39 #include <signal.h>
40 #include <sys/utsname.h>
41
42 #include <libcitadel.h>
43
44 #ifndef INADDR_NONE
45 #define INADDR_NONE 0xffffffff
46 #endif
47
48 #ifdef HAVE_ICONV
49 #include <iconv.h>
50 #endif
51
52 #ifdef ENABLE_NLS
53 #ifdef HAVE_XLOCALE_H
54 #include <xlocale.h>
55 #endif
56 #include <libintl.h>
57 #include <locale.h>
58 #ifdef HAVE_USELOCALE
59 extern locale_t wc_locales[];
60 #endif
61 #define _(string)       gettext(string)
62 #else
63 #define _(string)       (string)
64 #endif
65
66 #define IsEmptyStr(a) ((a)[0] == '\0')
67 /*
68  * Uncomment to dump an HTTP trace to stderr
69 #define HTTP_TRACING 1
70  */
71
72 #ifdef HTTP_TRACING
73 #undef HAVE_ZLIB_H
74 #undef HAVE_ZLIB
75 #endif
76
77 #ifdef HAVE_ZLIB_H
78 #include <zlib.h>
79 #endif
80
81 #include <libical/ical.h>
82
83 #undef PACKAGE
84 #undef VERSION
85 #undef PACKAGE_NAME
86 #undef PACKAGE_STRING
87 #undef PACKAGE_TARNAME
88 #undef PACKAGE_VERSION
89 #undef PACKAGE_BUGREPORT
90 #include "sysdep.h"
91
92 ////////#include "hash.h"
93
94 #ifdef HAVE_OPENSSL
95 /* Work around RedHat's b0rken OpenSSL includes */
96 #define OPENSSL_NO_KRB5
97 #include <openssl/ssl.h>
98 #include <openssl/err.h>
99 #include <openssl/rand.h>
100 #endif
101
102 #define CALENDAR_ROOM_NAME      "Calendar"
103 #define PRODID "-//Citadel//NONSGML Citadel Calendar//EN"
104
105 #define SIZ                     4096            /* generic buffer size */
106
107 #define TRACE fprintf(stderr, "Checkpoint: %s, %d\n", __FILE__, __LINE__)
108
109 #define SLEEPING                180             /* TCP connection timeout */
110 #define WEBCIT_TIMEOUT          900             /* WebCit session timeout */
111 #define PORT_NUM                2000            /* port number to listen on */
112 #define DEVELOPER_ID            0
113 #define CLIENT_ID               4
114 #define CLIENT_VERSION          739             /* This version of WebCit */
115 #define MINIMUM_CIT_VERSION     739             /* min required Citadel ver */
116 #define LIBCITADEL_MIN          739             /* min required libcitadel ver */
117 #define DEFAULT_HOST            "localhost"     /* Default Citadel server */
118 #define DEFAULT_PORT            "504"
119 #define TARGET                  "webcit01"      /* Target for inline URL's */
120 #define HOUSEKEEPING            15              /* Housekeeping frequency */
121 #define MIN_WORKER_THREADS      5
122 #define MAX_WORKER_THREADS      250
123 #define LISTEN_QUEUE_LENGTH     100             /* listen() backlog queue */
124
125 #define USERCONFIGROOM          "My Citadel Config"
126 #define DEFAULT_MAXMSGS         20
127
128
129 #ifdef LIBCITADEL_VERSION_NUMBER
130 #if LIBCITADEL_VERSION_NUMBER < LIBCITADEL_MIN
131 #error libcitadel is too old.  Please upgrade it before continuing.
132 #endif
133 #endif
134
135
136 /*
137  * Room flags (from Citadel)
138  *
139  * bucket one...
140  */
141 #define QR_PERMANENT    1               /* Room does not purge          */
142 #define QR_INUSE        2               /* Set if in use, clear if avail        */
143 #define QR_PRIVATE      4               /* Set for any type of private room     */
144 #define QR_PASSWORDED   8               /* Set if there's a password too        */
145 #define QR_GUESSNAME    16              /* Set if it's a guessname room */
146 #define QR_DIRECTORY    32              /* Directory room                       */
147 #define QR_UPLOAD       64              /* Allowed to upload                    */
148 #define QR_DOWNLOAD     128             /* Allowed to download          */
149 #define QR_VISDIR       256             /* Visible directory                    */
150 #define QR_ANONONLY     512             /* Anonymous-Only room          */
151 #define QR_ANONOPT      1024            /* Anonymous-Option room                */
152 #define QR_NETWORK      2048            /* Shared network room          */
153 #define QR_PREFONLY     4096            /* Preferred status needed to enter     */
154 #define QR_READONLY     8192            /* Aide status required to post */
155 #define QR_MAILBOX      16384           /* Set if this is a private mailbox     */
156
157 /*
158  * bucket two...
159  */
160 #define QR2_SYSTEM      1               /* System room; hide by default */
161 #define QR2_SELFLIST    2               /* Self-service mailing list mgmt       */
162 #define QR2_COLLABDEL   4               /* Anyone who can post can also delete*/
163 #define QR2_SUBJECTREQ  8               /* Subject strongly recommended */
164 #define QR2_SMTP_PUBLIC 16              /* smtp public postable room */
165 #define QR2_MODERATED   32              /* Listservice aide has to permit posts  */
166
167 /*
168  * user/room access
169  */
170 #define UA_KNOWN        2
171 #define UA_GOTOALLOWED  4
172 #define UA_HASNEWMSGS   8
173 #define UA_ZAPPED       16
174
175
176 /*
177  * User flags (from Citadel)
178  */
179 #define US_NEEDVALID    1               /* User needs to be validated           */
180 #define US_PERM         4               /* Permanent user                       */
181 #define US_LASTOLD      16              /* Print last old message with new      */
182 #define US_EXPERT       32              /* Experienced user                     */
183 #define US_UNLISTED     64              /* Unlisted userlog entry               */
184 #define US_NOPROMPT     128             /* Don't prompt after each message      */
185 #define US_PROMPTCTL    256             /* <N>ext & <S>top work at prompt       */
186 #define US_DISAPPEAR    512             /* Use "disappearing msg prompts"       */
187 #define US_REGIS        1024            /* Registered user                      */
188 #define US_PAGINATOR    2048            /* Pause after each screen of text      */
189 #define US_INTERNET     4096            /* Internet mail privileges             */
190 #define US_FLOORS       8192            /* User wants to see floors             */
191 #define US_COLOR        16384           /* User wants ANSI color support        */
192 #define US_USER_SET     (US_LASTOLD | US_EXPERT | US_UNLISTED | \
193                         US_NOPROMPT | US_DISAPPEAR | US_PAGINATOR | \
194                         US_FLOORS | US_COLOR | US_PROMPTCTL )
195
196 /*
197  * NLI is the string that shows up in a who's online listing for sessions
198  * that are active, but for which no user has yet authenticated.
199  */
200 #define NLI     "(not logged in)"
201
202
203 /*
204  * \brief       Linked list of session variables encoded in an x-www-urlencoded content type
205  */
206 typedef struct urlcontent urlcontent;
207 struct urlcontent {
208         char url_key[32];          /* the variable name */
209         StrBuf *url_data;            /* its value */
210 };
211
212 /*
213  * \brief information about us ???
214  */ 
215 struct serv_info {
216         int serv_pid;                   /* Process ID of the Citadel server */
217         char serv_nodename[32];         /* Node name of the Citadel server */
218         char serv_humannode[64];        /* human readable node name of the Citadel server */
219         char serv_fqdn[64];             /* fully quallified Domain Name (such as uncensored.citadel.org) */
220         char serv_software[64];         /* What version does our connected citadel server use */
221         int serv_rev_level;             /* Whats the citadel server revision */
222         char serv_bbs_city[64];         /* Geographic location of the Citadel server */
223         char serv_sysadm[64];           /* Name of system administrator */
224         char serv_moreprompt[256];      /* Whats the commandline textprompt */
225         int serv_ok_floors;             /* nonzero == server supports floors */
226         int serv_supports_ldap;         /* is the server linked against an ldap tree for adresses? */
227         int serv_newuser_disabled;      /* Has the server disabled self-service new user creation? */
228         char serv_default_cal_zone[128];/* Default timezone for unspecified calendar items */
229         int serv_supports_sieve;        /* Does the server support Sieve mail filtering? */
230         int serv_fulltext_enabled;      /* Does the server have the full text index enabled? */
231         char serv_svn_revision[256];    /* SVN revision of the server */
232         int serv_supports_openid;       /* Does the server support authentication via OpenID? */
233 };
234
235
236
237 /*
238  * \brief This struct holds a list of rooms for \\\<G\\\>oto operations.
239  */
240 struct march {
241         struct march *next;       /* pointer to next in linked list */
242         char march_name[128];     /* name of room */
243         int march_floor;          /* floor number of room */
244         int march_order;          /* sequence in which we are to visit this room */
245 };
246
247 /* *
248  * \brief       This struct holds a list of rooms for client display.
249  *              It is a binary tree.
250  */
251 struct roomlisting {
252         struct roomlisting *lnext;      /* pointer to 'left' tree node */
253         struct roomlisting *rnext;      /* pointer to 'right' tree node */
254         char rlname[128];               /* name of room */
255         unsigned rlflags;               /* room flags */
256         int rlfloor;                    /* the floor it resides on */
257         int rlorder;                    /* room listing order */
258 };
259
260
261 #define TYPE_STR   1
262 #define TYPE_LONG  2
263 #define TYPE_PREFSTR 3
264 #define TYPE_PREFINT 4
265 #define TYPE_GETTEXT 5
266 #define TYPE_BSTR 6
267 #define MAXPARAM  20
268
269
270 typedef struct _TemplateParam {
271         const char *Start;
272         int Type;
273         long len;
274         long lvalue;
275 } TemplateParam;
276
277 typedef struct _TemplateToken {
278         const StrBuf *FileName; /* Reference to print error messages; not to be freed */
279         StrBuf *FlatToken;
280         long Line;
281         const char *pTokenStart;
282         size_t TokenStart;
283         size_t TokenEnd;
284         const char *pTokenEnd;
285         int Flags;
286         void *PreEval;
287
288         const char *pName;
289         size_t NameEnd;
290
291         int HaveParameters;
292         int nParameters;
293         TemplateParam *Params[MAXPARAM];
294 } WCTemplateToken;
295
296 typedef void (*WCHandlerFunc)();
297
298
299 /*
300  * \brief Dynamic content for variable substitution in templates
301  */
302 typedef struct _wcsubst {
303         int wcs_type;                       /* which type of Substitution are we */
304         char wcs_key[32];                   /* copy of our hashkey for debugging */
305         StrBuf *wcs_value;                  /* if we're a string, keep it here */
306         long lvalue;                        /* type long? keep data here */
307         int ContextRequired;                /* do we require a context type? */
308         WCHandlerFunc wcs_function; /* funcion hook ???*/
309 } wcsubst;
310
311 #define CTX_NONE 0
312 #define CTX_SITECFG 1
313 #define CTX_SESSION 2
314 #define CTX_INETCFG 3
315 #define CTX_VNOTE 4
316 #define CTX_WHO 5
317 #define CTX_PREF 6
318 #define CTX_NODECONF 7
319 #define CTX_USERLIST 8
320 #define CTX_MAILSUM 9
321 #define CTX_MIME_ATACH 10
322 #define CTX_ATT 11
323 #define CTX_STRBUF 12
324
325 void RegisterNS(const char *NSName, long len, 
326                 int nMinArgs, 
327                 int nMaxArgs, 
328                 WCHandlerFunc HandlerFunc,
329                 int ContextRequired);
330 #define RegisterNamespace(a, b, c, d, e) RegisterNS(a, sizeof(a)-1, b, c, d, e)
331
332 typedef int (*WCConditionalFunc)(WCTemplateToken *Token, void *Context, int ContextType);
333 typedef struct _ConditionalStruct {
334         const char *PlainName;
335         int nParams;
336         int ContextRequired;
337         WCConditionalFunc CondF;
338 } ConditionalStruct;
339 void RegisterConditional(const char *Name, long len, 
340                          int nParams,
341                          WCConditionalFunc CondF, 
342                          int ContextRequired);
343
344
345
346 typedef void (*SubTemplFunc)(StrBuf *TemplBuffer, void *Context, WCTemplateToken *Token);
347 typedef HashList *(*RetrieveHashlistFunc)(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType);
348 typedef void (*HashDestructorFunc) (HashList **KillMe);
349 void RegisterITERATOR(const char *Name, long len, /* Our identifier */
350                       int AdditionalParams,       /* doe we use more parameters? */
351                       HashList *StaticList,       /* pointer to webcit lifetime hashlists */
352                       RetrieveHashlistFunc GetHash, /* else retrieve the hashlist by calling this function */
353                       SubTemplFunc DoSubTempl,       /* call this function on each iteration for svput & friends */
354                       HashDestructorFunc Destructor, /* use this function to shut down the hash; NULL if its a reference */
355                       int ContextType,               /* which context do we provide to the subtemplate? */
356                       int XPectContextType);         /* which context do we expct to be called in? */
357 #define RegisterIterator(a, b, c, d, e, f, g, h) RegisterITERATOR(a, sizeof(a)-1, b, c, d, e, f, g, h)
358
359 void GetTemplateTokenString(WCTemplateToken *Tokens,
360                             int N, 
361                             const char **Value, 
362                             long *len);
363
364
365 void SVPut(char *keyname, size_t keylen, int keytype, char *Data);
366 #define svput(a, b, c) SVPut(a, sizeof(a) - 1, b, c)
367 void SVPutLong(char *keyname, size_t keylen, long Data);
368 #define svputlong(a, b) SVPutLong(a, sizeof(a) - 1, b)
369 void svprintf(char *keyname, size_t keylen, int keytype, const char *format,...) __attribute__((__format__(__printf__,4,5)));
370 void SVPRINTF(char *keyname, int keytype, const char *format,...) __attribute__((__format__(__printf__,3,4)));
371 void SVCALLBACK(char *keyname, WCHandlerFunc fcn_ptr);
372 void SVCallback(char *keyname, size_t keylen,  WCHandlerFunc fcn_ptr);
373 #define svcallback(a, b) SVCallback(a, sizeof(a) - 1, b)
374
375 void SVPUTBuf(const char *keyname, int keylen, const StrBuf *Buf, int ref);
376 #define SVPutBuf(a, b, c); SVPUTBuf(a, sizeof(a) - 1, b, c)
377
378 void DoTemplate(const char *templatename, long len, StrBuf *Target, void *Context, int ContextType);
379 #define do_template(a, b) DoTemplate(a, sizeof(a) -1, NULL, b, 0);
380 void url_do_template(void);
381
382 int CompareSubstToToken(TemplateParam *ParamToCompare, TemplateParam *ParamToLookup);
383 int CompareSubstToStrBuf(StrBuf *Compare, TemplateParam *ParamToLookup);
384
385 void StrBufAppendTemplate(StrBuf *Target, 
386                           int nArgs, 
387                           WCTemplateToken *Tokens,
388                           void *Context, int ContextType,
389                           const StrBuf *Source, int FormatTypeIndex);
390
391
392
393 /*
394  * \brief Values for wcs_type
395  */
396 enum {
397         WCS_STRING,       /* its a string */
398         WCS_FUNCTION,     /* its a function callback */
399         WCS_SERVCMD,      /* its a command to send to the citadel server */
400         WCS_STRBUF,       /* its a strbuf we own */
401         WCS_STRBUF_REF,   /* its a strbuf we mustn't free */
402         WCS_LONG          /* its an integer */
403 };
404
405 /*
406  * \brief mail attachment ???
407  */
408 typedef struct _wc_attachment {
409         size_t length;                     /* length of the contenttype */
410         StrBuf *content_type;      /* the content itself ???*/
411         StrBuf *filename;                  /* the filename hooked to this content ??? */
412         char *data;                /* the data pool; aka this content */
413         long lvalue;               /* if we put a long... */
414 } wc_attachment;
415 void free_attachment(void *vattach);
416
417
418 typedef struct wc_mime_attachment wc_mime_attachment;
419 typedef void (*RenderMimeFunc)(wc_mime_attachment *Mime, StrBuf *RawData, StrBuf *FoundCharset);
420 struct wc_mime_attachment {
421         int level;
422         StrBuf *Name;
423         StrBuf *FileName;
424         StrBuf *PartNum;
425         StrBuf *Disposition;
426         StrBuf *ContentType;
427         StrBuf *Charset;
428         StrBuf *Data;
429         size_t length;                     /* length of the mimeatachment */
430         long size_known;
431         char content_type[SIZ];    /* the content itself ???*/
432         char filename[SIZ];                /* the filename hooked to this content ??? */
433         char *data;                /* the data pool; aka this content */
434         long lvalue;               /* if we put a long... */
435         long msgnum;            /**< the message number on the citadel server derived from message_summary */
436         RenderMimeFunc Renderer;
437 };
438 void DestroyMime(void *vMime);
439
440
441 /*
442  * \brief message summary structure. ???
443  */
444 typedef struct _message_summary {
445         time_t date;        /**< its creation date */
446         long msgnum;            /**< the message number on the citadel server */
447         int nhdr;
448         int format_type;
449         StrBuf *from;           /**< the author */
450         StrBuf *to;             /**< the recipient */
451         StrBuf *subj;           /**< the title / subject */
452         StrBuf *reply_inreplyto;
453         StrBuf *reply_references;
454         StrBuf *reply_to;
455         StrBuf *cccc;
456         StrBuf *hnod;
457         StrBuf *AllRcpt;
458         StrBuf *Room;
459         StrBuf *Rfca;
460         StrBuf *OtherNode;
461         const StrBuf *PartNum;
462
463         HashList *Attachments;  /**< list of Accachments */
464         HashList *Submessages;
465         HashList *AttachLinks;
466
467         HashList *AllAttach;
468
469         int is_new;         /**< is it yet read? */
470         int hasattachments;     /* does it have atachments? */
471
472
473         /** The mime part of the message */
474         wc_mime_attachment *MsgBody;
475 } message_summary;
476 void DestroyMessageSummary(void *vMsg);
477
478 typedef void (*ExamineMsgHeaderFunc)(message_summary *Msg, StrBuf *HdrLine, StrBuf *FoundCharset);
479
480 void evaluate_mime_part(message_summary *Msg, wc_mime_attachment *Mime);
481
482
483
484 /**
485  * \brief  Data structure for roomlist-to-folderlist conversion 
486  */
487 struct folder {
488         int floor;      /* which floor is it on */
489         char room[SIZ]; /* which roomname ??? */
490         char name[SIZ]; /* which is its own name??? */
491         int hasnewmsgs; /* are there unread messages inside */
492         int is_mailbox; /* is it a mailbox?  */
493         int selectable; /* can we select it ??? */
494         int view;       /* whats its default view? inbox/calendar.... */
495         int num_rooms;  /* If this is a floor, how many rooms does it have */
496 };
497
498 typedef struct _disp_cal {                                      
499         icalcomponent *cal;             /* cal items for display */
500         long cal_msgnum;                /* cal msgids for display */
501         char *from;                     /* owner of this component */
502         int unread;                     /* already seen by the user? */
503
504         time_t event_start;
505         time_t event_end;
506
507         int multi_day_event;
508         int is_repeat;
509 } disp_cal;                                             
510
511
512
513 /*
514  * Address book entry (keep it short and sweet, it's just a quickie lookup
515  * which we can use to get to the real meat and bones later)
516  */
517 typedef struct _addrbookent {
518         char ab_name[64]; /**< name string */
519         long ab_msgnum;   /**< message number of address book entry */
520 } addrbookent;
521
522
523 typedef struct _headereval {
524         ExamineMsgHeaderFunc evaluator;
525         int Type;
526 } headereval;
527
528
529 struct attach_link {
530         char partnum[32];
531         char html[1024];
532 };
533
534
535 enum {
536         eUp,
537         eDown,
538         eNone
539 };
540
541 /*
542  * One of these is kept for each active Citadel session.
543  * HTTP transactions are bound to one at a time.
544  */
545 struct wcsession {
546         struct wcsession *next;                 /**< Linked list */
547         int wc_session;                         /**< WebCit session ID */
548         char wc_username[128];                  /**< login name of current user */
549         char wc_fullname[128];                  /**< Screen name of current user */
550         char wc_password[128];                  /**< Password of current user */
551         char wc_roomname[256];                  /**< Room we are currently in */
552         int connected;                          /**< nonzero == we are connected to Citadel */
553         int logged_in;                          /**< nonzero == we are logged in  */
554         int axlevel;                            /**< this user's access level */
555         int is_aide;                            /**< nonzero == this user is an Aide */
556         int is_room_aide;                       /**< nonzero == this user is a Room Aide in this room */
557         int http_sock;                          /**< HTTP server socket */
558         int serv_sock;                          /**< Client socket to Citadel server */
559         int chat_sock;                          /**< Client socket to Citadel server - for chat */
560         unsigned room_flags;                    /**< flags associated with the current room */
561         unsigned room_flags2;                   /**< flags associated with the current room */
562         int wc_view;                            /**< view for the current room */
563         int wc_default_view;                    /**< default view for the current room */
564         int wc_is_trash;                        /**< nonzero == current room is a Trash folder */
565         int wc_floor;                           /**< floor number of current room */
566         char ugname[128];                       /**< where does 'ungoto' take us */
567         long uglsn;                             /**< last seen message number for ungoto */
568         int upload_length;                      /**< content length of http-uploaded data */
569         char *upload;                           /**< pointer to http-uploaded data */
570         char upload_filename[PATH_MAX];         /**< filename of http-uploaded data */
571         char upload_content_type[256];          /**< content type of http-uploaded data */
572         int new_mail;                           /**< user has new mail waiting */
573         int remember_new_mail;                  /**< last count of new mail messages */
574         int need_regi;                          /**< This user needs to register. */
575         int need_vali;                          /**< New users require validation. */
576         char cs_inet_email[256];                /**< User's preferred Internet addr. */
577         pthread_mutex_t SessionMutex;           /**< mutex for exclusive access */
578         time_t lastreq;                         /**< Timestamp of most recent HTTP */
579         int killthis;                           /**< Nonzero == purge this session */
580         struct march *march;                    /**< march mode room list */
581         char reply_to[512];                     /**< reply-to address */
582         long msgarr[10000];                     /**< for read operations */
583         HashList *summ;                         /**< list of messages for mailbox summary view */
584         int is_mobile;                  /**< Client is a handheld browser */
585         HashList *urlstrings;                   /**< variables passed to webcit in a URL */
586         HashList *vars;                         /**< HTTP variable substitutions for this page */
587         char this_page[512];                    /**< URL of current page */
588         char http_host[512];                    /**< HTTP Host: header */
589         HashList *hash_prefs;                   /**< WebCit preferences for this user */
590         HashList *disp_cal_items;               /**< sorted list of calendar items; startdate is the sort criteria. */
591         HashList *attachments;                  /**< list of attachments for 'enter message' */
592         char last_chat_user[256];               /**< ??? todo */
593         char ImportantMessage[SIZ];             /**< ??? todo */
594         int ctdl_pid;                           /**< Session ID on the Citadel server */
595         char httpauth_user[256];                /**< only for GroupDAV sessions */
596         char httpauth_pass[256];                /**< only for GroupDAV sessions */
597         int gzip_ok;                            /**< Nonzero if Accept-encoding: gzip */
598         int is_mailbox;                         /**< the current room is a private mailbox */
599         struct folder *cache_fold;              /**< cache the iconbar room list */
600         int cache_max_folders;                  /**< ??? todo */
601         int cache_num_floors;                   /**< ??? todo */
602         time_t cache_timestamp;                 /**< ??? todo */
603         HashList *IconBarSetttings;             /**< which icons should be shown / not shown? */
604         long current_iconbar;                   /**< What is currently in the iconbar? */
605         const StrBuf *floordiv_expanded;        /**< which floordiv currently expanded */
606         int selected_language;                  /**< Language selected by user */
607         time_t last_pager_check;                /**< last time we polled for instant msgs */
608         int nonce;                              /**< session nonce (to prevent session riding) */
609         int time_format_cache;                  /**< which timeformat does our user like? */
610         StrBuf *UrlFragment1;                   /**< first urlfragment, if NEED_URL is specified by the handler*/
611         StrBuf *UrlFragment2;                   /**< second urlfragment, if NEED_URL is specified by the handler*/
612         StrBuf *WBuf;                           /**< Our output buffer */
613         StrBuf *HBuf;                           /**< Our HeaderBuffer */
614         StrBuf *CLineBuf;                       /**< linebuffering client stuff */
615         StrBuf *DefaultCharset;                 /**< Charset the user preferes */
616         HashList *ServCfg;                      /**< cache our server config for editing */
617         HashList *InetCfg;                      /**< Our inet server config for editing */
618
619         StrBuf *trailing_javascript;            /**< extra javascript to be appended to page */
620 };
621
622 /* values for WC->current_iconbar */
623 enum {
624         current_iconbar_menu,     /* view the icon menue */
625         current_iconbar_roomlist  /* view the roomtree */
626 };
627 enum {
628         S_SELECT,
629         S_SHUTDOWN,
630         MAX_SEMAPHORES
631 };
632
633
634 /*
635  * calview contains data passed back and forth between the message fetching loop
636  * and the calendar view renderer.
637  */
638 enum {
639         calview_month,
640         calview_day,
641         calview_week,
642         calview_brief
643 };
644
645 struct calview {
646         int view;
647         int year;
648         int month;
649         int day;
650         time_t lower_bound;
651         time_t upper_bound;
652 };
653
654 #ifndef num_parms
655 #define num_parms(source)               num_tokens(source, '|') 
656 #endif
657
658 /* Per-session data */
659 #define WC ((struct wcsession *)pthread_getspecific(MyConKey))
660 extern pthread_key_t MyConKey;
661
662 /* Per-thread SSL context */
663 #ifdef HAVE_OPENSSL
664 #define THREADSSL ((SSL *)pthread_getspecific(ThreadSSL))
665 extern pthread_key_t ThreadSSL;
666 extern char ctdl_key_dir[PATH_MAX];
667 extern char file_crpt_file_key[PATH_MAX];
668 extern char file_crpt_file_csr[PATH_MAX];
669 extern char file_crpt_file_cer[PATH_MAX];
670 #endif
671
672 struct serv_info serv_info;
673 extern char floorlist[128][SIZ];
674 extern char *axdefs[];
675 extern char *ctdlhost, *ctdlport;
676 extern int http_port;
677 extern char *server_cookie;
678 extern int is_https;
679 extern int setup_wizard;
680 extern char wizard_filename[];
681 extern time_t if_modified_since;
682 extern int follow_xff;
683 extern HashList *HandlerHash;
684 extern HashList *PreferenceHooks;
685 extern HashList *WirelessTemplateCache;
686 extern HashList *WirelessLocalTemplateCache;
687 extern HashList *TemplateCache;
688 extern HashList *LocalTemplateCache;
689 extern HashList *GlobalNS;
690 extern HashList *Iterators;
691 extern HashList *ZoneHash;
692 extern HashList *Conditionals;
693 extern HashList *MsgHeaderHandler;
694 extern HashList *MimeRenderHandler;
695
696 void InitialiseSemaphores(void);
697 void begin_critical_section(int which_one);
698 void end_critical_section(int which_one);
699
700
701 void stuff_to_cookie(char *cookie, size_t clen, int session,
702                         char *user, char *pass, char *room);
703 void cookie_to_stuff(StrBuf *cookie, int *session,
704                 char *user, size_t user_len,
705                 char *pass, size_t pass_len,
706                 char *room, size_t room_len);
707 void locate_host(char *, int);
708 void become_logged_in(char *, char *, char *);
709 void openid_manual_create(void);
710 void display_login();
711 void display_openids(void);
712 void do_welcome(void);
713 void do_logout(void);
714 void display_main_menu(void);
715 void display_aide_menu(void);
716 void display_advanced_menu(void);
717 void slrp_highest(void);
718 void get_serv_info(char *, char *);
719 int uds_connectsock(char *);
720 int tcp_connectsock(char *, char *);
721 int serv_getln(char *strbuf, int bufsize);
722 int StrBuf_ServGetln(StrBuf *buf);
723 int GetServerStatus(StrBuf *Line, long* FullState);
724 void serv_puts(const char *string);
725 void who(void);
726 void who_inner_div(void);
727 void ajax_mini_calendar(void);
728 void fmout(char *align);
729 void _fmout(StrBuf *Targt, char *align);
730 void FmOut(StrBuf *Target, char *align, StrBuf *Source);
731 void pullquote_fmout(void);
732 void wDumpContent(int);
733
734 int Flathash(const char *str, long len);
735
736
737 /* These may return NULL if not foud */
738 #define sbstr(a) SBstr(a, sizeof(a) - 1)
739 const StrBuf *SBSTR(const char *key);
740 const StrBuf *SBstr(const char *key, size_t keylen);
741
742 #define xbstr(a, b) (char*) XBstr(a, sizeof(a) - 1, b)
743 const char *XBstr(const char *key, size_t keylen, size_t *len);
744 const char *XBSTR(const char *key, size_t *len);
745
746 #define lbstr(a) LBstr(a, sizeof(a) - 1)
747 long LBstr(const char *key, size_t keylen);
748 long LBSTR(const char *key);
749
750 #define ibstr(a) IBstr(a, sizeof(a) - 1)
751 int IBstr(const char *key, size_t keylen);
752 int IBSTR(const char *key);
753
754 #define havebstr(a) HaveBstr(a, sizeof(a) - 1)
755 int HaveBstr(const char *key, size_t keylen);
756 int HAVEBSTR(const char *key);
757
758 #define yesbstr(a) YesBstr(a, sizeof(a) - 1)
759 int YesBstr(const char *key, size_t keylen);
760 int YESBSTR(const char *key);
761
762 /* TODO: get rid of the non-const-typecast */
763 #define bstr(a) (char*) Bstr(a, sizeof(a) - 1)
764 const char *BSTR(const char *key);
765 const char *Bstr(const char *key, size_t keylen);
766
767
768
769 void UrlescPutStrBuf(const StrBuf *strbuf);
770 void StrEscPuts(const StrBuf *strbuf);
771 void StrEscputs1(const StrBuf *strbuf, int nbsp, int nolinebreaks);
772
773 void urlescputs(const char *);
774 void hurlescputs(const char *);
775 void jsesc(char *, size_t, char *);
776 void jsescputs(char *);
777 void output_headers(    int do_httpheaders,
778                         int do_htmlhead,
779                         int do_room_banner,
780                         int unset_cookies,
781                         int suppress_check,
782                         int cache);
783 void wprintf(const char *format,...)__attribute__((__format__(__printf__,1,2)));
784 void hprintf(const char *format,...)__attribute__((__format__(__printf__,1,2)));
785 void output_static(char *what);
786 void display_mime_icon(void);
787 void print_menu_box(char* Title, char *Class, int nLines, ...);
788 long stresc(char *target, long tSize, char *strbuf, int nbsp, int nolinebreaks);
789 void escputs(char *strbuf);
790 void url(char *buf, size_t bufsize);
791 void UrlizeText(StrBuf* Target, StrBuf *Source, StrBuf *WrkBuf);
792 void escputs1(char *strbuf, int nbsp, int nolinebreaks);
793 void msgesc(char *target, size_t tlen, char *strbuf);
794 void msgescputs(char *strbuf);
795 void msgescputs1(char *strbuf);
796 void stripout(char *str, char leftboundary, char rightboundary);
797 void dump_vars(void);
798 void embed_main_menu(void);
799 void serv_read(char *buf, int bytes);
800 void readloop(char *oper);
801 int  read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, int printable_view, const StrBuf *section);
802 void do_addrbook_view(addrbookent *addrbook, int num_ab);
803 void display_vcard(StrBuf *Target, const char *vcard_source, char alpha, int full, char *storename, long msgnum);
804 void text_to_server(char *ptr);
805 void text_to_server_qp(char *ptr);
806 void confirm_delete_msg(void);
807 void display_success(char *);
808 void authorization_required(const char *message);
809 void server_to_text(void);
810 void save_edit(char *description, char *enter_cmd, int regoto);
811 void display_edit(char *description, char *check_cmd,
812                   char *read_cmd, char *save_cmd, int with_room_banner);
813 int gotoroom(char *gname);
814 void confirm_delete_room(void);
815 void validate(void);
816 void display_graphics_upload(char *, char *, char *);
817 void do_graphics_upload(char *upl_cmd);
818 void serv_read(char *buf, int bytes);
819 void serv_gets(char *strbuf);
820 void serv_write(const char *buf, int nbytes);
821 void serv_puts(const char *string);
822 void serv_putbuf(const StrBuf *string);
823 void serv_printf(const char *format,...)__attribute__((__format__(__printf__,1,2)));
824 void load_floorlist(void);
825 void shutdown_sessions(void);
826 void do_housekeeping(void);
827 void smart_goto(char *);
828 void worker_entry(void);
829 void session_loop(HashList *HTTPHeaders, StrBuf *ReqLine, StrBuf *ReqType, StrBuf *ReadBuf);
830 size_t wc_strftime(char *s, size_t max, const char *format, const struct tm *tm);
831 void fmt_time(char *buf, time_t thetime);
832 void httpdate(char *buf, time_t thetime);
833 time_t httpdate_to_timestamp(StrBuf *buf);
834 void end_webcit_session(void);
835 void page_popup(void);
836 void http_redirect(const char *);
837 void clear_substs(struct wcsession *wc);
838 void clear_local_substs(void);
839
840
841
842 int lingering_close(int fd);
843 char *memreadline(char *start, char *buf, int maxlen);
844 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen);
845 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen);
846 void remove_token(char *source, int parmnum, char separator);
847 char *load_mimepart(long msgnum, char *partnum);
848 void MimeLoadData(wc_mime_attachment *Mime);
849 int pattern2(char *search, char *patn);
850 void do_edit_vcard(long, char *, char *, char *);
851 void striplt(char *);
852 void stripltlen(char *, int *);
853 void select_user_to_edit(char *message, char *preselect);
854 void delete_user(char *);
855 void do_change_view(int);
856 void folders(void);
857
858
859 void load_preferences(void);
860 void save_preferences(void);
861 #define get_preference(a, b) get_PREFERENCE(a, sizeof(a) - 1, b)
862 #define get_pref(a, b)       get_PREFERENCE(ChrPtr(a), StrLength(a), b)
863 int get_PREFERENCE(const char *key, size_t keylen, StrBuf **value);
864 #define set_preference(a, b, c) set_PREFERENCE(a, sizeof(a) - 1, b, c)
865 #define set_pref(a, b, c)       set_PREFERENCE(ChrPtr(a), StrLength(a), b, c)
866 void set_PREFERENCE(const char *key, size_t keylen, StrBuf *value, int save_to_server);
867
868 #define get_pref_long(a, b, c) get_PREF_LONG(a, sizeof(a) - 1, b, c)
869 int get_PREF_LONG(const char *key, size_t keylen, long *value, long Default);
870 #define set_pref_long(a, b, c) set_PREF_LONG(a, sizeof(a) - 1, b, c)
871 void set_PREF_LONG(const char *key, size_t keylen, long value, int save_to_server);
872
873 #define get_pref_yesno(a, b, c) get_PREF_YESNO(a, sizeof(a) - 1, b, c)
874 int get_PREF_YESNO(const char *key, size_t keylen, int *value, int Default);
875 #define set_pref_yesno(a, b, c) set_PREF_YESNO(a, sizeof(a) - 1, b, c)
876 void set_PREF_YESNO(const char *key, size_t keylen, int value, int save_to_server);
877
878 #define get_room_pref(a) get_ROOM_PREFS(a, sizeof(a) - 1)
879 StrBuf *get_ROOM_PREFS(const char *key, size_t keylen);
880
881 #define set_room_pref(a, b, c) set_ROOM_PREFS(a, sizeof(a) - 1, b, c)
882 void set_ROOM_PREFS(const char *key, size_t keylen, StrBuf *value, int save_to_server);
883
884 int is_msg_in_mset(char *mset, long msgnum);
885 void display_addressbook(long msgnum, char alpha);
886 void offer_start_page(StrBuf *Target, int nArgs, WCTemplateToken *Token, void *Context, int ContextType);
887 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext);
888 void output_html(const char *, int, int, StrBuf *, StrBuf *);
889 void do_listsub(void);
890 void toggle_self_service(void);
891 ssize_t write(int fd, const void *buf, size_t count);
892 void cal_process_attachment(wc_mime_attachment *Mime);
893 void load_calendar_item(message_summary *Msg, int unread, struct calview *c);
894 void display_calendar(message_summary *Msg, int unread);
895 void display_task(message_summary *Msg, int unread);
896 void display_note(message_summary *Msg, int unread);
897 void updatenote(void);
898 void parse_calendar_view_request(struct calview *c);
899 void render_calendar_view(struct calview *c);
900 void do_tasks_view(void);
901 void calendar_summary_view(void);
902 int load_msg_ptrs(char *servcmd, int with_headers);
903 void free_attachments(struct wcsession *sess);
904 void free_march_list(struct wcsession *wcf);
905 void display_rules_editor_inner_div(void);
906 void generate_uuid(char *);
907 void CtdlMakeTempFileName(char *, int);
908 void address_book_popup(void);
909 void begin_ajax_response(void);
910 void end_ajax_response(void);
911 void initialize_viewdefs(void);
912 void initialize_axdefs(void);
913 void burn_folder_cache(time_t age);
914 void list_all_rooms_by_floor(const char *viewpref);
915 void display_pictureview(void);
916
917 void display_edit_task(void);
918 void display_edit_event(void);
919 icaltimezone *get_default_icaltimezone(void);
920 void display_icaltimetype_as_webform(struct icaltimetype *, char *, int);
921 void icaltime_from_webform(struct icaltimetype *result, char *prefix);
922 void icaltime_from_webform_dateonly(struct icaltimetype *result, char *prefix);
923 void display_edit_individual_event(icalcomponent *supplied_vtodo, long msgnum, char *from,
924         int unread, struct calview *calv);
925 void save_individual_event(icalcomponent *supplied_vtodo, long msgnum, char *from,
926         int unread, struct calview *calv);
927 void ical_dezonify(icalcomponent *cal);
928 void partstat_as_string(char *buf, icalproperty *attendee);
929 icalcomponent *ical_encapsulate_subcomponent(icalcomponent *subcomp);
930 void check_attendee_availability(icalcomponent *supplied_vevent);
931 void do_freebusy(const char *req);
932 int ical_ctdl_is_overlap(
933                         struct icaltimetype t1start,
934                         struct icaltimetype t1end,
935                         struct icaltimetype t2start,
936                         struct icaltimetype t2end
937 );
938
939 #ifdef ENABLE_NLS
940 void initialize_locales(void);
941 void ShutdownLocale(void);
942 #endif
943 void TmplGettext(StrBuf *Target, int nTokens, WCTemplateToken *Token);
944
945 extern char *months[];
946 extern char *days[];
947 int read_server_binary(StrBuf *Ret, size_t total_len);
948 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize);
949 int read_server_text(StrBuf *Buf, long *nLines);;
950 int goto_config_room(void);
951 long locate_user_vcard(char *username, long usernum);
952 void sleeeeeeeeeep(int);
953 void http_transmit_thing(const char *content_type, int is_static);
954 long unescape_input(char *buf);
955 void do_selected_iconbar(void);
956 void spawn_another_worker_thread(void);
957 void display_rss(char *roomname, StrBuf *request_method);
958 void offer_languages(StrBuf *Target, int nArgs, WCTemplateToken *Token, void *Context, int ContextType);
959 void set_selected_language(const char *);
960 void go_selected_language(void);
961 void stop_selected_language(void);
962 void preset_locale(void);
963 void httplang_to_locale(StrBuf *LocaleString);
964 void StrEndTab(StrBuf *Target, int tabnum, int num_tabs);
965 void StrBeginTab(StrBuf *Target, int tabnum, int num_tabs);
966 void StrTabbedDialog(StrBuf *Target, int num_tabs, StrBuf *tabnames[]);
967 void tabbed_dialog(int num_tabs, char *tabnames[]);
968 void begin_tab(int tabnum, int num_tabs);
969 void end_tab(int tabnum, int num_tabs);
970 void str_wiki_index(char *s);
971 int get_time_format_cached (void);
972 int xtoi(const char *in, size_t len);
973 const char *get_selected_language(void);
974 void webcit_fmt_date(char *buf, time_t thetime, int brief);
975 int fetch_http(char *url, char *target_buf, int maxbytes);
976
977 int is_mobile_ua(char *user_agent);
978
979 void embed_room_banner(char *, int);
980
981 /* navbar types that can be passed to embed_room_banner */
982 enum {
983         navbar_none,
984         navbar_default
985 };
986
987
988 #ifdef HAVE_OPENSSL
989 void init_ssl(void);
990 void endtls(void);
991 void ssl_lock(int mode, int n, const char *file, int line);
992 int starttls(int sock);
993 extern SSL_CTX *ssl_ctx;  
994 int client_read_sslbuffer(StrBuf *buf, int timeout);
995 void client_write_ssl(const StrBuf *Buf);
996 #endif
997
998 #ifdef HAVE_ZLIB
999 #include <zlib.h>
1000 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
1001                           const Bytef * source, uLong sourceLen, int level);
1002 #endif
1003
1004 void utf8ify_rfc822_string(char *buf);
1005
1006 void begin_burst(void);
1007 long end_burst(void);
1008
1009 extern char *hourname[];        /* Names of hours (12am, 1am, etc.) */
1010
1011 void http_datestring(char *buf, size_t n, time_t xtime);
1012
1013
1014 typedef void (*WebcitHandlerFunc)(void);
1015 typedef struct  _WebcitHandler{
1016         WebcitHandlerFunc F;
1017         long Flags;
1018 } WebcitHandler;
1019 void WebcitAddUrlHandler(const char * UrlString, long UrlSLen, WebcitHandlerFunc F, long Flags);
1020
1021 #define AJAX (1<<0)
1022 #define ANONYMOUS (1<<1)
1023 #define NEED_URL (1<<2)
1024
1025
1026 /* These should be empty, but we have them for testing */
1027 #define DEFAULT_HTTPAUTH_USER   ""
1028 #define DEFAULT_HTTPAUTH_PASS   ""
1029
1030
1031 /* Exit codes 101 through 109 are initialization failures so we don't want to
1032  * just keep respawning indefinitely.
1033  */
1034 #define WC_EXIT_BIND            101     /* Can't bind to the port */
1035 #define WC_EXIT_SSL             102     /* Can't initialize SSL */
1036
1037
1038 #define WC_TIMEFORMAT_NONE 0
1039 #define WC_TIMEFORMAT_AMPM 1
1040 #define WC_TIMEFORMAT_24 2
1041
1042