4 * Utility functions that are used by both the client and server.
17 #if TIME_WITH_SYS_TIME
18 # include <sys/time.h>
22 # include <sys/time.h>
34 typedef unsigned char byte; /* Byte type */
35 static byte dtable[256]; /* base64 encode / decode table */
37 /* Month strings for date conversions */
38 char *ascmonths[12] = {
39 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
40 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
43 char *safestrncpy(char *dest, const char *src, size_t n)
47 if (dest == NULL || src == NULL) {
48 fprintf(stderr, "safestrncpy: NULL argument\n");
54 if (dest[i] == 0) return(dest);
63 #ifndef HAVE_STRNCASECMP
64 int strncasecmp(char *lstr, char *rstr, int len)
69 lc=tolower(lstr[pos]);
70 rc=tolower(rstr[pos]);
71 if ((lc==0)&&(rc==0)) return(0);
72 if (lc<rc) return(-1);
83 * num_tokens() - discover number of parameters/tokens in a string
85 int num_tokens(const char *source, char tok)
88 const char *ptr = source;
94 while (*ptr != '\0') {
105 * extract_token() - a string tokenizer
107 void extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
110 const char *s; /* source */
116 /* Locate desired parameter */
118 while (count < parmnum) {
119 /* End of string, bail! */
124 if (*s == separator) {
129 if (!s) return; /* Parameter not found */
131 for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
139 * remove_token() - a tokenizer that kills, maims, and destroys
141 void remove_token(char *source, int parmnum, char separator)
143 char *d, *s; /* dest, source */
146 /* Find desired parameter */
148 while (count < parmnum) {
149 /* End of string, bail! */
154 if (*d == separator) {
159 if (!d) return; /* Parameter not found */
161 /* Find next parameter */
163 while (*s && *s != separator) {
170 else if (d == source)
184 * extract_int() - extract an int parm w/o supplying a buffer
186 int extract_int(const char *source, int parmnum)
190 extract_token(buf, source, parmnum, '|', sizeof buf);
195 * extract_long() - extract an long parm w/o supplying a buffer
197 long extract_long(const char *source, int parmnum)
201 extract_token(buf, source, parmnum, '|', sizeof buf);
207 * extract_unsigned_long() - extract an unsigned long parm
209 unsigned long extract_unsigned_long(const char *source, int parmnum)
213 extract_token(buf, source, parmnum, '|', sizeof buf);
214 return strtoul(buf, NULL, 10);
219 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
220 * John Walker, found in full in the file "base64.c" included with this
221 * distribution. We are moving in the direction of eventually discarding
222 * the separate executables, and using the ones in our code exclusively.
225 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
227 int i, hiteof = FALSE;
231 /* Fill dtable with character encodings. */
233 for (i = 0; i < 26; i++) {
235 dtable[26 + i] = 'a' + i;
237 for (i = 0; i < 10; i++) {
238 dtable[52 + i] = '0' + i;
244 byte igroup[3], ogroup[4];
247 igroup[0] = igroup[1] = igroup[2] = 0;
248 for (n = 0; n < 3; n++) {
249 if (spos >= sourcelen) {
254 igroup[n] = (byte) c;
257 ogroup[0] = dtable[igroup[0] >> 2];
258 ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
259 ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
260 ogroup[3] = dtable[igroup[2] & 0x3F];
262 /* Replace characters in output stream with "=" pad
263 characters if fewer than three characters were
264 read from the end of the input stream. */
272 for (i = 0; i < 4; i++) {
273 dest[dpos++] = ogroup[i];
282 * Convert base64-encoded to binary. Returns the length of the decoded data.
283 * It will stop after reading 'length' bytes.
285 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
291 for (i = 0; i < 255; i++) {
294 for (i = 'A'; i <= 'Z'; i++) {
295 dtable[i] = 0 + (i - 'A');
297 for (i = 'a'; i <= 'z'; i++) {
298 dtable[i] = 26 + (i - 'a');
300 for (i = '0'; i <= '9'; i++) {
301 dtable[i] = 52 + (i - '0');
307 /*CONSTANTCONDITION*/
309 byte a[4], b[4], o[3];
311 for (i = 0; i < 4; i++) {
312 if (spos >= length) {
323 if (dtable[c] & 0x80) {
324 /* Ignoring errors: discard invalid character. */
329 b[i] = (byte) dtable[c];
331 o[0] = (b[0] << 2) | (b[1] >> 4);
332 o[1] = (b[1] << 4) | (b[2] >> 2);
333 o[2] = (b[2] << 6) | b[3];
334 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
335 if (i>=1) dest[dpos++] = o[0];
336 if (i>=2) dest[dpos++] = o[1];
337 if (i>=3) dest[dpos++] = o[2];
346 * if we send out non ascii subjects, we encode it this way.
348 char *rfc2047encode(char *line, long length)
350 char *AlreadyEncoded;
353 #define UTF8_HEADER "=?UTF-8?B?"
355 /* check if we're already done */
356 AlreadyEncoded = strstr(line, "=?");
357 if ((AlreadyEncoded != NULL) &&
358 ((strstr(AlreadyEncoded, "?B?") != NULL)||
359 (strstr(AlreadyEncoded, "?Q?") != NULL)))
364 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
365 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
366 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length);
367 end = strlen (result);
376 * Strip leading and trailing spaces from a string
378 void striplt(char *buf)
380 if (IsEmptyStr(buf)) return;
381 while ((!IsEmptyStr(buf)) && (isspace(buf[0])))
382 strcpy(buf, &buf[1]);
383 if (IsEmptyStr(buf)) return;
384 while ((!IsEmptyStr(buf)) && (isspace(buf[strlen(buf) - 1])))
385 buf[strlen(buf) - 1] = 0;
393 * Return the number of occurances of character ch in string st
395 int haschar(const char *st, int ch)
399 for (a = 0; a < strlen(st); ++a)
410 * Format a date/time stamp for output
411 * seconds is whether to print the seconds
413 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
418 localtime_r(&thetime, &tm);
421 if (hour == 0) hour = 12;
422 else if (hour > 12) hour = hour - 12;
425 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
426 ascmonths[tm.tm_mon],
432 ( (tm.tm_hour >= 12) ? "pm" : "am" )
435 snprintf(buf, n, "%s %d %4d %d:%02d%s",
436 ascmonths[tm.tm_mon],
441 ( (tm.tm_hour >= 12) ? "pm" : "am" )
449 * Determine whether the specified message number is contained within the
450 * specified sequence set.
452 int is_msg_in_sequence_set(char *mset, long msgnum) {
455 char setstr[128], lostr[128], histr[128];
458 num_sets = num_tokens(mset, ',');
459 for (s=0; s<num_sets; ++s) {
460 extract_token(setstr, mset, s, ',', sizeof setstr);
462 extract_token(lostr, setstr, 0, ':', sizeof lostr);
463 if (num_tokens(setstr, ':') >= 2) {
464 extract_token(histr, setstr, 1, ':', sizeof histr);
465 if (!strcmp(histr, "*")) {
466 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
470 strcpy(histr, lostr);
475 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
482 * \brief Utility function to "readline" from memory
483 * \param start Location in memory from which we are reading.
484 * \param buf the buffer to place the string in.
485 * \param maxlen Size of string buffer
486 * \return Pointer to the source memory right after we stopped reading.
488 char *memreadline(char *start, char *buf, int maxlen)
492 int len = 0; /**< tally our own length to avoid strlen() delays */
498 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
501 if ((ch == 10) || (ch == 0)) {
512 * Strip a boundarized substring out of a string (for example, remove
513 * parentheses and anything inside them).
515 void stripout(char *str, char leftboundary, char rightboundary) {
520 for (a = 0; a < strlen(str); ++a) {
521 if (str[a] == leftboundary) lb = a;
522 if (str[a] == rightboundary) rb = a;
525 if ( (lb > 0) && (rb > lb) ) {
526 strcpy(&str[lb - 1], &str[rb + 1]);
529 else if ( (lb == 0) && (rb > lb) ) {
530 strcpy(str, &str[rb + 1]);
537 * Reduce a string down to a boundarized substring (for example, remove
538 * parentheses and anything outside them).
540 void stripallbut(char *str, char leftboundary, char rightboundary) {
543 for (a = 0; a < strlen(str); ++ a) {
544 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
547 for (a = 0; a < strlen(str); ++ a) {
548 if (str[a] == rightboundary) str[a] = 0;
553 char *myfgets(char *s, int size, FILE *stream) {
554 char *ret = fgets(s, size, stream);
558 nl = strchr(s, '\n');
568 * Escape a string for feeding out as a URL.
569 * Output buffer must be big enough to handle escape expansion!
571 void urlesc(char *outbuf, char *strbuf)
574 char *ec = " #&;`'|*?-~<>^()[]{}$\\";
578 for (a = 0; a < (int)strlen(strbuf); ++a) {
580 for (b = 0; b < strlen(ec); ++b) {
581 if (strbuf[a] == ec[b])
586 sprintf(&outbuf[b], "%%%02x", strbuf[a]);
588 sprintf(&outbuf[b], "%c", strbuf[a]);
595 * In our world, we want strcpy() to be able to work with overlapping strings.
600 char *strcpy(char *dest, const char *src) {
601 memmove(dest, src, (strlen(src) + 1) );
607 * Generate a new, globally unique UID parameter for a calendar etc. object
609 void generate_uuid(char *buf) {
612 sprintf(buf, "%lx-"F_XPID_T"-%x",
620 * bmstrcasestr() -- case-insensitive substring search
622 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
623 * The code is roughly based on the strstr() replacement from 'tin' written
626 char *bmstrcasestr(char *text, char *pattern) {
628 register unsigned char *p, *t;
629 register int i, j, *delta;
635 textlen = strlen (text);
636 patlen = strlen (pattern);
638 /* algorithm fails if pattern is empty */
639 if ((p1 = patlen) == 0)
642 /* code below fails (whenever i is unsigned) if pattern too long */
648 for (i = 0; i <= 255; i++)
650 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
651 delta[tolower(*p++)] = i;
654 * From now on, we want patlen - 1.
655 * In the loop below, p points to the end of the pattern,
656 * t points to the end of the text to be tested against the
657 * pattern, and i counts the amount of text remaining, not
658 * including the part to be tested.
661 p = (unsigned char *) pattern + p1;
662 t = (unsigned char *) text + p1;
663 i = textlen - patlen;
665 if (tolower(p[0]) == tolower(t[0])) {
666 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
667 return ((char *)t - p1);
670 j = delta[tolower(t[0])];
682 * Local replacement for controversial C library function that generates
683 * names for temporary files. Included to shut up compiler warnings.
685 void CtdlMakeTempFileName(char *name, int len) {
688 while (i++, i < 100) {
689 snprintf(name, len, "/tmp/ctdl."F_XPID_T".%04x",
693 if (!access(name, F_OK)) {