Support optional WANT_JUNK configuration
[s-mailx.git] / aux.c
blob79027c996210edae6aaf01a1f2ee174ce93c8ea8
1 /*
2 * Heirloom mailx - a mail user agent derived from Berkeley Mail.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 */
6 /*
7 * Copyright (c) 1980, 1993
8 * The Regents of the University of California. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
39 #ifndef lint
40 #ifdef DOSCCS
41 static char sccsid[] = "@(#)aux.c 2.83 (gritter) 3/4/06";
42 #endif
43 #endif /* not lint */
45 #include "rcv.h"
46 #include "extern.h"
47 #include <sys/stat.h>
48 #include <utime.h>
49 #include <time.h>
50 #include <termios.h>
51 #include <ctype.h>
52 #ifdef HAVE_WCTYPE_H
53 #include <wctype.h>
54 #endif /* HAVE_WCTYPE_H */
55 #ifdef HAVE_WCWIDTH
56 #include <wchar.h>
57 #endif /* HAVE_WCWIDTH */
58 #include <errno.h>
59 #include <sys/stat.h>
60 #include <unistd.h>
61 #include <time.h>
62 #include <dirent.h>
63 #include <fcntl.h>
64 #include <limits.h>
66 #include "md5.h"
69 * Mail -- a mail program
71 * Auxiliary functions.
75 * Return a pointer to a dynamic copy of the argument.
77 char *
78 savestr(const char *str)
80 char *new;
81 int size = strlen(str) + 1;
83 if ((new = salloc(size)) != NULL)
84 memcpy(new, str, size);
85 return new;
89 * Make a copy of new argument incorporating old one.
91 char *
92 save2str(const char *str, const char *old)
94 char *new;
95 int newsize = strlen(str) + 1;
96 int oldsize = old ? strlen(old) + 1 : 0;
98 if ((new = salloc(newsize + oldsize)) != NULL) {
99 if (oldsize) {
100 memcpy(new, old, oldsize);
101 new[oldsize - 1] = ' ';
103 memcpy(new + oldsize, str, newsize);
105 return new;
108 char *
109 savecat(const char *s1, const char *s2)
111 const char *cp;
112 char *ns, *np;
114 np = ns = salloc(strlen(s1) + strlen(s2) + 1);
115 for (cp = s1; *cp; cp++)
116 *np++ = *cp;
117 for (cp = s2; *cp; cp++)
118 *np++ = *cp;
119 *np = '\0';
120 return ns;
123 #include <stdarg.h>
125 #ifndef HAVE_SNPRINTF
127 * Lazy vsprintf wrapper.
130 snprintf(char *str, size_t size, const char *format, ...)
132 va_list ap;
133 int ret;
135 va_start(ap, format);
136 ret = vsprintf(str, format, ap);
137 va_end(ap);
138 return ret;
140 #endif /* !HAVE_SNPRINTF */
143 * Announce a fatal error and die.
145 void
146 panic(const char *format, ...)
148 va_list ap;
150 va_start(ap, format);
151 fprintf(stderr, catgets(catd, CATSET, 1, "panic: "));
152 vfprintf(stderr, format, ap);
153 va_end(ap);
154 fprintf(stderr, catgets(catd, CATSET, 2, "\n"));
155 fflush(stderr);
156 abort();
159 void
160 holdint(void)
162 sigset_t set;
164 sigemptyset(&set);
165 sigaddset(&set, SIGINT);
166 sigprocmask(SIG_BLOCK, &set, NULL);
169 void
170 relseint(void)
172 sigset_t set;
174 sigemptyset(&set);
175 sigaddset(&set, SIGINT);
176 sigprocmask(SIG_UNBLOCK, &set, NULL);
180 * Touch the named message by setting its MTOUCH flag.
181 * Touched messages have the effect of not being sent
182 * back to the system mailbox on exit.
184 void
185 touch(struct message *mp)
188 mp->m_flag |= MTOUCH;
189 if ((mp->m_flag & MREAD) == 0)
190 mp->m_flag |= MREAD|MSTATUS;
194 * Test to see if the passed file name is a directory.
195 * Return true if it is.
197 int
198 is_dir(char *name)
200 struct stat sbuf;
202 if (stat(name, &sbuf) < 0)
203 return(0);
204 return(S_ISDIR(sbuf.st_mode));
208 * Count the number of arguments in the given string raw list.
210 int
211 argcount(char **argv)
213 char **ap;
215 for (ap = argv; *ap++ != NULL;)
217 return ap - argv - 1;
221 * Copy a string, lowercasing it as we go.
223 void
224 i_strcpy(char *dest, const char *src, int size)
226 char *max;
228 max=dest+size-1;
229 while (dest<=max) {
230 *dest++ = lowerconv(*src & 0377);
231 if (*src++ == '\0')
232 break;
236 char *
237 i_strdup(const char *src)
239 int sz;
240 char *dest;
242 sz = strlen(src) + 1;
243 dest = salloc(sz);
244 i_strcpy(dest, src, sz);
245 return dest;
249 * Convert a string to lowercase, in-place and with multibyte-aware.
251 void
252 makelow(char *cp)
254 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
255 if (mb_cur_max > 1) {
256 char *tp = cp;
257 wchar_t wc;
258 int len;
260 while (*cp) {
261 len = mbtowc(&wc, cp, mb_cur_max);
262 if (len < 0)
263 *tp++ = *cp++;
264 else {
265 wc = towlower(wc);
266 if (wctomb(tp, wc) == len)
267 tp += len, cp += len;
268 else
269 *tp++ = *cp++;
272 } else
273 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
276 *cp = tolower(*cp & 0377);
277 while (*cp++);
281 int
282 substr(const char *str, const char *sub)
284 const char *cp, *backup;
286 cp = sub;
287 backup = str;
288 while (*str && *cp) {
289 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
290 if (mb_cur_max > 1) {
291 wchar_t c, c2;
292 int sz;
294 if ((sz = mbtowc(&c, cp, mb_cur_max)) < 0)
295 goto singlebyte;
296 cp += sz;
297 if ((sz = mbtowc(&c2, str, mb_cur_max)) < 0)
298 goto singlebyte;
299 str += sz;
300 c = towupper(c);
301 c2 = towupper(c2);
302 if (c != c2) {
303 if ((sz = mbtowc(&c, backup, mb_cur_max)) > 0) {
304 backup += sz;
305 str = backup;
306 } else
307 str = ++backup;
308 cp = sub;
310 } else
311 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
313 int c, c2;
315 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
316 singlebyte:
317 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
318 c = *cp++ & 0377;
319 if (islower(c))
320 c = toupper(c);
321 c2 = *str++ & 0377;
322 if (islower(c2))
323 c2 = toupper(c2);
324 if (c != c2) {
325 str = ++backup;
326 cp = sub;
330 return *cp == '\0';
333 char *
334 colalign(const char *cp, int col, int fill)
336 int n, sz;
337 char *nb, *np;
339 np = nb = salloc(mb_cur_max * strlen(cp) + col + 1);
340 while (*cp) {
341 #if defined (HAVE_MBTOWC) && defined (HAVE_WCWIDTH)
342 if (mb_cur_max > 1) {
343 wchar_t wc;
345 if ((sz = mbtowc(&wc, cp, mb_cur_max)) < 0) {
346 n = sz = 1;
347 } else {
348 if ((n = wcwidth(wc)) < 0)
349 n = 1;
351 } else
352 #endif /* HAVE_MBTOWC && HAVE_WCWIDTH */
354 n = sz = 1;
356 if (n > col)
357 break;
358 col -= n;
359 if (sz == 1 && spacechar(*cp&0377)) {
360 *np++ = ' ';
361 cp++;
362 } else
363 while (sz--)
364 *np++ = *cp++;
366 if (fill)
367 while (col-- > 0)
368 *np++ = ' ';
369 *np = '\0';
370 return nb;
373 void
374 try_pager(FILE *fp)
376 long lines = 0;
377 int c;
378 char *cp;
380 fflush(fp);
381 rewind(fp);
382 while ((c = getc(fp)) != EOF)
383 if (c == '\n')
384 lines++;
385 rewind(fp);
386 if (is_a_tty[0] && is_a_tty[1] && (cp = value("crt")) != NULL &&
387 lines > (*cp ? atol(cp) : scrnheight))
388 run_command(get_pager(), 0, fileno(fp), -1, NULL, NULL, NULL);
389 else
390 while ((c = getc(fp)) != EOF)
391 putchar(c);
395 * The following code deals with input stacking to do source
396 * commands. All but the current file pointer are saved on
397 * the stack.
400 static int ssp; /* Top of file stack */
401 struct sstack {
402 FILE *s_file; /* File we were in. */
403 enum condition s_cond; /* Saved state of conditionals */
404 int s_loading; /* Loading .mailrc, etc. */
405 #define SSTACK 20
406 } sstack[SSTACK];
409 * Pushdown current input file and switch to a new one.
410 * Set the global flag "sourcing" so that others will realize
411 * that they are no longer reading from a tty (in all probability).
413 int
414 source(void *v)
416 char **arglist = v;
417 FILE *fi;
418 char *cp;
420 if ((cp = expand(*arglist)) == NULL)
421 return(1);
422 if ((fi = Fopen(cp, "r")) == NULL) {
423 perror(cp);
424 return(1);
426 if (ssp >= SSTACK - 1) {
427 printf(catgets(catd, CATSET, 3,
428 "Too much \"sourcing\" going on.\n"));
429 Fclose(fi);
430 return(1);
432 sstack[ssp].s_file = input;
433 sstack[ssp].s_cond = cond;
434 sstack[ssp].s_loading = loading;
435 ssp++;
436 loading = 0;
437 cond = CANY;
438 input = fi;
439 sourcing++;
440 return(0);
444 * Pop the current input back to the previous level.
445 * Update the "sourcing" flag as appropriate.
447 int
448 unstack(void)
450 if (ssp <= 0) {
451 printf(catgets(catd, CATSET, 4,
452 "\"Source\" stack over-pop.\n"));
453 sourcing = 0;
454 return(1);
456 Fclose(input);
457 if (cond != CANY)
458 printf(catgets(catd, CATSET, 5, "Unmatched \"if\"\n"));
459 ssp--;
460 cond = sstack[ssp].s_cond;
461 loading = sstack[ssp].s_loading;
462 input = sstack[ssp].s_file;
463 if (ssp == 0)
464 sourcing = loading;
465 return(0);
469 * Touch the indicated file.
470 * This is nifty for the shell.
472 void
473 alter(char *name)
475 struct stat sb;
476 struct utimbuf utb;
478 if (stat(name, &sb))
479 return;
480 utb.actime = time((time_t *)0) + 1;
481 utb.modtime = sb.st_mtime;
482 utime(name, &utb);
486 * Examine the passed line buffer and
487 * return true if it is all blanks and tabs.
489 int
490 blankline(char *linebuf)
492 char *cp;
494 for (cp = linebuf; *cp; cp++)
495 if (!blankchar(*cp & 0377))
496 return(0);
497 return(1);
501 * Are any of the characters in the two strings the same?
503 int
504 anyof(char *s1, char *s2)
507 while (*s1)
508 if (strchr(s2, *s1++))
509 return 1;
510 return 0;
514 * Determine if as1 is a valid prefix of as2.
515 * Return true if yep.
517 int
518 is_prefix(const char *as1, const char *as2)
520 const char *s1, *s2;
522 s1 = as1;
523 s2 = as2;
524 while (*s1++ == *s2)
525 if (*s2++ == '\0')
526 return(1);
527 return(*--s1 == '\0');
530 char *
531 last_at_before_slash(const char *sp)
533 const char *cp;
535 for (cp = sp; *cp; cp++)
536 if (*cp == '/')
537 break;
538 while (cp > sp && *--cp != '@');
539 return *cp == '@' ? (char *)cp : NULL;
542 enum protocol
543 which_protocol(const char *name)
545 register const char *cp;
546 char *np;
547 size_t sz;
548 struct stat st;
549 enum protocol p;
551 if (name[0] == '%' && name[1] == ':')
552 name += 2;
553 for (cp = name; *cp && *cp != ':'; cp++)
554 if (!alnumchar(*cp&0377))
555 goto file;
556 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
557 if (strncmp(name, "pop3://", 7) == 0)
558 #ifdef USE_POP3
559 return PROTO_POP3;
560 #else
561 fprintf(stderr, catgets(catd, CATSET, 216,
562 "No POP3 support compiled in.\n"));
563 #endif
564 if (strncmp(name, "pop3s://", 8) == 0)
565 #ifdef USE_SSL
566 return PROTO_POP3;
567 #else /* !USE_SSL */
568 fprintf(stderr, catgets(catd, CATSET, 225,
569 "No SSL support compiled in.\n"));
570 #endif /* !USE_SSL */
571 if (strncmp(name, "imap://", 7) == 0)
572 #ifdef USE_IMAP
573 return PROTO_IMAP;
574 #else
575 fprintf(stderr, catgets(catd, CATSET, 269,
576 "No IMAP support compiled in.\n"));
577 #endif
578 if (strncmp(name, "imaps://", 8) == 0)
579 #ifdef USE_SSL
580 return PROTO_IMAP;
581 #else /* !USE_SSL */
582 fprintf(stderr, catgets(catd, CATSET, 225,
583 "No SSL support compiled in.\n"));
584 #endif /* !USE_SSL */
585 return PROTO_UNKNOWN;
586 } else {
587 file: p = PROTO_FILE;
588 np = ac_alloc((sz = strlen(name)) + 5);
589 strcpy(np, name);
590 if (stat(name, &st) == 0) {
591 if (S_ISDIR(st.st_mode)) {
592 strcpy(&np[sz], "/tmp");
593 if (stat(np, &st) == 0 && S_ISDIR(st.st_mode)) {
594 strcpy(&np[sz], "/new");
595 if (stat(np, &st) == 0 &&
596 S_ISDIR(st.st_mode)) {
597 strcpy(&np[sz], "/cur");
598 if (stat(np, &st) == 0 &&
599 S_ISDIR(st.st_mode))
600 p = PROTO_MAILDIR;
604 } else {
605 strcpy(&np[sz], ".gz");
606 if (stat(np, &st) < 0) {
607 strcpy(&np[sz], ".bz2");
608 if (stat(np, &st) < 0) {
609 if ((cp = value("newfolders")) != 0 &&
610 strcmp(cp, "maildir") == 0)
611 p = PROTO_MAILDIR;
615 ac_free(np);
616 return p;
620 const char *
621 protfile(const char *xcp)
623 const char *cp = xcp;
624 int state = 0;
626 while (*cp) {
627 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
628 cp += 3;
629 state = 1;
631 if (cp[0] == '/' && state == 1)
632 return &cp[1];
633 if (cp[0] == '/')
634 return xcp;
635 cp++;
637 return cp;
640 char *
641 protbase(const char *cp)
643 char *n = salloc(strlen(cp) + 1);
644 char *np = n;
646 while (*cp) {
647 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
648 *np++ = *cp++;
649 *np++ = *cp++;
650 *np++ = *cp++;
651 } else if (cp[0] == '/')
652 break;
653 else
654 *np++ = *cp++;
656 *np = '\0';
657 return n;
660 int
661 disconnected(const char *file)
663 char *cp, *cq, *vp;
664 int vs, r;
666 if (value("disconnected"))
667 return 1;
668 cp = protbase(file);
669 if (strncmp(cp, "imap://", 7) == 0)
670 cp += 7;
671 else if (strncmp(cp, "imaps://", 8) == 0)
672 cp += 8;
673 else
674 return 0;
675 if ((cq = strchr(cp, ':')) != NULL)
676 *cq = '\0';
677 vp = ac_alloc(vs = strlen(cp) + 14);
678 snprintf(vp, vs, "disconnected-%s", cp);
679 r = value(vp) != NULL;
680 ac_free(vp);
681 return r;
684 unsigned
685 pjw(const char *cp)
687 unsigned h = 0, g;
689 cp--;
690 while (*++cp) {
691 h = (h << 4 & 0xffffffff) + (*cp&0377);
692 if ((g = h & 0xf0000000) != 0) {
693 h = h ^ g >> 24;
694 h = h ^ g;
697 return h;
700 long
701 nextprime(long n)
703 const long primes[] = {
704 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
705 131071, 262139, 524287, 1048573, 2097143, 4194301,
706 8388593, 16777213, 33554393, 67108859, 134217689,
707 268435399, 536870909, 1073741789, 2147483647
709 long mprime = 7;
710 int i;
712 for (i = 0; i < sizeof primes / sizeof *primes; i++)
713 if ((mprime = primes[i]) >= (n < 65536 ? n*4 :
714 n < 262144 ? n*2 : n))
715 break;
716 if (i == sizeof primes / sizeof *primes)
717 mprime = n; /* not so prime, but better than failure */
718 return mprime;
721 #define Hexchar(n) ((n)>9 ? (n)-10+'A' : (n)+'0')
722 #define hexchar(n) ((n)>9 ? (n)-10+'a' : (n)+'0')
724 char *
725 strenc(const char *cp)
727 char *n, *np;
729 np = n = salloc(strlen(cp) * 3 + 1);
730 while (*cp) {
731 if (alnumchar(*cp&0377) || *cp == '_' || *cp == '@' ||
732 (np > n && (*cp == '.' || *cp == '-' ||
733 *cp == ':')))
734 *np++ = *cp;
735 else {
736 *np++ = '%';
737 *np++ = Hexchar((*cp&0xf0) >> 4);
738 *np++ = Hexchar(*cp&0x0f);
740 cp++;
742 *np = '\0';
743 return n;
746 char *
747 strdec(const char *cp)
749 char *n, *np;
751 np = n = salloc(strlen(cp) + 1);
752 while (*cp) {
753 if (cp[0] == '%' && cp[1] && cp[2]) {
754 *np = (int)(cp[1]>'9'?cp[1]-'A'+10:cp[1]-'0') << 4;
755 *np++ |= cp[2]>'9'?cp[2]-'A'+10:cp[2]-'0';
756 cp += 3;
757 } else
758 *np++ = *cp++;
760 *np = '\0';
761 return n;
764 char *
765 md5tohex(const void *vp)
767 char *hex;
768 const char *cp = vp;
769 int i;
771 hex = salloc(33);
772 for (i = 0; i < 16; i++) {
773 hex[2*i] = hexchar((cp[i]&0xf0) >> 4);
774 hex[2*i+1] = hexchar(cp[i]&0x0f);
776 hex[32] = '\0';
777 return hex;
780 char *
781 cram_md5_string(const char *user, const char *pass, const char *b64)
783 struct str in, out;
784 char digest[16], *cp, *sp, *rp, *xp;
785 int ss, rs;
787 in.s = (char *)b64;
788 in.l = strlen(in.s);
789 mime_fromb64(&in, &out, 0);
790 hmac_md5((unsigned char *)out.s, out.l,
791 (unsigned char *)pass, strlen(pass),
792 digest);
793 free(out.s);
794 xp = md5tohex(digest);
795 sp = ac_alloc(ss = strlen(user) + strlen(xp) + 2);
796 snprintf(sp, ss, "%s %s", user, xp);
797 cp = strtob64(sp);
798 ac_free(sp);
799 rp = salloc(rs = strlen(cp) + 3);
800 snprintf(rp, rs, "%s\r\n", cp);
801 free(cp);
802 return rp;
805 char *
806 getuser(void)
808 char *line = NULL, *user;
809 size_t linesize = 0;
811 if (is_a_tty[0]) {
812 fputs("User: ", stdout);
813 fflush(stdout);
815 if (readline(stdin, &line, &linesize) == 0) {
816 if (line)
817 free(line);
818 return NULL;
820 user = savestr(line);
821 free(line);
822 return user;
825 char *
826 getpassword(struct termios *otio, int *reset_tio, const char *query)
828 struct termios tio;
829 char *line = NULL, *pass;
830 size_t linesize = 0;
831 int i;
833 if (is_a_tty[0]) {
834 fputs(query ? query : "Password:", stdout);
835 fflush(stdout);
836 tcgetattr(0, &tio);
837 *otio = tio;
838 tio.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
839 *reset_tio = 1;
840 tcsetattr(0, TCSAFLUSH, &tio);
842 i = readline(stdin, &line, &linesize);
843 if (is_a_tty[0]) {
844 fputc('\n', stdout);
845 tcsetattr(0, TCSADRAIN, otio);
847 *reset_tio = 0;
848 if (i < 0) {
849 if (line)
850 free(line);
851 return NULL;
853 pass = savestr(line);
854 free(line);
855 return pass;
858 void
859 transflags(struct message *omessage, long omsgCount, int transparent)
861 struct message *omp, *nmp, *newdot, *newprevdot;
862 int hf;
864 omp = omessage;
865 nmp = message;
866 newdot = message;
867 newprevdot = NULL;
868 while (omp < &omessage[omsgCount] &&
869 nmp < &message[msgCount]) {
870 if (dot && nmp->m_uid == dot->m_uid)
871 newdot = nmp;
872 if (prevdot && nmp->m_uid == prevdot->m_uid)
873 newprevdot = nmp;
874 if (omp->m_uid == nmp->m_uid) {
875 hf = nmp->m_flag & MHIDDEN;
876 if (transparent && mb.mb_type == MB_IMAP)
877 omp->m_flag &= ~MHIDDEN;
878 *nmp++ = *omp++;
879 if (transparent && mb.mb_type == MB_CACHE)
880 nmp[-1].m_flag |= hf;
881 } else if (omp->m_uid < nmp->m_uid)
882 omp++;
883 else
884 nmp++;
886 dot = newdot;
887 setdot(newdot);
888 prevdot = newprevdot;
889 free(omessage);
892 char *
893 getrandstring(size_t length)
895 static unsigned char nodedigest[16];
896 static pid_t pid;
897 int i, fd = -1;
898 char *data;
899 char *cp, *rp;
900 MD5_CTX ctx;
902 data = salloc(length);
903 if ((fd = open("/dev/urandom", O_RDONLY)) < 0 ||
904 read(fd, data, length) != length) {
905 if (pid == 0) {
906 pid = getpid();
907 srand(pid);
908 cp = nodename(0);
909 MD5Init(&ctx);
910 MD5Update(&ctx, (unsigned char *)cp, strlen(cp));
911 MD5Final(nodedigest, &ctx);
913 for (i = 0; i < length; i++)
914 data[i] = (int)(255 * (rand() / (RAND_MAX + 1.0))) ^
915 nodedigest[i % sizeof nodedigest];
917 if (fd > 0)
918 close(fd);
919 cp = memtob64(data, length);
920 rp = salloc(length+1);
921 strncpy(rp, cp, length)[length] = '\0';
922 free(cp);
923 return rp;
926 void
927 out_of_memory(void)
929 panic("no memory");
932 void *
933 smalloc(size_t s)
935 void *p;
937 if (s == 0)
938 s = 1;
939 if ((p = malloc(s)) == NULL)
940 out_of_memory();
941 return p;
944 void *
945 srealloc(void *v, size_t s)
947 void *r;
949 if (s == 0)
950 s = 1;
951 if (v == NULL)
952 return smalloc(s);
953 if ((r = realloc(v, s)) == NULL)
954 out_of_memory();
955 return r;
958 void *
959 scalloc(size_t nmemb, size_t size)
961 void *vp;
963 if (size == 0)
964 size = 1;
965 if ((vp = calloc(nmemb, size)) == NULL)
966 out_of_memory();
967 return vp;
970 char *
971 sstpcpy(char *dst, const char *src)
973 while ((*dst = *src++) != '\0')
974 dst++;
975 return dst;
978 char *
979 sstrdup(const char *cp)
981 char *dp;
983 if (cp) {
984 dp = smalloc(strlen(cp) + 1);
985 strcpy(dp, cp);
986 return dp;
987 } else
988 return NULL;
991 enum okay
992 makedir(const char *name)
994 int e;
995 struct stat st;
997 if (mkdir(name, 0700) < 0) {
998 e = errno;
999 if ((e == EEXIST || e == ENOSYS) &&
1000 stat(name, &st) == 0 &&
1001 (st.st_mode&S_IFMT) == S_IFDIR)
1002 return OKAY;
1003 return STOP;
1005 return OKAY;
1008 #ifdef HAVE_FCHDIR
1009 enum okay
1010 cwget(struct cw *cw)
1012 if ((cw->cw_fd = open(".", O_RDONLY)) < 0)
1013 return STOP;
1014 if (fchdir(cw->cw_fd) < 0) {
1015 close(cw->cw_fd);
1016 return STOP;
1018 return OKAY;
1021 enum okay
1022 cwret(struct cw *cw)
1024 if (fchdir(cw->cw_fd) < 0)
1025 return STOP;
1026 return OKAY;
1029 void
1030 cwrelse(struct cw *cw)
1032 close(cw->cw_fd);
1034 #else /* !HAVE_FCHDIR */
1035 enum okay
1036 cwget(struct cw *cw)
1038 if (getcwd(cw->cw_wd, sizeof cw->cw_wd) == NULL || chdir(cw->cw_wd) < 0)
1039 return STOP;
1040 return OKAY;
1043 enum okay
1044 cwret(struct cw *cw)
1046 if (chdir(cw->cw_wd) < 0)
1047 return STOP;
1048 return OKAY;
1051 /*ARGSUSED*/
1052 void
1053 cwrelse(struct cw *cw)
1056 #endif /* !HAVE_FCHDIR */
1058 void
1059 makeprint(struct str *in, struct str *out)
1061 static int print_all_chars = -1;
1062 char *inp, *outp;
1063 size_t msz, dist;
1065 out->s = smalloc(msz = in->l + 1);
1066 if (print_all_chars == -1)
1067 print_all_chars = value("print-all-chars") != NULL;
1068 if (print_all_chars) {
1069 memcpy(out->s, in->s, in->l);
1070 out->l = in->l;
1071 out->s[out->l] = '\0';
1072 return;
1074 inp = in->s;
1075 outp = out->s;
1076 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
1077 if (mb_cur_max > 1) {
1078 wchar_t wc;
1079 char mb[MB_LEN_MAX+1];
1080 int i, n;
1081 out->l = 0;
1082 while (inp < &in->s[in->l]) {
1083 if (*inp & 0200)
1084 n = mbtowc(&wc, inp, &in->s[in->l] - inp);
1085 else {
1086 wc = *inp;
1087 n = 1;
1089 if (n < 0) {
1090 mbtowc(&wc, NULL, mb_cur_max);
1091 wc = utf8 ? 0xFFFD : '?';
1092 n = 1;
1093 } else if (n == 0)
1094 n = 1;
1095 inp += n;
1096 if (!iswprint(wc) && wc != '\n' && wc != '\r' &&
1097 wc != '\b' && wc != '\t') {
1098 if ((wc & ~(wchar_t)037) == 0)
1099 wc = utf8 ? 0x2400 | wc : '?';
1100 else if (wc == 0177)
1101 wc = utf8 ? 0x2421 : '?';
1102 else
1103 wc = utf8 ? 0x2426 : '?';
1105 if ((n = wctomb(mb, wc)) <= 0)
1106 continue;
1107 out->l += n;
1108 if (out->l >= msz - 1) {
1109 dist = outp - out->s;
1110 out->s = srealloc(out->s, msz += 32);
1111 outp = &out->s[dist];
1113 for (i = 0; i < n; i++)
1114 *outp++ = mb[i];
1116 } else
1117 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
1119 int c;
1120 while (inp < &in->s[in->l]) {
1121 c = *inp++ & 0377;
1122 if (!isprint(c) && c != '\n' && c != '\r' &&
1123 c != '\b' && c != '\t')
1124 c = '?';
1125 *outp++ = c;
1127 out->l = in->l;
1129 out->s[out->l] = '\0';
1132 char *
1133 prstr(const char *s)
1135 struct str in, out;
1136 char *rp;
1138 in.s = (char *)s;
1139 in.l = strlen(s);
1140 makeprint(&in, &out);
1141 rp = salloc(out.l + 1);
1142 memcpy(rp, out.s, out.l);
1143 rp[out.l] = '\0';
1144 free(out.s);
1145 return rp;
1149 prout(const char *s, size_t sz, FILE *fp)
1151 struct str in, out;
1152 int n;
1154 in.s = (char *)s;
1155 in.l = sz;
1156 makeprint(&in, &out);
1157 n = fwrite(out.s, 1, out.l, fp);
1158 free(out.s);
1159 return n;
1163 * Print out a Unicode character or a substitute for it.
1166 putuc(int u, int c, FILE *fp)
1168 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
1169 if (utf8 && u & ~(wchar_t)0177) {
1170 char mb[MB_LEN_MAX];
1171 int i, n, r = 0;
1172 if ((n = wctomb(mb, u)) > 0) {
1173 for (i = 0; i < n; i++)
1174 r += putc(mb[i] & 0377, fp) != EOF;
1175 return r;
1176 } else if (n == 0)
1177 return putc('\0', fp) != EOF;
1178 else
1179 return 0;
1180 } else
1181 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
1182 return putc(c, fp) != EOF;
1186 * Locale-independent character class functions.
1188 int
1189 asccasecmp(const char *s1, const char *s2)
1191 register int cmp;
1194 if ((cmp = lowerconv(*s1 & 0377) - lowerconv(*s2 & 0377)) != 0)
1195 return cmp;
1196 while (*s1++ != '\0' && *s2++ != '\0');
1197 return 0;
1201 ascncasecmp(const char *s1, const char *s2, size_t sz)
1203 register int cmp;
1204 size_t i = 1;
1206 if (sz == 0)
1207 return 0;
1209 if ((cmp = lowerconv(*s1 & 0377) - lowerconv(*s2 & 0377)) != 0)
1210 return cmp;
1211 while (i++ < sz && *s1++ != '\0' && *s2++ != '\0');
1212 return 0;
1215 char *
1216 asccasestr(const char *haystack, const char *xneedle)
1218 char *needle, *NEEDLE;
1219 int i, sz;
1221 sz = strlen(xneedle);
1222 if (sz == 0)
1223 return (char *)haystack;
1224 needle = ac_alloc(sz);
1225 NEEDLE = ac_alloc(sz);
1226 for (i = 0; i < sz; i++) {
1227 needle[i] = lowerconv(xneedle[i]&0377);
1228 NEEDLE[i] = upperconv(xneedle[i]&0377);
1230 while (*haystack) {
1231 if (*haystack == *needle || *haystack == *NEEDLE) {
1232 for (i = 1; i < sz; i++)
1233 if (haystack[i] != needle[i] &&
1234 haystack[i] != NEEDLE[i])
1235 break;
1236 if (i == sz)
1237 return (char *)haystack;
1239 haystack++;
1241 return NULL;
1244 const unsigned char class_char[] = {
1245 /* 000 nul 001 soh 002 stx 003 etx 004 eot 005 enq 006 ack 007 bel */
1246 C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,
1247 /* 010 bs 011 ht 012 nl 013 vt 014 np 015 cr 016 so 017 si */
1248 C_CNTRL,C_BLANK,C_WHITE,C_SPACE,C_SPACE,C_SPACE,C_CNTRL,C_CNTRL,
1249 /* 020 dle 021 dc1 022 dc2 023 dc3 024 dc4 025 nak 026 syn 027 etb */
1250 C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,
1251 /* 030 can 031 em 032 sub 033 esc 034 fs 035 gs 036 rs 037 us */
1252 C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,
1253 /* 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' */
1254 C_BLANK,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,
1255 /* 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / */
1256 C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,
1257 /* 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 */
1258 C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,
1259 /* 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? */
1260 C_DIGIT,C_DIGIT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,
1261 /* 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G */
1262 C_PUNCT,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,
1263 /* 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O */
1264 C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,
1265 /* 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W */
1266 C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,
1267 /* 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ */
1268 C_UPPER,C_UPPER,C_UPPER,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,
1269 /* 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g */
1270 C_PUNCT,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,
1271 /* 150 h 151 i 152 j 153 k 154 l 155 m 156 n 157 o */
1272 C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,
1273 /* 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w */
1274 C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,
1275 /* 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del */
1276 C_LOWER,C_LOWER,C_LOWER,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_CNTRL