outof(): Mail NULL fix..
[s-mailx.git] / aux.c
blobb8e3700220699a9a250035af26ea4133cb90e2e4
1 /*
2 * S-nail - a mail user agent derived from Berkeley Mail.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 Steffen "Daode" Nurpmeso.
6 */
7 /*
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
40 #include "rcv.h"
41 #include "extern.h"
43 #include <sys/stat.h>
44 #include <utime.h>
45 #include <time.h>
46 #include <termios.h>
47 #include <ctype.h>
48 #ifdef HAVE_WCTYPE_H
49 # include <wctype.h>
50 #endif
51 #ifdef HAVE_WCWIDTH
52 # include <wchar.h>
53 #endif
54 #include <errno.h>
55 #include <sys/stat.h>
56 #include <unistd.h>
57 #include <time.h>
58 #include <dirent.h>
59 #include <fcntl.h>
60 #include <limits.h>
61 #include <stdarg.h>
63 #ifdef USE_MD5
64 # include "md5.h"
65 #endif
68 * Mail -- a mail program
70 * Auxiliary functions.
74 * Lazy vsprintf wrapper.
76 #ifndef HAVE_SNPRINTF
77 int
78 snprintf(char *str, size_t size, const char *format, ...)
80 va_list ap;
81 int ret;
83 va_start(ap, format);
84 ret = vsprintf(str, format, ap);
85 va_end(ap);
86 return ret;
88 #endif
91 * Announce a fatal error and die.
93 void
94 panic(const char *format, ...)
96 va_list ap;
98 va_start(ap, format);
99 fprintf(stderr, catgets(catd, CATSET, 1, "panic: "));
100 vfprintf(stderr, format, ap);
101 va_end(ap);
102 fprintf(stderr, catgets(catd, CATSET, 2, "\n"));
103 fflush(stderr);
104 abort();
107 void
108 holdint(void)
110 sigset_t set;
112 sigemptyset(&set);
113 sigaddset(&set, SIGINT);
114 sigprocmask(SIG_BLOCK, &set, NULL);
117 void
118 relseint(void)
120 sigset_t set;
122 sigemptyset(&set);
123 sigaddset(&set, SIGINT);
124 sigprocmask(SIG_UNBLOCK, &set, NULL);
128 * Touch the named message by setting its MTOUCH flag.
129 * Touched messages have the effect of not being sent
130 * back to the system mailbox on exit.
132 void
133 touch(struct message *mp)
136 mp->m_flag |= MTOUCH;
137 if ((mp->m_flag & MREAD) == 0)
138 mp->m_flag |= MREAD|MSTATUS;
142 * Test to see if the passed file name is a directory.
143 * Return true if it is.
145 int
146 is_dir(char *name)
148 struct stat sbuf;
150 if (stat(name, &sbuf) < 0)
151 return(0);
152 return(S_ISDIR(sbuf.st_mode));
156 * Count the number of arguments in the given string raw list.
158 int
159 argcount(char **argv)
161 char **ap;
163 for (ap = argv; *ap++ != NULL;)
165 return ap - argv - 1;
169 * Copy a string, lowercasing it as we go.
171 void
172 i_strcpy(char *dest, const char *src, int size)
174 char *max;
176 max=dest+size-1;
177 while (dest<=max) {
178 *dest++ = lowerconv(*src & 0377);
179 if (*src++ == '\0')
180 break;
184 char *
185 i_strdup(const char *src)
187 int sz;
188 char *dest;
190 sz = strlen(src) + 1;
191 dest = salloc(sz);
192 i_strcpy(dest, src, sz);
193 return dest;
197 * Convert a string to lowercase, in-place and with multibyte-aware.
199 void
200 makelow(char *cp)
202 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
203 if (mb_cur_max > 1) {
204 char *tp = cp;
205 wchar_t wc;
206 int len;
208 while (*cp) {
209 len = mbtowc(&wc, cp, mb_cur_max);
210 if (len < 0)
211 *tp++ = *cp++;
212 else {
213 wc = towlower(wc);
214 if (wctomb(tp, wc) == len)
215 tp += len, cp += len;
216 else
217 *tp++ = *cp++;
220 } else
221 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
224 *cp = tolower(*cp & 0377);
225 while (*cp++);
229 int
230 substr(const char *str, const char *sub)
232 const char *cp, *backup;
234 cp = sub;
235 backup = str;
236 while (*str && *cp) {
237 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
238 if (mb_cur_max > 1) {
239 wchar_t c, c2;
240 int sz;
242 if ((sz = mbtowc(&c, cp, mb_cur_max)) < 0)
243 goto singlebyte;
244 cp += sz;
245 if ((sz = mbtowc(&c2, str, mb_cur_max)) < 0)
246 goto singlebyte;
247 str += sz;
248 c = towupper(c);
249 c2 = towupper(c2);
250 if (c != c2) {
251 if ((sz = mbtowc(&c, backup, mb_cur_max)) > 0) {
252 backup += sz;
253 str = backup;
254 } else
255 str = ++backup;
256 cp = sub;
258 } else
259 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
261 int c, c2;
263 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
264 singlebyte:
265 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
266 c = *cp++ & 0377;
267 if (islower(c))
268 c = toupper(c);
269 c2 = *str++ & 0377;
270 if (islower(c2))
271 c2 = toupper(c2);
272 if (c != c2) {
273 str = ++backup;
274 cp = sub;
278 return *cp == '\0';
281 char *
282 colalign(const char *cp, int col, int fill)
284 int n, sz;
285 char *nb, *np;
287 np = nb = salloc(mb_cur_max * strlen(cp) + col + 1);
288 while (*cp) {
289 #if defined (HAVE_MBTOWC) && defined (HAVE_WCWIDTH)
290 if (mb_cur_max > 1) {
291 wchar_t wc;
293 if ((sz = mbtowc(&wc, cp, mb_cur_max)) < 0) {
294 n = sz = 1;
295 } else {
296 if ((n = wcwidth(wc)) < 0)
297 n = 1;
299 } else
300 #endif /* HAVE_MBTOWC && HAVE_WCWIDTH */
302 n = sz = 1;
304 if (n > col)
305 break;
306 col -= n;
307 if (sz == 1 && spacechar(*cp&0377)) {
308 *np++ = ' ';
309 cp++;
310 } else
311 while (sz--)
312 *np++ = *cp++;
314 if (fill)
315 while (col-- > 0)
316 *np++ = ' ';
317 *np = '\0';
318 return nb;
321 void
322 try_pager(FILE *fp)
324 long lines = 0;
325 int c;
326 char *cp;
328 fflush(fp);
329 rewind(fp);
330 while ((c = getc(fp)) != EOF)
331 if (c == '\n')
332 lines++;
333 rewind(fp);
334 if (is_a_tty[0] && is_a_tty[1] && (cp = value("crt")) != NULL &&
335 lines > (*cp ? atol(cp) : scrnheight))
336 run_command(get_pager(), 0, fileno(fp), -1, NULL, NULL, NULL);
337 else
338 while ((c = getc(fp)) != EOF)
339 putchar(c);
343 * The following code deals with input stacking to do source
344 * commands. All but the current file pointer are saved on
345 * the stack.
348 static int ssp; /* Top of file stack */
349 struct sstack {
350 FILE *s_file; /* File we were in. */
351 enum condition s_cond; /* Saved state of conditionals */
352 int s_loading; /* Loading .mailrc, etc. */
353 #define SSTACK 20
354 } sstack[SSTACK];
357 * Pushdown current input file and switch to a new one.
358 * Set the global flag "sourcing" so that others will realize
359 * that they are no longer reading from a tty (in all probability).
361 int
362 source(void *v)
364 char **arglist = v;
365 FILE *fi;
366 char *cp;
368 if ((cp = expand(*arglist)) == NULL)
369 return(1);
370 if ((fi = Fopen(cp, "r")) == NULL) {
371 perror(cp);
372 return(1);
374 if (ssp >= SSTACK - 1) {
375 printf(catgets(catd, CATSET, 3,
376 "Too much \"sourcing\" going on.\n"));
377 Fclose(fi);
378 return(1);
380 sstack[ssp].s_file = input;
381 sstack[ssp].s_cond = cond;
382 sstack[ssp].s_loading = loading;
383 ssp++;
384 loading = 0;
385 cond = CANY;
386 input = fi;
387 sourcing++;
388 return(0);
392 * Pop the current input back to the previous level.
393 * Update the "sourcing" flag as appropriate.
395 int
396 unstack(void)
398 if (ssp <= 0) {
399 printf(catgets(catd, CATSET, 4,
400 "\"Source\" stack over-pop.\n"));
401 sourcing = 0;
402 return(1);
404 Fclose(input);
405 if (cond != CANY)
406 printf(catgets(catd, CATSET, 5, "Unmatched \"if\"\n"));
407 ssp--;
408 cond = sstack[ssp].s_cond;
409 loading = sstack[ssp].s_loading;
410 input = sstack[ssp].s_file;
411 if (ssp == 0)
412 sourcing = loading;
413 return(0);
417 * Touch the indicated file.
418 * This is nifty for the shell.
420 void
421 alter(char *name)
423 struct stat sb;
424 struct utimbuf utb;
426 if (stat(name, &sb))
427 return;
428 utb.actime = time((time_t *)0) + 1;
429 utb.modtime = sb.st_mtime;
430 utime(name, &utb);
434 * Examine the passed line buffer and
435 * return true if it is all blanks and tabs.
437 int
438 blankline(char *linebuf)
440 char *cp;
442 for (cp = linebuf; *cp; cp++)
443 if (!blankchar(*cp & 0377))
444 return(0);
445 return(1);
449 * Are any of the characters in the two strings the same?
451 int
452 anyof(char const*s1, char const*s2)
455 while (*s1)
456 if (strchr(s2, *s1++))
457 return 1;
458 return 0;
462 * Determine if as1 is a valid prefix of as2.
463 * Return true if yep.
465 int
466 is_prefix(const char *as1, const char *as2)
468 const char *s1, *s2;
470 s1 = as1;
471 s2 = as2;
472 while (*s1++ == *s2)
473 if (*s2++ == '\0')
474 return(1);
475 return(*--s1 == '\0');
478 char *
479 last_at_before_slash(const char *sp)
481 const char *cp;
483 for (cp = sp; *cp; cp++)
484 if (*cp == '/')
485 break;
486 while (cp > sp && *--cp != '@');
487 return *cp == '@' ? (char *)cp : NULL;
490 enum protocol
491 which_protocol(const char *name)
493 register const char *cp;
494 char *np;
495 size_t sz;
496 struct stat st;
497 enum protocol p;
499 if (name[0] == '%' && name[1] == ':')
500 name += 2;
501 for (cp = name; *cp && *cp != ':'; cp++)
502 if (!alnumchar(*cp&0377))
503 goto file;
504 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
505 if (strncmp(name, "pop3://", 7) == 0)
506 #ifdef USE_POP3
507 return PROTO_POP3;
508 #else
509 fprintf(stderr, catgets(catd, CATSET, 216,
510 "No POP3 support compiled in.\n"));
511 #endif
512 if (strncmp(name, "pop3s://", 8) == 0)
513 #ifdef USE_SSL
514 return PROTO_POP3;
515 #else /* !USE_SSL */
516 fprintf(stderr, catgets(catd, CATSET, 225,
517 "No SSL support compiled in.\n"));
518 #endif /* !USE_SSL */
519 if (strncmp(name, "imap://", 7) == 0)
520 #ifdef USE_IMAP
521 return PROTO_IMAP;
522 #else
523 fprintf(stderr, catgets(catd, CATSET, 269,
524 "No IMAP support compiled in.\n"));
525 #endif
526 if (strncmp(name, "imaps://", 8) == 0)
527 #ifdef USE_SSL
528 return PROTO_IMAP;
529 #else /* !USE_SSL */
530 fprintf(stderr, catgets(catd, CATSET, 225,
531 "No SSL support compiled in.\n"));
532 #endif /* !USE_SSL */
533 return PROTO_UNKNOWN;
534 } else {
535 file: p = PROTO_FILE;
536 np = ac_alloc((sz = strlen(name)) + 5);
537 strcpy(np, name);
538 if (stat(name, &st) == 0) {
539 if (S_ISDIR(st.st_mode)) {
540 strcpy(&np[sz], "/tmp");
541 if (stat(np, &st) == 0 && S_ISDIR(st.st_mode)) {
542 strcpy(&np[sz], "/new");
543 if (stat(np, &st) == 0 &&
544 S_ISDIR(st.st_mode)) {
545 strcpy(&np[sz], "/cur");
546 if (stat(np, &st) == 0 &&
547 S_ISDIR(st.st_mode))
548 p = PROTO_MAILDIR;
552 } else {
553 strcpy(&np[sz], ".gz");
554 if (stat(np, &st) < 0) {
555 strcpy(&np[sz], ".bz2");
556 if (stat(np, &st) < 0) {
557 if ((cp = value("newfolders")) != 0 &&
558 strcmp(cp, "maildir") == 0)
559 p = PROTO_MAILDIR;
563 ac_free(np);
564 return p;
568 const char *
569 protfile(const char *xcp)
571 const char *cp = xcp;
572 int state = 0;
574 while (*cp) {
575 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
576 cp += 3;
577 state = 1;
579 if (cp[0] == '/' && state == 1)
580 return &cp[1];
581 if (cp[0] == '/')
582 return xcp;
583 cp++;
585 return cp;
588 char *
589 protbase(const char *cp)
591 char *n = salloc(strlen(cp) + 1);
592 char *np = n;
594 while (*cp) {
595 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
596 *np++ = *cp++;
597 *np++ = *cp++;
598 *np++ = *cp++;
599 } else if (cp[0] == '/')
600 break;
601 else
602 *np++ = *cp++;
604 *np = '\0';
605 return n;
608 int
609 disconnected(const char *file)
611 char *cp, *cq, *vp;
612 int vs, r;
614 if (value("disconnected"))
615 return 1;
616 cp = protbase(file);
617 if (strncmp(cp, "imap://", 7) == 0)
618 cp += 7;
619 else if (strncmp(cp, "imaps://", 8) == 0)
620 cp += 8;
621 else
622 return 0;
623 if ((cq = strchr(cp, ':')) != NULL)
624 *cq = '\0';
625 vp = ac_alloc(vs = strlen(cp) + 14);
626 snprintf(vp, vs, "disconnected-%s", cp);
627 r = value(vp) != NULL;
628 ac_free(vp);
629 return r;
632 unsigned
633 pjw(const char *cp)
635 unsigned h = 0, g;
637 cp--;
638 while (*++cp) {
639 h = (h << 4 & 0xffffffff) + (*cp&0377);
640 if ((g = h & 0xf0000000) != 0) {
641 h = h ^ g >> 24;
642 h = h ^ g;
645 return h;
648 long
649 nextprime(long n)
651 const long primes[] = {
652 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
653 131071, 262139, 524287, 1048573, 2097143, 4194301,
654 8388593, 16777213, 33554393, 67108859, 134217689,
655 268435399, 536870909, 1073741789, 2147483647
657 long mprime = 7;
658 size_t i;
660 for (i = 0; i < sizeof primes / sizeof *primes; i++)
661 if ((mprime = primes[i]) >= (n < 65536 ? n*4 :
662 n < 262144 ? n*2 : n))
663 break;
664 if (i == sizeof primes / sizeof *primes)
665 mprime = n; /* not so prime, but better than failure */
666 return mprime;
669 #define Hexchar(n) ((n)>9 ? (n)-10+'A' : (n)+'0')
670 #define hexchar(n) ((n)>9 ? (n)-10+'a' : (n)+'0')
672 char *
673 strenc(const char *cp)
675 char *n, *np;
677 np = n = salloc(strlen(cp) * 3 + 1);
678 while (*cp) {
679 if (alnumchar(*cp&0377) || *cp == '_' || *cp == '@' ||
680 (np > n && (*cp == '.' || *cp == '-' ||
681 *cp == ':')))
682 *np++ = *cp;
683 else {
684 *np++ = '%';
685 *np++ = Hexchar((*cp&0xf0) >> 4);
686 *np++ = Hexchar(*cp&0x0f);
688 cp++;
690 *np = '\0';
691 return n;
694 char *
695 strdec(const char *cp)
697 char *n, *np;
699 np = n = salloc(strlen(cp) + 1);
700 while (*cp) {
701 if (cp[0] == '%' && cp[1] && cp[2]) {
702 *np = (int)(cp[1]>'9'?cp[1]-'A'+10:cp[1]-'0') << 4;
703 *np++ |= cp[2]>'9'?cp[2]-'A'+10:cp[2]-'0';
704 cp += 3;
705 } else
706 *np++ = *cp++;
708 *np = '\0';
709 return n;
712 #ifdef USE_MD5
713 char *
714 md5tohex(const void *vp)
716 char *hex;
717 const char *cp = vp;
718 int i;
720 hex = salloc(33);
721 for (i = 0; i < 16; i++) {
722 hex[2*i] = hexchar((cp[i]&0xf0) >> 4);
723 hex[2*i+1] = hexchar(cp[i]&0x0f);
725 hex[32] = '\0';
726 return hex;
729 char *
730 cram_md5_string(const char *user, const char *pass, const char *b64)
732 struct str in, out;
733 char digest[16], *cp, *sp, *rp, *xp;
734 int ss, rs;
736 in.s = (char *)b64;
737 in.l = strlen(in.s);
738 mime_fromb64(&in, &out, 0);
739 hmac_md5((unsigned char *)out.s, out.l,
740 (unsigned char *)pass, strlen(pass),
741 digest);
742 free(out.s);
743 xp = md5tohex(digest);
744 sp = ac_alloc(ss = strlen(user) + strlen(xp) + 2);
745 snprintf(sp, ss, "%s %s", user, xp);
746 cp = strtob64(sp);
747 ac_free(sp);
748 rp = salloc(rs = strlen(cp) + 3);
749 snprintf(rp, rs, "%s\r\n", cp);
750 free(cp);
751 return rp;
753 #endif /* USE_MD5 */
755 char *
756 getuser(void)
758 char *line = NULL, *user;
759 size_t linesize = 0;
761 if (is_a_tty[0]) {
762 fputs("User: ", stdout);
763 fflush(stdout);
765 if (readline(stdin, &line, &linesize) == 0) {
766 if (line)
767 free(line);
768 return NULL;
770 user = savestr(line);
771 free(line);
772 return user;
775 char *
776 getpassword(struct termios *otio, int *reset_tio, const char *query)
778 struct termios tio;
779 char *line = NULL, *pass;
780 size_t linesize = 0;
781 int i;
783 if (is_a_tty[0]) {
784 fputs(query ? query : "Password:", stdout);
785 fflush(stdout);
786 tcgetattr(0, &tio);
787 *otio = tio;
788 tio.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
789 *reset_tio = 1;
790 tcsetattr(0, TCSAFLUSH, &tio);
792 i = readline(stdin, &line, &linesize);
793 if (is_a_tty[0]) {
794 fputc('\n', stdout);
795 tcsetattr(0, TCSADRAIN, otio);
797 *reset_tio = 0;
798 if (i < 0) {
799 if (line)
800 free(line);
801 return NULL;
803 pass = savestr(line);
804 free(line);
805 return pass;
808 void
809 transflags(struct message *omessage, long omsgCount, int transparent)
811 struct message *omp, *nmp, *newdot, *newprevdot;
812 int hf;
814 omp = omessage;
815 nmp = message;
816 newdot = message;
817 newprevdot = NULL;
818 while (omp < &omessage[omsgCount] &&
819 nmp < &message[msgCount]) {
820 if (dot && nmp->m_uid == dot->m_uid)
821 newdot = nmp;
822 if (prevdot && nmp->m_uid == prevdot->m_uid)
823 newprevdot = nmp;
824 if (omp->m_uid == nmp->m_uid) {
825 hf = nmp->m_flag & MHIDDEN;
826 if (transparent && mb.mb_type == MB_IMAP)
827 omp->m_flag &= ~MHIDDEN;
828 *nmp++ = *omp++;
829 if (transparent && mb.mb_type == MB_CACHE)
830 nmp[-1].m_flag |= hf;
831 } else if (omp->m_uid < nmp->m_uid)
832 omp++;
833 else
834 nmp++;
836 dot = newdot;
837 setdot(newdot);
838 prevdot = newprevdot;
839 free(omessage);
842 char *
843 getrandstring(size_t length)
845 static unsigned char nodedigest[16];
846 static pid_t pid;
847 int fd = -1;
848 char *data;
849 char *cp, *rp;
850 size_t i;
851 #ifdef USE_MD5
852 MD5_CTX ctx;
853 #else
854 size_t j;
855 #endif
857 data = salloc(length);
858 if ((fd = open("/dev/urandom", O_RDONLY)) < 0 ||
859 length != (size_t)read(fd, data, length)) {
860 if (pid == 0) {
861 pid = getpid();
862 srand(pid);
863 cp = nodename(0);
864 #ifdef USE_MD5
865 MD5Init(&ctx);
866 MD5Update(&ctx, (unsigned char *)cp, strlen(cp));
867 MD5Final(nodedigest, &ctx);
868 #else
869 /* In that case it's only used for boundaries and
870 * Message-Id:s so that srand(3) should suffice */
871 j = strlen(cp) + 1;
872 for (i = 0; i < sizeof(nodedigest); ++i)
873 nodedigest[i] = (unsigned char)(
874 cp[i % j] ^ rand());
875 #endif
877 for (i = 0; i < length; i++)
878 data[i] = (char)
879 ((int)(255 * (rand() / (RAND_MAX + 1.0))) ^
880 nodedigest[i % sizeof nodedigest]);
882 if (fd > 0)
883 close(fd);
884 cp = memtob64(data, length);
885 rp = salloc(length+1);
886 strncpy(rp, cp, length)[length] = '\0';
887 free(cp);
888 return rp;
891 void
892 out_of_memory(void)
894 panic("no memory");
897 void *
898 smalloc(size_t s)
900 void *p;
902 if (s == 0)
903 s = 1;
904 if ((p = malloc(s)) == NULL)
905 out_of_memory();
906 return p;
909 void *
910 srealloc(void *v, size_t s)
912 void *r;
914 if (s == 0)
915 s = 1;
916 if (v == NULL)
917 return smalloc(s);
918 if ((r = realloc(v, s)) == NULL)
919 out_of_memory();
920 return r;
923 void *
924 scalloc(size_t nmemb, size_t size)
926 void *vp;
928 if (size == 0)
929 size = 1;
930 if ((vp = calloc(nmemb, size)) == NULL)
931 out_of_memory();
932 return vp;
935 char *
936 sstpcpy(char *dst, const char *src)
938 while ((*dst = *src++) != '\0')
939 dst++;
940 return dst;
943 char *
944 sstrdup(const char *cp)
946 char *dp;
948 if (cp) {
949 dp = smalloc(strlen(cp) + 1);
950 strcpy(dp, cp);
951 return dp;
952 } else
953 return NULL;
956 enum okay
957 makedir(const char *name)
959 int e;
960 struct stat st;
962 if (mkdir(name, 0700) < 0) {
963 e = errno;
964 if ((e == EEXIST || e == ENOSYS) &&
965 stat(name, &st) == 0 &&
966 (st.st_mode&S_IFMT) == S_IFDIR)
967 return OKAY;
968 return STOP;
970 return OKAY;
973 #ifdef HAVE_FCHDIR
974 enum okay
975 cwget(struct cw *cw)
977 if ((cw->cw_fd = open(".", O_RDONLY)) < 0)
978 return STOP;
979 if (fchdir(cw->cw_fd) < 0) {
980 close(cw->cw_fd);
981 return STOP;
983 return OKAY;
986 enum okay
987 cwret(struct cw *cw)
989 if (fchdir(cw->cw_fd) < 0)
990 return STOP;
991 return OKAY;
994 void
995 cwrelse(struct cw *cw)
997 close(cw->cw_fd);
999 #else /* !HAVE_FCHDIR */
1000 enum okay
1001 cwget(struct cw *cw)
1003 if (getcwd(cw->cw_wd, sizeof cw->cw_wd) == NULL || chdir(cw->cw_wd) < 0)
1004 return STOP;
1005 return OKAY;
1008 enum okay
1009 cwret(struct cw *cw)
1011 if (chdir(cw->cw_wd) < 0)
1012 return STOP;
1013 return OKAY;
1016 /*ARGSUSED*/
1017 void
1018 cwrelse(struct cw *cw)
1021 #endif /* !HAVE_FCHDIR */
1023 void
1024 makeprint(struct str *in, struct str *out)
1026 static int print_all_chars = -1;
1027 char *inp, *outp;
1028 size_t msz, dist;
1030 out->s = smalloc(msz = in->l + 1);
1031 if (print_all_chars == -1)
1032 print_all_chars = value("print-all-chars") != NULL;
1033 if (print_all_chars) {
1034 memcpy(out->s, in->s, in->l);
1035 out->l = in->l;
1036 out->s[out->l] = '\0';
1037 return;
1039 inp = in->s;
1040 outp = out->s;
1041 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
1042 if (mb_cur_max > 1) {
1043 wchar_t wc;
1044 char mb[MB_LEN_MAX+1];
1045 int i, n;
1046 out->l = 0;
1047 while (inp < &in->s[in->l]) {
1048 if (*inp & 0200)
1049 n = mbtowc(&wc, inp, &in->s[in->l] - inp);
1050 else {
1051 wc = *inp;
1052 n = 1;
1054 if (n < 0) {
1055 mbtowc(&wc, NULL, mb_cur_max);
1056 wc = utf8 ? 0xFFFD : '?';
1057 n = 1;
1058 } else if (n == 0)
1059 n = 1;
1060 inp += n;
1061 if (!iswprint(wc) && wc != '\n' && wc != '\r' &&
1062 wc != '\b' && wc != '\t') {
1063 if ((wc & ~(wchar_t)037) == 0)
1064 wc = utf8 ? 0x2400 | wc : '?';
1065 else if (wc == 0177)
1066 wc = utf8 ? 0x2421 : '?';
1067 else
1068 wc = utf8 ? 0x2426 : '?';
1070 if ((n = wctomb(mb, wc)) <= 0)
1071 continue;
1072 out->l += n;
1073 if (out->l >= msz - 1) {
1074 dist = outp - out->s;
1075 out->s = srealloc(out->s, msz += 32);
1076 outp = &out->s[dist];
1078 for (i = 0; i < n; i++)
1079 *outp++ = mb[i];
1081 } else
1082 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
1084 int c;
1085 while (inp < &in->s[in->l]) {
1086 c = *inp++ & 0377;
1087 if (!isprint(c) && c != '\n' && c != '\r' &&
1088 c != '\b' && c != '\t')
1089 c = '?';
1090 *outp++ = c;
1092 out->l = in->l;
1094 out->s[out->l] = '\0';
1097 char *
1098 prstr(const char *s)
1100 struct str in, out;
1101 char *rp;
1103 in.s = (char *)s;
1104 in.l = strlen(s);
1105 makeprint(&in, &out);
1106 rp = salloc(out.l + 1);
1107 memcpy(rp, out.s, out.l);
1108 rp[out.l] = '\0';
1109 free(out.s);
1110 return rp;
1114 prout(const char *s, size_t sz, FILE *fp)
1116 struct str in, out;
1117 int n;
1119 in.s = (char *)s;
1120 in.l = sz;
1121 makeprint(&in, &out);
1122 n = fwrite(out.s, 1, out.l, fp);
1123 free(out.s);
1124 return n;
1128 * Print out a Unicode character or a substitute for it.
1131 putuc(int u, int c, FILE *fp)
1133 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
1134 if (utf8 && u & ~(wchar_t)0177) {
1135 char mb[MB_LEN_MAX];
1136 int i, n, r = 0;
1137 if ((n = wctomb(mb, u)) > 0) {
1138 for (i = 0; i < n; i++)
1139 r += putc(mb[i] & 0377, fp) != EOF;
1140 return r;
1141 } else if (n == 0)
1142 return putc('\0', fp) != EOF;
1143 else
1144 return 0;
1145 } else
1146 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
1147 return putc(c, fp) != EOF;
1151 * Locale-independent character class functions.
1153 int
1154 asccasecmp(const char *s1, const char *s2)
1156 register int cmp;
1159 if ((cmp = lowerconv(*s1 & 0377) - lowerconv(*s2 & 0377)) != 0)
1160 return cmp;
1161 while (*s1++ != '\0' && *s2++ != '\0');
1162 return 0;
1166 ascncasecmp(const char *s1, const char *s2, size_t sz)
1168 register int cmp;
1169 size_t i = 1;
1171 if (sz == 0)
1172 return 0;
1174 if ((cmp = lowerconv(*s1 & 0377) - lowerconv(*s2 & 0377)) != 0)
1175 return cmp;
1176 while (i++ < sz && *s1++ != '\0' && *s2++ != '\0');
1177 return 0;
1180 char *
1181 asccasestr(const char *haystack, const char *xneedle)
1183 char *needle, *NEEDLE;
1184 int i, sz;
1186 sz = strlen(xneedle);
1187 if (sz == 0)
1188 return (char *)haystack;
1189 needle = ac_alloc(sz);
1190 NEEDLE = ac_alloc(sz);
1191 for (i = 0; i < sz; i++) {
1192 needle[i] = lowerconv(xneedle[i]&0377);
1193 NEEDLE[i] = upperconv(xneedle[i]&0377);
1195 while (*haystack) {
1196 if (*haystack == *needle || *haystack == *NEEDLE) {
1197 for (i = 1; i < sz; i++)
1198 if (haystack[i] != needle[i] &&
1199 haystack[i] != NEEDLE[i])
1200 break;
1201 if (i == sz)
1202 return (char *)haystack;
1204 haystack++;
1206 return NULL;
1209 const unsigned char class_char[] = {
1210 /* 000 nul 001 soh 002 stx 003 etx 004 eot 005 enq 006 ack 007 bel */
1211 C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,
1212 /* 010 bs 011 ht 012 nl 013 vt 014 np 015 cr 016 so 017 si */
1213 C_CNTRL,C_BLANK,C_WHITE,C_SPACE,C_SPACE,C_SPACE,C_CNTRL,C_CNTRL,
1214 /* 020 dle 021 dc1 022 dc2 023 dc3 024 dc4 025 nak 026 syn 027 etb */
1215 C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,
1216 /* 030 can 031 em 032 sub 033 esc 034 fs 035 gs 036 rs 037 us */
1217 C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,C_CNTRL,
1218 /* 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' */
1219 C_BLANK,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,
1220 /* 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / */
1221 C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,
1222 /* 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 */
1223 C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,C_OCTAL,
1224 /* 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? */
1225 C_DIGIT,C_DIGIT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,
1226 /* 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G */
1227 C_PUNCT,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,
1228 /* 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O */
1229 C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,
1230 /* 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W */
1231 C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,C_UPPER,
1232 /* 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ */
1233 C_UPPER,C_UPPER,C_UPPER,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,
1234 /* 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g */
1235 C_PUNCT,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,
1236 /* 150 h 151 i 152 j 153 k 154 l 155 m 156 n 157 o */
1237 C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,
1238 /* 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w */
1239 C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,C_LOWER,
1240 /* 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del */
1241 C_LOWER,C_LOWER,C_LOWER,C_PUNCT,C_PUNCT,C_PUNCT,C_PUNCT,C_CNTRL