NEWS: update for v14.5.2
[s-mailx.git] / auxlily.c
blob97952c72db9cf3cc5d8da1e2a8799561ba89188d
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Auxiliary functions.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2014 Steffen "Daode" Nurpmeso <sdaoden@users.sf.net>.
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 #ifndef HAVE_AMALGAMATION
41 # include "nail.h"
42 #endif
44 #include <sys/utsname.h>
46 #include <ctype.h>
47 #include <dirent.h>
48 #include <fcntl.h>
50 #ifdef HAVE_SOCKETS
51 # ifdef HAVE_IPV6
52 # include <sys/socket.h>
53 # endif
55 # include <netdb.h>
56 #endif
58 #ifdef HAVE_MD5
59 # include "md5.h"
60 #endif
62 /* Create an ISO 6429 (ECMA-48/ANSI) terminal control escape sequence */
63 #ifdef HAVE_COLOUR
64 static char * _colour_iso6429(char const *wish);
65 #endif
67 /* {hold,rele}_all_sigs() */
68 static size_t _alls_depth;
69 static sigset_t _alls_nset, _alls_oset;
71 /* {hold,rele}_sigs() */
72 static size_t _hold_sigdepth;
73 static sigset_t _hold_nset, _hold_oset;
75 #ifdef HAVE_COLOUR
76 static char *
77 _colour_iso6429(char const *wish)
79 char const * const wish_orig = wish;
80 char *xwish, *cp, cfg[3] = {0, 0, 0};
82 /* Since we use salloc(), reuse the strcomma() buffer also for the return
83 * value, ensure we have enough room for that */
85 size_t i = strlen(wish) + 1;
86 xwish = salloc(MAX(i, sizeof("\033[1;30;40m")));
87 memcpy(xwish, wish, i);
88 wish = xwish;
91 /* Iterate over the colour spec */
92 while ((cp = strcomma(&xwish, TRU1)) != NULL) {
93 char *y, *x = strchr(cp, '=');
94 if (x == NULL) {
95 jbail:
96 fprintf(stderr, tr(527,
97 "Invalid colour specification \"%s\": >>> %s <<<\n"),
98 wish_orig, cp);
99 continue;
101 *x++ = '\0';
103 /* TODO convert the ft/fg/bg parser into a table-based one! */
104 if (!asccasecmp(cp, "ft")) {
105 if (!asccasecmp(x, "bold"))
106 cfg[0] = '1';
107 else if (!asccasecmp(x, "inverse"))
108 cfg[0] = '7';
109 else if (!asccasecmp(x, "underline"))
110 cfg[0] = '4';
111 else
112 goto jbail;
113 } else if (!asccasecmp(cp, "fg")) {
114 y = cfg + 1;
115 goto jiter_colour;
116 } else if (!asccasecmp(cp, "bg")) {
117 y = cfg + 2;
118 jiter_colour:
119 if (!asccasecmp(x, "black"))
120 *y = '0';
121 else if (!asccasecmp(x, "blue"))
122 *y = '4';
123 else if (!asccasecmp(x, "green"))
124 *y = '2';
125 else if (!asccasecmp(x, "red"))
126 *y = '1';
127 else if (!asccasecmp(x, "brown"))
128 *y = '3';
129 else if (!asccasecmp(x, "magenta"))
130 *y = '5';
131 else if (!asccasecmp(x, "cyan"))
132 *y = '6';
133 else if (!asccasecmp(x, "white"))
134 *y = '7';
135 else
136 goto jbail;
137 } else
138 goto jbail;
141 /* Restore our salloc() buffer, create return value */
142 xwish = UNCONST(wish);
143 if (cfg[0] || cfg[1] || cfg[2]) {
144 xwish[0] = '\033';
145 xwish[1] = '[';
146 xwish += 2;
147 if (cfg[0])
148 *xwish++ = cfg[0];
149 if (cfg[1]) {
150 if (cfg[0])
151 *xwish++ = ';';
152 xwish[0] = '3';
153 xwish[1] = cfg[1];
154 xwish += 2;
156 if (cfg[2]) {
157 if (cfg[0] || cfg[1])
158 *xwish++ = ';';
159 xwish[0] = '4';
160 xwish[1] = cfg[2];
161 xwish += 2;
163 *xwish++ = 'm';
165 *xwish = '\0';
166 return UNCONST(wish);
168 #endif /* HAVE_COLOUR */
170 FL void
171 panic(char const *format, ...)
173 va_list ap;
175 fprintf(stderr, tr(1, "Panic: "));
177 va_start(ap, format);
178 vfprintf(stderr, format, ap);
179 va_end(ap);
181 fputs("\n", stderr);
182 fflush(stderr);
183 exit(EXIT_ERR);
186 #ifdef HAVE_DEBUG
187 FL void
188 warn(char const *format, ...)
190 va_list ap;
192 fprintf(stderr, tr(1, "Panic: "));
194 va_start(ap, format);
195 vfprintf(stderr, format, ap);
196 va_end(ap);
198 fputs("\n", stderr);
199 fflush(stderr);
201 #endif
203 FL sighandler_type
204 safe_signal(int signum, sighandler_type handler)
206 struct sigaction nact, oact;
208 nact.sa_handler = handler;
209 sigemptyset(&nact.sa_mask);
210 nact.sa_flags = 0;
211 #ifdef SA_RESTART
212 nact.sa_flags |= SA_RESTART;
213 #endif
214 return ((sigaction(signum, &nact, &oact) != 0) ? SIG_ERR : oact.sa_handler);
217 FL void
218 hold_all_sigs(void)
220 if (_alls_depth++ == 0) {
221 sigfillset(&_alls_nset);
222 sigdelset(&_alls_nset, SIGABRT);
223 #ifdef SIGBUS
224 sigdelset(&_alls_nset, SIGBUS);
225 #endif
226 sigdelset(&_alls_nset, SIGCHLD);
227 sigdelset(&_alls_nset, SIGFPE);
228 sigdelset(&_alls_nset, SIGILL);
229 sigdelset(&_alls_nset, SIGKILL);
230 sigdelset(&_alls_nset, SIGSEGV);
231 sigdelset(&_alls_nset, SIGSTOP);
232 sigprocmask(SIG_BLOCK, &_alls_nset, &_alls_oset);
236 FL void
237 rele_all_sigs(void)
239 if (--_alls_depth == 0)
240 sigprocmask(SIG_SETMASK, &_alls_oset, (sigset_t*)NULL);
243 FL void
244 hold_sigs(void)
246 if (_hold_sigdepth++ == 0) {
247 sigemptyset(&_hold_nset);
248 sigaddset(&_hold_nset, SIGHUP);
249 sigaddset(&_hold_nset, SIGINT);
250 sigaddset(&_hold_nset, SIGQUIT);
251 sigprocmask(SIG_BLOCK, &_hold_nset, &_hold_oset);
255 FL void
256 rele_sigs(void)
258 if (--_hold_sigdepth == 0)
259 sigprocmask(SIG_SETMASK, &_hold_oset, NULL);
263 * Touch the named message by setting its MTOUCH flag.
264 * Touched messages have the effect of not being sent
265 * back to the system mailbox on exit.
267 FL void
268 touch(struct message *mp)
271 mp->m_flag |= MTOUCH;
272 if ((mp->m_flag & MREAD) == 0)
273 mp->m_flag |= MREAD|MSTATUS;
277 * Test to see if the passed file name is a directory.
278 * Return true if it is.
280 FL int
281 is_dir(char const *name)
283 struct stat sbuf;
285 if (stat(name, &sbuf) < 0)
286 return(0);
287 return(S_ISDIR(sbuf.st_mode));
291 * Count the number of arguments in the given string raw list.
293 FL int
294 argcount(char **argv)
296 char **ap;
298 for (ap = argv; *ap++ != NULL;)
300 return ap - argv - 1;
303 FL char *
304 colalign(const char *cp, int col, int fill, int *cols_decr_used_or_null)
306 int col_orig = col, n, sz;
307 char *nb, *np;
309 np = nb = salloc(mb_cur_max * strlen(cp) + col + 1);
310 while (*cp) {
311 #ifdef HAVE_WCWIDTH
312 if (mb_cur_max > 1) {
313 wchar_t wc;
315 if ((sz = mbtowc(&wc, cp, mb_cur_max)) < 0) {
316 n = sz = 1;
317 } else {
318 if ((n = wcwidth(wc)) < 0)
319 n = 1;
321 } else
322 #endif
324 n = sz = 1;
326 if (n > col)
327 break;
328 col -= n;
329 if (sz == 1 && spacechar(*cp)) {
330 *np++ = ' ';
331 cp++;
332 } else
333 while (sz--)
334 *np++ = *cp++;
337 if (fill && col != 0) {
338 if (fill > 0) {
339 memmove(nb + col, nb, (size_t)(np - nb));
340 memset(nb, ' ', col);
341 } else
342 memset(np, ' ', col);
343 np += col;
344 col = 0;
347 *np = '\0';
348 if (cols_decr_used_or_null != NULL)
349 *cols_decr_used_or_null -= col_orig - col;
350 return nb;
353 FL char const *
354 get_pager(void)
356 char const *cp;
358 cp = ok_vlook(PAGER);
359 if (cp == NULL || *cp == '\0')
360 cp = XPAGER;
361 return cp;
364 FL size_t
365 paging_seems_sensible(void)
367 size_t ret = 0;
368 char const *cp;
370 if (IS_TTY_SESSION() && (cp = ok_vlook(crt)) != NULL)
371 ret = (*cp != '\0') ? (size_t)atol(cp) : (size_t)scrnheight;
372 return ret;
375 FL void
376 page_or_print(FILE *fp, size_t lines)
378 size_t rows;
379 int c;
381 fflush_rewind(fp);
383 if ((rows = paging_seems_sensible()) != 0 && lines == 0) {
384 while ((c = getc(fp)) != EOF)
385 if (c == '\n' && ++lines > rows)
386 break;
387 rewind(fp);
390 if (rows != 0 && lines >= rows)
391 run_command(get_pager(), 0, fileno(fp), -1, NULL, NULL, NULL);
392 else
393 while ((c = getc(fp)) != EOF)
394 putchar(c);
397 FL enum protocol
398 which_protocol(const char *name)
400 register const char *cp;
401 char *np;
402 size_t sz;
403 struct stat st;
404 enum protocol p;
406 if (name[0] == '%' && name[1] == ':')
407 name += 2;
408 for (cp = name; *cp && *cp != ':'; cp++)
409 if (!alnumchar(*cp&0377))
410 goto file;
411 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
412 if (strncmp(name, "pop3://", 7) == 0)
413 #ifdef HAVE_POP3
414 return PROTO_POP3;
415 #else
416 fprintf(stderr,
417 tr(216, "No POP3 support compiled in.\n"));
418 #endif
419 if (strncmp(name, "pop3s://", 8) == 0)
420 #ifdef HAVE_SSL
421 return PROTO_POP3;
422 #else
423 fprintf(stderr,
424 tr(225, "No SSL support compiled in.\n"));
425 #endif
426 if (strncmp(name, "imap://", 7) == 0)
427 #ifdef HAVE_IMAP
428 return PROTO_IMAP;
429 #else
430 fprintf(stderr,
431 tr(269, "No IMAP support compiled in.\n"));
432 #endif
433 if (strncmp(name, "imaps://", 8) == 0)
434 #ifdef HAVE_SSL
435 return PROTO_IMAP;
436 #else
437 fprintf(stderr,
438 tr(225, "No SSL support compiled in.\n"));
439 #endif
440 return PROTO_UNKNOWN;
441 } else {
442 /* TODO This is the de facto maildir code and thus belongs
443 * TODO into maildir! */
444 file: p = PROTO_FILE;
445 np = ac_alloc((sz = strlen(name)) + 5);
446 memcpy(np, name, sz + 1);
447 if (stat(name, &st) == 0) {
448 if (S_ISDIR(st.st_mode)) {
449 strcpy(&np[sz], "/tmp");
450 if (stat(np, &st) == 0 && S_ISDIR(st.st_mode)) {
451 strcpy(&np[sz], "/new");
452 if (stat(np, &st) == 0 &&
453 S_ISDIR(st.st_mode)) {
454 strcpy(&np[sz], "/cur");
455 if (stat(np, &st) == 0 &&
456 S_ISDIR(st.st_mode))
457 p = PROTO_MAILDIR;
461 } else {
462 strcpy(&np[sz], ".gz");
463 if (stat(np, &st) < 0) {
464 strcpy(&np[sz], ".bz2");
465 if (stat(np, &st) < 0) {
466 if ((cp = ok_vlook(newfolders)) != NULL &&
467 strcmp(cp, "maildir") == 0)
468 p = PROTO_MAILDIR;
472 ac_free(np);
473 return p;
477 FL ui32_t
478 torek_hash(char const *name)
480 /* Chris Torek's hash.
481 * NOTE: need to change *at least* create-okey-map.pl when changing the
482 * algorithm!! */
483 ui32_t h = 0;
485 while (*name != '\0') {
486 h *= 33;
487 h += *name++;
489 return h;
492 FL unsigned
493 pjw(const char *cp)
495 unsigned h = 0, g;
497 cp--;
498 while (*++cp) {
499 h = (h << 4 & 0xffffffff) + (*cp&0377);
500 if ((g = h & 0xf0000000) != 0) {
501 h = h ^ g >> 24;
502 h = h ^ g;
505 return h;
508 FL long
509 nextprime(long n)
511 const long primes[] = {
512 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
513 131071, 262139, 524287, 1048573, 2097143, 4194301,
514 8388593, 16777213, 33554393, 67108859, 134217689,
515 268435399, 536870909, 1073741789, 2147483647
517 long mprime = 7;
518 size_t i;
520 for (i = 0; i < sizeof primes / sizeof *primes; i++)
521 if ((mprime = primes[i]) >= (n < 65536 ? n*4 :
522 n < 262144 ? n*2 : n))
523 break;
524 if (i == sizeof primes / sizeof *primes)
525 mprime = n; /* not so prime, but better than failure */
526 return mprime;
529 FL int
530 expand_shell_escape(char const **s, bool_t use_nail_extensions)
532 char const *xs = *s;
533 int c, n;
535 if ((c = *xs & 0xFF) == '\0')
536 goto jleave;
537 ++xs;
538 if (c != '\\')
539 goto jleave;
541 switch ((c = *xs & 0xFF)) {
542 case '\\': break;
543 case 'a': c = '\a'; break;
544 case 'b': c = '\b'; break;
545 case 'c': c = PROMPT_STOP; break;
546 case 'f': c = '\f'; break;
547 case 'n': c = '\n'; break;
548 case 'r': c = '\r'; break;
549 case 't': c = '\t'; break;
550 case 'v': c = '\v'; break;
551 case '0':
552 for (++xs, c = 0, n = 4; --n > 0 && octalchar(*xs); ++xs) {
553 c <<= 3;
554 c |= *xs - '0';
556 goto jleave;
557 /* S-nail extension for nice (get)prompt(()) support */
558 case '&':
559 case '?':
560 case '$':
561 case '@':
562 if (use_nail_extensions) {
563 switch (c) {
564 case '&': c = ok_blook(bsdcompat) ? '&' : '?'; break;
565 case '?': c = exec_last_comm_error ? '1' : '0'; break;
566 case '$': c = PROMPT_DOLLAR; break;
567 case '@': c = PROMPT_AT; break;
569 break;
571 /* FALLTHRU */
572 case '\0':
573 /* A sole <backslash> at EOS is treated as-is! */
574 /* FALLTHRU */
575 default:
576 c = '\\';
577 goto jleave;
579 ++xs;
580 jleave:
581 *s = xs;
582 return c;
585 FL char *
586 getprompt(void)
588 static char buf[PROMPT_BUFFER_SIZE];
590 char *cp = buf;
591 char const *ccp;
593 if ((ccp = ok_vlook(prompt)) == NULL || *ccp == '\0')
594 goto jleave;
596 for (; PTRCMP(cp, <, buf + sizeof(buf) - 1); ++cp) {
597 char const *a;
598 size_t l;
599 int c = expand_shell_escape(&ccp, TRU1);
601 if (c > 0) {
602 *cp = (char)c;
603 continue;
605 if (c == 0 || c == PROMPT_STOP)
606 break;
608 a = (c == PROMPT_DOLLAR) ? account_name : displayname;
609 if (a == NULL)
610 a = "";
611 l = strlen(a);
612 if (PTRCMP(cp + l, >=, buf + sizeof(buf) - 1))
613 *cp++ = '?';
614 else {
615 memcpy(cp, a, l);
616 cp += --l;
619 jleave:
620 *cp = '\0';
621 return buf;
624 FL char *
625 nodename(int mayoverride)
627 static char *hostname;
628 struct utsname ut;
629 char *hn;
630 #ifdef HAVE_SOCKETS
631 # ifdef HAVE_IPV6
632 struct addrinfo hints, *res;
633 # else
634 struct hostent *hent;
635 # endif
636 #endif
638 if (mayoverride && (hn = ok_vlook(hostname)) != NULL && *hn != '\0') {
639 if (hostname != NULL)
640 free(hostname);
641 hostname = sstrdup(hn);
642 } else if (hostname == NULL) {
643 uname(&ut);
644 hn = ut.nodename;
645 #ifdef HAVE_SOCKETS
646 # ifdef HAVE_IPV6
647 memset(&hints, 0, sizeof hints);
648 hints.ai_family = AF_UNSPEC;
649 hints.ai_socktype = SOCK_DGRAM; /* dummy */
650 hints.ai_flags = AI_CANONNAME;
651 if (getaddrinfo(hn, "0", &hints, &res) == 0) {
652 if (res->ai_canonname != NULL) {
653 size_t l = strlen(res->ai_canonname);
654 hn = ac_alloc(l + 1);
655 memcpy(hn, res->ai_canonname, l + 1);
657 freeaddrinfo(res);
659 # else
660 hent = gethostbyname(hn);
661 if (hent != NULL) {
662 hn = hent->h_name;
664 # endif
665 #endif
666 hostname = sstrdup(hn);
667 #if defined HAVE_SOCKETS && defined HAVE_IPV6
668 if (hn != ut.nodename)
669 ac_free(hn);
670 #endif
672 return (hostname);
675 FL char *
676 lookup_password_for_token(char const *token)
678 size_t tl;
679 char *var, *cp;
681 tl = strlen(token);
682 var = ac_alloc(tl + 10);
684 memcpy(var, "password-", 9);
685 memcpy(var + 9, token, tl);
686 var[tl + 9] = '\0';
688 if ((cp = vok_vlook(var)) != NULL)
689 cp = savestr(cp);
690 ac_free(var);
691 return cp;
694 FL char *
695 getrandstring(size_t length)
697 static unsigned char nodedigest[16];
698 static pid_t pid;
699 struct str b64;
700 int fd = -1;
701 char *data, *cp;
702 size_t i;
703 #ifdef HAVE_MD5
704 md5_ctx ctx;
705 #else
706 size_t j;
707 #endif
709 data = ac_alloc(length);
710 if ((fd = open("/dev/urandom", O_RDONLY)) < 0 ||
711 length != (size_t)read(fd, data, length)) {
712 if (pid == 0) {
713 pid = getpid();
714 srand(pid);
715 cp = nodename(0);
716 #ifdef HAVE_MD5
717 md5_init(&ctx);
718 md5_update(&ctx, (unsigned char*)cp, strlen(cp));
719 md5_final(nodedigest, &ctx);
720 #else
721 /* In that case it's only used for boundaries and
722 * Message-Id:s so that srand(3) should suffice */
723 j = strlen(cp) + 1;
724 for (i = 0; i < sizeof(nodedigest); ++i)
725 nodedigest[i] = (unsigned char)(
726 cp[i % j] ^ rand());
727 #endif
729 for (i = 0; i < length; i++)
730 data[i] = (char)(
731 (int)(255 * (rand() / (RAND_MAX + 1.0))) ^
732 nodedigest[i % sizeof nodedigest]);
734 if (fd >= 0)
735 close(fd);
737 (void)b64_encode_buf(&b64, data, length, B64_SALLOC);
738 ac_free(data);
739 assert(length < b64.l);
740 b64.s[length] = '\0';
741 return b64.s;
744 #ifdef HAVE_MD5
745 FL char *
746 md5tohex(char hex[MD5TOHEX_SIZE], void const *vp)
748 char const *cp = vp;
749 size_t i, j;
751 for (i = 0; i < MD5TOHEX_SIZE / 2; i++) {
752 j = i << 1;
753 hex[j] = hexchar((cp[i] & 0xf0) >> 4);
754 hex[++j] = hexchar(cp[i] & 0x0f);
756 return hex;
759 FL char *
760 cram_md5_string(char const *user, char const *pass, char const *b64)
762 struct str in, out;
763 char digest[16], *cp;
764 size_t lu;
766 out.s = NULL;
767 in.s = UNCONST(b64);
768 in.l = strlen(in.s);
769 (void)b64_decode(&out, &in, NULL);
770 assert(out.s != NULL);
772 hmac_md5((unsigned char*)out.s, out.l, UNCONST(pass), strlen(pass),
773 digest);
774 free(out.s);
775 cp = md5tohex(salloc(MD5TOHEX_SIZE + 1), digest);
777 lu = strlen(user);
778 in.l = lu + MD5TOHEX_SIZE +1;
779 in.s = ac_alloc(lu + 1 + MD5TOHEX_SIZE +1);
780 memcpy(in.s, user, lu);
781 in.s[lu] = ' ';
782 memcpy(in.s + lu + 1, cp, MD5TOHEX_SIZE);
783 (void)b64_encode(&out, &in, B64_SALLOC|B64_CRLF);
784 ac_free(in.s);
785 return out.s;
787 #endif /* HAVE_MD5 */
789 FL enum okay
790 makedir(const char *name)
792 int e;
793 struct stat st;
795 if (mkdir(name, 0700) < 0) {
796 e = errno;
797 if ((e == EEXIST || e == ENOSYS) &&
798 stat(name, &st) == 0 &&
799 (st.st_mode&S_IFMT) == S_IFDIR)
800 return OKAY;
801 return STOP;
803 return OKAY;
806 #ifdef HAVE_FCHDIR
807 FL enum okay
808 cwget(struct cw *cw)
810 if ((cw->cw_fd = open(".", O_RDONLY)) < 0)
811 return STOP;
812 if (fchdir(cw->cw_fd) < 0) {
813 close(cw->cw_fd);
814 return STOP;
816 return OKAY;
819 FL enum okay
820 cwret(struct cw *cw)
822 if (fchdir(cw->cw_fd) < 0)
823 return STOP;
824 return OKAY;
827 FL void
828 cwrelse(struct cw *cw)
830 close(cw->cw_fd);
832 #else /* !HAVE_FCHDIR */
833 FL enum okay
834 cwget(struct cw *cw)
836 if (getcwd(cw->cw_wd, sizeof cw->cw_wd) == NULL || chdir(cw->cw_wd) < 0)
837 return STOP;
838 return OKAY;
841 FL enum okay
842 cwret(struct cw *cw)
844 if (chdir(cw->cw_wd) < 0)
845 return STOP;
846 return OKAY;
849 /*ARGSUSED*/
850 FL void
851 cwrelse(struct cw *cw)
853 (void)cw;
855 #endif /* !HAVE_FCHDIR */
857 FL void
858 makeprint(struct str const *in, struct str *out)
860 static int print_all_chars = -1;
861 char const *inp, *maxp;
862 char *outp;
863 size_t msz;
865 if (print_all_chars == -1)
866 print_all_chars = ok_blook(print_all_chars);
868 msz = in->l + 1;
869 out->s = outp = smalloc(msz);
870 inp = in->s;
871 maxp = inp + in->l;
873 if (print_all_chars) {
874 out->l = in->l;
875 memcpy(outp, inp, out->l);
876 goto jleave;
879 #ifdef HAVE_C90AMEND1
880 if (mb_cur_max > 1) {
881 char mbb[MB_LEN_MAX + 1];
882 wchar_t wc;
883 int i, n;
884 size_t dist;
886 out->l = 0;
887 while (inp < maxp) {
888 if (*inp & 0200)
889 n = mbtowc(&wc, inp, maxp - inp);
890 else {
891 wc = *inp;
892 n = 1;
894 if (n < 0) {
895 /* FIXME Why mbtowc() resetting here?
896 * FIXME what about ISO 2022-JP plus -- those
897 * FIXME will loose shifts, then!
898 * FIXME THUS - we'd need special "known points"
899 * FIXME to do so - say, after a newline!!
900 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
901 (void)mbtowc(&wc, NULL, mb_cur_max);
902 wc = utf8 ? 0xFFFD : '?';
903 n = 1;
904 } else if (n == 0)
905 n = 1;
906 inp += n;
907 if (!iswprint(wc) && wc != '\n' && wc != '\r' &&
908 wc != '\b' && wc != '\t') {
909 if ((wc & ~(wchar_t)037) == 0)
910 wc = utf8 ? 0x2400 | wc : '?';
911 else if (wc == 0177)
912 wc = utf8 ? 0x2421 : '?';
913 else
914 wc = utf8 ? 0x2426 : '?';
916 if ((n = wctomb(mbb, wc)) <= 0)
917 continue;
918 out->l += n;
919 if (out->l >= msz - 1) {
920 dist = outp - out->s;
921 out->s = srealloc(out->s, msz += 32);
922 outp = &out->s[dist];
924 for (i = 0; i < n; i++)
925 *outp++ = mbb[i];
927 } else
928 #endif /* C90AMEND1 */
930 int c;
931 while (inp < maxp) {
932 c = *inp++ & 0377;
933 if (!isprint(c) && c != '\n' && c != '\r' &&
934 c != '\b' && c != '\t')
935 c = '?';
936 *outp++ = c;
938 out->l = in->l;
940 jleave:
941 out->s[out->l] = '\0';
944 FL char *
945 prstr(const char *s)
947 struct str in, out;
948 char *rp;
950 in.s = UNCONST(s);
951 in.l = strlen(s);
952 makeprint(&in, &out);
953 rp = salloc(out.l + 1);
954 memcpy(rp, out.s, out.l);
955 rp[out.l] = '\0';
956 free(out.s);
957 return rp;
960 FL int
961 prout(const char *s, size_t sz, FILE *fp)
963 struct str in, out;
964 int n;
966 in.s = UNCONST(s);
967 in.l = sz;
968 makeprint(&in, &out);
969 n = fwrite(out.s, 1, out.l, fp);
970 free(out.s);
971 return n;
974 FL size_t
975 putuc(int u, int c, FILE *fp)
977 size_t rv;
978 UNUSED(u);
980 #ifdef HAVE_C90AMEND1
981 if (utf8 && (u & ~(wchar_t)0177)) {
982 char mbb[MB_LEN_MAX];
983 int i, n;
984 if ((n = wctomb(mbb, u)) > 0) {
985 rv = wcwidth(u);
986 for (i = 0; i < n; ++i)
987 if (putc(mbb[i] & 0377, fp) == EOF) {
988 rv = 0;
989 break;
991 } else if (n == 0)
992 rv = (putc('\0', fp) != EOF);
993 else
994 rv = 0;
995 } else
996 #endif
997 rv = (putc(c, fp) != EOF);
998 return rv;
1001 #ifdef HAVE_COLOUR
1002 FL void
1003 colour_table_create(char const *pager_used)
1005 union {char *cp; char const *ccp; void *vp; struct colour_table *ctp;} u;
1006 size_t i;
1007 struct colour_table *ct;
1009 if (ok_blook(colour_disable))
1010 goto jleave;
1012 /* If pager, check wether it is allowed to use colour */
1013 if (pager_used != NULL) {
1014 char *pager;
1016 if ((u.cp = ok_vlook(colour_pagers)) == NULL)
1017 u.ccp = COLOUR_PAGERS;
1018 pager = savestr(u.cp);
1020 while ((u.cp = strcomma(&pager, TRU1)) != NULL)
1021 if (strstr(pager_used, u.cp) != NULL)
1022 goto jok;
1023 goto jleave;
1026 /* $TERM is different in that we default to false unless whitelisted */
1028 char *term, *okterms;
1030 /* Don't use getenv(), but force copy-in into our own tables.. */
1031 if ((term = _var_voklook("TERM")) == NULL)
1032 goto jleave;
1033 if ((okterms = ok_vlook(colour_terms)) == NULL)
1034 okterms = UNCONST(COLOUR_TERMS);
1035 okterms = savestr(okterms);
1037 i = strlen(term);
1038 while ((u.cp = strcomma(&okterms, TRU1)) != NULL)
1039 if (!strncmp(u.cp, term, i))
1040 goto jok;
1041 goto jleave;
1044 jok:
1045 colour_table = ct = salloc(sizeof *ct); /* XXX lex.c yet resets (FILTER!) */
1046 { static struct {
1047 enum okeys okey;
1048 enum colourspec cspec;
1049 char const *defval;
1050 } const map[] = {
1051 {ok_v_colour_msginfo, COLOURSPEC_MSGINFO, COLOUR_MSGINFO},
1052 {ok_v_colour_partinfo, COLOURSPEC_PARTINFO, COLOUR_PARTINFO},
1053 {ok_v_colour_from_, COLOURSPEC_FROM_, COLOUR_FROM_},
1054 {ok_v_colour_header, COLOURSPEC_HEADER, COLOUR_HEADER},
1055 {ok_v_colour_uheader, COLOURSPEC_UHEADER, COLOUR_UHEADER}
1058 for (i = 0; i < NELEM(map); ++i) {
1059 if ((u.cp = _var_oklook(map[i].okey)) == NULL)
1060 u.ccp = map[i].defval;
1061 u.cp = _colour_iso6429(u.ccp);
1062 ct->ct_csinfo[map[i].cspec].l = strlen(u.cp);
1063 ct->ct_csinfo[map[i].cspec].s = u.cp;
1066 ct->ct_csinfo[COLOURSPEC_RESET].l = sizeof("\033[0m") - 1;
1067 ct->ct_csinfo[COLOURSPEC_RESET].s = UNCONST("\033[0m");
1069 if ((u.cp = ok_vlook(colour_user_headers)) == NULL)
1070 u.ccp = COLOUR_USER_HEADERS;
1071 ct->ct_csinfo[COLOURSPEC_RESET + 1].l = i = strlen(u.ccp);
1072 ct->ct_csinfo[COLOURSPEC_RESET + 1].s = (i == 0) ? NULL : savestr(u.ccp);
1073 jleave:
1077 FL void
1078 colour_put(FILE *fp, enum colourspec cs)
1080 if (colour_table != NULL) {
1081 struct str const *cp = colour_get(cs);
1083 fwrite(cp->s, cp->l, 1, fp);
1087 FL void
1088 colour_put_header(FILE *fp, char const *name)
1090 enum colourspec cs = COLOURSPEC_HEADER;
1091 struct str const *uheads;
1092 char *cp, *cp_base, *x;
1093 size_t namelen;
1095 if (colour_table == NULL)
1096 goto j_leave;
1097 /* Normal header colours if there are no user headers */
1098 uheads = colour_table->ct_csinfo + COLOURSPEC_RESET + 1;
1099 if (uheads->s == NULL)
1100 goto jleave;
1102 /* Iterate over all entries in the *colour-user-headers* list */
1103 cp = ac_alloc(uheads->l + 1);
1104 memcpy(cp, uheads->s, uheads->l + 1);
1105 cp_base = cp;
1106 namelen = strlen(name);
1107 while ((x = strcomma(&cp, TRU1)) != NULL) {
1108 size_t l = (cp != NULL) ? PTR2SIZE(cp - x) - 1 : strlen(x);
1109 if (l == namelen && !ascncasecmp(x, name, namelen)) {
1110 cs = COLOURSPEC_UHEADER;
1111 break;
1114 ac_free(cp_base);
1115 jleave:
1116 colour_put(fp, cs);
1117 j_leave:
1121 FL void
1122 colour_reset(FILE *fp)
1124 if (colour_table != NULL)
1125 fwrite("\033[0m", 4, 1, fp);
1128 FL struct str const *
1129 colour_get(enum colourspec cs)
1131 struct str const *rv = NULL;
1133 if (colour_table != NULL)
1134 if ((rv = colour_table->ct_csinfo + cs)->s == NULL)
1135 rv = NULL;
1136 return rv;
1138 #endif /* HAVE_COLOUR */
1140 FL void
1141 time_current_update(struct time_current *tc, bool_t full_update)
1143 tc->tc_time = time(NULL);
1144 if (full_update) {
1145 memcpy(&tc->tc_gm, gmtime(&tc->tc_time), sizeof tc->tc_gm);
1146 memcpy(&tc->tc_local, localtime(&tc->tc_time),
1147 sizeof tc->tc_local);
1148 sstpcpy(tc->tc_ctime, ctime(&tc->tc_time));
1152 static void
1153 _out_of_memory(void)
1155 panic("no memory");
1158 #ifndef HAVE_DEBUG
1159 FL void *
1160 smalloc(size_t s SMALLOC_DEBUG_ARGS)
1162 void *rv;
1164 if (s == 0)
1165 s = 1;
1166 if ((rv = malloc(s)) == NULL)
1167 _out_of_memory();
1168 return rv;
1171 FL void *
1172 srealloc(void *v, size_t s SMALLOC_DEBUG_ARGS)
1174 void *rv;
1176 if (s == 0)
1177 s = 1;
1178 if (v == NULL)
1179 rv = smalloc(s);
1180 else if ((rv = realloc(v, s)) == NULL)
1181 _out_of_memory();
1182 return rv;
1185 FL void *
1186 scalloc(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1188 void *rv;
1190 if (size == 0)
1191 size = 1;
1192 if ((rv = calloc(nmemb, size)) == NULL)
1193 _out_of_memory();
1194 return rv;
1197 #else /* !HAVE_DEBUG */
1198 CTA(sizeof(char) == sizeof(ui8_t));
1200 # define _HOPE_SIZE (2 * 8 * sizeof(char))
1201 # define _HOPE_SET(C) \
1202 do {\
1203 union ptr __xl, __xu;\
1204 struct chunk *__xc;\
1205 __xl.p = (C).p;\
1206 __xc = __xl.c - 1;\
1207 __xu.p = __xc;\
1208 (C).cp += 8;\
1209 __xl.ui8p[0]=0xDE; __xl.ui8p[1]=0xAA; __xl.ui8p[2]=0x55; __xl.ui8p[3]=0xAD;\
1210 __xl.ui8p[4]=0xBE; __xl.ui8p[5]=0x55; __xl.ui8p[6]=0xAA; __xl.ui8p[7]=0xEF;\
1211 __xu.ui8p += __xc->size - 8;\
1212 __xu.ui8p[0]=0xDE; __xu.ui8p[1]=0xAA; __xu.ui8p[2]=0x55; __xu.ui8p[3]=0xAD;\
1213 __xu.ui8p[4]=0xBE; __xu.ui8p[5]=0x55; __xu.ui8p[6]=0xAA; __xu.ui8p[7]=0xEF;\
1214 } while (0)
1215 # define _HOPE_GET_TRACE(C,BAD) do {(C).cp += 8; _HOPE_GET(C, BAD);} while(0)
1216 # define _HOPE_GET(C,BAD) \
1217 do {\
1218 union ptr __xl, __xu;\
1219 struct chunk *__xc;\
1220 ui32_t __i;\
1221 __xl.p = (C).p;\
1222 __xl.cp -= 8;\
1223 (C).cp = __xl.cp;\
1224 __xc = __xl.c - 1;\
1225 (BAD) = FAL0;\
1226 __i = 0;\
1227 if (__xl.ui8p[0] != 0xDE) __i |= 1<<0;\
1228 if (__xl.ui8p[1] != 0xAA) __i |= 1<<1;\
1229 if (__xl.ui8p[2] != 0x55) __i |= 1<<2;\
1230 if (__xl.ui8p[3] != 0xAD) __i |= 1<<3;\
1231 if (__xl.ui8p[4] != 0xBE) __i |= 1<<4;\
1232 if (__xl.ui8p[5] != 0x55) __i |= 1<<5;\
1233 if (__xl.ui8p[6] != 0xAA) __i |= 1<<6;\
1234 if (__xl.ui8p[7] != 0xEF) __i |= 1<<7;\
1235 if (__i != 0) {\
1236 (BAD) = TRU1;\
1237 warn("%p: corrupted lower canary: 0x%02X: %s, line %u",\
1238 __xl.p, __i, mdbg_file, mdbg_line);\
1240 __xu.p = __xc;\
1241 __xu.ui8p += __xc->size - 8;\
1242 __i = 0;\
1243 if (__xu.ui8p[0] != 0xDE) __i |= 1<<0;\
1244 if (__xu.ui8p[1] != 0xAA) __i |= 1<<1;\
1245 if (__xu.ui8p[2] != 0x55) __i |= 1<<2;\
1246 if (__xu.ui8p[3] != 0xAD) __i |= 1<<3;\
1247 if (__xu.ui8p[4] != 0xBE) __i |= 1<<4;\
1248 if (__xu.ui8p[5] != 0x55) __i |= 1<<5;\
1249 if (__xu.ui8p[6] != 0xAA) __i |= 1<<6;\
1250 if (__xu.ui8p[7] != 0xEF) __i |= 1<<7;\
1251 if (__i != 0) {\
1252 (BAD) = TRU1;\
1253 warn("%p: corrupted upper canary: 0x%02X: %s, line %u",\
1254 __xl.p, __i, mdbg_file, mdbg_line);\
1256 if (BAD)\
1257 warn(" ..canary last seen: %s, line %u", __xc->file, __xc->line);\
1258 } while (0)
1260 struct chunk {
1261 struct chunk *prev;
1262 struct chunk *next;
1263 char const *file;
1264 ui16_t line;
1265 ui8_t isfree;
1266 ui8_t __dummy;
1267 ui32_t size;
1270 union ptr {
1271 void *p;
1272 struct chunk *c;
1273 char *cp;
1274 ui8_t *ui8p;
1277 struct chunk *_mlist, *_mfree;
1279 FL void *
1280 (smalloc)(size_t s SMALLOC_DEBUG_ARGS)
1282 union ptr p;
1284 if (s == 0)
1285 s = 1;
1286 s += sizeof(struct chunk) + _HOPE_SIZE;
1288 if ((p.p = (malloc)(s)) == NULL)
1289 _out_of_memory();
1290 p.c->prev = NULL;
1291 if ((p.c->next = _mlist) != NULL)
1292 _mlist->prev = p.c;
1293 p.c->file = mdbg_file;
1294 p.c->line = (ui16_t)mdbg_line;
1295 p.c->isfree = FAL0;
1296 p.c->size = (ui32_t)s;
1297 _mlist = p.c++;
1298 _HOPE_SET(p);
1299 return p.p;
1302 FL void *
1303 (srealloc)(void *v, size_t s SMALLOC_DEBUG_ARGS)
1305 union ptr p;
1306 bool_t isbad;
1308 if ((p.p = v) == NULL) {
1309 p.p = (smalloc)(s, mdbg_file, mdbg_line);
1310 goto jleave;
1313 _HOPE_GET(p, isbad);
1314 --p.c;
1315 if (p.c->isfree) {
1316 fprintf(stderr, "srealloc(): region freed! At %s, line %d\n"
1317 "\tLast seen: %s, line %d\n",
1318 mdbg_file, mdbg_line, p.c->file, p.c->line);
1319 goto jforce;
1322 if (p.c == _mlist)
1323 _mlist = p.c->next;
1324 else
1325 p.c->prev->next = p.c->next;
1326 if (p.c->next != NULL)
1327 p.c->next->prev = p.c->prev;
1329 jforce:
1330 if (s == 0)
1331 s = 1;
1332 s += sizeof(struct chunk) + _HOPE_SIZE;
1334 if ((p.p = (realloc)(p.c, s)) == NULL)
1335 _out_of_memory();
1336 p.c->prev = NULL;
1337 if ((p.c->next = _mlist) != NULL)
1338 _mlist->prev = p.c;
1339 p.c->file = mdbg_file;
1340 p.c->line = (ui16_t)mdbg_line;
1341 p.c->isfree = FAL0;
1342 p.c->size = (ui32_t)s;
1343 _mlist = p.c++;
1344 _HOPE_SET(p);
1345 jleave:
1346 return p.p;
1349 FL void *
1350 (scalloc)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1352 union ptr p;
1354 if (size == 0)
1355 size = 1;
1356 if (nmemb == 0)
1357 nmemb = 1;
1358 size *= nmemb;
1359 size += sizeof(struct chunk) + _HOPE_SIZE;
1361 if ((p.p = (malloc)(size)) == NULL)
1362 _out_of_memory();
1363 memset(p.p, 0, size);
1364 p.c->prev = NULL;
1365 if ((p.c->next = _mlist) != NULL)
1366 _mlist->prev = p.c;
1367 p.c->file = mdbg_file;
1368 p.c->line = (ui16_t)mdbg_line;
1369 p.c->isfree = FAL0;
1370 p.c->size = (ui32_t)size;
1371 _mlist = p.c++;
1372 _HOPE_SET(p);
1373 return p.p;
1376 FL void
1377 (sfree)(void *v SMALLOC_DEBUG_ARGS)
1379 union ptr p;
1380 bool_t isbad;
1382 if ((p.p = v) == NULL) {
1383 fprintf(stderr, "sfree(NULL) from %s, line %d\n", mdbg_file, mdbg_line);
1384 goto jleave;
1387 _HOPE_GET(p, isbad);
1388 --p.c;
1389 if (p.c->isfree) {
1390 fprintf(stderr, "sfree(): double-free avoided at %s, line %d\n"
1391 "\tLast seen: %s, line %d\n",
1392 mdbg_file, mdbg_line, p.c->file, p.c->line);
1393 goto jleave;
1396 if (p.c == _mlist)
1397 _mlist = p.c->next;
1398 else
1399 p.c->prev->next = p.c->next;
1400 if (p.c->next != NULL)
1401 p.c->next->prev = p.c->prev;
1402 p.c->isfree = TRU1;
1404 if (options & OPT_DEBUG) {
1405 p.c->next = _mfree;
1406 _mfree = p.c;
1407 } else
1408 (free)(p.c);
1409 jleave:
1413 FL void
1414 smemreset(void)
1416 union ptr p;
1417 size_t c = 0, s = 0;
1419 for (p.c = _mfree; p.c != NULL;) {
1420 void *vp = p.c;
1421 ++c;
1422 s += p.c->size;
1423 p.c = p.c->next;
1424 (free)(vp);
1426 _mfree = NULL;
1428 if (options & OPT_DEBUG)
1429 fprintf(stderr, "smemreset(): freed %" ZFMT " chunks/%" ZFMT " bytes\n",
1430 c, s);
1433 FL int
1434 smemtrace(void *v)
1436 /* For _HOPE_GET() */
1437 char const * const mdbg_file = "smemtrace()";
1438 int const mdbg_line = -1;
1440 FILE *fp;
1441 char *cp;
1442 union ptr p, xp;
1443 bool_t isbad;
1444 size_t lines;
1446 v = (void*)0x1;
1447 if ((fp = Ftemp(&cp, "Ra", "w+", 0600, 1)) == NULL) {
1448 perror("tmpfile");
1449 goto jleave;
1451 rm(cp);
1452 Ftfree(&cp);
1454 fprintf(fp, "Currently allocated memory chunks:\n");
1455 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1456 xp = p;
1457 ++xp.c;
1458 _HOPE_GET_TRACE(xp, isbad);
1459 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1460 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1461 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1464 if (options & OPT_DEBUG) {
1465 fprintf(fp, "sfree()d memory chunks awaiting free():\n");
1466 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1467 xp = p;
1468 ++xp.c;
1469 _HOPE_GET_TRACE(xp, isbad);
1470 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1471 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1472 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1476 page_or_print(fp, lines);
1477 Fclose(fp);
1478 v = NULL;
1479 jleave:
1480 return (v != NULL);
1483 # ifdef MEMCHECK
1484 FL bool_t
1485 _smemcheck(char const *mdbg_file, int mdbg_line)
1487 union ptr p, xp;
1488 bool_t anybad = FAL0, isbad;
1489 size_t lines;
1491 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1492 xp = p;
1493 ++xp.c;
1494 _HOPE_GET_TRACE(xp, isbad);
1495 if (isbad) {
1496 anybad = TRU1;
1497 fprintf(stderr,
1498 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1499 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1500 p.c->file, p.c->line);
1504 if (options & OPT_DEBUG) {
1505 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1506 xp = p;
1507 ++xp.c;
1508 _HOPE_GET_TRACE(xp, isbad);
1509 if (isbad) {
1510 anybad = TRU1;
1511 fprintf(stderr,
1512 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1513 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1514 p.c->file, p.c->line);
1518 return anybad;
1520 # endif /* MEMCHECK */
1521 #endif /* HAVE_DEBUG */
1523 /* vim:set fenc=utf-8:s-it-mode (TODO only partial true) */