* add function to shrink empty StrBufs so they don't permanently alloc unneeded sizes.
[citadel.git] / libcitadel / lib / libcitadel.h
1 /*
2  * $Id$
3  *
4  */
5
6
7 /* protect against double includes */
8 #ifndef LIBCITADEL_H
9 #define LIBCITADEL_H
10
11
12 /*
13  * since we reference time_t...
14  */
15 #include <time.h>
16 #include <stdlib.h>
17 #include <stdarg.h>
18 #define LIBCITADEL_VERSION_NUMBER       760
19
20 /*
21  * Here's a bunch of stupid magic to make the MIME parser portable.
22  */
23 #ifndef SIZ
24 #define SIZ     4096
25 #endif
26
27
28 /* Logging levels - correspond to syslog(3) */
29 enum LogLevel {
30         /* When about to exit the server for an unrecoverable error */
31          CTDL_EMERG,    /* system is unusable */
32         /* Manual intervention is required to avoid an abnormal exit */
33          CTDL_ALERT,    /* action must be taken immediately */
34         /* The server can continue to run with degraded functionality */
35          CTDL_CRIT,     /* critical conditions */
36         /* An error occurs but the server continues to run normally */
37          CTDL_ERR,      /* error conditions */
38         /* An abnormal condition was detected; server will continue normally */
39          CTDL_WARNING,  /* warning conditions */
40         /* Normal messages (login/out, activity, etc.) */
41          CTDL_NOTICE,   /* normal but significant condition */
42         /* Unimportant progress messages, etc. */
43          CTDL_INFO,     /* informational */
44         /* Debugging messages */
45          CTDL_DEBUG     /* debug-level messages */
46 };
47
48
49 /*
50  * View definitions.
51  * Note that not all views are implemented in all clients.
52  */
53 #define VIEW_BBS                0       /* Bulletin board view */
54 #define VIEW_MAILBOX            1       /* Mailbox summary */
55 #define VIEW_ADDRESSBOOK        2       /* Address book view */
56 #define VIEW_CALENDAR           3       /* Calendar view */
57 #define VIEW_TASKS              4       /* Tasks view */
58 #define VIEW_NOTES              5       /* Notes view */
59 #define VIEW_WIKI               6       /* Wiki view */
60 #define VIEW_CALBRIEF           7       /* Brief Calendar view */
61 #define VIEW_JOURNAL            8       /* Journal view */
62
63
64 #ifndef IsEmptyStr
65 #define IsEmptyStr(a) ((a)[0] == '\0')
66 #endif
67
68 /*
69  * Misc declarations
70  */
71
72 char *libcitadel_version_string(void);
73 int libcitadel_version_number(void);
74 void StartLibCitadel(size_t basesize);
75 void ShutDownLibCitadel(void);
76
77 /*
78  * MIME parser declarations
79  */
80
81 void extract_key(char *target, char *source, long sourcelen, char *key, long keylen);
82
83 void mime_parser(char *content_start, char *content_end,
84                 void (*CallBack)
85                         (char *cbname,
86                         char *cbfilename,
87                         char *cbpartnum,
88                         char *cbdisp,
89                         void *cbcontent,
90                         char *cbtype,
91                         char *cbcharset,
92                         size_t cblength,
93                         char *cbencoding,
94                         char *cbid,
95                         void *cbuserdata),
96                 void (*PreMultiPartCallBack)
97                         (char *cbname,
98                         char *cbfilename,
99                         char *cbpartnum,
100                         char *cbdisp,
101                         void *cbcontent,
102                         char *cbtype,
103                         char *cbcharset,
104                         size_t cblength,
105                         char *cbencoding,
106                         char *cbid,
107                         void *cbuserdata),
108                 void (*PostMultiPartCallBack)
109                         (char *cbname,
110                         char *cbfilename,
111                         char *cbpartnum,
112                         char *cbdisp,
113                         void *cbcontent,
114                         char *cbtype,
115                         char *cbcharset,
116                         size_t cblength,
117                         char *cbencoding,
118                         char *cbid,
119                         void *cbuserdata),
120                 void *userdata,
121                 int dont_decode
122 );
123
124
125
126 char *fixed_partnum(char *);
127 void mime_decode(char *partnum,
128                  char *part_start, size_t length,
129                  char *content_type, char *charset, char *encoding,
130                  char *disposition,
131                  char *id,
132                  char *name, char *filename,
133                  void (*CallBack)
134                   (char *cbname,
135                    char *cbfilename,
136                    char *cbpartnum,
137                    char *cbdisp,
138                    void *cbcontent,
139                    char *cbtype,
140                    char *cbcharset,
141                    size_t cblength,
142                    char *cbencoding,
143                    char *cbid,
144                    void *cbuserdata),
145                  void (*PreMultiPartCallBack)
146                   (char *cbname,
147                    char *cbfilename,
148                    char *cbpartnum,
149                    char *cbdisp,
150                    void *cbcontent,
151                    char *cbtype,
152                    char *cbcharset,
153                    size_t cblength,
154                    char *cbencoding,
155                    char *cbid,
156                    void *cbuserdata),
157                  void (*PostMultiPartCallBack)
158                   (char *cbname,
159                    char *cbfilename,
160                    char *cbpartnum,
161                    char *cbdisp,
162                    void *cbcontent,
163                    char *cbtype,
164                    char *cbcharset,
165                    size_t cblength,
166                    char *cbencoding,
167                    char *cbid,
168                    void *cbuserdata),
169                   void *userdata,
170                   int dont_decode
171 );
172 void the_mime_parser(char *partnum,
173                      char *content_start, char *content_end,
174                      void (*CallBack)
175                       (char *cbname,
176                        char *cbfilename,
177                        char *cbpartnum,
178                        char *cbdisp,
179                        void *cbcontent,
180                        char *cbtype,
181                        char *cbcharset,
182                        size_t cblength,
183                        char *cbencoding,
184                        char *cbid,
185                        void *cbuserdata),
186                      void (*PreMultiPartCallBack)
187                       (char *cbname,
188                        char *cbfilename,
189                        char *cbpartnum,
190                        char *cbdisp,
191                        void *cbcontent,
192                        char *cbtype,
193                        char *cbcharset,
194                        size_t cblength,
195                        char *cbencoding,
196                        char *cbid,
197                        void *cbuserdata),
198                      void (*PostMultiPartCallBack)
199                       (char *cbname,
200                        char *cbfilename,
201                        char *cbpartnum,
202                        char *cbdisp,
203                        void *cbcontent,
204                        char *cbtype,
205                        char *cbcharset,
206                        size_t cblength,
207                        char *cbencoding,
208                        char *cbid,
209                        void *cbuserdata),
210                       void *userdata,
211                       int dont_decode
212 );
213
214 typedef struct StrBuf StrBuf;
215
216 typedef struct _ConstStr {
217         const char *Key;
218         long len;
219 }ConstStr;
220
221
222 StrBuf* NewStrBuf(void);
223 StrBuf* NewStrBufDup(const StrBuf *CopyMe);
224 StrBuf* NewStrBufPlain(const char* ptr, int nChars);
225 long StrBufShrinkToFit(StrBuf *Buf, int Force);
226 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize);
227
228 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars);
229 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant);
230 #define NewConstStrBuf(a) _NewConstStrBuf(a, sizeof(a))
231 void FreeStrBuf (StrBuf **FreeMe);
232 void HFreeStrBuf (void *VFreeMe);
233 int FlushStrBuf(StrBuf *buf);
234 int FLUSHStrBuf(StrBuf *buf); /* expensive but doesn't leave content behind for others to find in case of errors */
235
236 const char *ChrPtr(const StrBuf *Str);
237 int StrLength(const StrBuf *Str);
238 #define SKEY(a) ChrPtr(a), StrLength(a)
239 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue);
240
241 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error);
242 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error);
243 #define NNN_TERM 1
244 #define O_TERM 0
245 int StrBufReadBLOBBuffered(StrBuf *Buf, 
246                            StrBuf *IOBuf, 
247                            const char **BufPos,
248                            int *fd, 
249                            int append, 
250                            long nBytes, 
251                            int check, 
252                            const char **Error);
253 int StrBufTCP_read_buffered_line(StrBuf *Line, 
254                                  StrBuf *buf, 
255                                  int *fd, 
256                                  int timeout, 
257                                  int selectresolution, 
258                                  const char **Error);
259 int StrBufTCP_read_buffered_line_fast(StrBuf *Line, 
260                                       StrBuf *buf, 
261                                       const char **Pos,
262                                       int *fd, 
263                                       int timeout, 
264                                       int selectresolution, 
265                                       const char **Error);
266
267 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr);
268 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator);
269 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars);
270
271 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator);
272 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator);
273 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator);
274 int StrBufNum_tokens(const StrBuf *source, char tok);
275 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator);
276
277 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator);
278 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens);
279 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator);
280 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator);
281 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator);
282
283
284 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset);
285 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset);
286 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...);
287 #ifdef SHOW_ME_VAPPEND_PRINTF
288 /* so owe don't create an include depndency, this is just visible on demand. */
289 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap);
290 #endif
291 void StrBufPrintf(StrBuf *Buf, const char *format, ...) __attribute__((__format__(__printf__,2,3)));
292 void StrBufCutLeft(StrBuf *Buf, int nChars);
293 void StrBufCutRight(StrBuf *Buf, int nChars);
294 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At);
295 void StrBufTrim(StrBuf *Buf);
296 void StrBufUpCase(StrBuf *Buf);
297 void StrBufLowerCase(StrBuf *Buf);
298 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source);
299 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source);
300
301 void StrBufReplaceChars(StrBuf *buf, char search, char replace);
302
303 int CompressBuffer(StrBuf *Buf);
304 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic);
305 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic);
306 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset);
307 int StrBufDecodeBase64(StrBuf *Buf);
308 int StrBufDecodeHex(StrBuf *Buf);
309 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source);
310 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute);
311 #define LB                      (1)             /* Internal escape chars */
312 #define RB                      (2)
313 #define QU                      (3)
314 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn);
315 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks);
316 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn);
317 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn);
318
319 long StrTol(const StrBuf *Buf);
320 int StrToi(const StrBuf *Buf);
321 int StrBufIsNumber(const StrBuf *Buf);
322 long StrBuf_Utf8StrLen(StrBuf *Buf);
323 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen);
324
325 const char *GuessMimeType(const char *data, size_t dlen);
326 const char* GuessMimeByFilename(const char *what, size_t len);
327
328 /* Run once at Programstart */
329 int LoadIconDir(const char *DirName);
330
331 /* Select the icon for a given MIME type */
332 const char *GetIconFilename(char *MimeType, size_t len);
333
334
335 /* tools */
336
337 int Ctdl_IsUtf8SequenceStart(char Char);
338 int Ctdl_GetUtf8SequenceLength(char Char);
339 int Ctdl_Utf8StrLen(char *str);
340 char *Ctdl_Utf8StrCut(char *str, int maxlen);
341
342
343 int safestrncpy(char *dest, const char *src, size_t n);
344 int num_tokens (const char *source, char tok);
345 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen);
346 long grab_token(char **dest, const char *source, int parmnum, char separator);
347 int extract_int (const char *source, int parmnum);
348 long extract_long (const char *source, int parmnum);
349 unsigned long extract_unsigned_long(const char *source, int parmnum);
350 void CtdlInitBase64Table(void);
351 size_t CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks);
352 int CtdlDecodeBase64(char *dest, const char *source, size_t length);
353 unsigned int decode_hex(char *Source);
354 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen);
355 void StripSlashes(char *Dir, int TrailingSlash);
356 size_t striplt(char *);
357 int haschar(const char *st, int ch);
358 void remove_token(char *source, int parmnum, char separator);
359 void fmt_date(char *buf, size_t n, time_t thetime, int seconds);
360 int is_msg_in_sequence_set(const char *mset, long msgnum);
361 char *memreadline(char *start, char *buf, int maxlen);
362 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen);
363 #define IsEmptyStr(a) ((a)[0] == '\0')
364 #define num_parms(source)               num_tokens(source,(char)'|')
365 int stripout(char *str, char leftboundary, char rightboundary);
366 void stripallbut(char *str, char leftboundary, char rightboundary);
367 char *myfgets(char *s, int size, FILE *stream);
368 void urlesc(char *outbuf, size_t oblen, char *strbuf);
369 char *CtdlTempFileName(char *prefix1, int prefix2);
370 FILE *CtdlTempFile(void);
371 void generate_uuid(char *buf);
372 char *bmstrcasestr(char *text, char *pattern);
373 char *bmstrcasestr_len(char *text, size_t textlen, char *pattern, size_t patlen);
374 void CtdlMakeTempFileName(char *name, int len);
375 char *rfc2047encode(char *line, long length);
376 int is_msg_in_mset(const char *mset, long msgnum);
377 int pattern2(char *search, char *patn);
378 void stripltlen(char *, int *);
379 char *html_to_ascii(char *inputmsg, int msglen, int screenwidth, int do_citaformat);
380 void LoadEntityList(char *FileName);
381
382
383
384 /* vCard stuff */
385
386 #define CTDL_VCARD_MAGIC        0xa1f9
387
388 /* This data structure represents a vCard object currently in memory. */
389 struct vCard {
390         int magic;
391         int numprops;
392         struct vCardProp {
393                 char *name;
394                 char *value;
395         } *prop;
396 };
397
398
399 struct vCard *vcard_new(void);
400 void vcard_add_prop(struct vCard *v, char *propname, char *propvalue);
401 struct vCard *vcard_load(char *vtext);
402 struct vCard *VCardLoad(StrBuf *vbtext);
403
404 void vcard_free(struct vCard *);
405 void vcard_set_prop(struct vCard *v, char *name, char *value, int append);
406 char *vcard_get_prop(struct vCard *v, char *propname, int is_partial,
407                         int instance, int return_propname);
408 char *vcard_serialize(struct vCard *);
409 void vcard_fn_to_n(char *vname, char *n, size_t vname_size);
410 void remove_charset_attribute(char *strbuf);
411 long StrBufUnescape(StrBuf *Buf, int StripBlanks);
412
413 /*
414  * Hash list implementation for Citadel
415  */
416 #define HKEY(a) a, (sizeof(a) - 1)
417
418 typedef struct HashList HashList;
419
420 typedef struct HashKey HashKey;
421
422 typedef struct HashPos HashPos;
423
424 typedef void (*DeleteHashDataFunc)(void * Data);
425 typedef const char *(*PrintHashContent)(void * Data);
426 typedef int (*CompareFunc)(const void* Item1, const void*Item2);
427 typedef int (*HashFunc)(const char *Str, long Len);
428 typedef void (*TransitionFunc) (void *Item1, void *Item2, int Odd);
429 typedef void (*PrintHashDataFunc) (const char *Key, void *Item, int Odd);
430
431 int Flathash(const char *str, long len);
432 #define IKEY(a) (const char*)(&((int)a)), sizeof(int)
433
434 HashList *NewHash(int Uniq, HashFunc F);
435 void DeleteHash(HashList **Hash);
436 void HDeleteHash(void *vHash);
437 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data);
438 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt);
439 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Data);
440 int GetHashKeys(HashList *Hash, char ***List);
441 int dbg_PrintHash(HashList *Hash, PrintHashContent first, PrintHashContent Second);
442 int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry);
443 HashPos *GetNewHashPos(HashList *Hash, int StepWidth);
444 int GetHashPosCounter(HashPos *At);
445 void DeleteHashPos(HashPos **DelMe);
446 int GetNextHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data);
447 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data);
448 void SortByHashKey(HashList *Hash, int Order);
449 void SortByHashKeyStr(HashList *Hash);
450 int GetCount(HashList *Hash);
451 const void *GetSearchPayload(const void *HashVoid);
452 void SortByPayload(HashList *Hash, CompareFunc SortBy);
453 void generic_free_handler(void *ptr);
454 void reference_free_handler(void *ptr);
455 int HashLittle(const void *key, size_t length);
456
457
458 void convert_spaces_to_underscores(char *str);
459
460 /*
461  * Convert 4 bytes char into an Integer.
462  * usefull for easy inexpensive hashing 
463  * of for char strings.
464  */
465 #define CHAR4TO_INT(a) ((int) (a[0] | (a[1]<<8) | (a[2]<<16) | (a[3]<<24)))
466
467 /* vNote implementation */
468
469 #define CTDL_VNOTE_MAGIC        0xa1fa
470
471 struct vnote {
472         int magic;
473         char *uid;
474         char *summary;
475         char *body;
476         int pos_left;
477         int pos_top;
478         int pos_width;
479         int pos_height;
480         int color_red;
481         int color_green;
482         int color_blue;
483 };
484
485
486
487 struct vnote *vnote_new(void);
488 struct vnote *vnote_new_from_str(char *s);
489 void vnote_free(struct vnote *v);
490 char *vnote_serialize(struct vnote *v);
491 void vnote_serialize_output_field(char *append_to, char *field, char *label);
492
493
494
495
496 /*
497  * Create JSON style structures in C plus serialize them to one string
498  */
499
500 typedef struct JsonValue JsonValue;
501
502
503 void DeleteJSONValue(void *vJsonValue);
504
505 JsonValue *NewJsonObject(const char *Key, long keylen);
506
507 JsonValue *NewJsonArray(const char *Key, long keylen);
508
509 JsonValue *NewJsonNumber(const char *Key, long keylen, long Number);
510
511 JsonValue *NewJsonBigNumber(const char *Key, long keylen, double Number);
512
513 JsonValue *NewJsonString(const char *Key, long keylen, StrBuf *CopyMe);
514
515 JsonValue *NewJsonPlainString(const char *Key, long keylen, const char *CopyMe, long len);
516
517 JsonValue *NewJsonNull(const char *Key, long keylen);
518
519 JsonValue *NewJsonBool(const char *Key, long keylen, int value);
520
521 void JsonArrayAppend(JsonValue *Array, JsonValue *Val);
522
523 void JsonObjectAppend(JsonValue *Array, JsonValue *Val);
524
525 void SerializeJson(StrBuf *Target, JsonValue *Val, int FreeVal);
526
527
528
529 /*
530  * Citadels Wildfire implementation, see 
531  * http://www.firephp.org/Wiki/Reference/Protocol
532  * and http://wildfirehq.org/ for details
533  */
534 typedef void (*AddHeaderFunc)(const char *HdrName, const char *HdrValue);
535
536 typedef enum _WF_MessageType {
537         eLOG, 
538         eINFO,
539         eWARN,
540         eERROR,
541         eTRACE,
542         eEXCEPTION
543 } WF_MessageType;
544
545 JsonValue *WildFireException(const char *Filename, long FileLen,
546                              long LineNo,
547                              StrBuf *Message,
548                              int StackOffset);
549
550 void WildFireAddArray(JsonValue *ReportBase, JsonValue *Array, WF_MessageType Type);
551
552 JsonValue *WildFireMessagePlain(const char *Filename, long fnlen,
553                                    long LineNo,
554                                    const char *Message, long len, 
555                                    WF_MessageType Type);
556
557 JsonValue *WildFireMessage(const char *Filename, long fnlen,
558                            long lineno,
559                            StrBuf *Msg, 
560                            WF_MessageType Type);
561
562 void WildFireInitBacktrace(const char *argvNull, int AddBaseFrameSkip);
563
564 void WildFireSerializePayload(StrBuf *JsonBuffer, StrBuf *OutBuf, int *MsgCount, AddHeaderFunc AddHdr);
565
566 #define WF_MAJOR "1"
567 #define WF_STRUCTINDEX "1"
568 #define WF_SUB "1"
569
570
571 #endif  // LIBCITADEL_H