Add `var-inspect' command
[s-mailx.git] / auxlily.c
blob96e4452643abdb8724409be9017eb64bdac2ffd9
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 - 2013 Steffen "Daode" Nurpmeso <sdaoden@users.sf.net>.
6 */
7 /*
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
40 #ifndef HAVE_AMALGAMATION
41 # include "nail.h"
42 #endif
44 #include <sys/utsname.h>
46 #include <ctype.h>
47 #include <dirent.h>
48 #include <fcntl.h>
50 #ifdef HAVE_SOCKETS
51 # ifdef HAVE_IPV6
52 # include <sys/socket.h>
53 # endif
55 # include <netdb.h>
56 #endif
58 #ifdef HAVE_MD5
59 # include "md5.h"
60 #endif
62 /* {hold,rele}_all_sigs() */
63 static size_t _alls_depth;
64 static sigset_t _alls_nset, _alls_oset;
66 /* {hold,rele}_sigs() */
67 static size_t _hold_sigdepth;
68 static sigset_t _hold_nset, _hold_oset;
70 FL void
71 panic(char const *format, ...)
73 va_list ap;
75 fprintf(stderr, tr(1, "Panic: "));
77 va_start(ap, format);
78 vfprintf(stderr, format, ap);
79 va_end(ap);
81 fputs("\n", stderr);
82 fflush(stderr);
83 exit(EXIT_ERR);
86 #ifdef HAVE_DEBUG
87 FL void
88 warn(char const *format, ...)
90 va_list ap;
92 fprintf(stderr, tr(1, "Panic: "));
94 va_start(ap, format);
95 vfprintf(stderr, format, ap);
96 va_end(ap);
98 fputs("\n", stderr);
99 fflush(stderr);
101 #endif
103 FL sighandler_type
104 safe_signal(int signum, sighandler_type handler)
106 struct sigaction nact, oact;
108 nact.sa_handler = handler;
109 sigemptyset(&nact.sa_mask);
110 nact.sa_flags = 0;
111 #ifdef SA_RESTART
112 nact.sa_flags |= SA_RESTART;
113 #endif
114 return ((sigaction(signum, &nact, &oact) != 0) ? SIG_ERR : oact.sa_handler);
117 FL void
118 hold_all_sigs(void)
120 if (_alls_depth++ == 0) {
121 sigfillset(&_alls_nset);
122 sigdelset(&_alls_nset, SIGKILL);
123 sigdelset(&_alls_nset, SIGSTOP);
124 sigdelset(&_alls_nset, SIGCHLD);
125 sigprocmask(SIG_BLOCK, &_alls_nset, &_alls_oset);
129 FL void
130 rele_all_sigs(void)
132 if (--_alls_depth == 0)
133 sigprocmask(SIG_SETMASK, &_alls_oset, (sigset_t*)NULL);
136 FL void
137 hold_sigs(void)
139 if (_hold_sigdepth++ == 0) {
140 sigemptyset(&_hold_nset);
141 sigaddset(&_hold_nset, SIGHUP);
142 sigaddset(&_hold_nset, SIGINT);
143 sigaddset(&_hold_nset, SIGQUIT);
144 sigprocmask(SIG_BLOCK, &_hold_nset, &_hold_oset);
148 FL void
149 rele_sigs(void)
151 if (--_hold_sigdepth == 0)
152 sigprocmask(SIG_SETMASK, &_hold_oset, NULL);
156 * Touch the named message by setting its MTOUCH flag.
157 * Touched messages have the effect of not being sent
158 * back to the system mailbox on exit.
160 FL void
161 touch(struct message *mp)
164 mp->m_flag |= MTOUCH;
165 if ((mp->m_flag & MREAD) == 0)
166 mp->m_flag |= MREAD|MSTATUS;
170 * Test to see if the passed file name is a directory.
171 * Return true if it is.
173 FL int
174 is_dir(char const *name)
176 struct stat sbuf;
178 if (stat(name, &sbuf) < 0)
179 return(0);
180 return(S_ISDIR(sbuf.st_mode));
184 * Count the number of arguments in the given string raw list.
186 FL int
187 argcount(char **argv)
189 char **ap;
191 for (ap = argv; *ap++ != NULL;)
193 return ap - argv - 1;
196 FL char *
197 colalign(const char *cp, int col, int fill, int *cols_decr_used_or_null)
199 int col_orig = col, n, sz;
200 char *nb, *np;
202 np = nb = salloc(mb_cur_max * strlen(cp) + col + 1);
203 while (*cp) {
204 #ifdef HAVE_WCWIDTH
205 if (mb_cur_max > 1) {
206 wchar_t wc;
208 if ((sz = mbtowc(&wc, cp, mb_cur_max)) < 0) {
209 n = sz = 1;
210 } else {
211 if ((n = wcwidth(wc)) < 0)
212 n = 1;
214 } else
215 #endif
217 n = sz = 1;
219 if (n > col)
220 break;
221 col -= n;
222 if (sz == 1 && spacechar(*cp)) {
223 *np++ = ' ';
224 cp++;
225 } else
226 while (sz--)
227 *np++ = *cp++;
230 if (fill && col != 0) {
231 if (fill > 0) {
232 memmove(nb + col, nb, (size_t)(np - nb));
233 memset(nb, ' ', col);
234 } else
235 memset(np, ' ', col);
236 np += col;
237 col = 0;
240 *np = '\0';
241 if (cols_decr_used_or_null != NULL)
242 *cols_decr_used_or_null -= col_orig - col;
243 return nb;
246 FL size_t
247 paging_seems_sensible(void)
249 size_t ret = 0;
250 char const *cp;
252 if (IS_TTY_SESSION() && (cp = ok_vlook(crt)) != NULL)
253 ret = (*cp != '\0') ? (size_t)atol(cp) : (size_t)scrnheight;
254 return ret;
257 FL void
258 page_or_print(FILE *fp, size_t lines)
260 size_t rows;
261 int c;
263 fflush_rewind(fp);
265 if ((rows = paging_seems_sensible()) != 0 && lines == 0) {
266 while ((c = getc(fp)) != EOF)
267 if (c == '\n' && ++lines > rows)
268 break;
269 rewind(fp);
272 if (rows != 0 && lines >= rows)
273 run_command(get_pager(), 0, fileno(fp), -1, NULL, NULL, NULL);
274 else
275 while ((c = getc(fp)) != EOF)
276 putchar(c);
279 FL enum protocol
280 which_protocol(const char *name)
282 register const char *cp;
283 char *np;
284 size_t sz;
285 struct stat st;
286 enum protocol p;
288 if (name[0] == '%' && name[1] == ':')
289 name += 2;
290 for (cp = name; *cp && *cp != ':'; cp++)
291 if (!alnumchar(*cp&0377))
292 goto file;
293 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
294 if (strncmp(name, "pop3://", 7) == 0)
295 #ifdef HAVE_POP3
296 return PROTO_POP3;
297 #else
298 fprintf(stderr,
299 tr(216, "No POP3 support compiled in.\n"));
300 #endif
301 if (strncmp(name, "pop3s://", 8) == 0)
302 #ifdef HAVE_SSL
303 return PROTO_POP3;
304 #else
305 fprintf(stderr,
306 tr(225, "No SSL support compiled in.\n"));
307 #endif
308 if (strncmp(name, "imap://", 7) == 0)
309 #ifdef HAVE_IMAP
310 return PROTO_IMAP;
311 #else
312 fprintf(stderr,
313 tr(269, "No IMAP support compiled in.\n"));
314 #endif
315 if (strncmp(name, "imaps://", 8) == 0)
316 #ifdef HAVE_SSL
317 return PROTO_IMAP;
318 #else
319 fprintf(stderr,
320 tr(225, "No SSL support compiled in.\n"));
321 #endif
322 return PROTO_UNKNOWN;
323 } else {
324 /* TODO This is the de facto maildir code and thus belongs
325 * TODO into maildir! */
326 file: p = PROTO_FILE;
327 np = ac_alloc((sz = strlen(name)) + 5);
328 memcpy(np, name, sz + 1);
329 if (stat(name, &st) == 0) {
330 if (S_ISDIR(st.st_mode)) {
331 strcpy(&np[sz], "/tmp");
332 if (stat(np, &st) == 0 && S_ISDIR(st.st_mode)) {
333 strcpy(&np[sz], "/new");
334 if (stat(np, &st) == 0 &&
335 S_ISDIR(st.st_mode)) {
336 strcpy(&np[sz], "/cur");
337 if (stat(np, &st) == 0 &&
338 S_ISDIR(st.st_mode))
339 p = PROTO_MAILDIR;
343 } else {
344 strcpy(&np[sz], ".gz");
345 if (stat(np, &st) < 0) {
346 strcpy(&np[sz], ".bz2");
347 if (stat(np, &st) < 0) {
348 if ((cp = ok_vlook(newfolders)) != NULL &&
349 strcmp(cp, "maildir") == 0)
350 p = PROTO_MAILDIR;
354 ac_free(np);
355 return p;
359 FL ui32_t
360 torek_hash(char const *name)
362 /* Chris Torek's hash.
363 * NOTE: need to change *at least* create-okey-map.pl when changing the
364 * algorithm!! */
365 ui32_t h = 0;
367 while (*name != '\0') {
368 h *= 33;
369 h += *name++;
371 return h;
374 FL unsigned
375 pjw(const char *cp)
377 unsigned h = 0, g;
379 cp--;
380 while (*++cp) {
381 h = (h << 4 & 0xffffffff) + (*cp&0377);
382 if ((g = h & 0xf0000000) != 0) {
383 h = h ^ g >> 24;
384 h = h ^ g;
387 return h;
390 FL long
391 nextprime(long n)
393 const long primes[] = {
394 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
395 131071, 262139, 524287, 1048573, 2097143, 4194301,
396 8388593, 16777213, 33554393, 67108859, 134217689,
397 268435399, 536870909, 1073741789, 2147483647
399 long mprime = 7;
400 size_t i;
402 for (i = 0; i < sizeof primes / sizeof *primes; i++)
403 if ((mprime = primes[i]) >= (n < 65536 ? n*4 :
404 n < 262144 ? n*2 : n))
405 break;
406 if (i == sizeof primes / sizeof *primes)
407 mprime = n; /* not so prime, but better than failure */
408 return mprime;
411 FL int
412 expand_shell_escape(char const **s, bool_t use_nail_extensions)
414 char const *xs = *s;
415 int c, n;
417 if ((c = *xs & 0xFF) == '\0')
418 goto jleave;
419 ++xs;
420 if (c != '\\')
421 goto jleave;
423 switch ((c = *xs & 0xFF)) {
424 case '\\': break;
425 case 'a': c = '\a'; break;
426 case 'b': c = '\b'; break;
427 case 'c': c = PROMPT_STOP; break;
428 case 'f': c = '\f'; break;
429 case 'n': c = '\n'; break;
430 case 'r': c = '\r'; break;
431 case 't': c = '\t'; break;
432 case 'v': c = '\v'; break;
433 case '0':
434 for (++xs, c = 0, n = 4; --n > 0 && octalchar(*xs); ++xs) {
435 c <<= 3;
436 c |= *xs - '0';
438 goto jleave;
439 /* S-nail extension for nice (get)prompt(()) support */
440 case '&':
441 case '?':
442 case '$':
443 case '@':
444 if (use_nail_extensions) {
445 switch (c) {
446 case '&': c = ok_blook(bsdcompat) ? '&' : '?'; break;
447 case '?': c = exec_last_comm_error ? '1' : '0'; break;
448 case '$': c = PROMPT_DOLLAR; break;
449 case '@': c = PROMPT_AT; break;
451 break;
453 /* FALLTHRU */
454 case '\0':
455 /* A sole <backslash> at EOS is treated as-is! */
456 /* FALLTHRU */
457 default:
458 c = '\\';
459 goto jleave;
461 ++xs;
462 jleave:
463 *s = xs;
464 return c;
467 FL char *
468 getprompt(void)
470 static char buf[PROMPT_BUFFER_SIZE];
472 char *cp = buf;
473 char const *ccp;
475 if ((ccp = ok_vlook(prompt)) == NULL || *ccp == '\0')
476 goto jleave;
478 for (; PTRCMP(cp, <, buf + sizeof(buf) - 1); ++cp) {
479 char const *a;
480 size_t l;
481 int c = expand_shell_escape(&ccp, TRU1);
483 if (c > 0) {
484 *cp = (char)c;
485 continue;
487 if (c == 0 || c == PROMPT_STOP)
488 break;
490 a = (c == PROMPT_DOLLAR) ? account_name : displayname;
491 if (a == NULL)
492 a = "";
493 l = strlen(a);
494 if (PTRCMP(cp + l, >=, buf + sizeof(buf) - 1))
495 *cp++ = '?';
496 else {
497 memcpy(cp, a, l);
498 cp += --l;
501 jleave:
502 *cp = '\0';
503 return buf;
506 FL char *
507 nodename(int mayoverride)
509 static char *hostname;
510 struct utsname ut;
511 char *hn;
512 #ifdef HAVE_SOCKETS
513 # ifdef HAVE_IPV6
514 struct addrinfo hints, *res;
515 # else
516 struct hostent *hent;
517 # endif
518 #endif
520 if (mayoverride && (hn = ok_vlook(hostname)) != NULL && *hn != '\0') {
521 if (hostname != NULL)
522 free(hostname);
523 hostname = sstrdup(hn);
524 } else if (hostname == NULL) {
525 uname(&ut);
526 hn = ut.nodename;
527 #ifdef HAVE_SOCKETS
528 # ifdef HAVE_IPV6
529 memset(&hints, 0, sizeof hints);
530 hints.ai_family = AF_UNSPEC;
531 hints.ai_socktype = SOCK_DGRAM; /* dummy */
532 hints.ai_flags = AI_CANONNAME;
533 if (getaddrinfo(hn, "0", &hints, &res) == 0) {
534 if (res->ai_canonname != NULL) {
535 size_t l = strlen(res->ai_canonname);
536 hn = ac_alloc(l + 1);
537 memcpy(hn, res->ai_canonname, l + 1);
539 freeaddrinfo(res);
541 # else
542 hent = gethostbyname(hn);
543 if (hent != NULL) {
544 hn = hent->h_name;
546 # endif
547 #endif
548 hostname = sstrdup(hn);
549 #if defined HAVE_SOCKETS && defined HAVE_IPV6
550 if (hn != ut.nodename)
551 ac_free(hn);
552 #endif
554 return (hostname);
557 FL char *
558 lookup_password_for_token(char const *token)
560 size_t tl;
561 char *var, *cp;
563 tl = strlen(token);
564 var = ac_alloc(tl + 10);
566 memcpy(var, "password-", 9);
567 memcpy(var + 9, token, tl);
568 var[tl + 9] = '\0';
570 if ((cp = vok_vlook(var)) != NULL)
571 cp = savestr(cp);
572 ac_free(var);
573 return cp;
576 FL char *
577 getrandstring(size_t length)
579 static unsigned char nodedigest[16];
580 static pid_t pid;
581 struct str b64;
582 int fd = -1;
583 char *data, *cp;
584 size_t i;
585 #ifdef HAVE_MD5
586 md5_ctx ctx;
587 #else
588 size_t j;
589 #endif
591 data = ac_alloc(length);
592 if ((fd = open("/dev/urandom", O_RDONLY)) < 0 ||
593 length != (size_t)read(fd, data, length)) {
594 if (pid == 0) {
595 pid = getpid();
596 srand(pid);
597 cp = nodename(0);
598 #ifdef HAVE_MD5
599 md5_init(&ctx);
600 md5_update(&ctx, (unsigned char*)cp, strlen(cp));
601 md5_final(nodedigest, &ctx);
602 #else
603 /* In that case it's only used for boundaries and
604 * Message-Id:s so that srand(3) should suffice */
605 j = strlen(cp) + 1;
606 for (i = 0; i < sizeof(nodedigest); ++i)
607 nodedigest[i] = (unsigned char)(
608 cp[i % j] ^ rand());
609 #endif
611 for (i = 0; i < length; i++)
612 data[i] = (char)(
613 (int)(255 * (rand() / (RAND_MAX + 1.0))) ^
614 nodedigest[i % sizeof nodedigest]);
616 if (fd >= 0)
617 close(fd);
619 (void)b64_encode_buf(&b64, data, length, B64_SALLOC);
620 ac_free(data);
621 assert(length < b64.l);
622 b64.s[length] = '\0';
623 return b64.s;
626 #ifdef HAVE_MD5
627 FL char *
628 md5tohex(char hex[MD5TOHEX_SIZE], void const *vp)
630 char const *cp = vp;
631 size_t i, j;
633 for (i = 0; i < MD5TOHEX_SIZE / 2; i++) {
634 j = i << 1;
635 hex[j] = hexchar((cp[i] & 0xf0) >> 4);
636 hex[++j] = hexchar(cp[i] & 0x0f);
638 return hex;
641 FL char *
642 cram_md5_string(char const *user, char const *pass, char const *b64)
644 struct str in, out;
645 char digest[16], *cp;
646 size_t lu;
648 out.s = NULL;
649 in.s = UNCONST(b64);
650 in.l = strlen(in.s);
651 (void)b64_decode(&out, &in, NULL);
652 assert(out.s != NULL);
654 hmac_md5((unsigned char*)out.s, out.l, UNCONST(pass), strlen(pass),
655 digest);
656 free(out.s);
657 cp = md5tohex(salloc(MD5TOHEX_SIZE + 1), digest);
659 lu = strlen(user);
660 in.l = lu + MD5TOHEX_SIZE +1;
661 in.s = ac_alloc(lu + 1 + MD5TOHEX_SIZE +1);
662 memcpy(in.s, user, lu);
663 in.s[lu] = ' ';
664 memcpy(in.s + lu + 1, cp, MD5TOHEX_SIZE);
665 (void)b64_encode(&out, &in, B64_SALLOC|B64_CRLF);
666 ac_free(in.s);
667 return out.s;
669 #endif /* HAVE_MD5 */
671 FL enum okay
672 makedir(const char *name)
674 int e;
675 struct stat st;
677 if (mkdir(name, 0700) < 0) {
678 e = errno;
679 if ((e == EEXIST || e == ENOSYS) &&
680 stat(name, &st) == 0 &&
681 (st.st_mode&S_IFMT) == S_IFDIR)
682 return OKAY;
683 return STOP;
685 return OKAY;
688 #ifdef HAVE_FCHDIR
689 FL enum okay
690 cwget(struct cw *cw)
692 if ((cw->cw_fd = open(".", O_RDONLY)) < 0)
693 return STOP;
694 if (fchdir(cw->cw_fd) < 0) {
695 close(cw->cw_fd);
696 return STOP;
698 return OKAY;
701 FL enum okay
702 cwret(struct cw *cw)
704 if (fchdir(cw->cw_fd) < 0)
705 return STOP;
706 return OKAY;
709 FL void
710 cwrelse(struct cw *cw)
712 close(cw->cw_fd);
714 #else /* !HAVE_FCHDIR */
715 FL enum okay
716 cwget(struct cw *cw)
718 if (getcwd(cw->cw_wd, sizeof cw->cw_wd) == NULL || chdir(cw->cw_wd) < 0)
719 return STOP;
720 return OKAY;
723 FL enum okay
724 cwret(struct cw *cw)
726 if (chdir(cw->cw_wd) < 0)
727 return STOP;
728 return OKAY;
731 /*ARGSUSED*/
732 FL void
733 cwrelse(struct cw *cw)
735 (void)cw;
737 #endif /* !HAVE_FCHDIR */
739 FL void
740 makeprint(struct str const *in, struct str *out)
742 static int print_all_chars = -1;
743 char const *inp, *maxp;
744 char *outp;
745 size_t msz;
747 if (print_all_chars == -1)
748 print_all_chars = ok_blook(print_all_chars);
750 msz = in->l + 1;
751 out->s = outp = smalloc(msz);
752 inp = in->s;
753 maxp = inp + in->l;
755 if (print_all_chars) {
756 out->l = in->l;
757 memcpy(outp, inp, out->l);
758 goto jleave;
761 #ifdef HAVE_C90AMEND1
762 if (mb_cur_max > 1) {
763 char mbb[MB_LEN_MAX + 1];
764 wchar_t wc;
765 int i, n;
766 size_t dist;
768 out->l = 0;
769 while (inp < maxp) {
770 if (*inp & 0200)
771 n = mbtowc(&wc, inp, maxp - inp);
772 else {
773 wc = *inp;
774 n = 1;
776 if (n < 0) {
777 /* FIXME Why mbtowc() resetting here?
778 * FIXME what about ISO 2022-JP plus -- those
779 * FIXME will loose shifts, then!
780 * FIXME THUS - we'd need special "known points"
781 * FIXME to do so - say, after a newline!!
782 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
783 (void)mbtowc(&wc, NULL, mb_cur_max);
784 wc = utf8 ? 0xFFFD : '?';
785 n = 1;
786 } else if (n == 0)
787 n = 1;
788 inp += n;
789 if (!iswprint(wc) && wc != '\n' && wc != '\r' &&
790 wc != '\b' && wc != '\t') {
791 if ((wc & ~(wchar_t)037) == 0)
792 wc = utf8 ? 0x2400 | wc : '?';
793 else if (wc == 0177)
794 wc = utf8 ? 0x2421 : '?';
795 else
796 wc = utf8 ? 0x2426 : '?';
798 if ((n = wctomb(mbb, wc)) <= 0)
799 continue;
800 out->l += n;
801 if (out->l >= msz - 1) {
802 dist = outp - out->s;
803 out->s = srealloc(out->s, msz += 32);
804 outp = &out->s[dist];
806 for (i = 0; i < n; i++)
807 *outp++ = mbb[i];
809 } else
810 #endif /* C90AMEND1 */
812 int c;
813 while (inp < maxp) {
814 c = *inp++ & 0377;
815 if (!isprint(c) && c != '\n' && c != '\r' &&
816 c != '\b' && c != '\t')
817 c = '?';
818 *outp++ = c;
820 out->l = in->l;
822 jleave:
823 out->s[out->l] = '\0';
826 FL char *
827 prstr(const char *s)
829 struct str in, out;
830 char *rp;
832 in.s = UNCONST(s);
833 in.l = strlen(s);
834 makeprint(&in, &out);
835 rp = salloc(out.l + 1);
836 memcpy(rp, out.s, out.l);
837 rp[out.l] = '\0';
838 free(out.s);
839 return rp;
842 FL int
843 prout(const char *s, size_t sz, FILE *fp)
845 struct str in, out;
846 int n;
848 in.s = UNCONST(s);
849 in.l = sz;
850 makeprint(&in, &out);
851 n = fwrite(out.s, 1, out.l, fp);
852 free(out.s);
853 return n;
856 FL size_t
857 putuc(int u, int c, FILE *fp)
859 size_t rv;
860 UNUSED(u);
862 #ifdef HAVE_C90AMEND1
863 if (utf8 && (u & ~(wchar_t)0177)) {
864 char mbb[MB_LEN_MAX];
865 int i, n;
866 if ((n = wctomb(mbb, u)) > 0) {
867 rv = wcwidth(u);
868 for (i = 0; i < n; ++i)
869 if (putc(mbb[i] & 0377, fp) == EOF) {
870 rv = 0;
871 break;
873 } else if (n == 0)
874 rv = (putc('\0', fp) != EOF);
875 else
876 rv = 0;
877 } else
878 #endif
879 rv = (putc(c, fp) != EOF);
880 return rv;
883 FL void
884 time_current_update(struct time_current *tc, bool_t full_update)
886 tc->tc_time = time(NULL);
887 if (full_update) {
888 memcpy(&tc->tc_gm, gmtime(&tc->tc_time), sizeof tc->tc_gm);
889 memcpy(&tc->tc_local, localtime(&tc->tc_time),
890 sizeof tc->tc_local);
891 sstpcpy(tc->tc_ctime, ctime(&tc->tc_time));
895 static void
896 _out_of_memory(void)
898 panic("no memory");
901 FL void *
902 (smalloc_safe)(size_t s SMALLOC_DEBUG_ARGS)
904 void *rv;
906 hold_all_sigs();
907 rv = (smalloc)(s SMALLOC_DEBUG_ARGSCALL);
908 rele_all_sigs();
909 return rv;
912 FL void *
913 (srealloc_safe)(void *v, size_t s SMALLOC_DEBUG_ARGS)
915 void *rv;
917 hold_all_sigs();
918 rv = (srealloc)(v, s SMALLOC_DEBUG_ARGSCALL);
919 rele_all_sigs();
920 return rv;
923 #ifdef notyet
924 FL void *
925 (scalloc_safe)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
927 void *rv;
929 hold_all_sigs();
930 rv = (scalloc)(nmemb, size SMALLOC_DEBUG_ARGSCALL);
931 rele_all_sigs();
932 return rv;
934 #endif
936 #ifndef HAVE_DEBUG
937 FL void *
938 smalloc(size_t s SMALLOC_DEBUG_ARGS)
940 void *rv;
942 if (s == 0)
943 s = 1;
944 if ((rv = malloc(s)) == NULL)
945 _out_of_memory();
946 return rv;
949 FL void *
950 srealloc(void *v, size_t s SMALLOC_DEBUG_ARGS)
952 void *rv;
954 if (s == 0)
955 s = 1;
956 if (v == NULL)
957 rv = smalloc(s);
958 else if ((rv = realloc(v, s)) == NULL)
959 _out_of_memory();
960 return rv;
963 FL void *
964 scalloc(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
966 void *rv;
968 if (size == 0)
969 size = 1;
970 if ((rv = calloc(nmemb, size)) == NULL)
971 _out_of_memory();
972 return rv;
975 #else /* !HAVE_DEBUG */
976 CTA(sizeof(char) == sizeof(ui8_t));
978 # define _HOPE_SIZE (2 * 8 * sizeof(char))
979 # define _HOPE_SET(C) \
980 do {\
981 union ptr __xl, __xu;\
982 struct chunk *__xc;\
983 __xl.p = (C).p;\
984 __xc = __xl.c - 1;\
985 __xu.p = __xc;\
986 (C).cp += 8;\
987 __xl.ui8p[0]=0xDE; __xl.ui8p[1]=0xAA; __xl.ui8p[2]=0x55; __xl.ui8p[3]=0xAD;\
988 __xl.ui8p[4]=0xBE; __xl.ui8p[5]=0x55; __xl.ui8p[6]=0xAA; __xl.ui8p[7]=0xEF;\
989 __xu.ui8p += __xc->size - 8;\
990 __xu.ui8p[0]=0xDE; __xu.ui8p[1]=0xAA; __xu.ui8p[2]=0x55; __xu.ui8p[3]=0xAD;\
991 __xu.ui8p[4]=0xBE; __xu.ui8p[5]=0x55; __xu.ui8p[6]=0xAA; __xu.ui8p[7]=0xEF;\
992 } while (0)
993 # define _HOPE_GET_TRACE(C,BAD) do {(C).cp += 8; _HOPE_GET(C, BAD);} while(0)
994 # define _HOPE_GET(C,BAD) \
995 do {\
996 union ptr __xl, __xu;\
997 struct chunk *__xc;\
998 ui32_t __i;\
999 __xl.p = (C).p;\
1000 __xl.cp -= 8;\
1001 (C).cp = __xl.cp;\
1002 __xc = __xl.c - 1;\
1003 (BAD) = FAL0;\
1004 __i = 0;\
1005 if (__xl.ui8p[0] != 0xDE) __i |= 1<<0;\
1006 if (__xl.ui8p[1] != 0xAA) __i |= 1<<1;\
1007 if (__xl.ui8p[2] != 0x55) __i |= 1<<2;\
1008 if (__xl.ui8p[3] != 0xAD) __i |= 1<<3;\
1009 if (__xl.ui8p[4] != 0xBE) __i |= 1<<4;\
1010 if (__xl.ui8p[5] != 0x55) __i |= 1<<5;\
1011 if (__xl.ui8p[6] != 0xAA) __i |= 1<<6;\
1012 if (__xl.ui8p[7] != 0xEF) __i |= 1<<7;\
1013 if (__i != 0) {\
1014 (BAD) = TRU1;\
1015 warn("%p: corrupted lower canary: 0x%02X: %s, line %u",\
1016 __xl.p, __i, mdbg_file, mdbg_line);\
1018 __xu.p = __xc;\
1019 __xu.ui8p += __xc->size - 8;\
1020 __i = 0;\
1021 if (__xu.ui8p[0] != 0xDE) __i |= 1<<0;\
1022 if (__xu.ui8p[1] != 0xAA) __i |= 1<<1;\
1023 if (__xu.ui8p[2] != 0x55) __i |= 1<<2;\
1024 if (__xu.ui8p[3] != 0xAD) __i |= 1<<3;\
1025 if (__xu.ui8p[4] != 0xBE) __i |= 1<<4;\
1026 if (__xu.ui8p[5] != 0x55) __i |= 1<<5;\
1027 if (__xu.ui8p[6] != 0xAA) __i |= 1<<6;\
1028 if (__xu.ui8p[7] != 0xEF) __i |= 1<<7;\
1029 if (__i != 0) {\
1030 (BAD) = TRU1;\
1031 warn("%p: corrupted upper canary: 0x%02X: %s, line %u",\
1032 __xl.p, __i, mdbg_file, mdbg_line);\
1034 if (BAD)\
1035 warn(" ..canary last seen: %s, line %u", __xc->file, __xc->line);\
1036 } while (0)
1038 struct chunk {
1039 struct chunk *prev;
1040 struct chunk *next;
1041 char const *file;
1042 ui16_t line;
1043 ui8_t isfree;
1044 ui8_t __dummy;
1045 ui32_t size;
1048 union ptr {
1049 void *p;
1050 struct chunk *c;
1051 char *cp;
1052 ui8_t *ui8p;
1055 struct chunk *_mlist, *_mfree;
1057 FL void *
1058 (smalloc)(size_t s SMALLOC_DEBUG_ARGS)
1060 union ptr p;
1062 if (s == 0)
1063 s = 1;
1064 s += sizeof(struct chunk) + _HOPE_SIZE;
1066 if ((p.p = (malloc)(s)) == NULL)
1067 _out_of_memory();
1068 p.c->prev = NULL;
1069 if ((p.c->next = _mlist) != NULL)
1070 _mlist->prev = p.c;
1071 p.c->file = mdbg_file;
1072 p.c->line = (ui16_t)mdbg_line;
1073 p.c->isfree = FAL0;
1074 p.c->size = (ui32_t)s;
1075 _mlist = p.c++;
1076 _HOPE_SET(p);
1077 return p.p;
1080 FL void *
1081 (srealloc)(void *v, size_t s SMALLOC_DEBUG_ARGS)
1083 union ptr p;
1084 bool_t isbad;
1086 if ((p.p = v) == NULL) {
1087 p.p = (smalloc)(s, mdbg_file, mdbg_line);
1088 goto jleave;
1091 _HOPE_GET(p, isbad);
1092 --p.c;
1093 if (p.c->isfree) {
1094 fprintf(stderr, "srealloc(): region freed! At %s, line %d\n"
1095 "\tLast seen: %s, line %d\n",
1096 mdbg_file, mdbg_line, p.c->file, p.c->line);
1097 goto jforce;
1100 if (p.c == _mlist)
1101 _mlist = p.c->next;
1102 else
1103 p.c->prev->next = p.c->next;
1104 if (p.c->next != NULL)
1105 p.c->next->prev = p.c->prev;
1107 jforce:
1108 if (s == 0)
1109 s = 1;
1110 s += sizeof(struct chunk) + _HOPE_SIZE;
1112 if ((p.p = (realloc)(p.c, s)) == NULL)
1113 _out_of_memory();
1114 p.c->prev = NULL;
1115 if ((p.c->next = _mlist) != NULL)
1116 _mlist->prev = p.c;
1117 p.c->file = mdbg_file;
1118 p.c->line = (ui16_t)mdbg_line;
1119 p.c->isfree = FAL0;
1120 p.c->size = (ui32_t)s;
1121 _mlist = p.c++;
1122 _HOPE_SET(p);
1123 jleave:
1124 return p.p;
1127 FL void *
1128 (scalloc)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1130 union ptr p;
1132 if (size == 0)
1133 size = 1;
1134 if (nmemb == 0)
1135 nmemb = 1;
1136 size *= nmemb;
1137 size += sizeof(struct chunk) + _HOPE_SIZE;
1139 if ((p.p = (malloc)(size)) == NULL)
1140 _out_of_memory();
1141 memset(p.p, 0, size);
1142 p.c->prev = NULL;
1143 if ((p.c->next = _mlist) != NULL)
1144 _mlist->prev = p.c;
1145 p.c->file = mdbg_file;
1146 p.c->line = (ui16_t)mdbg_line;
1147 p.c->isfree = FAL0;
1148 p.c->size = (ui32_t)size;
1149 _mlist = p.c++;
1150 _HOPE_SET(p);
1151 return p.p;
1154 FL void
1155 (sfree)(void *v SMALLOC_DEBUG_ARGS)
1157 union ptr p;
1158 bool_t isbad;
1160 if ((p.p = v) == NULL) {
1161 fprintf(stderr, "sfree(NULL) from %s, line %d\n", mdbg_file, mdbg_line);
1162 goto jleave;
1165 _HOPE_GET(p, isbad);
1166 --p.c;
1167 if (p.c->isfree) {
1168 fprintf(stderr, "sfree(): double-free avoided at %s, line %d\n"
1169 "\tLast seen: %s, line %d\n",
1170 mdbg_file, mdbg_line, p.c->file, p.c->line);
1171 goto jleave;
1174 if (p.c == _mlist)
1175 _mlist = p.c->next;
1176 else
1177 p.c->prev->next = p.c->next;
1178 if (p.c->next != NULL)
1179 p.c->next->prev = p.c->prev;
1180 p.c->isfree = TRU1;
1182 if (options & OPT_DEBUG) {
1183 p.c->next = _mfree;
1184 _mfree = p.c;
1185 } else
1186 (free)(p.c);
1187 jleave:
1191 FL void
1192 smemreset(void)
1194 union ptr p;
1195 size_t c = 0, s = 0;
1197 for (p.c = _mfree; p.c != NULL;) {
1198 void *vp = p.c;
1199 ++c;
1200 s += p.c->size;
1201 p.c = p.c->next;
1202 (free)(vp);
1204 _mfree = NULL;
1206 if (options & OPT_DEBUG)
1207 fprintf(stderr, "smemreset(): freed %" ZFMT " chunks/%" ZFMT " bytes\n",
1208 c, s);
1211 FL int
1212 smemtrace(void *v)
1214 /* For _HOPE_GET() */
1215 char const * const mdbg_file = "smemtrace()";
1216 int const mdbg_line = -1;
1218 FILE *fp;
1219 char *cp;
1220 union ptr p, xp;
1221 bool_t isbad;
1222 size_t lines;
1224 v = (void*)0x1;
1225 if ((fp = Ftemp(&cp, "Ra", "w+", 0600, 1)) == NULL) {
1226 perror("tmpfile");
1227 goto jleave;
1229 rm(cp);
1230 Ftfree(&cp);
1232 fprintf(fp, "Currently allocated memory chunks:\n");
1233 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1234 xp = p;
1235 ++xp.c;
1236 _HOPE_GET_TRACE(xp, isbad);
1237 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1238 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1239 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1242 if (options & OPT_DEBUG) {
1243 fprintf(fp, "sfree()d memory chunks awaiting free():\n");
1244 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1245 xp = p;
1246 ++xp.c;
1247 _HOPE_GET_TRACE(xp, isbad);
1248 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1249 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1250 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1254 page_or_print(fp, lines);
1255 Fclose(fp);
1256 v = NULL;
1257 jleave:
1258 return (v != NULL);
1261 # ifdef MEMCHECK
1262 FL bool_t
1263 _smemcheck(char const *mdbg_file, int mdbg_line)
1265 union ptr p, xp;
1266 bool_t anybad = FAL0, isbad;
1267 size_t lines;
1269 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1270 xp = p;
1271 ++xp.c;
1272 _HOPE_GET_TRACE(xp, isbad);
1273 if (isbad) {
1274 anybad = TRU1;
1275 fprintf(stderr,
1276 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1277 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1278 p.c->file, p.c->line);
1282 if (options & OPT_DEBUG) {
1283 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1284 xp = p;
1285 ++xp.c;
1286 _HOPE_GET_TRACE(xp, isbad);
1287 if (isbad) {
1288 anybad = TRU1;
1289 fprintf(stderr,
1290 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1291 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1292 p.c->file, p.c->line);
1296 return anybad;
1298 # endif /* MEMCHECK */
1299 #endif /* HAVE_DEBUG */
1301 /* vim:set fenc=utf-8:s-it-mode (TODO only partial true) */