NEWS: update for v14.6
[s-mailx.git] / auxlily.c
blobec663e981187ab7e8a4f837176011dae2d03924a
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)) {
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)) {
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)) {
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)) {
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;
593 int c, n;
594 NYD_ENTER;
596 xs = *s;
598 if ((c = *xs & 0xFF) == '\0')
599 goto jleave;
600 ++xs;
601 if (c != '\\')
602 goto jleave;
604 switch ((c = *xs & 0xFF)) {
605 case '\\': break;
606 case 'a': c = '\a'; break;
607 case 'b': c = '\b'; break;
608 case 'c': c = PROMPT_STOP; break;
609 case 'f': c = '\f'; break;
610 case 'n': c = '\n'; break;
611 case 'r': c = '\r'; break;
612 case 't': c = '\t'; break;
613 case 'v': c = '\v'; break;
614 case '0':
615 for (++xs, c = 0, n = 4; --n > 0 && octalchar(*xs); ++xs) {
616 c <<= 3;
617 c |= *xs - '0';
619 goto jleave;
620 /* S-nail extension for nice (get)prompt(()) support */
621 case '&':
622 case '?':
623 case '$':
624 case '@':
625 if (use_nail_extensions) {
626 switch (c) {
627 case '&': c = ok_blook(bsdcompat) ? '&' : '?'; break;
628 case '?': c = exec_last_comm_error ? '1' : '0'; break;
629 case '$': c = PROMPT_DOLLAR; break;
630 case '@': c = PROMPT_AT; break;
632 break;
634 /* FALLTHRU */
635 case '\0':
636 /* A sole <backslash> at EOS is treated as-is! */
637 /* FALLTHRU */
638 default:
639 c = '\\';
640 goto jleave;
642 ++xs;
643 jleave:
644 *s = xs;
645 NYD_LEAVE;
646 return c;
649 FL char *
650 getprompt(void)
652 static char buf[PROMPT_BUFFER_SIZE];
654 char *cp = buf;
655 char const *ccp;
656 NYD_ENTER;
658 if ((ccp = ok_vlook(prompt)) == NULL || *ccp == '\0')
659 goto jleave;
661 for (; PTRCMP(cp, <, buf + sizeof(buf) - 1); ++cp) {
662 char const *a;
663 size_t l;
664 int c = expand_shell_escape(&ccp, TRU1);
666 if (c > 0) {
667 *cp = (char)c;
668 continue;
670 if (c == 0 || c == PROMPT_STOP)
671 break;
673 a = (c == PROMPT_DOLLAR) ? account_name : displayname;
674 if (a == NULL)
675 a = "";
676 l = strlen(a);
677 if (PTRCMP(cp + l, >=, buf + sizeof(buf) - 1))
678 *cp++ = '?';
679 else {
680 memcpy(cp, a, l);
681 cp += --l;
684 jleave:
685 *cp = '\0';
686 NYD_LEAVE;
687 return buf;
690 FL char *
691 nodename(int mayoverride)
693 static char *hostname;
694 struct utsname ut;
695 char *hn;
696 #ifdef HAVE_SOCKETS
697 # ifdef HAVE_IPV6
698 struct addrinfo hints, *res;
699 # else
700 struct hostent *hent;
701 # endif
702 #endif
703 NYD_ENTER;
705 if (mayoverride && (hn = ok_vlook(hostname)) != NULL && *hn != '\0') {
706 if (hostname != NULL)
707 free(hostname);
708 hostname = sstrdup(hn);
709 } else if (hostname == NULL) {
710 uname(&ut);
711 hn = ut.nodename;
712 #ifdef HAVE_SOCKETS
713 # ifdef HAVE_IPV6
714 memset(&hints, 0, sizeof hints);
715 hints.ai_family = AF_UNSPEC;
716 hints.ai_socktype = SOCK_DGRAM; /* dummy */
717 hints.ai_flags = AI_CANONNAME;
718 if (getaddrinfo(hn, "0", &hints, &res) == 0) {
719 if (res->ai_canonname != NULL) {
720 size_t l = strlen(res->ai_canonname);
721 hn = ac_alloc(l + 1);
722 memcpy(hn, res->ai_canonname, l + 1);
724 freeaddrinfo(res);
726 # else
727 hent = gethostbyname(hn);
728 if (hent != NULL)
729 hn = hent->h_name;
730 # endif
731 #endif
732 hostname = sstrdup(hn);
733 #if defined HAVE_SOCKETS && defined HAVE_IPV6
734 if (hn != ut.nodename)
735 ac_free(hn);
736 #endif
738 NYD_LEAVE;
739 return hostname;
742 FL char *
743 lookup_password_for_token(char const *token)
745 size_t tl;
746 char *var, *cp;
747 NYD_ENTER;
749 tl = strlen(token);
750 var = ac_alloc(tl + 9 +1);
752 memcpy(var, "password-", 9);
753 memcpy(var + 9, token, tl);
754 var[tl + 9] = '\0';
756 if ((cp = vok_vlook(var)) != NULL)
757 cp = savestr(cp);
758 ac_free(var);
759 NYD_LEAVE;
760 return cp;
763 FL char *
764 getrandstring(size_t length)
766 static unsigned char nodedigest[16];
767 static pid_t pid;
769 struct str b64;
770 char *data, *cp;
771 size_t i;
772 int fd = -1;
773 #ifdef HAVE_MD5
774 md5_ctx ctx;
775 #else
776 size_t j;
777 #endif
778 NYD_ENTER;
780 data = ac_alloc(length);
781 if ((fd = open("/dev/urandom", O_RDONLY)) == -1 ||
782 length != (size_t)read(fd, data, length)) {
783 if (pid == 0) {
784 pid = getpid();
785 srand(pid);
786 cp = nodename(0);
787 #ifdef HAVE_MD5
788 md5_init(&ctx);
789 md5_update(&ctx, (unsigned char*)cp, strlen(cp));
790 md5_final(nodedigest, &ctx);
791 #else
792 /* In that case it's only used for boundaries and Message-Id:s so that
793 * srand(3) should suffice */
794 j = strlen(cp) + 1;
795 for (i = 0; i < sizeof(nodedigest); ++i)
796 nodedigest[i] = (unsigned char)(cp[i % j] ^ rand());
797 #endif
799 for (i = 0; i < length; i++)
800 data[i] = (char)((int)(255 * (rand() / (RAND_MAX + 1.0))) ^
801 nodedigest[i % sizeof nodedigest]);
803 if (fd >= 0)
804 close(fd);
806 (void)b64_encode_buf(&b64, data, length, B64_SALLOC);
807 ac_free(data);
808 assert(length < b64.l);
809 b64.s[length] = '\0';
810 NYD_LEAVE;
811 return b64.s;
814 #ifdef HAVE_MD5
815 FL char *
816 md5tohex(char hex[MD5TOHEX_SIZE], void const *vp)
818 char const *cp = vp;
819 size_t i, j;
820 NYD_ENTER;
822 for (i = 0; i < MD5TOHEX_SIZE / 2; i++) {
823 j = i << 1;
824 hex[j] = hexchar((cp[i] & 0xf0) >> 4);
825 hex[++j] = hexchar(cp[i] & 0x0f);
827 NYD_LEAVE;
828 return hex;
831 FL char *
832 cram_md5_string(char const *user, char const *pass, char const *b64)
834 struct str in, out;
835 char digest[16], *cp;
836 size_t lu;
837 NYD_ENTER;
839 out.s = NULL;
840 in.s = UNCONST(b64);
841 in.l = strlen(in.s);
842 (void)b64_decode(&out, &in, NULL);
843 assert(out.s != NULL);
845 hmac_md5((unsigned char*)out.s, out.l, UNCONST(pass), strlen(pass), digest);
846 free(out.s);
847 cp = md5tohex(salloc(MD5TOHEX_SIZE + 1), digest);
849 lu = strlen(user);
850 in.l = lu + MD5TOHEX_SIZE +1;
851 in.s = ac_alloc(lu + 1 + MD5TOHEX_SIZE +1);
852 memcpy(in.s, user, lu);
853 in.s[lu] = ' ';
854 memcpy(in.s + lu + 1, cp, MD5TOHEX_SIZE);
855 b64_encode(&out, &in, B64_SALLOC | B64_CRLF);
856 ac_free(in.s);
857 NYD_LEAVE;
858 return out.s;
861 FL void
862 hmac_md5(unsigned char *text, int text_len, unsigned char *key, int key_len,
863 void *digest)
866 * This code is taken from
868 * Network Working Group H. Krawczyk
869 * Request for Comments: 2104 IBM
870 * Category: Informational M. Bellare
871 * UCSD
872 * R. Canetti
873 * IBM
874 * February 1997
877 * HMAC: Keyed-Hashing for Message Authentication
879 md5_ctx context;
880 unsigned char k_ipad[65]; /* inner padding - key XORd with ipad */
881 unsigned char k_opad[65]; /* outer padding - key XORd with opad */
882 unsigned char tk[16];
883 int i;
884 NYD_ENTER;
886 /* if key is longer than 64 bytes reset it to key=MD5(key) */
887 if (key_len > 64) {
888 md5_ctx tctx;
890 md5_init(&tctx);
891 md5_update(&tctx, key, key_len);
892 md5_final(tk, &tctx);
894 key = tk;
895 key_len = 16;
898 /* the HMAC_MD5 transform looks like:
900 * MD5(K XOR opad, MD5(K XOR ipad, text))
902 * where K is an n byte key
903 * ipad is the byte 0x36 repeated 64 times
904 * opad is the byte 0x5c repeated 64 times
905 * and text is the data being protected */
907 /* start out by storing key in pads */
908 memset(k_ipad, 0, sizeof k_ipad);
909 memset(k_opad, 0, sizeof k_opad);
910 memcpy(k_ipad, key, key_len);
911 memcpy(k_opad, key, key_len);
913 /* XOR key with ipad and opad values */
914 for (i=0; i<64; i++) {
915 k_ipad[i] ^= 0x36;
916 k_opad[i] ^= 0x5c;
919 /* perform inner MD5 */
920 md5_init(&context); /* init context for 1st pass */
921 md5_update(&context, k_ipad, 64); /* start with inner pad */
922 md5_update(&context, text, text_len); /* then text of datagram */
923 md5_final(digest, &context); /* finish up 1st pass */
925 /* perform outer MD5 */
926 md5_init(&context); /* init context for 2nd pass */
927 md5_update(&context, k_opad, 64); /* start with outer pad */
928 md5_update(&context, digest, 16); /* then results of 1st hash */
929 md5_final(digest, &context); /* finish up 2nd pass */
930 NYD_LEAVE;
932 #endif /* HAVE_MD5 */
934 FL enum okay
935 makedir(char const *name)
937 struct stat st;
938 enum okay rv = STOP;
939 NYD_ENTER;
941 if (!mkdir(name, 0700))
942 rv = OKAY;
943 else {
944 int e = errno;
945 if ((e == EEXIST || e == ENOSYS) && stat(name, &st) == 0 &&
946 S_ISDIR(st.st_mode))
947 rv = OKAY;
949 NYD_LEAVE;
950 return rv;
953 #ifdef HAVE_FCHDIR
954 FL enum okay
955 cwget(struct cw *cw)
957 enum okay rv = STOP;
958 NYD_ENTER;
960 if ((cw->cw_fd = open(".", O_RDONLY)) == -1)
961 goto jleave;
962 if (fchdir(cw->cw_fd) == -1) {
963 close(cw->cw_fd);
964 goto jleave;
966 rv = OKAY;
967 jleave:
968 NYD_LEAVE;
969 return rv;
972 FL enum okay
973 cwret(struct cw *cw)
975 enum okay rv = STOP;
976 NYD_ENTER;
978 if (!fchdir(cw->cw_fd))
979 rv = OKAY;
980 NYD_LEAVE;
981 return rv;
984 FL void
985 cwrelse(struct cw *cw)
987 NYD_ENTER;
988 close(cw->cw_fd);
989 NYD_LEAVE;
992 #else /* !HAVE_FCHDIR */
993 FL enum okay
994 cwget(struct cw *cw)
996 enum okay rv = STOP;
997 NYD_ENTER;
999 if (getcwd(cw->cw_wd, sizeof cw->cw_wd) != NULL && !chdir(cw->cw_wd))
1000 rv = OKAY;
1001 NYD_LEAVE;
1002 return rv;
1005 FL enum okay
1006 cwret(struct cw *cw)
1008 enum okay rv = STOP;
1009 NYD_ENTER;
1011 if (!chdir(cw->cw_wd))
1012 rv = OKAY;
1013 NYD_LEAVE;
1014 return rv;
1017 FL void
1018 cwrelse(struct cw *cw)
1020 NYD_ENTER;
1021 UNUSED(cw);
1022 NYD_LEAVE;
1024 #endif /* !HAVE_FCHDIR */
1026 FL char *
1027 colalign(char const *cp, int col, int fill, int *cols_decr_used_or_null)
1029 int col_orig = col, n, sz;
1030 char *nb, *np;
1031 NYD_ENTER;
1033 np = nb = salloc(mb_cur_max * strlen(cp) + col + 1);
1034 while (*cp) {
1035 #ifdef HAVE_WCWIDTH
1036 if (mb_cur_max > 1) {
1037 wchar_t wc;
1039 if ((sz = mbtowc(&wc, cp, mb_cur_max)) < 0)
1040 n = sz = 1;
1041 else if ((n = wcwidth(wc)) < 0)
1042 n = 1;
1043 } else
1044 #endif
1045 n = sz = 1;
1046 if (n > col)
1047 break;
1048 col -= n;
1049 if (sz == 1 && spacechar(*cp)) {
1050 *np++ = ' ';
1051 cp++;
1052 } else
1053 while (sz--)
1054 *np++ = *cp++;
1057 if (fill && col != 0) {
1058 if (fill > 0) {
1059 memmove(nb + col, nb, (size_t)(np - nb));
1060 memset(nb, ' ', col);
1061 } else
1062 memset(np, ' ', col);
1063 np += col;
1064 col = 0;
1067 *np = '\0';
1068 if (cols_decr_used_or_null != NULL)
1069 *cols_decr_used_or_null -= col_orig - col;
1070 NYD_LEAVE;
1071 return nb;
1074 FL void
1075 makeprint(struct str const *in, struct str *out)
1077 static int print_all_chars = -1;
1079 char const *inp, *maxp;
1080 char *outp;
1081 size_t msz;
1082 NYD_ENTER;
1084 if (print_all_chars == -1)
1085 print_all_chars = ok_blook(print_all_chars);
1087 msz = in->l + 1;
1088 out->s = outp = smalloc(msz);
1089 inp = in->s;
1090 maxp = inp + in->l;
1092 if (print_all_chars) {
1093 out->l = in->l;
1094 memcpy(outp, inp, out->l);
1095 goto jleave;
1098 #ifdef HAVE_C90AMEND1
1099 if (mb_cur_max > 1) {
1100 char mbb[MB_LEN_MAX + 1];
1101 wchar_t wc;
1102 int i, n;
1103 size_t dist;
1105 out->l = 0;
1106 while (inp < maxp) {
1107 if (*inp & 0200)
1108 n = mbtowc(&wc, inp, maxp - inp);
1109 else {
1110 wc = *inp;
1111 n = 1;
1113 if (n < 0) {
1114 /* FIXME Why mbtowc() resetting here?
1115 * FIXME what about ISO 2022-JP plus -- those
1116 * FIXME will loose shifts, then!
1117 * FIXME THUS - we'd need special "known points"
1118 * FIXME to do so - say, after a newline!!
1119 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
1120 (void)mbtowc(&wc, NULL, mb_cur_max);
1121 wc = utf8 ? 0xFFFD : '?';
1122 n = 1;
1123 } else if (n == 0)
1124 n = 1;
1125 inp += n;
1126 if (!iswprint(wc) && wc != '\n' && wc != '\r' && wc != '\b' &&
1127 wc != '\t') {
1128 if ((wc & ~(wchar_t)037) == 0)
1129 wc = utf8 ? 0x2400 | wc : '?';
1130 else if (wc == 0177)
1131 wc = utf8 ? 0x2421 : '?';
1132 else
1133 wc = utf8 ? 0x2426 : '?';
1135 if ((n = wctomb(mbb, wc)) <= 0)
1136 continue;
1137 out->l += n;
1138 if (out->l >= msz - 1) {
1139 dist = outp - out->s;
1140 out->s = srealloc(out->s, msz += 32);
1141 outp = &out->s[dist];
1143 for (i = 0; i < n; i++)
1144 *outp++ = mbb[i];
1146 } else
1147 #endif /* C90AMEND1 */
1149 int c;
1150 while (inp < maxp) {
1151 c = *inp++ & 0377;
1152 if (!isprint(c) && c != '\n' && c != '\r' && c != '\b' && c != '\t')
1153 c = '?';
1154 *outp++ = c;
1156 out->l = in->l;
1158 jleave:
1159 NYD_LEAVE;
1160 out->s[out->l] = '\0';
1163 FL char *
1164 prstr(char const *s)
1166 struct str in, out;
1167 char *rp;
1168 NYD_ENTER;
1170 in.s = UNCONST(s);
1171 in.l = strlen(s);
1172 makeprint(&in, &out);
1173 rp = savestrbuf(out.s, out.l);
1174 free(out.s);
1175 NYD_LEAVE;
1176 return rp;
1179 FL int
1180 prout(char const *s, size_t sz, FILE *fp)
1182 struct str in, out;
1183 int n;
1184 NYD_ENTER;
1186 in.s = UNCONST(s);
1187 in.l = sz;
1188 makeprint(&in, &out);
1189 n = fwrite(out.s, 1, out.l, fp);
1190 free(out.s);
1191 NYD_LEAVE;
1192 return n;
1195 FL size_t
1196 putuc(int u, int c, FILE *fp)
1198 size_t rv;
1199 UNUSED(u);
1200 NYD_ENTER;
1202 #ifdef HAVE_C90AMEND1
1203 if (utf8 && (u & ~(wchar_t)0177)) {
1204 char mbb[MB_LEN_MAX];
1205 int i, n;
1207 if ((n = wctomb(mbb, u)) > 0) {
1208 rv = wcwidth(u);
1209 for (i = 0; i < n; ++i)
1210 if (putc(mbb[i] & 0377, fp) == EOF) {
1211 rv = 0;
1212 break;
1214 } else if (n == 0)
1215 rv = (putc('\0', fp) != EOF);
1216 else
1217 rv = 0;
1218 } else
1219 #endif
1220 rv = (putc(c, fp) != EOF);
1221 NYD_LEAVE;
1222 return rv;
1225 #ifdef HAVE_COLOUR
1226 FL void
1227 colour_table_create(char const *pager_used)
1229 union {char *cp; char const *ccp; void *vp; struct colour_table *ctp;} u;
1230 size_t i;
1231 struct colour_table *ct;
1232 NYD_ENTER;
1234 if (ok_blook(colour_disable))
1235 goto jleave;
1237 /* If pager, check wether it is allowed to use colour */
1238 if (pager_used != NULL) {
1239 char *pager;
1241 if ((u.cp = ok_vlook(colour_pagers)) == NULL)
1242 u.ccp = COLOUR_PAGERS;
1243 pager = savestr(u.cp);
1245 while ((u.cp = n_strsep(&pager, ',', TRU1)) != NULL)
1246 if (strstr(pager_used, u.cp) != NULL)
1247 goto jok;
1248 goto jleave;
1251 /* $TERM is different in that we default to false unless whitelisted */
1253 char *term, *okterms;
1255 /* Don't use getenv(), but force copy-in into our own tables.. */
1256 if ((term = _var_voklook("TERM")) == NULL)
1257 goto jleave;
1258 if ((okterms = ok_vlook(colour_terms)) == NULL)
1259 okterms = UNCONST(COLOUR_TERMS);
1260 okterms = savestr(okterms);
1262 i = strlen(term);
1263 while ((u.cp = n_strsep(&okterms, ',', TRU1)) != NULL)
1264 if (!strncmp(u.cp, term, i))
1265 goto jok;
1266 goto jleave;
1269 jok:
1270 colour_table = ct = salloc(sizeof *ct); /* XXX lex.c yet resets (FILTER!) */
1271 { static struct {
1272 enum okeys okey;
1273 enum colourspec cspec;
1274 char const *defval;
1275 } const map[] = {
1276 {ok_v_colour_msginfo, COLOURSPEC_MSGINFO, COLOUR_MSGINFO},
1277 {ok_v_colour_partinfo, COLOURSPEC_PARTINFO, COLOUR_PARTINFO},
1278 {ok_v_colour_from_, COLOURSPEC_FROM_, COLOUR_FROM_},
1279 {ok_v_colour_header, COLOURSPEC_HEADER, COLOUR_HEADER},
1280 {ok_v_colour_uheader, COLOURSPEC_UHEADER, COLOUR_UHEADER}
1283 for (i = 0; i < NELEM(map); ++i) {
1284 if ((u.cp = _var_oklook(map[i].okey)) == NULL)
1285 u.ccp = map[i].defval;
1286 u.cp = _colour_iso6429(u.ccp);
1287 ct->ct_csinfo[map[i].cspec].l = strlen(u.cp);
1288 ct->ct_csinfo[map[i].cspec].s = u.cp;
1291 ct->ct_csinfo[COLOURSPEC_RESET].l = sizeof("\033[0m") - 1;
1292 ct->ct_csinfo[COLOURSPEC_RESET].s = UNCONST("\033[0m");
1294 if ((u.cp = ok_vlook(colour_user_headers)) == NULL)
1295 u.ccp = COLOUR_USER_HEADERS;
1296 ct->ct_csinfo[COLOURSPEC_RESET + 1].l = i = strlen(u.ccp);
1297 ct->ct_csinfo[COLOURSPEC_RESET + 1].s = (i == 0) ? NULL : savestr(u.ccp);
1298 jleave:
1299 NYD_LEAVE;
1302 FL void
1303 colour_put(FILE *fp, enum colourspec cs)
1305 NYD_ENTER;
1306 if (colour_table != NULL) {
1307 struct str const *cp = colour_get(cs);
1309 fwrite(cp->s, cp->l, 1, fp);
1311 NYD_LEAVE;
1314 FL void
1315 colour_put_header(FILE *fp, char const *name)
1317 enum colourspec cs = COLOURSPEC_HEADER;
1318 struct str const *uheads;
1319 char *cp, *cp_base, *x;
1320 size_t namelen;
1321 NYD_ENTER;
1323 if (colour_table == NULL)
1324 goto j_leave;
1325 /* Normal header colours if there are no user headers */
1326 uheads = colour_table->ct_csinfo + COLOURSPEC_RESET + 1;
1327 if (uheads->s == NULL)
1328 goto jleave;
1330 /* Iterate over all entries in the *colour-user-headers* list */
1331 cp = ac_alloc(uheads->l + 1);
1332 memcpy(cp, uheads->s, uheads->l + 1);
1333 cp_base = cp;
1334 namelen = strlen(name);
1335 while ((x = n_strsep(&cp, ',', TRU1)) != NULL) {
1336 size_t l = (cp != NULL) ? PTR2SIZE(cp - x) - 1 : strlen(x);
1337 if (l == namelen && !ascncasecmp(x, name, namelen)) {
1338 cs = COLOURSPEC_UHEADER;
1339 break;
1342 ac_free(cp_base);
1343 jleave:
1344 colour_put(fp, cs);
1345 j_leave:
1346 NYD_LEAVE;
1349 FL void
1350 colour_reset(FILE *fp)
1352 NYD_ENTER;
1353 if (colour_table != NULL)
1354 fwrite("\033[0m", 4, 1, fp);
1355 NYD_LEAVE;
1358 FL struct str const *
1359 colour_get(enum colourspec cs)
1361 struct str const *rv = NULL;
1362 NYD_ENTER;
1364 if (colour_table != NULL)
1365 if ((rv = colour_table->ct_csinfo + cs)->s == NULL)
1366 rv = NULL;
1367 NYD_LEAVE;
1368 return rv;
1370 #endif /* HAVE_COLOUR */
1372 FL void
1373 time_current_update(struct time_current *tc, bool_t full_update)
1375 NYD_ENTER;
1376 tc->tc_time = time(NULL);
1377 if (full_update) {
1378 memcpy(&tc->tc_gm, gmtime(&tc->tc_time), sizeof tc->tc_gm);
1379 memcpy(&tc->tc_local, localtime(&tc->tc_time), sizeof tc->tc_local);
1380 sstpcpy(tc->tc_ctime, ctime(&tc->tc_time));
1382 NYD_LEAVE;
1385 static void
1386 _out_of_memory(void)
1388 panic("no memory");
1391 #ifndef HAVE_DEBUG
1392 FL void *
1393 smalloc(size_t s SMALLOC_DEBUG_ARGS)
1395 void *rv;
1396 NYD_ENTER;
1398 if (s == 0)
1399 s = 1;
1400 if ((rv = malloc(s)) == NULL)
1401 _out_of_memory();
1402 NYD_LEAVE;
1403 return rv;
1406 FL void *
1407 srealloc(void *v, size_t s SMALLOC_DEBUG_ARGS)
1409 void *rv;
1410 NYD_ENTER;
1412 if (s == 0)
1413 s = 1;
1414 if (v == NULL)
1415 rv = smalloc(s);
1416 else if ((rv = realloc(v, s)) == NULL)
1417 _out_of_memory();
1418 NYD_LEAVE;
1419 return rv;
1422 FL void *
1423 scalloc(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1425 void *rv;
1426 NYD_ENTER;
1428 if (size == 0)
1429 size = 1;
1430 if ((rv = calloc(nmemb, size)) == NULL)
1431 _out_of_memory();
1432 NYD_LEAVE;
1433 return rv;
1436 #else /* !HAVE_DEBUG */
1437 CTA(sizeof(char) == sizeof(ui8_t));
1439 # define _HOPE_SIZE (2 * 8 * sizeof(char))
1440 # define _HOPE_SET(C) \
1441 do {\
1442 union ptr __xl, __xu;\
1443 struct chunk *__xc;\
1444 __xl.p = (C).p;\
1445 __xc = __xl.c - 1;\
1446 __xu.p = __xc;\
1447 (C).cp += 8;\
1448 __xl.ui8p[0]=0xDE; __xl.ui8p[1]=0xAA; __xl.ui8p[2]=0x55; __xl.ui8p[3]=0xAD;\
1449 __xl.ui8p[4]=0xBE; __xl.ui8p[5]=0x55; __xl.ui8p[6]=0xAA; __xl.ui8p[7]=0xEF;\
1450 __xu.ui8p += __xc->size - 8;\
1451 __xu.ui8p[0]=0xDE; __xu.ui8p[1]=0xAA; __xu.ui8p[2]=0x55; __xu.ui8p[3]=0xAD;\
1452 __xu.ui8p[4]=0xBE; __xu.ui8p[5]=0x55; __xu.ui8p[6]=0xAA; __xu.ui8p[7]=0xEF;\
1453 } while (0)
1454 # define _HOPE_GET_TRACE(C,BAD) do {(C).cp += 8; _HOPE_GET(C, BAD);} while(0)
1455 # define _HOPE_GET(C,BAD) \
1456 do {\
1457 union ptr __xl, __xu;\
1458 struct chunk *__xc;\
1459 ui32_t __i;\
1460 __xl.p = (C).p;\
1461 __xl.cp -= 8;\
1462 (C).cp = __xl.cp;\
1463 __xc = __xl.c - 1;\
1464 (BAD) = FAL0;\
1465 __i = 0;\
1466 if (__xl.ui8p[0] != 0xDE) __i |= 1<<0;\
1467 if (__xl.ui8p[1] != 0xAA) __i |= 1<<1;\
1468 if (__xl.ui8p[2] != 0x55) __i |= 1<<2;\
1469 if (__xl.ui8p[3] != 0xAD) __i |= 1<<3;\
1470 if (__xl.ui8p[4] != 0xBE) __i |= 1<<4;\
1471 if (__xl.ui8p[5] != 0x55) __i |= 1<<5;\
1472 if (__xl.ui8p[6] != 0xAA) __i |= 1<<6;\
1473 if (__xl.ui8p[7] != 0xEF) __i |= 1<<7;\
1474 if (__i != 0) {\
1475 (BAD) = TRU1;\
1476 alert("%p: corrupt lower canary: 0x%02X: %s, line %u",\
1477 __xl.p, __i, mdbg_file, mdbg_line);\
1479 __xu.p = __xc;\
1480 __xu.ui8p += __xc->size - 8;\
1481 __i = 0;\
1482 if (__xu.ui8p[0] != 0xDE) __i |= 1<<0;\
1483 if (__xu.ui8p[1] != 0xAA) __i |= 1<<1;\
1484 if (__xu.ui8p[2] != 0x55) __i |= 1<<2;\
1485 if (__xu.ui8p[3] != 0xAD) __i |= 1<<3;\
1486 if (__xu.ui8p[4] != 0xBE) __i |= 1<<4;\
1487 if (__xu.ui8p[5] != 0x55) __i |= 1<<5;\
1488 if (__xu.ui8p[6] != 0xAA) __i |= 1<<6;\
1489 if (__xu.ui8p[7] != 0xEF) __i |= 1<<7;\
1490 if (__i != 0) {\
1491 (BAD) = TRU1;\
1492 alert("%p: corrupt upper canary: 0x%02X: %s, line %u",\
1493 __xl.p, __i, mdbg_file, mdbg_line);\
1495 if (BAD)\
1496 alert(" ..canary last seen: %s, line %u", __xc->file, __xc->line);\
1497 } while (0)
1499 struct chunk {
1500 struct chunk *prev;
1501 struct chunk *next;
1502 char const *file;
1503 ui16_t line;
1504 ui8_t isfree;
1505 ui8_t __dummy;
1506 ui32_t size;
1509 union ptr {
1510 void *p;
1511 struct chunk *c;
1512 char *cp;
1513 ui8_t *ui8p;
1516 struct chunk *_mlist, *_mfree;
1518 FL void *
1519 (smalloc)(size_t s SMALLOC_DEBUG_ARGS)
1521 union ptr p;
1522 NYD_ENTER;
1524 if (s == 0)
1525 s = 1;
1526 s += sizeof(struct chunk) + _HOPE_SIZE;
1528 if ((p.p = (malloc)(s)) == NULL)
1529 _out_of_memory();
1530 p.c->prev = NULL;
1531 if ((p.c->next = _mlist) != NULL)
1532 _mlist->prev = p.c;
1533 p.c->file = mdbg_file;
1534 p.c->line = (ui16_t)mdbg_line;
1535 p.c->isfree = FAL0;
1536 p.c->size = (ui32_t)s;
1537 _mlist = p.c++;
1538 _HOPE_SET(p);
1539 NYD_LEAVE;
1540 return p.p;
1543 FL void *
1544 (srealloc)(void *v, size_t s SMALLOC_DEBUG_ARGS)
1546 union ptr p;
1547 bool_t isbad;
1548 NYD_ENTER;
1550 if ((p.p = v) == NULL) {
1551 p.p = (smalloc)(s, mdbg_file, mdbg_line);
1552 goto jleave;
1555 _HOPE_GET(p, isbad);
1556 --p.c;
1557 if (p.c->isfree) {
1558 fprintf(stderr, "srealloc(): region freed! At %s, line %d\n"
1559 "\tLast seen: %s, line %d\n",
1560 mdbg_file, mdbg_line, p.c->file, p.c->line);
1561 goto jforce;
1564 if (p.c == _mlist)
1565 _mlist = p.c->next;
1566 else
1567 p.c->prev->next = p.c->next;
1568 if (p.c->next != NULL)
1569 p.c->next->prev = p.c->prev;
1571 jforce:
1572 if (s == 0)
1573 s = 1;
1574 s += sizeof(struct chunk) + _HOPE_SIZE;
1576 if ((p.p = (realloc)(p.c, s)) == NULL)
1577 _out_of_memory();
1578 p.c->prev = NULL;
1579 if ((p.c->next = _mlist) != NULL)
1580 _mlist->prev = p.c;
1581 p.c->file = mdbg_file;
1582 p.c->line = (ui16_t)mdbg_line;
1583 p.c->isfree = FAL0;
1584 p.c->size = (ui32_t)s;
1585 _mlist = p.c++;
1586 _HOPE_SET(p);
1587 jleave:
1588 NYD_LEAVE;
1589 return p.p;
1592 FL void *
1593 (scalloc)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1595 union ptr p;
1596 NYD_ENTER;
1598 if (size == 0)
1599 size = 1;
1600 if (nmemb == 0)
1601 nmemb = 1;
1602 size *= nmemb;
1603 size += sizeof(struct chunk) + _HOPE_SIZE;
1605 if ((p.p = (malloc)(size)) == NULL)
1606 _out_of_memory();
1607 memset(p.p, 0, size);
1608 p.c->prev = NULL;
1609 if ((p.c->next = _mlist) != NULL)
1610 _mlist->prev = p.c;
1611 p.c->file = mdbg_file;
1612 p.c->line = (ui16_t)mdbg_line;
1613 p.c->isfree = FAL0;
1614 p.c->size = (ui32_t)size;
1615 _mlist = p.c++;
1616 _HOPE_SET(p);
1617 NYD_LEAVE;
1618 return p.p;
1621 FL void
1622 (sfree)(void *v SMALLOC_DEBUG_ARGS)
1624 union ptr p;
1625 bool_t isbad;
1626 NYD_ENTER;
1628 if ((p.p = v) == NULL) {
1629 fprintf(stderr, "sfree(NULL) from %s, line %d\n", mdbg_file, mdbg_line);
1630 goto jleave;
1633 _HOPE_GET(p, isbad);
1634 --p.c;
1635 if (p.c->isfree) {
1636 fprintf(stderr, "sfree(): double-free avoided at %s, line %d\n"
1637 "\tLast seen: %s, line %d\n",
1638 mdbg_file, mdbg_line, p.c->file, p.c->line);
1639 goto jleave;
1642 if (p.c == _mlist)
1643 _mlist = p.c->next;
1644 else
1645 p.c->prev->next = p.c->next;
1646 if (p.c->next != NULL)
1647 p.c->next->prev = p.c->prev;
1648 p.c->isfree = TRU1;
1650 if (options & OPT_DEBUG) {
1651 p.c->next = _mfree;
1652 _mfree = p.c;
1653 } else
1654 (free)(p.c);
1655 jleave:
1656 NYD_LEAVE;
1659 FL void
1660 smemreset(void)
1662 union ptr p;
1663 size_t c = 0, s = 0;
1664 NYD_ENTER;
1666 for (p.c = _mfree; p.c != NULL;) {
1667 void *vp = p.c;
1668 ++c;
1669 s += p.c->size;
1670 p.c = p.c->next;
1671 (free)(vp);
1673 _mfree = NULL;
1675 if (options & OPT_DEBUG)
1676 fprintf(stderr, "smemreset(): freed %" ZFMT " chunks/%" ZFMT " bytes\n",
1677 c, s);
1678 NYD_LEAVE;
1681 FL int
1682 c_smemtrace(void *v)
1684 /* For _HOPE_GET() */
1685 char const * const mdbg_file = "smemtrace()";
1686 int const mdbg_line = -1;
1687 FILE *fp;
1688 union ptr p, xp;
1689 bool_t isbad;
1690 size_t lines;
1691 NYD_ENTER;
1693 v = (void*)0x1;
1694 if ((fp = Ftmp(NULL, "memtr", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600)) ==
1695 NULL) {
1696 perror("tmpfile");
1697 goto jleave;
1700 fprintf(fp, "Currently allocated memory chunks:\n");
1701 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1702 xp = p;
1703 ++xp.c;
1704 _HOPE_GET_TRACE(xp, isbad);
1705 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1706 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1707 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1710 if (options & OPT_DEBUG) {
1711 fprintf(fp, "sfree()d memory chunks awaiting free():\n");
1712 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1713 xp = p;
1714 ++xp.c;
1715 _HOPE_GET_TRACE(xp, isbad);
1716 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1717 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1718 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1722 page_or_print(fp, lines);
1723 Fclose(fp);
1724 v = NULL;
1725 jleave:
1726 NYD_LEAVE;
1727 return (v != NULL);
1730 # ifdef MEMCHECK
1731 FL bool_t
1732 _smemcheck(char const *mdbg_file, int mdbg_line)
1734 union ptr p, xp;
1735 bool_t anybad = FAL0, isbad;
1736 size_t lines;
1737 NYD_ENTER;
1739 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1740 xp = p;
1741 ++xp.c;
1742 _HOPE_GET_TRACE(xp, isbad);
1743 if (isbad) {
1744 anybad = TRU1;
1745 fprintf(stderr,
1746 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1747 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1748 p.c->file, p.c->line);
1752 if (options & OPT_DEBUG) {
1753 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1754 xp = p;
1755 ++xp.c;
1756 _HOPE_GET_TRACE(xp, isbad);
1757 if (isbad) {
1758 anybad = TRU1;
1759 fprintf(stderr,
1760 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1761 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1762 p.c->file, p.c->line);
1766 NYD_LEAVE;
1767 return anybad;
1769 # endif /* MEMCHECK */
1770 #endif /* HAVE_DEBUG */
1772 /* vim:set fenc=utf-8:s-it-mode */