Removed the 'ascmonths' global declaration from libCitadel.
[citadel.git] / libcitadel / lib / tools.c
1 /*
2  * A basic toolset containing miscellaneous functions for string manipluation,
3  * encoding/decoding, and a bunch of other stuff.
4  */
5
6
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <stdio.h>
10 #include <signal.h>
11 #include <sys/types.h>
12 #include <ctype.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 #include <errno.h>
16 #include <limits.h>
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #include "libcitadel.h"
30
31
32 #define TRUE  1
33 #define FALSE 0
34
35 typedef unsigned char byte;           /* Byte type */
36 static byte dtable[256] = "\0";       /* base64 decode table */
37 static byte etable[256] = "\0";       /* base64 encode table */
38
39 char *safestrncpy(char *dest, const char *src, size_t n)
40 {
41         int i = 0;
42
43         if (dest == NULL || src == NULL) {
44                 fprintf(stderr, "safestrncpy: NULL argument\n");
45                 abort();
46         }
47
48         do {
49                 dest[i] = src[i];
50                 if (dest[i] == 0) return(dest);
51                 ++i;
52         } while (i<n);
53         dest[n - 1] = 0;
54         return dest;
55 }
56
57
58
59 /*
60  * num_tokens()  -  discover number of parameters/tokens in a string
61  */
62 int num_tokens(const char *source, char tok)
63 {
64         int count = 1;
65         const char *ptr = source;
66
67         if (source == NULL) {
68                 return (0);
69         }
70
71         while (*ptr != '\0') {
72                 if (*ptr++ == tok) {
73                         ++count;
74                 }
75         }
76         
77         return (count);
78 }
79
80 //extern void cit_backtrace(void);
81
82
83 /*
84  * extract_token() - a string tokenizer
85  * returns -1 if not found, or length of token.
86  */
87 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
88 {
89         const char *s;                  //* source * /
90         int len = 0;                    //* running total length of extracted string * /
91         int current_token = 0;          //* token currently being processed * /
92
93         s = source;
94
95         if (dest == NULL) {
96                 return(-1);
97         }
98
99         //cit_backtrace();
100         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
101         dest[0] = 0;
102
103         if (s == NULL) {
104                 return(-1);
105         }
106         
107         maxlen--;
108
109         while (*s) {
110                 if (*s == separator) {
111                         ++current_token;
112                 }
113                 if ( (current_token == parmnum) && 
114                      (*s != separator) && 
115                      (len < maxlen) ) {
116                         dest[len] = *s;
117                         ++len;
118                 }
119                 else if ((current_token > parmnum) || (len >= maxlen)) {
120                         break;
121                 }
122                 ++s;
123         }
124
125         dest[len] = '\0';
126         if (current_token < parmnum) {
127                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
128                 return(-1);
129         }
130         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
131         return(len);
132 }
133 //*/
134
135
136 /*
137  * extract_token() - a string tokenizer
138  * /
139 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
140 {
141         char *d;                // dest
142         const char *s;          // source
143         int count = 0;
144         int len = 0;
145
146         
147         //cit_backtrace();
148         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
149         strcpy(dest, "");
150
151         //  Locate desired parameter 
152         s = source;
153         while (count < parmnum) {
154                 //  End of string, bail!
155                 if (!*s) {
156                         s = NULL;
157                         break;
158                 }
159                 if (*s == separator) {
160                         count++;
161                 }
162                 s++;
163         }
164         if (!s) {
165                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
166                 return -1;              // Parameter not found
167         }
168         
169         for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
170                 *d = *s;
171         }
172         *d = 0;
173         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
174         return 0;
175 }
176 */
177
178
179 /*
180  * remove_token() - a tokenizer that kills, maims, and destroys
181  */
182 void remove_token(char *source, int parmnum, char separator)
183 {
184         char *d, *s;            /* dest, source */
185         int count = 0;
186
187         /* Find desired parameter */
188         d = source;
189         while (count < parmnum) {
190                 /* End of string, bail! */
191                 if (!*d) {
192                         d = NULL;
193                         break;
194                 }
195                 if (*d == separator) {
196                         count++;
197                 }
198                 d++;
199         }
200         if (!d) return;         /* Parameter not found */
201
202         /* Find next parameter */
203         s = d;
204         while (*s && *s != separator) {
205                 s++;
206         }
207
208         /* Hack and slash */
209         if (*s)
210                 strcpy(d, ++s);
211         else if (d == source)
212                 *d = 0;
213         else
214                 *--d = 0;
215         /*
216         while (*s) {
217                 *d++ = *s++;
218         }
219         *d = 0;
220         */
221 }
222
223
224 /*
225  * extract_int()  -  extract an int parm w/o supplying a buffer
226  */
227 int extract_int(const char *source, int parmnum)
228 {
229         char buf[32];
230         
231         extract_token(buf, source, parmnum, '|', sizeof buf);
232         return(atoi(buf));
233 }
234
235 /*
236  * extract_long()  -  extract an long parm w/o supplying a buffer
237  */
238 long extract_long(const char *source, int parmnum)
239 {
240         char buf[32];
241         
242         extract_token(buf, source, parmnum, '|', sizeof buf);
243         return(atol(buf));
244 }
245
246
247 /*
248  * extract_unsigned_long() - extract an unsigned long parm
249  */
250 unsigned long extract_unsigned_long(const char *source, int parmnum)
251 {
252         char buf[32];
253
254         extract_token(buf, source, parmnum, '|', sizeof buf);
255         return strtoul(buf, NULL, 10);
256 }
257
258
259
260 void CtdlInitBase64Table(void)
261 {
262         int i;
263         /*      Fill dtable with character encodings.  */
264         
265         /* Encoder Table */
266         for (i = 0; i < 26; i++) {
267                 etable[i] = 'A' + i;
268                 etable[26 + i] = 'a' + i;
269         }
270         for (i = 0; i < 10; i++) {
271                 etable[52 + i] = '0' + i;
272         }
273         etable[62] = '+';
274         etable[63] = '/';
275         
276         /* Decoder Table */
277         for (i = 0; i < 255; i++) {
278                 dtable[i] = 0x80;
279         }
280         for (i = 'A'; i <= 'Z'; i++) {
281                 dtable[i] = 0 + (i - 'A');
282         }
283         for (i = 'a'; i <= 'z'; i++) {
284                 dtable[i] = 26 + (i - 'a');
285         }
286         for (i = '0'; i <= '9'; i++) {
287                 dtable[i] = 52 + (i - '0');
288         }
289         dtable['+'] = 62;
290         dtable['/'] = 63;
291         dtable['='] = 0;
292 }
293
294
295 /*
296  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by John Walker.
297  */
298
299 size_t CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks)
300 {
301         int i, hiteof = FALSE;
302         int spos = 0;
303         int dpos = 0;
304         int thisline = 0;
305
306         /**  Fill dtable with character encodings.  */
307
308         for (i = 0; i < 26; i++) {
309                 dtable[i] = 'A' + i;
310                 dtable[26 + i] = 'a' + i;
311         }
312         for (i = 0; i < 10; i++) {
313                 dtable[52 + i] = '0' + i;
314         }
315         dtable[62] = '+';
316         dtable[63] = '/';
317
318         while (!hiteof) {
319                 byte igroup[3], ogroup[4];
320                 int c, n;
321
322                 igroup[0] = igroup[1] = igroup[2] = 0;
323                 for (n = 0; n < 3; n++) {
324                         if (spos >= sourcelen) {
325                                 hiteof = TRUE;
326                                 break;
327                         }
328                         c = source[spos++];
329                         igroup[n] = (byte) c;
330                 }
331                 if (n > 0) {
332                         ogroup[0] = dtable[igroup[0] >> 2];
333                         ogroup[1] =
334                             dtable[((igroup[0] & 3) << 4) |
335                                    (igroup[1] >> 4)];
336                         ogroup[2] =
337                             dtable[((igroup[1] & 0xF) << 2) |
338                                    (igroup[2] >> 6)];
339                         ogroup[3] = dtable[igroup[2] & 0x3F];
340
341                         /**
342                          * Replace characters in output stream with "=" pad
343                          * characters if fewer than three characters were
344                          * read from the end of the input stream. 
345                          */
346
347                         if (n < 3) {
348                                 ogroup[3] = '=';
349                                 if (n < 2) {
350                                         ogroup[2] = '=';
351                                 }
352                         }
353                         for (i = 0; i < 4; i++) {
354                                 dest[dpos++] = ogroup[i];
355                                 dest[dpos] = 0;
356                         }
357                         thisline += 4;
358                         if ( (linebreaks) && (thisline > 70) ) {
359                                 dest[dpos++] = '\r';
360                                 dest[dpos++] = '\n';
361                                 dest[dpos] = 0;
362                                 thisline = 0;
363                         }
364                 }
365         }
366         if ( (linebreaks) && (thisline > 70) ) {
367                 dest[dpos++] = '\r';
368                 dest[dpos++] = '\n';
369                 dest[dpos] = 0;
370                 thisline = 0;
371         }
372
373         return(dpos);
374 }
375
376
377
378 /* 
379  * Convert base64-encoded to binary.  Returns the length of the decoded data.
380  * It will stop after reading 'length' bytes.
381  */
382 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
383 {
384     int i, c;
385     int dpos = 0;
386     int spos = 0;
387
388
389     /*CONSTANTCONDITION*/
390     while (TRUE) {
391         byte a[4], b[4], o[3];
392
393         for (i = 0; i < 4; i++) {
394             if (spos >= length) {
395                 return(dpos);
396             }
397             c = source[spos++];
398
399             if (c == 0) {
400                 if (i > 0) {
401                     return(dpos);
402                 }
403                 return(dpos);
404             }
405             if (dtable[c] & 0x80) {
406                 /* Ignoring errors: discard invalid character. */
407                 i--;
408                 continue;
409             }
410             a[i] = (byte) c;
411             b[i] = (byte) dtable[c];
412         }
413         o[0] = (b[0] << 2) | (b[1] >> 4);
414         o[1] = (b[1] << 4) | (b[2] >> 2);
415         o[2] = (b[2] << 6) | b[3];
416         i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
417         if (i>=1) dest[dpos++] = o[0];
418         if (i>=2) dest[dpos++] = o[1];
419         if (i>=3) dest[dpos++] = o[2];
420         dest[dpos] = 0;
421         if (i < 3) {
422             return(dpos);
423         }
424     }
425 }
426
427
428 /*
429  * if we send out non ascii subjects, we encode it this way.
430  */
431 char *rfc2047encode(char *line, long length)
432 {
433         char *AlreadyEncoded;
434         char *result;
435         long end;
436 #define UTF8_HEADER "=?UTF-8?B?"
437
438         /* check if we're already done */
439         AlreadyEncoded = strstr(line, "=?");
440         if ((AlreadyEncoded != NULL) &&
441             ((strstr(AlreadyEncoded, "?B?") != NULL)||
442              (strstr(AlreadyEncoded, "?Q?") != NULL)))
443         {
444                 return strdup(line);
445         }
446
447         result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
448         strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
449         CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
450         end = strlen (result);
451         result[end]='?';
452         result[end+1]='=';
453         result[end+2]='\0';
454         return result;
455 }
456
457
458 /*
459  * Strip leading and trailing spaces from a string
460  */
461 void striplt(char *buf)
462 {
463         size_t len;
464         int a;
465
466         if (buf==NULL) return;
467         if (IsEmptyStr(buf)) return;
468         len = strlen(buf);
469         while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1])))
470                 buf[--len] = 0;
471         if (IsEmptyStr(buf)) return;
472         a = 0;
473         while ((!IsEmptyStr(buf)) && (isspace(buf[a])))
474                 a++;
475         if (a > 0)
476                 memmove(buf, &buf[a], len - a + 1);
477 }
478
479
480
481
482
483 /**
484  * \brief check for the presence of a character within a string (returns count)
485  * \param st the string to examine
486  * \param ch the char to search
487  * \return the position inside of st
488  */
489 int haschar(const char *st,int ch)
490 {
491         const char *ptr;
492         int b;
493         b = 0;
494         ptr = st;
495         while (!IsEmptyStr(ptr))
496         {
497                 if (*ptr == ch)
498                         ++b;
499                 ptr ++;
500         }
501         return (b);
502 }
503
504
505
506
507
508 /*
509  * Format a date/time stamp for output 
510  * seconds is whether to print the seconds
511  */
512 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
513         struct tm tm;
514         int hour;
515
516         /* Month strings for date conversions ... this needs to be localized eventually */
517         char *fmt_date_months[12] = {
518                 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
519         };
520
521         strcpy(buf, "");
522         localtime_r(&thetime, &tm);
523
524         hour = tm.tm_hour;
525         if (hour == 0)  hour = 12;
526         else if (hour > 12) hour = hour - 12;
527
528         if (seconds) {
529                 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
530                         fmt_date_months[tm.tm_mon],
531                         tm.tm_mday,
532                         tm.tm_year + 1900,
533                         hour,
534                         tm.tm_min,
535                         tm.tm_sec,
536                         ( (tm.tm_hour >= 12) ? "pm" : "am" )
537                 );
538         } else {
539                 snprintf(buf, n, "%s %d %4d %d:%02d%s",
540                         fmt_date_months[tm.tm_mon],
541                         tm.tm_mday,
542                         tm.tm_year + 1900,
543                         hour,
544                         tm.tm_min,
545                         ( (tm.tm_hour >= 12) ? "pm" : "am" )
546                 );
547         }
548 }
549
550
551
552 /*
553  * Determine whether the specified message number is contained within the
554  * specified sequence set.
555  */
556 int is_msg_in_sequence_set(char *mset, long msgnum) {
557         int num_sets;
558         int s;
559         char setstr[128], lostr[128], histr[128];
560         long lo, hi;
561
562         num_sets = num_tokens(mset, ',');
563         for (s=0; s<num_sets; ++s) {
564                 extract_token(setstr, mset, s, ',', sizeof setstr);
565
566                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
567                 if (num_tokens(setstr, ':') >= 2) {
568                         extract_token(histr, setstr, 1, ':', sizeof histr);
569                         if (!strcmp(histr, "*")) {
570                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
571                         }
572                 } 
573                 else {
574                         strcpy(histr, lostr);
575                 }
576                 lo = atol(lostr);
577                 hi = atol(histr);
578
579                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
580         }
581
582         return(0);
583 }
584
585 /** 
586  * \brief Utility function to "readline" from memory
587  * \param start Location in memory from which we are reading.
588  * \param buf the buffer to place the string in.
589  * \param maxlen Size of string buffer
590  * \return Pointer to the source memory right after we stopped reading.
591  */
592 char *memreadline(char *start, char *buf, int maxlen)
593 {
594         char ch;
595         char *ptr;
596         int len = 0;            /**< tally our own length to avoid strlen() delays */
597
598         ptr = start;
599
600         while (1) {
601                 ch = *ptr++;
602                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
603                         buf[len++] = ch;
604                 }
605                 if ((ch == 10) || (ch == 0)) {
606                         buf[len] = 0;
607                         return ptr;
608                 }
609         }
610 }
611
612
613 /** 
614  * \brief Utility function to "readline" from memory
615  * \param start Location in memory from which we are reading.
616  * \param buf the buffer to place the string in.
617  * \param maxlen Size of string buffer
618  * \param retlen the length of the returned string
619  * \return Pointer to the source memory right after we stopped reading.
620  */
621 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
622 {
623         char ch;
624         char *ptr;
625         int len = 0;            /**< tally our own length to avoid strlen() delays */
626
627         ptr = start;
628
629         while (1) {
630                 ch = *ptr++;
631                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
632                         buf[len++] = ch;
633                 }
634                 if ((ch == 10) || (ch == 0)) {
635                         buf[len] = 0;
636                         *retlen = len;
637                         return ptr;
638                 }
639         }
640 }
641
642
643
644
645 /*
646  * Strip a boundarized substring out of a string (for example, remove
647  * parentheses and anything inside them).
648  */
649 void stripout(char *str, char leftboundary, char rightboundary) {
650         int a;
651         int lb = (-1);
652         int rb = (-1);
653
654         for (a = 0; a < strlen(str); ++a) {
655                 if (str[a] == leftboundary) lb = a;
656                 if (str[a] == rightboundary) rb = a;
657         }
658
659         if ( (lb > 0) && (rb > lb) ) {
660                 strcpy(&str[lb - 1], &str[rb + 1]);
661         }
662
663         else if ( (lb == 0) && (rb > lb) ) {
664                 strcpy(str, &str[rb + 1]);
665         }
666
667 }
668
669
670 /*
671  * Reduce a string down to a boundarized substring (for example, remove
672  * parentheses and anything outside them).
673  */
674 void stripallbut(char *str, char leftboundary, char rightboundary) {
675         int a;
676
677         for (a = 0; a < strlen(str); ++ a) {
678                 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
679         }
680
681         for (a = 0; a < strlen(str); ++ a) {
682                 if (str[a] == rightboundary) str[a] = 0;
683         }
684
685 }
686
687 char *myfgets(char *s, int size, FILE *stream) {
688         char *ret = fgets(s, size, stream);
689         char *nl;
690
691         if (ret != NULL) {
692                 nl = strchr(s, '\n');
693
694                 if (nl != NULL)
695                         *nl = 0;
696         }
697
698         return ret;
699 }
700
701 /*
702  * Escape a string for feeding out as a URL.
703  * Output buffer must be big enough to handle escape expansion!
704  */
705 void urlesc(char *outbuf, char *strbuf)
706 {
707         int a, b, c;
708         char *ec = " #&;`'|*?-~<>^()[]{}$\\";
709
710         strcpy(outbuf, "");
711
712         for (a = 0; a < (int)strlen(strbuf); ++a) {
713                 c = 0;
714                 for (b = 0; b < strlen(ec); ++b) {
715                         if (strbuf[a] == ec[b])
716                                 c = 1;
717                 }
718                 b = strlen(outbuf);
719                 if (c == 1)
720                         sprintf(&outbuf[b], "%%%02x", strbuf[a]);
721                 else
722                         sprintf(&outbuf[b], "%c", strbuf[a]);
723         }
724 }
725
726
727
728 /*
729  * In our world, we want strcpy() to be able to work with overlapping strings.
730  */
731 #ifdef strcpy
732 #undef strcpy
733 #endif
734 char *strcpy(char *dest, const char *src) {
735         memmove(dest, src, (strlen(src) + 1) );
736         return(dest);
737 }
738
739
740 /*
741  * Generate a new, globally unique UID parameter for a calendar etc. object
742  */
743 void generate_uuid(char *buf) {
744         static int seq = 0;
745
746         sprintf(buf, "%lx-%lx-%x",
747                 time(NULL),
748                 (long)getpid(),
749                 (seq++)
750         );
751 }
752
753 /*
754  * bmstrcasestr() -- case-insensitive substring search
755  *
756  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
757  * The code is roughly based on the strstr() replacement from 'tin' written
758  * by Urs Jannsen.
759  */
760 char *bmstrcasestr(char *text, char *pattern) {
761
762         register unsigned char *p, *t;
763         register int i, j, *delta;
764         register size_t p1;
765         int deltaspace[256];
766         size_t textlen;
767         size_t patlen;
768
769         textlen = strlen (text);
770         patlen = strlen (pattern);
771
772         /* algorithm fails if pattern is empty */
773         if ((p1 = patlen) == 0)
774                 return (text);
775
776         /* code below fails (whenever i is unsigned) if pattern too long */
777         if (p1 > textlen)
778                 return (NULL);
779
780         /* set up deltas */
781         delta = deltaspace;
782         for (i = 0; i <= 255; i++)
783                 delta[i] = p1;
784         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
785                 delta[tolower(*p++)] = i;
786
787         /*
788          * From now on, we want patlen - 1.
789          * In the loop below, p points to the end of the pattern,
790          * t points to the end of the text to be tested against the
791          * pattern, and i counts the amount of text remaining, not
792          * including the part to be tested.
793          */
794         p1--;
795         p = (unsigned char *) pattern + p1;
796         t = (unsigned char *) text + p1;
797         i = textlen - patlen;
798         while(1) {
799                 if (tolower(p[0]) == tolower(t[0])) {
800                         if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
801                                 return ((char *)t - p1);
802                         }
803                 }
804                 j = delta[tolower(t[0])];
805                 if (i < j)
806                         break;
807                 i -= j;
808                 t += j;
809         }
810         return (NULL);
811 }
812
813
814
815 /*
816  * Local replacement for controversial C library function that generates
817  * names for temporary files.  Included to shut up compiler warnings.
818  */
819 void CtdlMakeTempFileName(char *name, int len) {
820         int i = 0;
821
822         while (i++, i < 100) {
823                 snprintf(name, len, "/tmp/ctdl.%4lx.%04x",
824                         (long)getpid(),
825                         rand()
826                 );
827                 if (!access(name, F_OK)) {
828                         return;
829                 }
830         }
831 }
832
833
834
835 /*
836  * Determine whether the specified message number is contained within the specified set.
837  * Returns nonzero if the specified message number is in the specified message set string.
838  */
839 int is_msg_in_mset(char *mset, long msgnum) {
840         int num_sets;
841         int s;
842         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
843         long lo, hi;
844
845         /*
846          * Now set it for all specified messages.
847          */
848         num_sets = num_tokens(mset, ',');
849         for (s=0; s<num_sets; ++s) {
850                 extract_token(setstr, mset, s, ',', sizeof setstr);
851
852                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
853                 if (num_tokens(setstr, ':') >= 2) {
854                         extract_token(histr, setstr, 1, ':', sizeof histr);
855                         if (!strcmp(histr, "*")) {
856                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
857                         }
858                 }
859                 else {
860                         strcpy(histr, lostr);
861                 }
862                 lo = atol(lostr);
863                 hi = atol(histr);
864
865                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
866         }
867
868         return(0);
869 }
870
871
872 /*
873  * \brief searches for a  paternn within asearch string
874  * \param search the string to search 
875  * \param patn the pattern to find in string
876  * \returns position in string
877  */
878 int pattern2(char *search, char *patn)
879 {
880         int a;
881         int len, plen;
882         len = strlen (search);
883         plen = strlen (patn);
884         for (a = 0; a < len; ++a) {
885                 if (!strncasecmp(&search[a], patn, plen))
886                         return (a);
887         }
888         return (-1);
889 }
890
891
892 /**
893  * \brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
894  * \param buf the string to modify
895  * \param len length of the string. 
896  */
897 void stripltlen(char *buf, int *len)
898 {
899         int delta = 0;
900         if (*len == 0) return;
901         while ((*len > delta) && (isspace(buf[delta]))){
902                 delta ++;
903         }
904         memmove (buf, &buf[delta], *len - delta + 1);
905         (*len) -=delta;
906
907         if (*len == 0) return;
908         while (isspace(buf[(*len) - 1])){
909                 buf[--(*len)] = '\0';
910         }
911 }
912