Add `-L spec-list' argument and print_header_summary()
[s-mailx.git] / auxlily.c
blob17176a55d870c2857d7a6aa16fe6acfb085306e4
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_DEBUG
59 struct nyd_info {
60 char const *ni_file;
61 char const *ni_fun;
62 ui32_t ni_chirp_line;
63 ui32_t ni_level;
65 #endif
67 /* NYD */
68 #ifdef HAVE_DEBUG
69 static ui32_t _nyd_curr;
70 static ui32_t _nyd_level;
71 static struct nyd_info _nyd_infos[NYD_CALLS_MAX];
72 #endif
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 */
83 #ifdef HAVE_COLOUR
84 static char * _colour_iso6429(char const *wish);
85 #endif
87 #ifdef HAVE_DEBUG
88 static void _nyd_print(struct nyd_info *nip);
89 #endif
91 #ifdef HAVE_COLOUR
92 static char *
93 _colour_iso6429(char const *wish)
95 char const * const wish_orig = wish;
96 char *xwish, *cp, cfg[3] = {0, 0, 0};
97 NYD_ENTER;
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);
105 wish = xwish;
108 /* Iterate over the colour spec */
109 while ((cp = n_strsep(&xwish, ',', TRU1)) != NULL) {
110 char *y, *x = strchr(cp, '=');
111 if (x == NULL) {
112 jbail:
113 fprintf(stderr, tr(527,
114 "Invalid colour specification \"%s\": >>> %s <<<\n"),
115 wish_orig, cp);
116 continue;
118 *x++ = '\0';
120 /* TODO convert the ft/fg/bg parser into a table-based one! */
121 if (!asccasecmp(cp, "ft")) {
122 if (!asccasecmp(x, "bold"))
123 cfg[0] = '1';
124 else if (!asccasecmp(x, "inverse"))
125 cfg[0] = '7';
126 else if (!asccasecmp(x, "underline"))
127 cfg[0] = '4';
128 else
129 goto jbail;
130 } else if (!asccasecmp(cp, "fg")) {
131 y = cfg + 1;
132 goto jiter_colour;
133 } else if (!asccasecmp(cp, "bg")) {
134 y = cfg + 2;
135 jiter_colour:
136 if (!asccasecmp(x, "black"))
137 *y = '0';
138 else if (!asccasecmp(x, "blue"))
139 *y = '4';
140 else if (!asccasecmp(x, "green"))
141 *y = '2';
142 else if (!asccasecmp(x, "red"))
143 *y = '1';
144 else if (!asccasecmp(x, "brown"))
145 *y = '3';
146 else if (!asccasecmp(x, "magenta"))
147 *y = '5';
148 else if (!asccasecmp(x, "cyan"))
149 *y = '6';
150 else if (!asccasecmp(x, "white"))
151 *y = '7';
152 else
153 goto jbail;
154 } else
155 goto jbail;
158 /* Restore our salloc() buffer, create return value */
159 xwish = UNCONST(wish);
160 if (cfg[0] || cfg[1] || cfg[2]) {
161 xwish[0] = '\033';
162 xwish[1] = '[';
163 xwish += 2;
164 if (cfg[0])
165 *xwish++ = cfg[0];
166 if (cfg[1]) {
167 if (cfg[0])
168 *xwish++ = ';';
169 xwish[0] = '3';
170 xwish[1] = cfg[1];
171 xwish += 2;
173 if (cfg[2]) {
174 if (cfg[0] || cfg[1])
175 *xwish++ = ';';
176 xwish[0] = '4';
177 xwish[1] = cfg[2];
178 xwish += 2;
180 *xwish++ = 'm';
182 *xwish = '\0';
183 NYD_LEAVE;
184 return UNCONST(wish);
186 #endif /* HAVE_COLOUR */
188 #ifdef HAVE_DEBUG
189 static void
190 _nyd_print(struct nyd_info *nip) /* XXX like SFSYS;no magics;jumps:lvl wrong */
192 char buf[80];
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));
198 if (u.i > 0) {
199 u.z = u.i;
200 if (u.z > sizeof buf)
201 u.z = sizeof buf - 1; /* (Skip \0) */
202 write(STDERR_FILENO, buf, u.z);
205 #endif
207 FL void
208 panic(char const *format, ...)
210 va_list ap;
211 NYD_ENTER;
213 fprintf(stderr, tr(1, "Panic: "));
215 va_start(ap, format);
216 vfprintf(stderr, format, ap);
217 va_end(ap);
219 fputs("\n", stderr);
220 fflush(stderr);
221 NYD_LEAVE;
222 abort(); /* Was exit(EXIT_ERR); for a while, but no */
225 FL void
226 alert(char const *format, ...)
228 va_list ap;
229 NYD_ENTER;
231 fprintf(stderr, tr(1, "Panic: "));
233 va_start(ap, format);
234 vfprintf(stderr, format, ap);
235 va_end(ap);
237 fputs("\n", stderr);
238 fflush(stderr);
239 NYD_LEAVE;
242 FL sighandler_type
243 safe_signal(int signum, sighandler_type handler)
245 struct sigaction nact, oact;
246 sighandler_type rv;
247 NYD_ENTER;
249 nact.sa_handler = handler;
250 sigemptyset(&nact.sa_mask);
251 nact.sa_flags = 0;
252 #ifdef SA_RESTART
253 nact.sa_flags |= SA_RESTART;
254 #endif
255 rv = (sigaction(signum, &nact, &oact) != 0) ? SIG_ERR : oact.sa_handler;
256 NYD_LEAVE;
257 return rv;
260 FL void
261 hold_all_sigs(void)
263 NYD_ENTER;
264 if (_alls_depth++ == 0) {
265 sigfillset(&_alls_nset);
266 sigdelset(&_alls_nset, SIGABRT);
267 #ifdef SIGBUS
268 sigdelset(&_alls_nset, SIGBUS);
269 #endif
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);
278 NYD_LEAVE;
281 FL void
282 rele_all_sigs(void)
284 NYD_ENTER;
285 if (--_alls_depth == 0)
286 sigprocmask(SIG_SETMASK, &_alls_oset, (sigset_t*)NULL);
287 NYD_LEAVE;
290 FL void
291 hold_sigs(void)
293 NYD_ENTER;
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);
301 NYD_LEAVE;
304 FL void
305 rele_sigs(void)
307 NYD_ENTER;
308 if (--_hold_sigdepth == 0)
309 sigprocmask(SIG_SETMASK, &_hold_oset, NULL);
310 NYD_LEAVE;
313 #ifdef HAVE_DEBUG
314 FL void
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))
320 nip += _nyd_curr++;
321 else
322 _nyd_curr = 1;
323 nip->ni_file = file;
324 nip->ni_fun = fun;
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--);
330 FL void
331 _nyd_oncrash(int signo)
333 struct sigaction xact;
334 sigset_t xset;
335 struct nyd_info *nip;
336 size_t i;
338 xact.sa_handler = SIG_DFL;
339 sigemptyset(&xact.sa_mask);
340 xact.sa_flags = 0;
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)
346 _nyd_print(nip++);
347 for (i = 0, nip = _nyd_infos; i < _nyd_curr; ++i)
348 _nyd_print(nip++);
350 sigemptyset(&xset);
351 sigaddset(&xset, signo);
352 sigprocmask(SIG_UNBLOCK, &xset, NULL);
353 kill(0, signo);
354 while (1)
355 exit(1);
357 #endif
359 FL void
360 touch(struct message *mp)
362 NYD_ENTER;
363 mp->m_flag |= MTOUCH;
364 if (!(mp->m_flag & MREAD))
365 mp->m_flag |= MREAD | MSTATUS;
366 NYD_LEAVE;
369 FL bool_t
370 is_dir(char const *name)
372 struct stat sbuf;
373 bool_t rv = FAL0;
374 NYD_ENTER;
376 if (!stat(name, &sbuf))
377 rv = !!S_ISDIR(sbuf.st_mode);
378 NYD_LEAVE;
379 return rv;
382 FL int
383 argcount(char **argv)
385 char **ap;
386 NYD_ENTER;
388 for (ap = argv; *ap++ != NULL;)
390 NYD_LEAVE;
391 return ap - argv - 1;
394 FL int
395 screensize(void)
397 int s;
398 char *cp;
399 NYD_ENTER;
401 if ((cp = ok_vlook(screen)) == NULL || (s = atoi(cp)) <= 0)
402 s = scrnheight - 4;
403 NYD_LEAVE;
404 return s;
407 FL char const *
408 get_pager(void)
410 char const *cp;
411 NYD_ENTER;
413 cp = ok_vlook(PAGER);
414 if (cp == NULL || *cp == '\0')
415 cp = XPAGER;
416 NYD_LEAVE;
417 return cp;
420 FL size_t
421 paging_seems_sensible(void)
423 size_t rv = 0;
424 char const *cp;
425 NYD_ENTER;
427 if (IS_TTY_SESSION() && (cp = ok_vlook(crt)) != NULL)
428 rv = (*cp != '\0') ? (size_t)atol(cp) : (size_t)scrnheight;
429 NYD_LEAVE;
430 return rv;
433 FL void
434 page_or_print(FILE *fp, size_t lines)
436 size_t rows;
437 int c;
438 NYD_ENTER;
440 fflush_rewind(fp);
442 if ((rows = paging_seems_sensible()) != 0 && lines == 0) {
443 while ((c = getc(fp)) != EOF)
444 if (c == '\n' && ++lines > rows)
445 break;
446 rewind(fp);
449 if (rows != 0 && lines >= rows)
450 run_command(get_pager(), 0, fileno(fp), -1, NULL, NULL, NULL);
451 else
452 while ((c = getc(fp)) != EOF)
453 putchar(c);
454 NYD_LEAVE;
457 FL enum protocol
458 which_protocol(char const *name)
460 struct stat st;
461 char const *cp;
462 char *np;
463 size_t sz;
464 enum protocol rv = PROTO_UNKNOWN;
465 NYD_ENTER;
467 if (name[0] == '%' && name[1] == ':')
468 name += 2;
469 for (cp = name; *cp && *cp != ':'; cp++)
470 if (!alnumchar(*cp))
471 goto jfile;
473 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
474 if (strncmp(name, "pop3://", 7) == 0) {
475 #ifdef HAVE_POP3
476 rv = PROTO_POP3;
477 #else
478 fprintf(stderr, tr(216, "No POP3 support compiled in.\n"));
479 #endif
480 } else if (strncmp(name, "pop3s://", 8) == 0) {
481 #if defined HAVE_POP3 && defined HAVE_SSL
482 rv = PROTO_POP3;
483 #else
484 # ifndef HAVE_POP3
485 fprintf(stderr, tr(216, "No POP3 support compiled in.\n"));
486 # endif
487 # ifndef HAVE_SSL
488 fprintf(stderr, tr(225, "No SSL support compiled in.\n"));
489 # endif
490 #endif
491 } else if (strncmp(name, "imap://", 7) == 0) {
492 #ifdef HAVE_IMAP
493 rv = PROTO_IMAP;
494 #else
495 fprintf(stderr, tr(269, "No IMAP support compiled in.\n"));
496 #endif
497 } else if (strncmp(name, "imaps://", 8) == 0) {
498 #if defined HAVE_IMAP && defined HAVE_SSL
499 rv = PROTO_IMAP;
500 #else
501 # ifndef HAVE_IMAP
502 fprintf(stderr, tr(269, "No IMAP support compiled in.\n"));
503 # endif
504 # ifndef HAVE_SSL
505 fprintf(stderr, tr(225, "No SSL support compiled in.\n"));
506 # endif
507 #endif
509 goto jleave;
512 /* TODO This is the de facto maildir code and thus belongs into there! */
513 jfile:
514 rv = PROTO_FILE;
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)))
522 rv = PROTO_MAILDIR;
523 } else if ((cp = ok_vlook(newfolders)) != NULL && !strcmp(cp, "maildir"))
524 rv = PROTO_MAILDIR;
525 ac_free(np);
526 jleave:
527 NYD_LEAVE;
528 return rv;
531 FL ui32_t
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
536 * algorithm!! */
537 ui32_t h = 0;
538 NYD_ENTER;
540 while (*name != '\0') {
541 h *= 33;
542 h += *name++;
544 NYD_LEAVE;
545 return h;
548 FL unsigned
549 pjw(char const *cp) /* XXX obsolete that -> torek_hash */
551 unsigned h = 0, g;
552 NYD_ENTER;
554 cp--;
555 while (*++cp) {
556 h = (h << 4 & 0xffffffff) + (*cp&0377);
557 if ((g = h & 0xf0000000) != 0) {
558 h = h ^ g >> 24;
559 h = h ^ g;
562 NYD_LEAVE;
563 return h;
566 FL ui32_t
567 nextprime(ui32_t n)
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
576 ui32_t mprime = 7;
577 size_t i;
578 NYD_ENTER;
580 for (i = 0; i < NELEM(primes); i++)
581 if ((mprime = primes[i]) >= (n < 65536 ? n*4 : (n < 262144u ? n*2 : n)))
582 break;
583 if (i == NELEM(primes))
584 mprime = n; /* TODO not so prime, but better than failure */
585 NYD_LEAVE;
586 return mprime;
589 FL int
590 expand_shell_escape(char const **s, bool_t use_nail_extensions)
592 char const *xs = *s;
593 int c, n;
594 NYD_ENTER;
596 if ((c = *xs & 0xFF) == '\0')
597 goto jleave;
598 ++xs;
599 if (c != '\\')
600 goto jleave;
602 switch ((c = *xs & 0xFF)) {
603 case '\\': break;
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;
612 case '0':
613 for (++xs, c = 0, n = 4; --n > 0 && octalchar(*xs); ++xs) {
614 c <<= 3;
615 c |= *xs - '0';
617 goto jleave;
618 /* S-nail extension for nice (get)prompt(()) support */
619 case '&':
620 case '?':
621 case '$':
622 case '@':
623 if (use_nail_extensions) {
624 switch (c) {
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;
630 break;
632 /* FALLTHRU */
633 case '\0':
634 /* A sole <backslash> at EOS is treated as-is! */
635 /* FALLTHRU */
636 default:
637 c = '\\';
638 goto jleave;
640 ++xs;
641 jleave:
642 *s = xs;
643 NYD_LEAVE;
644 return c;
647 FL char *
648 getprompt(void)
650 static char buf[PROMPT_BUFFER_SIZE];
652 char *cp = buf;
653 char const *ccp;
654 NYD_ENTER;
656 if ((ccp = ok_vlook(prompt)) == NULL || *ccp == '\0')
657 goto jleave;
659 for (; PTRCMP(cp, <, buf + sizeof(buf) - 1); ++cp) {
660 char const *a;
661 size_t l;
662 int c = expand_shell_escape(&ccp, TRU1);
664 if (c > 0) {
665 *cp = (char)c;
666 continue;
668 if (c == 0 || c == PROMPT_STOP)
669 break;
671 a = (c == PROMPT_DOLLAR) ? account_name : displayname;
672 if (a == NULL)
673 a = "";
674 l = strlen(a);
675 if (PTRCMP(cp + l, >=, buf + sizeof(buf) - 1))
676 *cp++ = '?';
677 else {
678 memcpy(cp, a, l);
679 cp += --l;
682 jleave:
683 *cp = '\0';
684 NYD_LEAVE;
685 return buf;
688 FL char *
689 nodename(int mayoverride)
691 static char *hostname;
692 struct utsname ut;
693 char *hn;
694 #ifdef HAVE_SOCKETS
695 # ifdef HAVE_IPV6
696 struct addrinfo hints, *res;
697 # else
698 struct hostent *hent;
699 # endif
700 #endif
701 NYD_ENTER;
703 if (mayoverride && (hn = ok_vlook(hostname)) != NULL && *hn != '\0') {
704 if (hostname != NULL)
705 free(hostname);
706 hostname = sstrdup(hn);
707 } else if (hostname == NULL) {
708 uname(&ut);
709 hn = ut.nodename;
710 #ifdef HAVE_SOCKETS
711 # ifdef HAVE_IPV6
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);
722 freeaddrinfo(res);
724 # else
725 hent = gethostbyname(hn);
726 if (hent != NULL)
727 hn = hent->h_name;
728 # endif
729 #endif
730 hostname = sstrdup(hn);
731 #if defined HAVE_SOCKETS && defined HAVE_IPV6
732 if (hn != ut.nodename)
733 ac_free(hn);
734 #endif
736 NYD_LEAVE;
737 return hostname;
740 FL char *
741 lookup_password_for_token(char const *token)
743 size_t tl;
744 char *var, *cp;
745 NYD_ENTER;
747 tl = strlen(token);
748 var = ac_alloc(tl + 9 +1);
750 memcpy(var, "password-", 9);
751 memcpy(var + 9, token, tl);
752 var[tl + 9] = '\0';
754 if ((cp = vok_vlook(var)) != NULL)
755 cp = savestr(cp);
756 ac_free(var);
757 NYD_LEAVE;
758 return cp;
761 FL char *
762 getrandstring(size_t length)
764 static unsigned char nodedigest[16];
765 static pid_t pid;
767 struct str b64;
768 char *data, *cp;
769 size_t i;
770 int fd = -1;
771 #ifdef HAVE_MD5
772 md5_ctx ctx;
773 #else
774 size_t j;
775 #endif
776 NYD_ENTER;
778 data = ac_alloc(length);
779 if ((fd = open("/dev/urandom", O_RDONLY)) == -1 ||
780 length != (size_t)read(fd, data, length)) {
781 if (pid == 0) {
782 pid = getpid();
783 srand(pid);
784 cp = nodename(0);
785 #ifdef HAVE_MD5
786 md5_init(&ctx);
787 md5_update(&ctx, (unsigned char*)cp, strlen(cp));
788 md5_final(nodedigest, &ctx);
789 #else
790 /* In that case it's only used for boundaries and Message-Id:s so that
791 * srand(3) should suffice */
792 j = strlen(cp) + 1;
793 for (i = 0; i < sizeof(nodedigest); ++i)
794 nodedigest[i] = (unsigned char)(cp[i % j] ^ rand());
795 #endif
797 for (i = 0; i < length; i++)
798 data[i] = (char)((int)(255 * (rand() / (RAND_MAX + 1.0))) ^
799 nodedigest[i % sizeof nodedigest]);
801 if (fd >= 0)
802 close(fd);
804 (void)b64_encode_buf(&b64, data, length, B64_SALLOC);
805 ac_free(data);
806 assert(length < b64.l);
807 b64.s[length] = '\0';
808 NYD_LEAVE;
809 return b64.s;
812 #ifdef HAVE_MD5
813 FL char *
814 md5tohex(char hex[MD5TOHEX_SIZE], void const *vp)
816 char const *cp = vp;
817 size_t i, j;
818 NYD_ENTER;
820 for (i = 0; i < MD5TOHEX_SIZE / 2; i++) {
821 j = i << 1;
822 hex[j] = hexchar((cp[i] & 0xf0) >> 4);
823 hex[++j] = hexchar(cp[i] & 0x0f);
825 NYD_LEAVE;
826 return hex;
829 FL char *
830 cram_md5_string(char const *user, char const *pass, char const *b64)
832 struct str in, out;
833 char digest[16], *cp;
834 size_t lu;
835 NYD_ENTER;
837 out.s = NULL;
838 in.s = UNCONST(b64);
839 in.l = strlen(in.s);
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);
844 free(out.s);
845 cp = md5tohex(salloc(MD5TOHEX_SIZE + 1), digest);
847 lu = strlen(user);
848 in.l = lu + MD5TOHEX_SIZE +1;
849 in.s = ac_alloc(lu + 1 + MD5TOHEX_SIZE +1);
850 memcpy(in.s, user, lu);
851 in.s[lu] = ' ';
852 memcpy(in.s + lu + 1, cp, MD5TOHEX_SIZE);
853 b64_encode(&out, &in, B64_SALLOC | B64_CRLF);
854 ac_free(in.s);
855 NYD_LEAVE;
856 return out.s;
859 FL void
860 hmac_md5(unsigned char *text, int text_len, unsigned char *key, int key_len,
861 void *digest)
864 * This code is taken from
866 * Network Working Group H. Krawczyk
867 * Request for Comments: 2104 IBM
868 * Category: Informational M. Bellare
869 * UCSD
870 * R. Canetti
871 * IBM
872 * February 1997
875 * HMAC: Keyed-Hashing for Message Authentication
877 md5_ctx context;
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];
881 int i;
882 NYD_ENTER;
884 /* if key is longer than 64 bytes reset it to key=MD5(key) */
885 if (key_len > 64) {
886 md5_ctx tctx;
888 md5_init(&tctx);
889 md5_update(&tctx, key, key_len);
890 md5_final(tk, &tctx);
892 key = tk;
893 key_len = 16;
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++) {
913 k_ipad[i] ^= 0x36;
914 k_opad[i] ^= 0x5c;
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 */
928 NYD_LEAVE;
930 #endif /* HAVE_MD5 */
932 FL enum okay
933 makedir(char const *name)
935 struct stat st;
936 enum okay rv = STOP;
937 NYD_ENTER;
939 if (!mkdir(name, 0700))
940 rv = OKAY;
941 else {
942 int e = errno;
943 if ((e == EEXIST || e == ENOSYS) && stat(name, &st) == 0 &&
944 S_ISDIR(st.st_mode))
945 rv = OKAY;
947 NYD_LEAVE;
948 return rv;
951 #ifdef HAVE_FCHDIR
952 FL enum okay
953 cwget(struct cw *cw)
955 enum okay rv = STOP;
956 NYD_ENTER;
958 if ((cw->cw_fd = open(".", O_RDONLY)) == -1)
959 goto jleave;
960 if (fchdir(cw->cw_fd) == -1) {
961 close(cw->cw_fd);
962 goto jleave;
964 rv = OKAY;
965 jleave:
966 NYD_LEAVE;
967 return rv;
970 FL enum okay
971 cwret(struct cw *cw)
973 enum okay rv = STOP;
974 NYD_ENTER;
976 if (!fchdir(cw->cw_fd))
977 rv = OKAY;
978 NYD_LEAVE;
979 return rv;
982 FL void
983 cwrelse(struct cw *cw)
985 NYD_ENTER;
986 close(cw->cw_fd);
987 NYD_LEAVE;
990 #else /* !HAVE_FCHDIR */
991 FL enum okay
992 cwget(struct cw *cw)
994 enum okay rv = STOP;
995 NYD_ENTER;
997 if (getcwd(cw->cw_wd, sizeof cw->cw_wd) != NULL && !chdir(cw->cw_wd))
998 rv = OKAY;
999 NYD_LEAVE;
1000 return rv;
1003 FL enum okay
1004 cwret(struct cw *cw)
1006 enum okay rv = STOP;
1007 NYD_ENTER;
1009 if (!chdir(cw->cw_wd))
1010 rv = OKAY;
1011 NYD_LEAVE;
1012 return rv;
1015 FL void
1016 cwrelse(struct cw *cw)
1018 NYD_ENTER;
1019 UNUSED(cw);
1020 NYD_LEAVE;
1022 #endif /* !HAVE_FCHDIR */
1024 FL char *
1025 colalign(char const *cp, int col, int fill, int *cols_decr_used_or_null)
1027 int col_orig = col, n, sz;
1028 char *nb, *np;
1029 NYD_ENTER;
1031 np = nb = salloc(mb_cur_max * strlen(cp) + col + 1);
1032 while (*cp) {
1033 #ifdef HAVE_WCWIDTH
1034 if (mb_cur_max > 1) {
1035 wchar_t wc;
1037 if ((sz = mbtowc(&wc, cp, mb_cur_max)) < 0)
1038 n = sz = 1;
1039 else if ((n = wcwidth(wc)) < 0)
1040 n = 1;
1041 } else
1042 #endif
1043 n = sz = 1;
1044 if (n > col)
1045 break;
1046 col -= n;
1047 if (sz == 1 && spacechar(*cp)) {
1048 *np++ = ' ';
1049 cp++;
1050 } else
1051 while (sz--)
1052 *np++ = *cp++;
1055 if (fill && col != 0) {
1056 if (fill > 0) {
1057 memmove(nb + col, nb, (size_t)(np - nb));
1058 memset(nb, ' ', col);
1059 } else
1060 memset(np, ' ', col);
1061 np += col;
1062 col = 0;
1065 *np = '\0';
1066 if (cols_decr_used_or_null != NULL)
1067 *cols_decr_used_or_null -= col_orig - col;
1068 NYD_LEAVE;
1069 return nb;
1072 FL void
1073 makeprint(struct str const *in, struct str *out)
1075 static int print_all_chars = -1;
1077 char const *inp, *maxp;
1078 char *outp;
1079 size_t msz;
1080 NYD_ENTER;
1082 if (print_all_chars == -1)
1083 print_all_chars = ok_blook(print_all_chars);
1085 msz = in->l + 1;
1086 out->s = outp = smalloc(msz);
1087 inp = in->s;
1088 maxp = inp + in->l;
1090 if (print_all_chars) {
1091 out->l = in->l;
1092 memcpy(outp, inp, out->l);
1093 goto jleave;
1096 #ifdef HAVE_C90AMEND1
1097 if (mb_cur_max > 1) {
1098 char mbb[MB_LEN_MAX + 1];
1099 wchar_t wc;
1100 int i, n;
1101 size_t dist;
1103 out->l = 0;
1104 while (inp < maxp) {
1105 if (*inp & 0200)
1106 n = mbtowc(&wc, inp, maxp - inp);
1107 else {
1108 wc = *inp;
1109 n = 1;
1111 if (n < 0) {
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 : '?';
1120 n = 1;
1121 } else if (n == 0)
1122 n = 1;
1123 inp += n;
1124 if (!iswprint(wc) && wc != '\n' && wc != '\r' && wc != '\b' &&
1125 wc != '\t') {
1126 if ((wc & ~(wchar_t)037) == 0)
1127 wc = utf8 ? 0x2400 | wc : '?';
1128 else if (wc == 0177)
1129 wc = utf8 ? 0x2421 : '?';
1130 else
1131 wc = utf8 ? 0x2426 : '?';
1133 if ((n = wctomb(mbb, wc)) <= 0)
1134 continue;
1135 out->l += n;
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++)
1142 *outp++ = mbb[i];
1144 } else
1145 #endif /* C90AMEND1 */
1147 int c;
1148 while (inp < maxp) {
1149 c = *inp++ & 0377;
1150 if (!isprint(c) && c != '\n' && c != '\r' && c != '\b' && c != '\t')
1151 c = '?';
1152 *outp++ = c;
1154 out->l = in->l;
1156 jleave:
1157 NYD_LEAVE;
1158 out->s[out->l] = '\0';
1161 FL char *
1162 prstr(char const *s)
1164 struct str in, out;
1165 char *rp;
1166 NYD_ENTER;
1168 in.s = UNCONST(s);
1169 in.l = strlen(s);
1170 makeprint(&in, &out);
1171 rp = savestrbuf(out.s, out.l);
1172 free(out.s);
1173 NYD_LEAVE;
1174 return rp;
1177 FL int
1178 prout(char const *s, size_t sz, FILE *fp)
1180 struct str in, out;
1181 int n;
1182 NYD_ENTER;
1184 in.s = UNCONST(s);
1185 in.l = sz;
1186 makeprint(&in, &out);
1187 n = fwrite(out.s, 1, out.l, fp);
1188 free(out.s);
1189 NYD_LEAVE;
1190 return n;
1193 FL size_t
1194 putuc(int u, int c, FILE *fp)
1196 size_t rv;
1197 UNUSED(u);
1198 NYD_ENTER;
1200 #ifdef HAVE_C90AMEND1
1201 if (utf8 && (u & ~(wchar_t)0177)) {
1202 char mbb[MB_LEN_MAX];
1203 int i, n;
1205 if ((n = wctomb(mbb, u)) > 0) {
1206 rv = wcwidth(u);
1207 for (i = 0; i < n; ++i)
1208 if (putc(mbb[i] & 0377, fp) == EOF) {
1209 rv = 0;
1210 break;
1212 } else if (n == 0)
1213 rv = (putc('\0', fp) != EOF);
1214 else
1215 rv = 0;
1216 } else
1217 #endif
1218 rv = (putc(c, fp) != EOF);
1219 NYD_LEAVE;
1220 return rv;
1223 #ifdef HAVE_COLOUR
1224 FL void
1225 colour_table_create(char const *pager_used)
1227 union {char *cp; char const *ccp; void *vp; struct colour_table *ctp;} u;
1228 size_t i;
1229 struct colour_table *ct;
1230 NYD_ENTER;
1232 if (ok_blook(colour_disable))
1233 goto jleave;
1235 /* If pager, check wether it is allowed to use colour */
1236 if (pager_used != NULL) {
1237 char *pager;
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)
1245 goto jok;
1246 goto jleave;
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)
1255 goto jleave;
1256 if ((okterms = ok_vlook(colour_terms)) == NULL)
1257 okterms = UNCONST(COLOUR_TERMS);
1258 okterms = savestr(okterms);
1260 i = strlen(term);
1261 while ((u.cp = n_strsep(&okterms, ',', TRU1)) != NULL)
1262 if (!strncmp(u.cp, term, i))
1263 goto jok;
1264 goto jleave;
1267 jok:
1268 colour_table = ct = salloc(sizeof *ct); /* XXX lex.c yet resets (FILTER!) */
1269 { static struct {
1270 enum okeys okey;
1271 enum colourspec cspec;
1272 char const *defval;
1273 } const map[] = {
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);
1296 jleave:
1297 NYD_LEAVE;
1300 FL void
1301 colour_put(FILE *fp, enum colourspec cs)
1303 NYD_ENTER;
1304 if (colour_table != NULL) {
1305 struct str const *cp = colour_get(cs);
1307 fwrite(cp->s, cp->l, 1, fp);
1309 NYD_LEAVE;
1312 FL void
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;
1318 size_t namelen;
1319 NYD_ENTER;
1321 if (colour_table == NULL)
1322 goto j_leave;
1323 /* Normal header colours if there are no user headers */
1324 uheads = colour_table->ct_csinfo + COLOURSPEC_RESET + 1;
1325 if (uheads->s == NULL)
1326 goto jleave;
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);
1331 cp_base = cp;
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;
1337 break;
1340 ac_free(cp_base);
1341 jleave:
1342 colour_put(fp, cs);
1343 j_leave:
1344 NYD_LEAVE;
1347 FL void
1348 colour_reset(FILE *fp)
1350 NYD_ENTER;
1351 if (colour_table != NULL)
1352 fwrite("\033[0m", 4, 1, fp);
1353 NYD_LEAVE;
1356 FL struct str const *
1357 colour_get(enum colourspec cs)
1359 struct str const *rv = NULL;
1360 NYD_ENTER;
1362 if (colour_table != NULL)
1363 if ((rv = colour_table->ct_csinfo + cs)->s == NULL)
1364 rv = NULL;
1365 NYD_LEAVE;
1366 return rv;
1368 #endif /* HAVE_COLOUR */
1370 FL void
1371 time_current_update(struct time_current *tc, bool_t full_update)
1373 NYD_ENTER;
1374 tc->tc_time = time(NULL);
1375 if (full_update) {
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));
1380 NYD_LEAVE;
1383 static void
1384 _out_of_memory(void)
1386 panic("no memory");
1389 #ifndef HAVE_DEBUG
1390 FL void *
1391 smalloc(size_t s SMALLOC_DEBUG_ARGS)
1393 void *rv;
1394 NYD_ENTER;
1396 if (s == 0)
1397 s = 1;
1398 if ((rv = malloc(s)) == NULL)
1399 _out_of_memory();
1400 NYD_LEAVE;
1401 return rv;
1404 FL void *
1405 srealloc(void *v, size_t s SMALLOC_DEBUG_ARGS)
1407 void *rv;
1408 NYD_ENTER;
1410 if (s == 0)
1411 s = 1;
1412 if (v == NULL)
1413 rv = smalloc(s);
1414 else if ((rv = realloc(v, s)) == NULL)
1415 _out_of_memory();
1416 NYD_LEAVE;
1417 return rv;
1420 FL void *
1421 scalloc(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1423 void *rv;
1424 NYD_ENTER;
1426 if (size == 0)
1427 size = 1;
1428 if ((rv = calloc(nmemb, size)) == NULL)
1429 _out_of_memory();
1430 NYD_LEAVE;
1431 return rv;
1434 #else /* !HAVE_DEBUG */
1435 CTA(sizeof(char) == sizeof(ui8_t));
1437 # define _HOPE_SIZE (2 * 8 * sizeof(char))
1438 # define _HOPE_SET(C) \
1439 do {\
1440 union ptr __xl, __xu;\
1441 struct chunk *__xc;\
1442 __xl.p = (C).p;\
1443 __xc = __xl.c - 1;\
1444 __xu.p = __xc;\
1445 (C).cp += 8;\
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;\
1451 } while (0)
1452 # define _HOPE_GET_TRACE(C,BAD) do {(C).cp += 8; _HOPE_GET(C, BAD);} while(0)
1453 # define _HOPE_GET(C,BAD) \
1454 do {\
1455 union ptr __xl, __xu;\
1456 struct chunk *__xc;\
1457 ui32_t __i;\
1458 __xl.p = (C).p;\
1459 __xl.cp -= 8;\
1460 (C).cp = __xl.cp;\
1461 __xc = __xl.c - 1;\
1462 (BAD) = FAL0;\
1463 __i = 0;\
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;\
1472 if (__i != 0) {\
1473 (BAD) = TRU1;\
1474 alert("%p: corrupt lower canary: 0x%02X: %s, line %u",\
1475 __xl.p, __i, mdbg_file, mdbg_line);\
1477 __xu.p = __xc;\
1478 __xu.ui8p += __xc->size - 8;\
1479 __i = 0;\
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;\
1488 if (__i != 0) {\
1489 (BAD) = TRU1;\
1490 alert("%p: corrupt upper canary: 0x%02X: %s, line %u",\
1491 __xl.p, __i, mdbg_file, mdbg_line);\
1493 if (BAD)\
1494 alert(" ..canary last seen: %s, line %u", __xc->file, __xc->line);\
1495 } while (0)
1497 struct chunk {
1498 struct chunk *prev;
1499 struct chunk *next;
1500 char const *file;
1501 ui16_t line;
1502 ui8_t isfree;
1503 ui8_t __dummy;
1504 ui32_t size;
1507 union ptr {
1508 void *p;
1509 struct chunk *c;
1510 char *cp;
1511 ui8_t *ui8p;
1514 struct chunk *_mlist, *_mfree;
1516 FL void *
1517 (smalloc)(size_t s SMALLOC_DEBUG_ARGS)
1519 union ptr p;
1520 NYD_ENTER;
1522 if (s == 0)
1523 s = 1;
1524 s += sizeof(struct chunk) + _HOPE_SIZE;
1526 if ((p.p = (malloc)(s)) == NULL)
1527 _out_of_memory();
1528 p.c->prev = NULL;
1529 if ((p.c->next = _mlist) != NULL)
1530 _mlist->prev = p.c;
1531 p.c->file = mdbg_file;
1532 p.c->line = (ui16_t)mdbg_line;
1533 p.c->isfree = FAL0;
1534 p.c->size = (ui32_t)s;
1535 _mlist = p.c++;
1536 _HOPE_SET(p);
1537 NYD_LEAVE;
1538 return p.p;
1541 FL void *
1542 (srealloc)(void *v, size_t s SMALLOC_DEBUG_ARGS)
1544 union ptr p;
1545 bool_t isbad;
1546 NYD_ENTER;
1548 if ((p.p = v) == NULL) {
1549 p.p = (smalloc)(s, mdbg_file, mdbg_line);
1550 goto jleave;
1553 _HOPE_GET(p, isbad);
1554 --p.c;
1555 if (p.c->isfree) {
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);
1559 goto jforce;
1562 if (p.c == _mlist)
1563 _mlist = p.c->next;
1564 else
1565 p.c->prev->next = p.c->next;
1566 if (p.c->next != NULL)
1567 p.c->next->prev = p.c->prev;
1569 jforce:
1570 if (s == 0)
1571 s = 1;
1572 s += sizeof(struct chunk) + _HOPE_SIZE;
1574 if ((p.p = (realloc)(p.c, s)) == NULL)
1575 _out_of_memory();
1576 p.c->prev = NULL;
1577 if ((p.c->next = _mlist) != NULL)
1578 _mlist->prev = p.c;
1579 p.c->file = mdbg_file;
1580 p.c->line = (ui16_t)mdbg_line;
1581 p.c->isfree = FAL0;
1582 p.c->size = (ui32_t)s;
1583 _mlist = p.c++;
1584 _HOPE_SET(p);
1585 jleave:
1586 NYD_LEAVE;
1587 return p.p;
1590 FL void *
1591 (scalloc)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1593 union ptr p;
1594 NYD_ENTER;
1596 if (size == 0)
1597 size = 1;
1598 if (nmemb == 0)
1599 nmemb = 1;
1600 size *= nmemb;
1601 size += sizeof(struct chunk) + _HOPE_SIZE;
1603 if ((p.p = (malloc)(size)) == NULL)
1604 _out_of_memory();
1605 memset(p.p, 0, size);
1606 p.c->prev = NULL;
1607 if ((p.c->next = _mlist) != NULL)
1608 _mlist->prev = p.c;
1609 p.c->file = mdbg_file;
1610 p.c->line = (ui16_t)mdbg_line;
1611 p.c->isfree = FAL0;
1612 p.c->size = (ui32_t)size;
1613 _mlist = p.c++;
1614 _HOPE_SET(p);
1615 NYD_LEAVE;
1616 return p.p;
1619 FL void
1620 (sfree)(void *v SMALLOC_DEBUG_ARGS)
1622 union ptr p;
1623 bool_t isbad;
1624 NYD_ENTER;
1626 if ((p.p = v) == NULL) {
1627 fprintf(stderr, "sfree(NULL) from %s, line %d\n", mdbg_file, mdbg_line);
1628 goto jleave;
1631 _HOPE_GET(p, isbad);
1632 --p.c;
1633 if (p.c->isfree) {
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);
1637 goto jleave;
1640 if (p.c == _mlist)
1641 _mlist = p.c->next;
1642 else
1643 p.c->prev->next = p.c->next;
1644 if (p.c->next != NULL)
1645 p.c->next->prev = p.c->prev;
1646 p.c->isfree = TRU1;
1648 if (options & OPT_DEBUG) {
1649 p.c->next = _mfree;
1650 _mfree = p.c;
1651 } else
1652 (free)(p.c);
1653 jleave:
1654 NYD_LEAVE;
1657 FL void
1658 smemreset(void)
1660 union ptr p;
1661 size_t c = 0, s = 0;
1662 NYD_ENTER;
1664 for (p.c = _mfree; p.c != NULL;) {
1665 void *vp = p.c;
1666 ++c;
1667 s += p.c->size;
1668 p.c = p.c->next;
1669 (free)(vp);
1671 _mfree = NULL;
1673 if (options & OPT_DEBUG)
1674 fprintf(stderr, "smemreset(): freed %" ZFMT " chunks/%" ZFMT " bytes\n",
1675 c, s);
1676 NYD_LEAVE;
1679 FL int
1680 c_smemtrace(void *v)
1682 /* For _HOPE_GET() */
1683 char const * const mdbg_file = "smemtrace()";
1684 int const mdbg_line = -1;
1685 FILE *fp;
1686 union ptr p, xp;
1687 bool_t isbad;
1688 size_t lines;
1689 NYD_ENTER;
1691 v = (void*)0x1;
1692 if ((fp = Ftmp(NULL, "memtr", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600)) ==
1693 NULL) {
1694 perror("tmpfile");
1695 goto jleave;
1698 fprintf(fp, "Currently allocated memory chunks:\n");
1699 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1700 xp = p;
1701 ++xp.c;
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) {
1711 xp = p;
1712 ++xp.c;
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);
1721 Fclose(fp);
1722 v = NULL;
1723 jleave:
1724 NYD_LEAVE;
1725 return (v != NULL);
1728 # ifdef MEMCHECK
1729 FL bool_t
1730 _smemcheck(char const *mdbg_file, int mdbg_line)
1732 union ptr p, xp;
1733 bool_t anybad = FAL0, isbad;
1734 size_t lines;
1735 NYD_ENTER;
1737 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1738 xp = p;
1739 ++xp.c;
1740 _HOPE_GET_TRACE(xp, isbad);
1741 if (isbad) {
1742 anybad = TRU1;
1743 fprintf(stderr,
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) {
1752 xp = p;
1753 ++xp.c;
1754 _HOPE_GET_TRACE(xp, isbad);
1755 if (isbad) {
1756 anybad = TRU1;
1757 fprintf(stderr,
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);
1764 NYD_LEAVE;
1765 return anybad;
1767 # endif /* MEMCHECK */
1768 #endif /* HAVE_DEBUG */
1770 /* vim:set fenc=utf-8:s-it-mode */