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 struct mem_chunk
*mc_prev
;
70 struct mem_chunk
*mc_next
;
80 struct mem_chunk
*p_c
;
86 /* NYD, memory pool debug */
88 static ui32_t _nyd_curr
, _nyd_level
;
89 static struct nyd_info _nyd_infos
[NYD_CALLS_MAX
];
93 static size_t _mem_aall
, _mem_acur
, _mem_amax
,
94 _mem_mall
, _mem_mcur
, _mem_mmax
;
96 static struct mem_chunk
*_mem_list
, *_mem_free
;
99 /* {hold,rele}_all_sigs() */
100 static size_t _alls_depth
;
101 static sigset_t _alls_nset
, _alls_oset
;
103 /* {hold,rele}_sigs() */
104 static size_t _hold_sigdepth
;
105 static sigset_t _hold_nset
, _hold_oset
;
107 /* Create an ISO 6429 (ECMA-48/ANSI) terminal control escape sequence */
109 static char * _colour_iso6429(char const *wish
);
113 static void _nyd_print(struct nyd_info
*nip
);
118 _colour_iso6429(char const *wish
)
120 char const * const wish_orig
= wish
;
121 char *xwish
, *cp
, cfg
[3] = {0, 0, 0};
124 /* Since we use salloc(), reuse the n_strsep() buffer also for the return
125 * value, ensure we have enough room for that */
127 size_t i
= strlen(wish
) +1;
128 xwish
= salloc(MAX(i
, sizeof("\033[1;30;40m")));
129 memcpy(xwish
, wish
, i
);
133 /* Iterate over the colour spec */
134 while ((cp
= n_strsep(&xwish
, ',', TRU1
)) != NULL
) {
135 char *y
, *x
= strchr(cp
, '=');
139 "Invalid colour specification \"%s\": >>> %s <<<\n"),
145 /* TODO convert the ft/fg/bg parser into a table-based one! */
146 if (!asccasecmp(cp
, "ft")) {
147 if (!asccasecmp(x
, "bold"))
149 else if (!asccasecmp(x
, "inverse"))
151 else if (!asccasecmp(x
, "underline"))
155 } else if (!asccasecmp(cp
, "fg")) {
158 } else if (!asccasecmp(cp
, "bg")) {
161 if (!asccasecmp(x
, "black"))
163 else if (!asccasecmp(x
, "blue"))
165 else if (!asccasecmp(x
, "green"))
167 else if (!asccasecmp(x
, "red"))
169 else if (!asccasecmp(x
, "brown"))
171 else if (!asccasecmp(x
, "magenta"))
173 else if (!asccasecmp(x
, "cyan"))
175 else if (!asccasecmp(x
, "white"))
183 /* Restore our salloc() buffer, create return value */
184 xwish
= UNCONST(wish
);
185 if (cfg
[0] || cfg
[1] || cfg
[2]) {
199 if (cfg
[0] || cfg
[1])
209 return UNCONST(wish
);
211 #endif /* HAVE_COLOUR */
215 _nyd_print(struct nyd_info
*nip
) /* XXX like SFSYS;no magics;jumps:lvl wrong */
218 union {int i
; size_t z
;} u
;
220 u
.i
= snprintf(buf
, sizeof buf
, "%c [%2u] %.25s (%.16s:%u)\n",
221 "=><"[(nip
->ni_chirp_line
>> 29) & 0x3], nip
->ni_level
, nip
->ni_fun
,
222 nip
->ni_file
, (nip
->ni_chirp_line
& 0x1FFFFFFFu
));
225 if (u
.z
> sizeof buf
)
226 u
.z
= sizeof buf
- 1; /* (Skip \0) */
227 write(STDERR_FILENO
, buf
, u
.z
);
233 panic(char const *format
, ...)
238 fprintf(stderr
, _("Panic: "));
240 va_start(ap
, format
);
241 vfprintf(stderr
, format
, ap
);
247 abort(); /* Was exit(EXIT_ERR); for a while, but no */
251 alert(char const *format
, ...)
256 fprintf(stderr
, _("Panic: "));
258 va_start(ap
, format
);
259 vfprintf(stderr
, format
, ap
);
268 safe_signal(int signum
, sighandler_type handler
)
270 struct sigaction nact
, oact
;
274 nact
.sa_handler
= handler
;
275 sigemptyset(&nact
.sa_mask
);
278 nact
.sa_flags
|= SA_RESTART
;
280 rv
= (sigaction(signum
, &nact
, &oact
) != 0) ? SIG_ERR
: oact
.sa_handler
;
289 if (_alls_depth
++ == 0) {
290 sigfillset(&_alls_nset
);
291 sigdelset(&_alls_nset
, SIGABRT
);
293 sigdelset(&_alls_nset
, SIGBUS
);
295 sigdelset(&_alls_nset
, SIGCHLD
);
296 sigdelset(&_alls_nset
, SIGFPE
);
297 sigdelset(&_alls_nset
, SIGILL
);
298 sigdelset(&_alls_nset
, SIGKILL
);
299 sigdelset(&_alls_nset
, SIGSEGV
);
300 sigdelset(&_alls_nset
, SIGSTOP
);
301 sigprocmask(SIG_BLOCK
, &_alls_nset
, &_alls_oset
);
310 if (--_alls_depth
== 0)
311 sigprocmask(SIG_SETMASK
, &_alls_oset
, (sigset_t
*)NULL
);
319 if (_hold_sigdepth
++ == 0) {
320 sigemptyset(&_hold_nset
);
321 sigaddset(&_hold_nset
, SIGHUP
);
322 sigaddset(&_hold_nset
, SIGINT
);
323 sigaddset(&_hold_nset
, SIGQUIT
);
324 sigprocmask(SIG_BLOCK
, &_hold_nset
, &_hold_oset
);
333 if (--_hold_sigdepth
== 0)
334 sigprocmask(SIG_SETMASK
, &_hold_oset
, NULL
);
340 _nyd_chirp(ui8_t act
, char const *file
, ui32_t line
, char const *fun
)
342 struct nyd_info
*nip
= _nyd_infos
;
344 if (_nyd_curr
!= NELEM(_nyd_infos
))
350 nip
->ni_chirp_line
= ((ui32_t
)(act
& 0x3) << 29) | (line
& 0x1FFFFFFFu
);
351 nip
->ni_level
= ((act
== 0) ? _nyd_level
352 : (act
== 1) ? ++_nyd_level
: _nyd_level
--);
356 _nyd_oncrash(int signo
)
358 struct sigaction xact
;
360 struct nyd_info
*nip
;
363 xact
.sa_handler
= SIG_DFL
;
364 sigemptyset(&xact
.sa_mask
);
366 sigaction(signo
, &xact
, NULL
);
368 fprintf(stderr
, "\n\nNYD: program dying due to signal %d:\n", signo
);
369 if (_nyd_infos
[NELEM(_nyd_infos
) - 1].ni_file
!= NULL
)
370 for (i
= _nyd_curr
, nip
= _nyd_infos
+ i
; i
< NELEM(_nyd_infos
); ++i
)
372 for (i
= 0, nip
= _nyd_infos
; i
< _nyd_curr
; ++i
)
376 sigaddset(&xset
, signo
);
377 sigprocmask(SIG_UNBLOCK
, &xset
, NULL
);
382 #endif /* HAVE_NYD */
385 touch(struct message
*mp
)
388 mp
->m_flag
|= MTOUCH
;
389 if (!(mp
->m_flag
& MREAD
))
390 mp
->m_flag
|= MREAD
| MSTATUS
;
395 is_dir(char const *name
)
401 if (!stat(name
, &sbuf
))
402 rv
= (S_ISDIR(sbuf
.st_mode
) != 0);
408 argcount(char **argv
)
413 for (ap
= argv
; *ap
++ != NULL
;)
416 return (int)PTR2SIZE(ap
- argv
- 1);
426 if ((cp
= ok_vlook(screen
)) == NULL
|| (s
= atoi(cp
)) <= 0)
427 s
= scrnheight
- 4; /* XXX no magics */
433 get_pager(char const **env_addon
)
438 cp
= ok_vlook(PAGER
);
439 if (cp
== NULL
|| *cp
== '\0')
442 if (env_addon
!= NULL
) {
444 if (strstr(cp
, "less") != NULL
) {
445 if (getenv("LESS") == NULL
)
446 *env_addon
= "LESS=FRSXi";
447 } else if (strstr(cp
, "lv") != NULL
) {
448 if (getenv("LV") == NULL
)
449 *env_addon
= "LV=-c";
457 paging_seems_sensible(void)
463 if (IS_TTY_SESSION() && (cp
= ok_vlook(crt
)) != NULL
)
464 rv
= (*cp
!= '\0') ? (size_t)atol(cp
) : (size_t)scrnheight
;
470 page_or_print(FILE *fp
, size_t lines
)
478 if ((rows
= paging_seems_sensible()) != 0 && lines
== 0) {
479 while ((c
= getc(fp
)) != EOF
)
480 if (c
== '\n' && ++lines
> rows
)
485 if (rows
!= 0 && lines
>= rows
)
486 run_command(get_pager(NULL
), 0, fileno(fp
), -1, NULL
, NULL
, NULL
);
488 while ((c
= getc(fp
)) != EOF
)
494 which_protocol(char const *name
) /* XXX (->URL (yet auxlily.c)) */
500 enum protocol rv
= PROTO_UNKNOWN
;
503 if (name
[0] == '%' && name
[1] == ':')
505 for (cp
= name
; *cp
&& *cp
!= ':'; cp
++)
509 if (cp
[0] == ':' && cp
[1] == '/' && cp
[2] == '/') {
510 if (!strncmp(name
, "pop3://", 7)) {
514 fprintf(stderr
, _("No POP3 support compiled in.\n"));
516 } else if (!strncmp(name
, "pop3s://", 8)) {
517 #if defined HAVE_POP3 && defined HAVE_SSL
521 fprintf(stderr
, _("No POP3 support compiled in.\n"));
524 fprintf(stderr
, _("No SSL support compiled in.\n"));
527 } else if (!strncmp(name
, "imap://", 7)) {
531 fprintf(stderr
, _("No IMAP support compiled in.\n"));
533 } else if (!strncmp(name
, "imaps://", 8)) {
534 #if defined HAVE_IMAP && defined HAVE_SSL
538 fprintf(stderr
, _("No IMAP support compiled in.\n"));
541 fprintf(stderr
, _("No SSL support compiled in.\n"));
548 /* TODO This is the de facto maildir code and thus belongs into there!
549 * TODO and: we should have maildir:// and mbox:// pseudo-protos, instead of
550 * TODO or (more likely) in addition to *newfolders*) */
553 np
= ac_alloc((sz
= strlen(name
)) + 4 +1);
554 memcpy(np
, name
, sz
+ 1);
555 if (!stat(name
, &st
)) {
556 if (S_ISDIR(st
.st_mode
) &&
557 (memcpy(np
+sz
, "/tmp", 4), !stat(np
, &st
) && S_ISDIR(st
.st_mode
)) &&
558 (memcpy(np
+sz
, "/new", 4), !stat(np
, &st
) && S_ISDIR(st
.st_mode
)) &&
559 (memcpy(np
+sz
, "/cur", 4), !stat(np
, &st
) && S_ISDIR(st
.st_mode
)))
561 } else if ((cp
= ok_vlook(newfolders
)) != NULL
&& !strcmp(cp
, "maildir"))
570 torek_hash(char const *name
)
572 /* Chris Torek's hash.
573 * NOTE: need to change *at least* create-okey-map.pl when changing the
578 while (*name
!= '\0') {
587 pjw(char const *cp
) /* TODO obsolete that -> torek_hash */
594 h
= (h
<< 4 & 0xffffffff) + (*cp
&0377);
595 if ((g
= h
& 0xf0000000) != 0) {
607 static ui32_t
const primes
[] = {
608 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
609 131071, 262139, 524287, 1048573, 2097143, 4194301,
610 8388593, 16777213, 33554393, 67108859, 134217689,
611 268435399, 536870909, 1073741789, 2147483647
614 ui32_t mprime
= 7, cutlim
;
618 cutlim
= (n
< 65536 ? n
<< 2 : (n
< 262144 ? n
<< 1 : n
));
620 for (i
= 0; i
< NELEM(primes
); i
++)
621 if ((mprime
= primes
[i
]) >= cutlim
)
623 if (i
== NELEM(primes
) && mprime
< n
)
630 expand_shell_escape(char const **s
, bool_t use_nail_extensions
)
638 if ((c
= *xs
& 0xFF) == '\0')
644 switch ((c
= *xs
& 0xFF)) {
646 case 'a': c
= '\a'; break;
647 case 'b': c
= '\b'; break;
648 case 'c': c
= PROMPT_STOP
; break;
649 case 'f': c
= '\f'; break;
650 case 'n': c
= '\n'; break;
651 case 'r': c
= '\r'; break;
652 case 't': c
= '\t'; break;
653 case 'v': c
= '\v'; break;
655 for (++xs
, c
= 0, n
= 4; --n
> 0 && octalchar(*xs
); ++xs
) {
660 /* S-nail extension for nice (get)prompt(()) support */
665 if (use_nail_extensions
) {
667 case '&': c
= ok_blook(bsdcompat
) ? '&' : '?'; break;
668 case '?': c
= exec_last_comm_error
? '1' : '0'; break;
669 case '$': c
= PROMPT_DOLLAR
; break;
670 case '@': c
= PROMPT_AT
; break;
676 /* A sole <backslash> at EOS is treated as-is! */
690 getprompt(void) /* TODO evaluate only as necessary (needs a bit) */
692 static char buf
[PROMPT_BUFFER_SIZE
];
695 char const *ccp_base
, *ccp
;
696 size_t NATCH_CHAR( cclen_base COMMA cclen COMMA
) maxlen
, dfmaxlen
;
701 if ((ccp_base
= ok_vlook(prompt
)) == NULL
|| *ccp_base
== '\0')
703 NATCH_CHAR( cclen_base
= strlen(ccp_base
); )
705 dfmaxlen
= 0; /* keep CC happy */
709 NATCH_CHAR( cclen
= cclen_base
; )
710 maxlen
= sizeof(buf
) -1;
718 #ifdef HAVE_NATCH_CHAR
719 c
= mblen(ccp
, cclen
); /* TODO use mbrtowc() */
728 } else if ((l
= c
) > 1) {
738 if ((c
= expand_shell_escape(&ccp
, TRU1
)) > 0) {
744 if (c
== 0 || c
== PROMPT_STOP
)
748 char const *a
= (c
== PROMPT_DOLLAR
) ? account_name
: displayname
;
751 if ((l
= field_put_bidi_clip(cp
, dfmaxlen
, a
, strlen(a
))) > 0) {
771 nodename(int mayoverride
)
773 static char *sys_hostname
, *hostname
; /* XXX free-at-exit */
779 struct addrinfo hints
, *res
;
781 struct hostent
*hent
;
786 if (mayoverride
&& (hn
= ok_vlook(hostname
)) != NULL
&& *hn
!= '\0') {
788 } else if ((hn
= sys_hostname
) == NULL
) {
793 memset(&hints
, 0, sizeof hints
);
794 hints
.ai_family
= AF_UNSPEC
;
795 hints
.ai_socktype
= SOCK_DGRAM
; /* (dummy) */
796 hints
.ai_flags
= AI_CANONNAME
;
797 if (getaddrinfo(hn
, "0", &hints
, &res
) == 0) {
798 if (res
->ai_canonname
!= NULL
) {
799 size_t l
= strlen(res
->ai_canonname
) +1;
801 memcpy(hn
, res
->ai_canonname
, l
);
806 hent
= gethostbyname(hn
);
811 sys_hostname
= sstrdup(hn
);
812 #if defined HAVE_SOCKETS && defined HAVE_IPV6
813 if (hn
!= ut
.nodename
)
819 if (hostname
!= NULL
&& hostname
!= sys_hostname
)
821 hostname
= sstrdup(hn
);
827 getrandstring(size_t length
)
829 static unsigned char nodedigest
[16];
843 data
= ac_alloc(length
);
845 if ((fd
= open("/dev/urandom", O_RDONLY
)) == -1 ||
846 length
!= (size_t)read(fd
, data
, length
)) {
853 md5_update(&ctx
, (unsigned char*)cp
, strlen(cp
));
854 md5_final(nodedigest
, &ctx
);
856 /* In that case it's only used for boundaries and Message-Id:s so that
857 * srand(3) should suffice */
859 for (i
= 0; i
< sizeof(nodedigest
); ++i
)
860 nodedigest
[i
] = (unsigned char)(cp
[i
% j
] ^ rand());
863 for (i
= 0; i
< length
; i
++)
864 data
[i
] = (char)((int)(255 * (rand() / (RAND_MAX
+ 1.0))) ^
865 nodedigest
[i
% sizeof nodedigest
]);
870 b64_encode_buf(&b64
, data
, length
, B64_SALLOC
);
872 assert(length
< b64
.l
);
873 b64
.s
[length
] = '\0';
875 /* Base64 includes + and /, replace them with _ and - */
876 for (data
= b64
.s
; length
-- > 0; ++data
)
879 else if (*data
== '/')
886 makedir(char const *name
)
892 if (!mkdir(name
, 0700))
896 if ((e
== EEXIST
|| e
== ENOSYS
) && !stat(name
, &st
) &&
911 if ((cw
->cw_fd
= open(".", O_RDONLY
)) == -1)
913 if (fchdir(cw
->cw_fd
) == -1) {
929 if (!fchdir(cw
->cw_fd
))
936 cwrelse(struct cw
*cw
)
943 #else /* !HAVE_FCHDIR */
950 if (getcwd(cw
->cw_wd
, sizeof cw
->cw_wd
) != NULL
&& !chdir(cw
->cw_wd
))
962 if (!chdir(cw
->cw_wd
))
969 cwrelse(struct cw
*cw
)
975 #endif /* !HAVE_FCHDIR */
978 field_detect_clip(size_t maxlen
, char const *buf
, size_t blen
)/*TODO mbrtowc()*/
983 #ifdef HAVE_NATCH_CHAR
984 maxlen
= MIN(maxlen
, blen
);
985 for (rv
= 0; maxlen
> 0;) {
986 int ml
= mblen(buf
, maxlen
);
996 rv
= MIN(blen
, maxlen
);
1003 field_put_bidi_clip(char *store
, size_t maxlen
, char const *buf
, size_t blen
)
1005 NATCH_CHAR( struct bidi_info bi
; )
1006 size_t rv
NATCH_CHAR( COMMA i
);
1013 #ifdef HAVE_NATCH_CHAR
1014 bidi_info_create(&bi
);
1015 if (bi
.bi_start
.l
== 0 || !bidi_info_needed(buf
, blen
)) {
1020 if (maxlen
>= (i
= bi
.bi_pad
+ bi
.bi_end
.l
+ bi
.bi_start
.l
))
1025 if ((i
= bi
.bi_start
.l
) > 0) {
1026 memcpy(store
, bi
.bi_start
.s
, i
);
1032 while (maxlen
> 0) {
1033 int ml
= mblen(buf
, blen
);
1038 if (UICMP(z
, maxlen
, <, ml
))
1043 memcpy(store
, buf
, ml
);
1050 if ((i
= bi
.bi_end
.l
) > 0) {
1051 memcpy(store
, bi
.bi_end
.s
, i
);
1059 rv
= MIN(blen
, maxlen
);
1060 memcpy(store
, buf
, rv
);
1069 colalign(char const *cp
, int col
, int fill
, int *cols_decr_used_or_null
)
1071 NATCH_CHAR( struct bidi_info bi
; )
1072 int col_orig
= col
, n
, sz
;
1073 bool_t isbidi
, isuni
, istab
, isrepl
;
1077 /* Bidi only on request and when there is 8-bit data */
1078 isbidi
= isuni
= FAL0
;
1079 #ifdef HAVE_NATCH_CHAR
1080 isuni
= ((options
& OPT_UNICODE
) != 0);
1081 bidi_info_create(&bi
);
1082 if (bi
.bi_start
.l
== 0)
1084 if (!(isbidi
= bidi_info_needed(cp
, strlen(cp
))))
1087 if ((size_t)col
>= bi
.bi_pad
)
1094 np
= nb
= salloc(mb_cur_max
* strlen(cp
) +
1096 NATCH_CHAR( + (isbidi
? bi
.bi_start
.l
+ bi
.bi_end
.l
: 0) )
1099 #ifdef HAVE_NATCH_CHAR
1101 memcpy(np
, bi
.bi_start
.s
, bi
.bi_start
.l
);
1102 np
+= bi
.bi_start
.l
;
1106 while (*cp
!= '\0') {
1108 #ifdef HAVE_C90AMEND1
1109 if (mb_cur_max
> 1) {
1114 if ((sz
= mbtowc(&wc
, cp
, mb_cur_max
)) == -1)
1116 else if (wc
== L
'\t') {
1117 cp
+= sz
- 1; /* Silly, no such charset known (.. until S-Ctext) */
1120 } else if (iswprint(wc
)) {
1121 # ifndef HAVE_WCWIDTH
1122 n
= 1 + (wc
>= 0x1100u
); /* TODO use S-CText isfullwidth() */
1124 if ((n
= wcwidth(wc
)) == -1)
1134 istab
= (*cp
== '\t');
1135 isrepl
= !(istab
|| isprint((uc_it
)*cp
));
1144 np
[0] = (char)0xEFu
;
1145 np
[1] = (char)0xBFu
;
1146 np
[2] = (char)0xBDu
;
1151 } else if (istab
|| (sz
== 1 && spacechar(*cp
))) {
1159 if (fill
&& col
!= 0) {
1161 memmove(nb
+ col
, nb
, PTR2SIZE(np
- nb
));
1162 memset(nb
, ' ', col
);
1164 memset(np
, ' ', col
);
1169 #ifdef HAVE_NATCH_CHAR
1171 memcpy(np
, bi
.bi_end
.s
, bi
.bi_end
.l
);
1177 if (cols_decr_used_or_null
!= NULL
)
1178 *cols_decr_used_or_null
-= col_orig
- col
;
1184 makeprint(struct str
const *in
, struct str
*out
)
1186 static int print_all_chars
= -1;
1188 char const *inp
, *maxp
;
1193 if (print_all_chars
== -1)
1194 print_all_chars
= ok_blook(print_all_chars
);
1196 out
->s
= outp
= smalloc(DBG( msz
= ) in
->l
*mb_cur_max
+ 2u*mb_cur_max
);
1200 if (print_all_chars
) {
1202 memcpy(outp
, inp
, out
->l
);
1206 #ifdef HAVE_NATCH_CHAR
1207 if (mb_cur_max
> 1) {
1208 char mbb
[MB_LEN_MAX
+ 1];
1211 bool_t isuni
= ((options
& OPT_UNICODE
) != 0);
1214 while (inp
< maxp
) {
1216 n
= mbtowc(&wc
, inp
, PTR2SIZE(maxp
- inp
));
1222 /* FIXME Why mbtowc() resetting here?
1223 * FIXME what about ISO 2022-JP plus -- those
1224 * FIXME will loose shifts, then!
1225 * FIXME THUS - we'd need special "known points"
1226 * FIXME to do so - say, after a newline!!
1227 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
1228 mbtowc(&wc
, NULL
, mb_cur_max
);
1229 wc
= isuni
? 0xFFFD : '?';
1234 if (!iswprint(wc
) && wc
!= '\n' && wc
!= '\r' && wc
!= '\b' &&
1236 if ((wc
& ~(wchar_t)037) == 0)
1237 wc
= isuni
? 0x2400 | wc
: '?';
1238 else if (wc
== 0177)
1239 wc
= isuni
? 0x2421 : '?';
1241 wc
= isuni
? 0x2426 : '?';
1243 if ((n
= wctomb(mbb
, wc
)) <= 0)
1246 assert(out
->l
< msz
);
1247 for (i
= 0; i
< n
; ++i
)
1251 #endif /* NATCH_CHAR */
1254 while (inp
< maxp
) {
1256 if (!isprint(c
) && c
!= '\n' && c
!= '\r' && c
!= '\b' && c
!= '\t')
1263 out
->s
[out
->l
] = '\0';
1268 prstr(char const *s
)
1276 makeprint(&in
, &out
);
1277 rp
= savestrbuf(out
.s
, out
.l
);
1284 prout(char const *s
, size_t sz
, FILE *fp
)
1292 makeprint(&in
, &out
);
1293 n
= fwrite(out
.s
, 1, out
.l
, fp
);
1300 putuc(int u
, int c
, FILE *fp
)
1306 #ifdef HAVE_NATCH_CHAR
1307 if ((options
& OPT_UNICODE
) && (u
& ~(wchar_t)0177)) {
1308 char mbb
[MB_LEN_MAX
];
1311 if ((n
= wctomb(mbb
, u
)) > 0) {
1313 for (i
= 0; i
< n
; ++i
)
1314 if (putc(mbb
[i
] & 0377, fp
) == EOF
) {
1319 rv
= (putc('\0', fp
) != EOF
);
1324 rv
= (putc(c
, fp
) != EOF
);
1330 bidi_info_needed(char const *bdat
, size_t blen
)
1335 #ifdef HAVE_NATCH_CHAR
1336 if (options
& OPT_UNICODE
)
1337 for (; blen
> 0; ++bdat
, --blen
) {
1338 if ((ui8_t
)*bdat
> 0x7F) {
1339 /* TODO Checking for BIDI character: use S-CText fromutf8
1340 * TODO plus isrighttoleft (or whatever there will be)! */
1341 ui32_t c
, x
= (ui8_t
)*bdat
;
1343 if ((x
& 0xE0) == 0xC0) {
1348 } else if ((x
& 0xF0) == 0xE0) {
1372 /* (Very very fuzzy, awaiting S-CText for good) */
1373 if ((c
>= 0x05BE && c
<= 0x08E3) ||
1374 (c
>= 0xFB1D && c
<= 0xFEFC) ||
1375 (c
>= 0x10800 && c
<= 0x10C48) ||
1376 (c
>= 0x1EE00 && c
<= 0x1EEF1)) {
1382 #endif /* HAVE_NATCH_CHAR */
1388 bidi_info_create(struct bidi_info
*bip
)
1390 /* Unicode: how to isolate RIGHT-TO-LEFT scripts via *headline-bidi*
1391 * 1.1 (Jun 1993): U+200E (E2 80 8E) LEFT-TO-RIGHT MARK
1392 * 6.3 (Sep 2013): U+2068 (E2 81 A8) FIRST STRONG ISOLATE,
1393 * U+2069 (E2 81 A9) POP DIRECTIONAL ISOLATE
1394 * Worse results seen for: U+202D "\xE2\x80\xAD" U+202C "\xE2\x80\xAC" */
1395 NATCH_CHAR( char const *hb
; )
1398 memset(bip
, 0, sizeof *bip
);
1399 bip
->bi_start
.s
= bip
->bi_end
.s
= UNCONST("");
1401 #ifdef HAVE_NATCH_CHAR
1402 if ((options
& OPT_UNICODE
) && (hb
= ok_vlook(headline_bidi
)) != NULL
) {
1408 bip
->bi_start
.s
= bip
->bi_end
.s
= UNCONST("\xE2\x80\x8E");
1414 bip
->bi_start
.s
= UNCONST("\xE2\x81\xA8");
1415 bip
->bi_end
.s
= UNCONST("\xE2\x81\xA9");
1418 bip
->bi_start
.l
= bip
->bi_end
.l
= 3;
1426 colour_table_create(bool_t pager_used
)
1428 union {char *cp
; char const *ccp
; void *vp
; struct colour_table
*ctp
;} u
;
1430 struct colour_table
*ct
;
1433 if (ok_blook(colour_disable
) || (pager_used
&& !ok_blook(colour_pager
)))
1436 char *term
, *okterms
;
1438 /* Don't use getenv(), but force copy-in into our own tables.. */
1439 if ((term
= _var_voklook("TERM")) == NULL
)
1441 /* terminfo rocks: if we find "color", assume it's right */
1442 if (strstr(term
, "color") != NULL
)
1444 if ((okterms
= ok_vlook(colour_terms
)) == NULL
)
1445 okterms
= UNCONST(COLOUR_TERMS
);
1446 okterms
= savestr(okterms
);
1449 while ((u
.cp
= n_strsep(&okterms
, ',', TRU1
)) != NULL
)
1450 if (!strncmp(u
.cp
, term
, i
))
1456 colour_table
= ct
= salloc(sizeof *ct
); /* XXX lex.c yet resets (FILTER!) */
1459 enum colourspec cspec
;
1462 {ok_v_colour_msginfo
, COLOURSPEC_MSGINFO
, COLOUR_MSGINFO
},
1463 {ok_v_colour_partinfo
, COLOURSPEC_PARTINFO
, COLOUR_PARTINFO
},
1464 {ok_v_colour_from_
, COLOURSPEC_FROM_
, COLOUR_FROM_
},
1465 {ok_v_colour_header
, COLOURSPEC_HEADER
, COLOUR_HEADER
},
1466 {ok_v_colour_uheader
, COLOURSPEC_UHEADER
, COLOUR_UHEADER
}
1469 for (i
= 0; i
< NELEM(map
); ++i
) {
1470 if ((u
.cp
= _var_oklook(map
[i
].okey
)) == NULL
)
1471 u
.ccp
= map
[i
].defval
;
1472 u
.cp
= _colour_iso6429(u
.ccp
);
1473 ct
->ct_csinfo
[map
[i
].cspec
].l
= strlen(u
.cp
);
1474 ct
->ct_csinfo
[map
[i
].cspec
].s
= u
.cp
;
1477 ct
->ct_csinfo
[COLOURSPEC_RESET
].l
= sizeof("\033[0m") -1;
1478 ct
->ct_csinfo
[COLOURSPEC_RESET
].s
= UNCONST("\033[0m");
1480 if ((u
.cp
= ok_vlook(colour_user_headers
)) == NULL
)
1481 u
.ccp
= COLOUR_USER_HEADERS
;
1482 ct
->ct_csinfo
[COLOURSPEC_RESET
+ 1].l
= i
= strlen(u
.ccp
);
1483 ct
->ct_csinfo
[COLOURSPEC_RESET
+ 1].s
= (i
== 0) ? NULL
: savestr(u
.ccp
);
1489 colour_put(FILE *fp
, enum colourspec cs
)
1492 if (colour_table
!= NULL
) {
1493 struct str
const *cp
= colour_get(cs
);
1495 fwrite(cp
->s
, cp
->l
, 1, fp
);
1501 colour_put_header(FILE *fp
, char const *name
)
1503 enum colourspec cs
= COLOURSPEC_HEADER
;
1504 struct str
const *uheads
;
1505 char *cp
, *cp_base
, *x
;
1509 if (colour_table
== NULL
)
1511 /* Normal header colours if there are no user headers */
1512 uheads
= colour_table
->ct_csinfo
+ COLOURSPEC_RESET
+ 1;
1513 if (uheads
->s
== NULL
)
1516 /* Iterate over all entries in the *colour-user-headers* list */
1517 cp
= ac_alloc(uheads
->l
+1);
1518 memcpy(cp
, uheads
->s
, uheads
->l
+1);
1520 namelen
= strlen(name
);
1521 while ((x
= n_strsep(&cp
, ',', TRU1
)) != NULL
) {
1522 size_t l
= (cp
!= NULL
) ? PTR2SIZE(cp
- x
) - 1 : strlen(x
);
1523 if (l
== namelen
&& !ascncasecmp(x
, name
, namelen
)) {
1524 cs
= COLOURSPEC_UHEADER
;
1536 colour_reset(FILE *fp
)
1539 if (colour_table
!= NULL
)
1540 fwrite("\033[0m", 4, 1, fp
);
1544 FL
struct str
const *
1545 colour_get(enum colourspec cs
)
1547 struct str
const *rv
= NULL
;
1550 if (colour_table
!= NULL
)
1551 if ((rv
= colour_table
->ct_csinfo
+ cs
)->s
== NULL
)
1556 #endif /* HAVE_COLOUR */
1559 time_current_update(struct time_current
*tc
, bool_t full_update
)
1562 tc
->tc_time
= time(NULL
);
1564 memcpy(&tc
->tc_gm
, gmtime(&tc
->tc_time
), sizeof tc
->tc_gm
);
1565 memcpy(&tc
->tc_local
, localtime(&tc
->tc_time
), sizeof tc
->tc_local
);
1566 sstpcpy(tc
->tc_ctime
, ctime(&tc
->tc_time
));
1572 _out_of_memory(void)
1579 smalloc(size_t s SMALLOC_DEBUG_ARGS
)
1586 if ((rv
= malloc(s
)) == NULL
)
1593 srealloc(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
1602 else if ((rv
= realloc(v
, s
)) == NULL
)
1609 scalloc(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
1616 if ((rv
= calloc(nmemb
, size
)) == NULL
)
1622 #else /* !HAVE_DEBUG */
1623 CTA(sizeof(char) == sizeof(ui8_t
));
1625 # define _HOPE_SIZE (2 * 8 * sizeof(char))
1626 # define _HOPE_SET(C) \
1628 union mem_ptr __xl, __xu;\
1629 struct mem_chunk *__xc;\
1630 __xl.p_p = (C).p_p;\
1631 __xc = __xl.p_c - 1;\
1634 __xl.p_ui8p[0]=0xDE; __xl.p_ui8p[1]=0xAA;\
1635 __xl.p_ui8p[2]=0x55; __xl.p_ui8p[3]=0xAD;\
1636 __xl.p_ui8p[4]=0xBE; __xl.p_ui8p[5]=0x55;\
1637 __xl.p_ui8p[6]=0xAA; __xl.p_ui8p[7]=0xEF;\
1638 __xu.p_ui8p += __xc->mc_size - 8;\
1639 __xu.p_ui8p[0]=0xDE; __xu.p_ui8p[1]=0xAA;\
1640 __xu.p_ui8p[2]=0x55; __xu.p_ui8p[3]=0xAD;\
1641 __xu.p_ui8p[4]=0xBE; __xu.p_ui8p[5]=0x55;\
1642 __xu.p_ui8p[6]=0xAA; __xu.p_ui8p[7]=0xEF;\
1644 # define _HOPE_GET_TRACE(C,BAD) \
1650 # define _HOPE_GET(C,BAD) \
1652 union mem_ptr __xl, __xu;\
1653 struct mem_chunk *__xc;\
1655 __xl.p_p = (C).p_p;\
1657 (C).p_cp = __xl.p_cp;\
1658 __xc = __xl.p_c - 1;\
1661 if (__xl.p_ui8p[0] != 0xDE) __i |= 1<<0;\
1662 if (__xl.p_ui8p[1] != 0xAA) __i |= 1<<1;\
1663 if (__xl.p_ui8p[2] != 0x55) __i |= 1<<2;\
1664 if (__xl.p_ui8p[3] != 0xAD) __i |= 1<<3;\
1665 if (__xl.p_ui8p[4] != 0xBE) __i |= 1<<4;\
1666 if (__xl.p_ui8p[5] != 0x55) __i |= 1<<5;\
1667 if (__xl.p_ui8p[6] != 0xAA) __i |= 1<<6;\
1668 if (__xl.p_ui8p[7] != 0xEF) __i |= 1<<7;\
1671 alert("%p: corrupt lower canary: 0x%02X: %s, line %u",\
1672 __xl.p_p, __i, mdbg_file, mdbg_line);\
1675 __xu.p_ui8p += __xc->mc_size - 8;\
1677 if (__xu.p_ui8p[0] != 0xDE) __i |= 1<<0;\
1678 if (__xu.p_ui8p[1] != 0xAA) __i |= 1<<1;\
1679 if (__xu.p_ui8p[2] != 0x55) __i |= 1<<2;\
1680 if (__xu.p_ui8p[3] != 0xAD) __i |= 1<<3;\
1681 if (__xu.p_ui8p[4] != 0xBE) __i |= 1<<4;\
1682 if (__xu.p_ui8p[5] != 0x55) __i |= 1<<5;\
1683 if (__xu.p_ui8p[6] != 0xAA) __i |= 1<<6;\
1684 if (__xu.p_ui8p[7] != 0xEF) __i |= 1<<7;\
1687 alert("%p: corrupt upper canary: 0x%02X: %s, line %u",\
1688 __xl.p_p, __i, mdbg_file, mdbg_line);\
1691 alert(" ..canary last seen: %s, line %u",\
1692 __xc->mc_file, __xc->mc_line);\
1696 (smalloc
)(size_t s SMALLOC_DEBUG_ARGS
)
1703 s
+= sizeof(struct mem_chunk
) + _HOPE_SIZE
;
1705 if ((p
.p_p
= (malloc
)(s
)) == NULL
)
1707 p
.p_c
->mc_prev
= NULL
;
1708 if ((p
.p_c
->mc_next
= _mem_list
) != NULL
)
1709 _mem_list
->mc_prev
= p
.p_c
;
1710 p
.p_c
->mc_file
= mdbg_file
;
1711 p
.p_c
->mc_line
= (ui16_t
)mdbg_line
;
1712 p
.p_c
->mc_isfree
= FAL0
;
1713 p
.p_c
->mc_size
= (ui32_t
)s
;
1714 _mem_list
= p
.p_c
++;
1719 _mem_amax
= MAX(_mem_amax
, _mem_acur
);
1722 _mem_mmax
= MAX(_mem_mmax
, _mem_mcur
);
1728 (srealloc
)(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
1734 if ((p
.p_p
= v
) == NULL
) {
1735 p
.p_p
= (smalloc
)(s
, mdbg_file
, mdbg_line
);
1739 _HOPE_GET(p
, isbad
);
1741 if (p
.p_c
->mc_isfree
) {
1742 fprintf(stderr
, "srealloc(): region freed! At %s, line %d\n"
1743 "\tLast seen: %s, line %d\n",
1744 mdbg_file
, mdbg_line
, p
.p_c
->mc_file
, p
.p_c
->mc_line
);
1748 if (p
.p_c
== _mem_list
)
1749 _mem_list
= p
.p_c
->mc_next
;
1751 p
.p_c
->mc_prev
->mc_next
= p
.p_c
->mc_next
;
1752 if (p
.p_c
->mc_next
!= NULL
)
1753 p
.p_c
->mc_next
->mc_prev
= p
.p_c
->mc_prev
;
1756 _mem_mcur
-= p
.p_c
->mc_size
;
1760 s
+= sizeof(struct mem_chunk
) + _HOPE_SIZE
;
1762 if ((p
.p_p
= (realloc
)(p
.p_c
, s
)) == NULL
)
1764 p
.p_c
->mc_prev
= NULL
;
1765 if ((p
.p_c
->mc_next
= _mem_list
) != NULL
)
1766 _mem_list
->mc_prev
= p
.p_c
;
1767 p
.p_c
->mc_file
= mdbg_file
;
1768 p
.p_c
->mc_line
= (ui16_t
)mdbg_line
;
1769 p
.p_c
->mc_isfree
= FAL0
;
1770 p
.p_c
->mc_size
= (ui32_t
)s
;
1771 _mem_list
= p
.p_c
++;
1776 _mem_amax
= MAX(_mem_amax
, _mem_acur
);
1779 _mem_mmax
= MAX(_mem_mmax
, _mem_mcur
);
1786 (scalloc
)(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
1796 size
+= sizeof(struct mem_chunk
) + _HOPE_SIZE
;
1798 if ((p
.p_p
= (malloc
)(size
)) == NULL
)
1800 memset(p
.p_p
, 0, size
);
1801 p
.p_c
->mc_prev
= NULL
;
1802 if ((p
.p_c
->mc_next
= _mem_list
) != NULL
)
1803 _mem_list
->mc_prev
= p
.p_c
;
1804 p
.p_c
->mc_file
= mdbg_file
;
1805 p
.p_c
->mc_line
= (ui16_t
)mdbg_line
;
1806 p
.p_c
->mc_isfree
= FAL0
;
1807 p
.p_c
->mc_size
= (ui32_t
)size
;
1808 _mem_list
= p
.p_c
++;
1813 _mem_amax
= MAX(_mem_amax
, _mem_acur
);
1816 _mem_mmax
= MAX(_mem_mmax
, _mem_mcur
);
1822 (sfree
)(void *v SMALLOC_DEBUG_ARGS
)
1828 if ((p
.p_p
= v
) == NULL
) {
1829 fprintf(stderr
, "sfree(NULL) from %s, line %d\n", mdbg_file
, mdbg_line
);
1833 _HOPE_GET(p
, isbad
);
1835 if (p
.p_c
->mc_isfree
) {
1836 fprintf(stderr
, "sfree(): double-free avoided at %s, line %d\n"
1837 "\tLast seen: %s, line %d\n",
1838 mdbg_file
, mdbg_line
, p
.p_c
->mc_file
, p
.p_c
->mc_line
);
1842 if (p
.p_c
== _mem_list
)
1843 _mem_list
= p
.p_c
->mc_next
;
1845 p
.p_c
->mc_prev
->mc_next
= p
.p_c
->mc_next
;
1846 if (p
.p_c
->mc_next
!= NULL
)
1847 p
.p_c
->mc_next
->mc_prev
= p
.p_c
->mc_prev
;
1848 p
.p_c
->mc_isfree
= TRU1
;
1851 _mem_mcur
-= p
.p_c
->mc_size
;
1853 if (options
& OPT_DEBUG
) {
1854 p
.p_c
->mc_next
= _mem_free
;
1866 size_t c
= 0, s
= 0;
1869 for (p
.p_c
= _mem_free
; p
.p_c
!= NULL
;) {
1872 s
+= p
.p_c
->mc_size
;
1873 p
.p_c
= p
.p_c
->mc_next
;
1878 if (options
& OPT_DEBUG
)
1879 fprintf(stderr
, "smemreset(): freed %" ZFMT
" chunks/%" ZFMT
" bytes\n",
1885 c_smemtrace(void *v
)
1887 /* For _HOPE_GET() */
1888 char const * const mdbg_file
= "smemtrace()";
1889 int const mdbg_line
= -1;
1891 union mem_ptr p
, xp
;
1897 if ((fp
= Ftmp(NULL
, "memtr", OF_RDWR
| OF_UNLINK
| OF_REGISTER
, 0600)) ==
1903 fprintf(fp
, "Memory statistics:\n"
1904 " Count cur/peek/all: %7" ZFMT
"/%7" ZFMT
"/%10" ZFMT
"\n"
1905 " Bytes cur/peek/all: %7" ZFMT
"/%7" ZFMT
"/%10" ZFMT
"\n\n",
1906 _mem_acur
, _mem_amax
, _mem_aall
, _mem_mcur
, _mem_mmax
, _mem_mall
);
1908 fprintf(fp
, "Currently allocated memory chunks:\n");
1909 for (lines
= 0, p
.p_c
= _mem_list
; p
.p_c
!= NULL
;
1910 ++lines
, p
.p_c
= p
.p_c
->mc_next
) {
1913 _HOPE_GET_TRACE(xp
, isbad
);
1914 fprintf(fp
, "%s%p (%5" ZFMT
" bytes): %s, line %u\n",
1915 (isbad
? "! CANARY ERROR: " : ""), xp
.p_p
,
1916 (size_t)(p
.p_c
->mc_size
- sizeof(struct mem_chunk
)), p
.p_c
->mc_file
,
1920 if (options
& OPT_DEBUG
) {
1921 fprintf(fp
, "sfree()d memory chunks awaiting free():\n");
1922 for (p
.p_c
= _mem_free
; p
.p_c
!= NULL
; ++lines
, p
.p_c
= p
.p_c
->mc_next
) {
1925 _HOPE_GET_TRACE(xp
, isbad
);
1926 fprintf(fp
, "%s%p (%5" ZFMT
" bytes): %s, line %u\n",
1927 (isbad
? "! CANARY ERROR: " : ""), xp
.p_p
,
1928 (size_t)(p
.p_c
->mc_size
- sizeof(struct mem_chunk
)),
1929 p
.p_c
->mc_file
, p
.p_c
->mc_line
);
1933 page_or_print(fp
, lines
);
1941 # ifdef _HAVE_MEMCHECK
1943 _smemcheck(char const *mdbg_file
, int mdbg_line
)
1945 union mem_ptr p
, xp
;
1946 bool_t anybad
= FAL0
, isbad
;
1950 for (lines
= 0, p
.p_c
= _mem_list
; p
.p_c
!= NULL
;
1951 ++lines
, p
.p_c
= p
.p_c
->mc_next
) {
1954 _HOPE_GET_TRACE(xp
, isbad
);
1958 "! CANARY ERROR: %p (%5" ZFMT
" bytes): %s, line %u\n",
1959 xp
.p_p
, (size_t)(p
.p_c
->mc_size
- sizeof(struct mem_chunk
)),
1960 p
.p_c
->mc_file
, p
.p_c
->mc_line
);
1964 if (options
& OPT_DEBUG
) {
1965 for (p
.p_c
= _mem_free
; p
.p_c
!= NULL
; ++lines
, p
.p_c
= p
.p_c
->mc_next
) {
1968 _HOPE_GET_TRACE(xp
, isbad
);
1972 "! CANARY ERROR: %p (%5" ZFMT
" bytes): %s, line %u\n",
1973 xp
.p_p
, (size_t)(p
.p_c
->mc_size
- sizeof(struct mem_chunk
)),
1974 p
.p_c
->mc_file
, p
.p_c
->mc_line
);
1981 # endif /* _HAVE_MEMCHECK */
1985 # undef _HOPE_GET_TRACE
1987 #endif /* HAVE_DEBUG */