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>.
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
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
40 #ifndef HAVE_AMALGAMATION
44 #include <sys/utsname.h>
52 # include <sys/socket.h>
69 static ui32_t _nyd_curr
;
70 static ui32_t _nyd_level
;
71 static struct nyd_info _nyd_infos
[NYD_CALLS_MAX
];
74 /* {hold,rele}_all_sigs() */
75 static size_t _alls_depth
;
76 static sigset_t _alls_nset
, _alls_oset
;
78 /* {hold,rele}_sigs() */
79 static size_t _hold_sigdepth
;
80 static sigset_t _hold_nset
, _hold_oset
;
82 /* Create an ISO 6429 (ECMA-48/ANSI) terminal control escape sequence */
84 static char * _colour_iso6429(char const *wish
);
88 static void _nyd_print(struct nyd_info
*nip
);
93 _colour_iso6429(char const *wish
)
95 char const * const wish_orig
= wish
;
96 char *xwish
, *cp
, cfg
[3] = {0, 0, 0};
99 /* Since we use salloc(), reuse the n_strsep() buffer also for the return
100 * value, ensure we have enough room for that */
102 size_t i
= strlen(wish
) + 1;
103 xwish
= salloc(MAX(i
, sizeof("\033[1;30;40m")));
104 memcpy(xwish
, wish
, i
);
108 /* Iterate over the colour spec */
109 while ((cp
= n_strsep(&xwish
, ',', TRU1
)) != NULL
) {
110 char *y
, *x
= strchr(cp
, '=');
113 fprintf(stderr
, tr(527,
114 "Invalid colour specification \"%s\": >>> %s <<<\n"),
120 /* TODO convert the ft/fg/bg parser into a table-based one! */
121 if (!asccasecmp(cp
, "ft")) {
122 if (!asccasecmp(x
, "bold"))
124 else if (!asccasecmp(x
, "inverse"))
126 else if (!asccasecmp(x
, "underline"))
130 } else if (!asccasecmp(cp
, "fg")) {
133 } else if (!asccasecmp(cp
, "bg")) {
136 if (!asccasecmp(x
, "black"))
138 else if (!asccasecmp(x
, "blue"))
140 else if (!asccasecmp(x
, "green"))
142 else if (!asccasecmp(x
, "red"))
144 else if (!asccasecmp(x
, "brown"))
146 else if (!asccasecmp(x
, "magenta"))
148 else if (!asccasecmp(x
, "cyan"))
150 else if (!asccasecmp(x
, "white"))
158 /* Restore our salloc() buffer, create return value */
159 xwish
= UNCONST(wish
);
160 if (cfg
[0] || cfg
[1] || cfg
[2]) {
174 if (cfg
[0] || cfg
[1])
184 return UNCONST(wish
);
186 #endif /* HAVE_COLOUR */
190 _nyd_print(struct nyd_info
*nip
) /* XXX like SFSYS;no magics;jumps:lvl wrong */
193 union {int i
; size_t z
;} u
;
195 u
.i
= snprintf(buf
, sizeof buf
, "%c [%2u] %-25.25s %.16s:%-5u\n",
196 "=><"[(nip
->ni_chirp_line
>> 29) & 0x3], nip
->ni_level
, nip
->ni_fun
,
197 nip
->ni_file
, (nip
->ni_chirp_line
& 0x1FFFFFFFu
));
200 if (u
.z
> sizeof buf
)
201 u
.z
= sizeof buf
- 1; /* (Skip \0) */
202 write(STDERR_FILENO
, buf
, u
.z
);
208 panic(char const *format
, ...)
213 fprintf(stderr
, tr(1, "Panic: "));
215 va_start(ap
, format
);
216 vfprintf(stderr
, format
, ap
);
222 abort(); /* Was exit(EXIT_ERR); for a while, but no */
226 alert(char const *format
, ...)
231 fprintf(stderr
, tr(1, "Panic: "));
233 va_start(ap
, format
);
234 vfprintf(stderr
, format
, ap
);
243 safe_signal(int signum
, sighandler_type handler
)
245 struct sigaction nact
, oact
;
249 nact
.sa_handler
= handler
;
250 sigemptyset(&nact
.sa_mask
);
253 nact
.sa_flags
|= SA_RESTART
;
255 rv
= (sigaction(signum
, &nact
, &oact
) != 0) ? SIG_ERR
: oact
.sa_handler
;
264 if (_alls_depth
++ == 0) {
265 sigfillset(&_alls_nset
);
266 sigdelset(&_alls_nset
, SIGABRT
);
268 sigdelset(&_alls_nset
, SIGBUS
);
270 sigdelset(&_alls_nset
, SIGCHLD
);
271 sigdelset(&_alls_nset
, SIGFPE
);
272 sigdelset(&_alls_nset
, SIGILL
);
273 sigdelset(&_alls_nset
, SIGKILL
);
274 sigdelset(&_alls_nset
, SIGSEGV
);
275 sigdelset(&_alls_nset
, SIGSTOP
);
276 sigprocmask(SIG_BLOCK
, &_alls_nset
, &_alls_oset
);
285 if (--_alls_depth
== 0)
286 sigprocmask(SIG_SETMASK
, &_alls_oset
, (sigset_t
*)NULL
);
294 if (_hold_sigdepth
++ == 0) {
295 sigemptyset(&_hold_nset
);
296 sigaddset(&_hold_nset
, SIGHUP
);
297 sigaddset(&_hold_nset
, SIGINT
);
298 sigaddset(&_hold_nset
, SIGQUIT
);
299 sigprocmask(SIG_BLOCK
, &_hold_nset
, &_hold_oset
);
308 if (--_hold_sigdepth
== 0)
309 sigprocmask(SIG_SETMASK
, &_hold_oset
, NULL
);
315 _nyd_chirp(ui8_t act
, char const *file
, ui32_t line
, char const *fun
)
317 struct nyd_info
*nip
= _nyd_infos
;
319 if (_nyd_curr
!= NELEM(_nyd_infos
))
325 nip
->ni_chirp_line
= ((ui32_t
)(act
& 0x3) << 29) | (line
& 0x1FFFFFFFu
);
326 nip
->ni_level
= ((act
== 0) ? _nyd_level
327 : (act
== 1) ? ++_nyd_level
: _nyd_level
--);
331 _nyd_oncrash(int signo
)
333 struct sigaction xact
;
335 struct nyd_info
*nip
;
338 xact
.sa_handler
= SIG_DFL
;
339 sigemptyset(&xact
.sa_mask
);
341 sigaction(signo
, &xact
, NULL
);
343 fprintf(stderr
, "\n\nNYD: program dying due to signal %d:\n", signo
);
344 if (_nyd_infos
[NELEM(_nyd_infos
) - 1].ni_file
!= NULL
)
345 for (i
= _nyd_curr
, nip
= _nyd_infos
+ i
; i
< NELEM(_nyd_infos
); ++i
)
347 for (i
= 0, nip
= _nyd_infos
; i
< _nyd_curr
; ++i
)
351 sigaddset(&xset
, signo
);
352 sigprocmask(SIG_UNBLOCK
, &xset
, NULL
);
360 touch(struct message
*mp
)
363 mp
->m_flag
|= MTOUCH
;
364 if (!(mp
->m_flag
& MREAD
))
365 mp
->m_flag
|= MREAD
| MSTATUS
;
370 is_dir(char const *name
)
376 if (!stat(name
, &sbuf
))
377 rv
= !!S_ISDIR(sbuf
.st_mode
);
383 argcount(char **argv
)
388 for (ap
= argv
; *ap
++ != NULL
;)
391 return ap
- argv
- 1;
401 if ((cp
= ok_vlook(screen
)) == NULL
|| (s
= atoi(cp
)) <= 0)
413 cp
= ok_vlook(PAGER
);
414 if (cp
== NULL
|| *cp
== '\0')
421 paging_seems_sensible(void)
427 if (IS_TTY_SESSION() && (cp
= ok_vlook(crt
)) != NULL
)
428 rv
= (*cp
!= '\0') ? (size_t)atol(cp
) : (size_t)scrnheight
;
434 page_or_print(FILE *fp
, size_t lines
)
442 if ((rows
= paging_seems_sensible()) != 0 && lines
== 0) {
443 while ((c
= getc(fp
)) != EOF
)
444 if (c
== '\n' && ++lines
> rows
)
449 if (rows
!= 0 && lines
>= rows
)
450 run_command(get_pager(), 0, fileno(fp
), -1, NULL
, NULL
, NULL
);
452 while ((c
= getc(fp
)) != EOF
)
458 which_protocol(char const *name
)
464 enum protocol rv
= PROTO_UNKNOWN
;
467 if (name
[0] == '%' && name
[1] == ':')
469 for (cp
= name
; *cp
&& *cp
!= ':'; cp
++)
473 if (cp
[0] == ':' && cp
[1] == '/' && cp
[2] == '/') {
474 if (strncmp(name
, "pop3://", 7) == 0) {
478 fprintf(stderr
, tr(216, "No POP3 support compiled in.\n"));
480 } else if (strncmp(name
, "pop3s://", 8) == 0) {
481 #if defined HAVE_POP3 && defined HAVE_SSL
485 fprintf(stderr
, tr(216, "No POP3 support compiled in.\n"));
488 fprintf(stderr
, tr(225, "No SSL support compiled in.\n"));
491 } else if (strncmp(name
, "imap://", 7) == 0) {
495 fprintf(stderr
, tr(269, "No IMAP support compiled in.\n"));
497 } else if (strncmp(name
, "imaps://", 8) == 0) {
498 #if defined HAVE_IMAP && defined HAVE_SSL
502 fprintf(stderr
, tr(269, "No IMAP support compiled in.\n"));
505 fprintf(stderr
, tr(225, "No SSL support compiled in.\n"));
512 /* TODO This is the de facto maildir code and thus belongs into there! */
515 np
= ac_alloc((sz
= strlen(name
)) + 4 +1);
516 memcpy(np
, name
, sz
+ 1);
517 if (!stat(name
, &st
)) {
518 if (S_ISDIR(st
.st_mode
) &&
519 (strcpy(&np
[sz
], "/tmp"), !stat(np
, &st
) && S_ISDIR(st
.st_mode
)) &&
520 (strcpy(&np
[sz
], "/new"), !stat(np
, &st
) && S_ISDIR(st
.st_mode
)) &&
521 (strcpy(&np
[sz
], "/cur"), !stat(np
, &st
) && S_ISDIR(st
.st_mode
)))
523 } else if ((cp
= ok_vlook(newfolders
)) != NULL
&& !strcmp(cp
, "maildir"))
532 torek_hash(char const *name
)
534 /* Chris Torek's hash.
535 * NOTE: need to change *at least* create-okey-map.pl when changing the
540 while (*name
!= '\0') {
549 pjw(char const *cp
) /* XXX obsolete that -> torek_hash */
556 h
= (h
<< 4 & 0xffffffff) + (*cp
&0377);
557 if ((g
= h
& 0xf0000000) != 0) {
569 static ui32_t
const primes
[] = {
570 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
571 131071, 262139, 524287, 1048573, 2097143, 4194301,
572 8388593, 16777213, 33554393, 67108859, 134217689,
573 268435399, 536870909, 1073741789, 2147483647
580 for (i
= 0; i
< NELEM(primes
); i
++)
581 if ((mprime
= primes
[i
]) >= (n
< 65536 ? n
*4 : (n
< 262144u ? n
*2 : n
)))
583 if (i
== NELEM(primes
))
584 mprime
= n
; /* TODO not so prime, but better than failure */
590 expand_shell_escape(char const **s
, bool_t use_nail_extensions
)
596 if ((c
= *xs
& 0xFF) == '\0')
602 switch ((c
= *xs
& 0xFF)) {
604 case 'a': c
= '\a'; break;
605 case 'b': c
= '\b'; break;
606 case 'c': c
= PROMPT_STOP
; break;
607 case 'f': c
= '\f'; break;
608 case 'n': c
= '\n'; break;
609 case 'r': c
= '\r'; break;
610 case 't': c
= '\t'; break;
611 case 'v': c
= '\v'; break;
613 for (++xs
, c
= 0, n
= 4; --n
> 0 && octalchar(*xs
); ++xs
) {
618 /* S-nail extension for nice (get)prompt(()) support */
623 if (use_nail_extensions
) {
625 case '&': c
= ok_blook(bsdcompat
) ? '&' : '?'; break;
626 case '?': c
= exec_last_comm_error
? '1' : '0'; break;
627 case '$': c
= PROMPT_DOLLAR
; break;
628 case '@': c
= PROMPT_AT
; break;
634 /* A sole <backslash> at EOS is treated as-is! */
650 static char buf
[PROMPT_BUFFER_SIZE
];
656 if ((ccp
= ok_vlook(prompt
)) == NULL
|| *ccp
== '\0')
659 for (; PTRCMP(cp
, <, buf
+ sizeof(buf
) - 1); ++cp
) {
662 int c
= expand_shell_escape(&ccp
, TRU1
);
668 if (c
== 0 || c
== PROMPT_STOP
)
671 a
= (c
== PROMPT_DOLLAR
) ? account_name
: displayname
;
675 if (PTRCMP(cp
+ l
, >=, buf
+ sizeof(buf
) - 1))
689 nodename(int mayoverride
)
691 static char *hostname
;
696 struct addrinfo hints
, *res
;
698 struct hostent
*hent
;
703 if (mayoverride
&& (hn
= ok_vlook(hostname
)) != NULL
&& *hn
!= '\0') {
704 if (hostname
!= NULL
)
706 hostname
= sstrdup(hn
);
707 } else if (hostname
== NULL
) {
712 memset(&hints
, 0, sizeof hints
);
713 hints
.ai_family
= AF_UNSPEC
;
714 hints
.ai_socktype
= SOCK_DGRAM
; /* dummy */
715 hints
.ai_flags
= AI_CANONNAME
;
716 if (getaddrinfo(hn
, "0", &hints
, &res
) == 0) {
717 if (res
->ai_canonname
!= NULL
) {
718 size_t l
= strlen(res
->ai_canonname
);
719 hn
= ac_alloc(l
+ 1);
720 memcpy(hn
, res
->ai_canonname
, l
+ 1);
725 hent
= gethostbyname(hn
);
730 hostname
= sstrdup(hn
);
731 #if defined HAVE_SOCKETS && defined HAVE_IPV6
732 if (hn
!= ut
.nodename
)
741 lookup_password_for_token(char const *token
)
748 var
= ac_alloc(tl
+ 9 +1);
750 memcpy(var
, "password-", 9);
751 memcpy(var
+ 9, token
, tl
);
754 if ((cp
= vok_vlook(var
)) != NULL
)
762 getrandstring(size_t length
)
764 static unsigned char nodedigest
[16];
778 data
= ac_alloc(length
);
779 if ((fd
= open("/dev/urandom", O_RDONLY
)) == -1 ||
780 length
!= (size_t)read(fd
, data
, length
)) {
787 md5_update(&ctx
, (unsigned char*)cp
, strlen(cp
));
788 md5_final(nodedigest
, &ctx
);
790 /* In that case it's only used for boundaries and Message-Id:s so that
791 * srand(3) should suffice */
793 for (i
= 0; i
< sizeof(nodedigest
); ++i
)
794 nodedigest
[i
] = (unsigned char)(cp
[i
% j
] ^ rand());
797 for (i
= 0; i
< length
; i
++)
798 data
[i
] = (char)((int)(255 * (rand() / (RAND_MAX
+ 1.0))) ^
799 nodedigest
[i
% sizeof nodedigest
]);
804 (void)b64_encode_buf(&b64
, data
, length
, B64_SALLOC
);
806 assert(length
< b64
.l
);
807 b64
.s
[length
] = '\0';
814 md5tohex(char hex
[MD5TOHEX_SIZE
], void const *vp
)
820 for (i
= 0; i
< MD5TOHEX_SIZE
/ 2; i
++) {
822 hex
[j
] = hexchar((cp
[i
] & 0xf0) >> 4);
823 hex
[++j
] = hexchar(cp
[i
] & 0x0f);
830 cram_md5_string(char const *user
, char const *pass
, char const *b64
)
833 char digest
[16], *cp
;
840 (void)b64_decode(&out
, &in
, NULL
);
841 assert(out
.s
!= NULL
);
843 hmac_md5((unsigned char*)out
.s
, out
.l
, UNCONST(pass
), strlen(pass
), digest
);
845 cp
= md5tohex(salloc(MD5TOHEX_SIZE
+ 1), digest
);
848 in
.l
= lu
+ MD5TOHEX_SIZE
+1;
849 in
.s
= ac_alloc(lu
+ 1 + MD5TOHEX_SIZE
+1);
850 memcpy(in
.s
, user
, lu
);
852 memcpy(in
.s
+ lu
+ 1, cp
, MD5TOHEX_SIZE
);
853 b64_encode(&out
, &in
, B64_SALLOC
| B64_CRLF
);
860 hmac_md5(unsigned char *text
, int text_len
, unsigned char *key
, int key_len
,
864 * This code is taken from
866 * Network Working Group H. Krawczyk
867 * Request for Comments: 2104 IBM
868 * Category: Informational M. Bellare
875 * HMAC: Keyed-Hashing for Message Authentication
878 unsigned char k_ipad
[65]; /* inner padding - key XORd with ipad */
879 unsigned char k_opad
[65]; /* outer padding - key XORd with opad */
880 unsigned char tk
[16];
884 /* if key is longer than 64 bytes reset it to key=MD5(key) */
889 md5_update(&tctx
, key
, key_len
);
890 md5_final(tk
, &tctx
);
896 /* the HMAC_MD5 transform looks like:
898 * MD5(K XOR opad, MD5(K XOR ipad, text))
900 * where K is an n byte key
901 * ipad is the byte 0x36 repeated 64 times
902 * opad is the byte 0x5c repeated 64 times
903 * and text is the data being protected */
905 /* start out by storing key in pads */
906 memset(k_ipad
, 0, sizeof k_ipad
);
907 memset(k_opad
, 0, sizeof k_opad
);
908 memcpy(k_ipad
, key
, key_len
);
909 memcpy(k_opad
, key
, key_len
);
911 /* XOR key with ipad and opad values */
912 for (i
=0; i
<64; i
++) {
917 /* perform inner MD5 */
918 md5_init(&context
); /* init context for 1st pass */
919 md5_update(&context
, k_ipad
, 64); /* start with inner pad */
920 md5_update(&context
, text
, text_len
); /* then text of datagram */
921 md5_final(digest
, &context
); /* finish up 1st pass */
923 /* perform outer MD5 */
924 md5_init(&context
); /* init context for 2nd pass */
925 md5_update(&context
, k_opad
, 64); /* start with outer pad */
926 md5_update(&context
, digest
, 16); /* then results of 1st hash */
927 md5_final(digest
, &context
); /* finish up 2nd pass */
930 #endif /* HAVE_MD5 */
933 makedir(char const *name
)
939 if (!mkdir(name
, 0700))
943 if ((e
== EEXIST
|| e
== ENOSYS
) && stat(name
, &st
) == 0 &&
958 if ((cw
->cw_fd
= open(".", O_RDONLY
)) == -1)
960 if (fchdir(cw
->cw_fd
) == -1) {
976 if (!fchdir(cw
->cw_fd
))
983 cwrelse(struct cw
*cw
)
990 #else /* !HAVE_FCHDIR */
997 if (getcwd(cw
->cw_wd
, sizeof cw
->cw_wd
) != NULL
&& !chdir(cw
->cw_wd
))
1004 cwret(struct cw
*cw
)
1006 enum okay rv
= STOP
;
1009 if (!chdir(cw
->cw_wd
))
1016 cwrelse(struct cw
*cw
)
1022 #endif /* !HAVE_FCHDIR */
1025 colalign(char const *cp
, int col
, int fill
, int *cols_decr_used_or_null
)
1027 int col_orig
= col
, n
, sz
;
1031 np
= nb
= salloc(mb_cur_max
* strlen(cp
) + col
+ 1);
1034 if (mb_cur_max
> 1) {
1037 if ((sz
= mbtowc(&wc
, cp
, mb_cur_max
)) < 0)
1039 else if ((n
= wcwidth(wc
)) < 0)
1047 if (sz
== 1 && spacechar(*cp
)) {
1055 if (fill
&& col
!= 0) {
1057 memmove(nb
+ col
, nb
, (size_t)(np
- nb
));
1058 memset(nb
, ' ', col
);
1060 memset(np
, ' ', col
);
1066 if (cols_decr_used_or_null
!= NULL
)
1067 *cols_decr_used_or_null
-= col_orig
- col
;
1073 makeprint(struct str
const *in
, struct str
*out
)
1075 static int print_all_chars
= -1;
1077 char const *inp
, *maxp
;
1082 if (print_all_chars
== -1)
1083 print_all_chars
= ok_blook(print_all_chars
);
1086 out
->s
= outp
= smalloc(msz
);
1090 if (print_all_chars
) {
1092 memcpy(outp
, inp
, out
->l
);
1096 #ifdef HAVE_C90AMEND1
1097 if (mb_cur_max
> 1) {
1098 char mbb
[MB_LEN_MAX
+ 1];
1104 while (inp
< maxp
) {
1106 n
= mbtowc(&wc
, inp
, maxp
- inp
);
1112 /* FIXME Why mbtowc() resetting here?
1113 * FIXME what about ISO 2022-JP plus -- those
1114 * FIXME will loose shifts, then!
1115 * FIXME THUS - we'd need special "known points"
1116 * FIXME to do so - say, after a newline!!
1117 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
1118 (void)mbtowc(&wc
, NULL
, mb_cur_max
);
1119 wc
= utf8
? 0xFFFD : '?';
1124 if (!iswprint(wc
) && wc
!= '\n' && wc
!= '\r' && wc
!= '\b' &&
1126 if ((wc
& ~(wchar_t)037) == 0)
1127 wc
= utf8
? 0x2400 | wc
: '?';
1128 else if (wc
== 0177)
1129 wc
= utf8
? 0x2421 : '?';
1131 wc
= utf8
? 0x2426 : '?';
1133 if ((n
= wctomb(mbb
, wc
)) <= 0)
1136 if (out
->l
>= msz
- 1) {
1137 dist
= outp
- out
->s
;
1138 out
->s
= srealloc(out
->s
, msz
+= 32);
1139 outp
= &out
->s
[dist
];
1141 for (i
= 0; i
< n
; i
++)
1145 #endif /* C90AMEND1 */
1148 while (inp
< maxp
) {
1150 if (!isprint(c
) && c
!= '\n' && c
!= '\r' && c
!= '\b' && c
!= '\t')
1158 out
->s
[out
->l
] = '\0';
1162 prstr(char const *s
)
1170 makeprint(&in
, &out
);
1171 rp
= savestrbuf(out
.s
, out
.l
);
1178 prout(char const *s
, size_t sz
, FILE *fp
)
1186 makeprint(&in
, &out
);
1187 n
= fwrite(out
.s
, 1, out
.l
, fp
);
1194 putuc(int u
, int c
, FILE *fp
)
1200 #ifdef HAVE_C90AMEND1
1201 if (utf8
&& (u
& ~(wchar_t)0177)) {
1202 char mbb
[MB_LEN_MAX
];
1205 if ((n
= wctomb(mbb
, u
)) > 0) {
1207 for (i
= 0; i
< n
; ++i
)
1208 if (putc(mbb
[i
] & 0377, fp
) == EOF
) {
1213 rv
= (putc('\0', fp
) != EOF
);
1218 rv
= (putc(c
, fp
) != EOF
);
1225 colour_table_create(char const *pager_used
)
1227 union {char *cp
; char const *ccp
; void *vp
; struct colour_table
*ctp
;} u
;
1229 struct colour_table
*ct
;
1232 if (ok_blook(colour_disable
))
1235 /* If pager, check wether it is allowed to use colour */
1236 if (pager_used
!= NULL
) {
1239 if ((u
.cp
= ok_vlook(colour_pagers
)) == NULL
)
1240 u
.ccp
= COLOUR_PAGERS
;
1241 pager
= savestr(u
.cp
);
1243 while ((u
.cp
= n_strsep(&pager
, ',', TRU1
)) != NULL
)
1244 if (strstr(pager_used
, u
.cp
) != NULL
)
1249 /* $TERM is different in that we default to false unless whitelisted */
1251 char *term
, *okterms
;
1253 /* Don't use getenv(), but force copy-in into our own tables.. */
1254 if ((term
= _var_voklook("TERM")) == NULL
)
1256 if ((okterms
= ok_vlook(colour_terms
)) == NULL
)
1257 okterms
= UNCONST(COLOUR_TERMS
);
1258 okterms
= savestr(okterms
);
1261 while ((u
.cp
= n_strsep(&okterms
, ',', TRU1
)) != NULL
)
1262 if (!strncmp(u
.cp
, term
, i
))
1268 colour_table
= ct
= salloc(sizeof *ct
); /* XXX lex.c yet resets (FILTER!) */
1271 enum colourspec cspec
;
1274 {ok_v_colour_msginfo
, COLOURSPEC_MSGINFO
, COLOUR_MSGINFO
},
1275 {ok_v_colour_partinfo
, COLOURSPEC_PARTINFO
, COLOUR_PARTINFO
},
1276 {ok_v_colour_from_
, COLOURSPEC_FROM_
, COLOUR_FROM_
},
1277 {ok_v_colour_header
, COLOURSPEC_HEADER
, COLOUR_HEADER
},
1278 {ok_v_colour_uheader
, COLOURSPEC_UHEADER
, COLOUR_UHEADER
}
1281 for (i
= 0; i
< NELEM(map
); ++i
) {
1282 if ((u
.cp
= _var_oklook(map
[i
].okey
)) == NULL
)
1283 u
.ccp
= map
[i
].defval
;
1284 u
.cp
= _colour_iso6429(u
.ccp
);
1285 ct
->ct_csinfo
[map
[i
].cspec
].l
= strlen(u
.cp
);
1286 ct
->ct_csinfo
[map
[i
].cspec
].s
= u
.cp
;
1289 ct
->ct_csinfo
[COLOURSPEC_RESET
].l
= sizeof("\033[0m") - 1;
1290 ct
->ct_csinfo
[COLOURSPEC_RESET
].s
= UNCONST("\033[0m");
1292 if ((u
.cp
= ok_vlook(colour_user_headers
)) == NULL
)
1293 u
.ccp
= COLOUR_USER_HEADERS
;
1294 ct
->ct_csinfo
[COLOURSPEC_RESET
+ 1].l
= i
= strlen(u
.ccp
);
1295 ct
->ct_csinfo
[COLOURSPEC_RESET
+ 1].s
= (i
== 0) ? NULL
: savestr(u
.ccp
);
1301 colour_put(FILE *fp
, enum colourspec cs
)
1304 if (colour_table
!= NULL
) {
1305 struct str
const *cp
= colour_get(cs
);
1307 fwrite(cp
->s
, cp
->l
, 1, fp
);
1313 colour_put_header(FILE *fp
, char const *name
)
1315 enum colourspec cs
= COLOURSPEC_HEADER
;
1316 struct str
const *uheads
;
1317 char *cp
, *cp_base
, *x
;
1321 if (colour_table
== NULL
)
1323 /* Normal header colours if there are no user headers */
1324 uheads
= colour_table
->ct_csinfo
+ COLOURSPEC_RESET
+ 1;
1325 if (uheads
->s
== NULL
)
1328 /* Iterate over all entries in the *colour-user-headers* list */
1329 cp
= ac_alloc(uheads
->l
+ 1);
1330 memcpy(cp
, uheads
->s
, uheads
->l
+ 1);
1332 namelen
= strlen(name
);
1333 while ((x
= n_strsep(&cp
, ',', TRU1
)) != NULL
) {
1334 size_t l
= (cp
!= NULL
) ? PTR2SIZE(cp
- x
) - 1 : strlen(x
);
1335 if (l
== namelen
&& !ascncasecmp(x
, name
, namelen
)) {
1336 cs
= COLOURSPEC_UHEADER
;
1348 colour_reset(FILE *fp
)
1351 if (colour_table
!= NULL
)
1352 fwrite("\033[0m", 4, 1, fp
);
1356 FL
struct str
const *
1357 colour_get(enum colourspec cs
)
1359 struct str
const *rv
= NULL
;
1362 if (colour_table
!= NULL
)
1363 if ((rv
= colour_table
->ct_csinfo
+ cs
)->s
== NULL
)
1368 #endif /* HAVE_COLOUR */
1371 time_current_update(struct time_current
*tc
, bool_t full_update
)
1374 tc
->tc_time
= time(NULL
);
1376 memcpy(&tc
->tc_gm
, gmtime(&tc
->tc_time
), sizeof tc
->tc_gm
);
1377 memcpy(&tc
->tc_local
, localtime(&tc
->tc_time
), sizeof tc
->tc_local
);
1378 sstpcpy(tc
->tc_ctime
, ctime(&tc
->tc_time
));
1384 _out_of_memory(void)
1391 smalloc(size_t s SMALLOC_DEBUG_ARGS
)
1398 if ((rv
= malloc(s
)) == NULL
)
1405 srealloc(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
1414 else if ((rv
= realloc(v
, s
)) == NULL
)
1421 scalloc(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
1428 if ((rv
= calloc(nmemb
, size
)) == NULL
)
1434 #else /* !HAVE_DEBUG */
1435 CTA(sizeof(char) == sizeof(ui8_t
));
1437 # define _HOPE_SIZE (2 * 8 * sizeof(char))
1438 # define _HOPE_SET(C) \
1440 union ptr __xl, __xu;\
1441 struct chunk *__xc;\
1446 __xl.ui8p[0]=0xDE; __xl.ui8p[1]=0xAA; __xl.ui8p[2]=0x55; __xl.ui8p[3]=0xAD;\
1447 __xl.ui8p[4]=0xBE; __xl.ui8p[5]=0x55; __xl.ui8p[6]=0xAA; __xl.ui8p[7]=0xEF;\
1448 __xu.ui8p += __xc->size - 8;\
1449 __xu.ui8p[0]=0xDE; __xu.ui8p[1]=0xAA; __xu.ui8p[2]=0x55; __xu.ui8p[3]=0xAD;\
1450 __xu.ui8p[4]=0xBE; __xu.ui8p[5]=0x55; __xu.ui8p[6]=0xAA; __xu.ui8p[7]=0xEF;\
1452 # define _HOPE_GET_TRACE(C,BAD) do {(C).cp += 8; _HOPE_GET(C, BAD);} while(0)
1453 # define _HOPE_GET(C,BAD) \
1455 union ptr __xl, __xu;\
1456 struct chunk *__xc;\
1464 if (__xl.ui8p[0] != 0xDE) __i |= 1<<0;\
1465 if (__xl.ui8p[1] != 0xAA) __i |= 1<<1;\
1466 if (__xl.ui8p[2] != 0x55) __i |= 1<<2;\
1467 if (__xl.ui8p[3] != 0xAD) __i |= 1<<3;\
1468 if (__xl.ui8p[4] != 0xBE) __i |= 1<<4;\
1469 if (__xl.ui8p[5] != 0x55) __i |= 1<<5;\
1470 if (__xl.ui8p[6] != 0xAA) __i |= 1<<6;\
1471 if (__xl.ui8p[7] != 0xEF) __i |= 1<<7;\
1474 alert("%p: corrupt lower canary: 0x%02X: %s, line %u",\
1475 __xl.p, __i, mdbg_file, mdbg_line);\
1478 __xu.ui8p += __xc->size - 8;\
1480 if (__xu.ui8p[0] != 0xDE) __i |= 1<<0;\
1481 if (__xu.ui8p[1] != 0xAA) __i |= 1<<1;\
1482 if (__xu.ui8p[2] != 0x55) __i |= 1<<2;\
1483 if (__xu.ui8p[3] != 0xAD) __i |= 1<<3;\
1484 if (__xu.ui8p[4] != 0xBE) __i |= 1<<4;\
1485 if (__xu.ui8p[5] != 0x55) __i |= 1<<5;\
1486 if (__xu.ui8p[6] != 0xAA) __i |= 1<<6;\
1487 if (__xu.ui8p[7] != 0xEF) __i |= 1<<7;\
1490 alert("%p: corrupt upper canary: 0x%02X: %s, line %u",\
1491 __xl.p, __i, mdbg_file, mdbg_line);\
1494 alert(" ..canary last seen: %s, line %u", __xc->file, __xc->line);\
1514 struct chunk
*_mlist
, *_mfree
;
1517 (smalloc
)(size_t s SMALLOC_DEBUG_ARGS
)
1524 s
+= sizeof(struct chunk
) + _HOPE_SIZE
;
1526 if ((p
.p
= (malloc
)(s
)) == NULL
)
1529 if ((p
.c
->next
= _mlist
) != NULL
)
1531 p
.c
->file
= mdbg_file
;
1532 p
.c
->line
= (ui16_t
)mdbg_line
;
1534 p
.c
->size
= (ui32_t
)s
;
1542 (srealloc
)(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
1548 if ((p
.p
= v
) == NULL
) {
1549 p
.p
= (smalloc
)(s
, mdbg_file
, mdbg_line
);
1553 _HOPE_GET(p
, isbad
);
1556 fprintf(stderr
, "srealloc(): region freed! At %s, line %d\n"
1557 "\tLast seen: %s, line %d\n",
1558 mdbg_file
, mdbg_line
, p
.c
->file
, p
.c
->line
);
1565 p
.c
->prev
->next
= p
.c
->next
;
1566 if (p
.c
->next
!= NULL
)
1567 p
.c
->next
->prev
= p
.c
->prev
;
1572 s
+= sizeof(struct chunk
) + _HOPE_SIZE
;
1574 if ((p
.p
= (realloc
)(p
.c
, s
)) == NULL
)
1577 if ((p
.c
->next
= _mlist
) != NULL
)
1579 p
.c
->file
= mdbg_file
;
1580 p
.c
->line
= (ui16_t
)mdbg_line
;
1582 p
.c
->size
= (ui32_t
)s
;
1591 (scalloc
)(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
1601 size
+= sizeof(struct chunk
) + _HOPE_SIZE
;
1603 if ((p
.p
= (malloc
)(size
)) == NULL
)
1605 memset(p
.p
, 0, size
);
1607 if ((p
.c
->next
= _mlist
) != NULL
)
1609 p
.c
->file
= mdbg_file
;
1610 p
.c
->line
= (ui16_t
)mdbg_line
;
1612 p
.c
->size
= (ui32_t
)size
;
1620 (sfree
)(void *v SMALLOC_DEBUG_ARGS
)
1626 if ((p
.p
= v
) == NULL
) {
1627 fprintf(stderr
, "sfree(NULL) from %s, line %d\n", mdbg_file
, mdbg_line
);
1631 _HOPE_GET(p
, isbad
);
1634 fprintf(stderr
, "sfree(): double-free avoided at %s, line %d\n"
1635 "\tLast seen: %s, line %d\n",
1636 mdbg_file
, mdbg_line
, p
.c
->file
, p
.c
->line
);
1643 p
.c
->prev
->next
= p
.c
->next
;
1644 if (p
.c
->next
!= NULL
)
1645 p
.c
->next
->prev
= p
.c
->prev
;
1648 if (options
& OPT_DEBUG
) {
1661 size_t c
= 0, s
= 0;
1664 for (p
.c
= _mfree
; p
.c
!= NULL
;) {
1673 if (options
& OPT_DEBUG
)
1674 fprintf(stderr
, "smemreset(): freed %" ZFMT
" chunks/%" ZFMT
" bytes\n",
1680 c_smemtrace(void *v
)
1682 /* For _HOPE_GET() */
1683 char const * const mdbg_file
= "smemtrace()";
1684 int const mdbg_line
= -1;
1692 if ((fp
= Ftmp(NULL
, "memtr", OF_RDWR
| OF_UNLINK
| OF_REGISTER
, 0600)) ==
1698 fprintf(fp
, "Currently allocated memory chunks:\n");
1699 for (lines
= 0, p
.c
= _mlist
; p
.c
!= NULL
; ++lines
, p
.c
= p
.c
->next
) {
1702 _HOPE_GET_TRACE(xp
, isbad
);
1703 fprintf(fp
, "%s%p (%5" ZFMT
" bytes): %s, line %u\n",
1704 (isbad
? "! CANARY ERROR: " : ""), xp
.p
,
1705 (size_t)(p
.c
->size
- sizeof(struct chunk
)), p
.c
->file
, p
.c
->line
);
1708 if (options
& OPT_DEBUG
) {
1709 fprintf(fp
, "sfree()d memory chunks awaiting free():\n");
1710 for (p
.c
= _mfree
; p
.c
!= NULL
; ++lines
, p
.c
= p
.c
->next
) {
1713 _HOPE_GET_TRACE(xp
, isbad
);
1714 fprintf(fp
, "%s%p (%5" ZFMT
" bytes): %s, line %u\n",
1715 (isbad
? "! CANARY ERROR: " : ""), xp
.p
,
1716 (size_t)(p
.c
->size
- sizeof(struct chunk
)), p
.c
->file
, p
.c
->line
);
1720 page_or_print(fp
, lines
);
1730 _smemcheck(char const *mdbg_file
, int mdbg_line
)
1733 bool_t anybad
= FAL0
, isbad
;
1737 for (lines
= 0, p
.c
= _mlist
; p
.c
!= NULL
; ++lines
, p
.c
= p
.c
->next
) {
1740 _HOPE_GET_TRACE(xp
, isbad
);
1744 "! CANARY ERROR: %p (%5" ZFMT
" bytes): %s, line %u\n",
1745 xp
.p
, (size_t)(p
.c
->size
- sizeof(struct chunk
)),
1746 p
.c
->file
, p
.c
->line
);
1750 if (options
& OPT_DEBUG
) {
1751 for (p
.c
= _mfree
; p
.c
!= NULL
; ++lines
, p
.c
= p
.c
->next
) {
1754 _HOPE_GET_TRACE(xp
, isbad
);
1758 "! CANARY ERROR: %p (%5" ZFMT
" bytes): %s, line %u\n",
1759 xp
.p
, (size_t)(p
.c
->size
- sizeof(struct chunk
)),
1760 p
.c
->file
, p
.c
->line
);
1767 # endif /* MEMCHECK */
1768 #endif /* HAVE_DEBUG */
1770 /* vim:set fenc=utf-8:s-it-mode */