nail.1: some small tweaks
[s-mailx.git] / auxlily.c
blobb7a7db2e3bf3dd62447bdd31c51c0c1265e515a9
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 #if defined (HAVE_MBTOWC) && defined (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 /* HAVE_MBTOWC && HAVE_WCWIDTH */
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 = voption("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 = value("newfolders")) != 0 &&
349 strcmp(cp, "maildir") == 0)
350 p = PROTO_MAILDIR;
354 ac_free(np);
355 return p;
359 FL unsigned
360 pjw(const char *cp)
362 unsigned h = 0, g;
364 cp--;
365 while (*++cp) {
366 h = (h << 4 & 0xffffffff) + (*cp&0377);
367 if ((g = h & 0xf0000000) != 0) {
368 h = h ^ g >> 24;
369 h = h ^ g;
372 return h;
375 FL long
376 nextprime(long n)
378 const long primes[] = {
379 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
380 131071, 262139, 524287, 1048573, 2097143, 4194301,
381 8388593, 16777213, 33554393, 67108859, 134217689,
382 268435399, 536870909, 1073741789, 2147483647
384 long mprime = 7;
385 size_t i;
387 for (i = 0; i < sizeof primes / sizeof *primes; i++)
388 if ((mprime = primes[i]) >= (n < 65536 ? n*4 :
389 n < 262144 ? n*2 : n))
390 break;
391 if (i == sizeof primes / sizeof *primes)
392 mprime = n; /* not so prime, but better than failure */
393 return mprime;
396 FL int
397 expand_shell_escape(char const **s, bool_t use_nail_extensions)
399 char const *xs = *s;
400 int c, n;
402 if ((c = *xs & 0xFF) == '\0')
403 goto jleave;
404 ++xs;
405 if (c != '\\')
406 goto jleave;
408 switch ((c = *xs & 0xFF)) {
409 case '\\': break;
410 case 'a': c = '\a'; break;
411 case 'b': c = '\b'; break;
412 case 'c': c = PROMPT_STOP; break;
413 case 'f': c = '\f'; break;
414 case 'n': c = '\n'; break;
415 case 'r': c = '\r'; break;
416 case 't': c = '\t'; break;
417 case 'v': c = '\v'; break;
418 case '0':
419 for (++xs, c = 0, n = 4; --n > 0 && octalchar(*xs); ++xs) {
420 c <<= 3;
421 c |= *xs - '0';
423 goto jleave;
424 /* S-nail extension for nice (get)prompt(()) support */
425 case '&':
426 case '?':
427 case '$':
428 case '@':
429 if (use_nail_extensions) {
430 switch (c) {
431 case '&': c = boption("bsdcompat") ? '&' : '?'; break;
432 case '?': c = exec_last_comm_error ? '1' : '0'; break;
433 case '$': c = PROMPT_DOLLAR; break;
434 case '@': c = PROMPT_AT; break;
436 break;
438 /* FALLTHRU */
439 case '\0':
440 /* A sole <backslash> at EOS is treated as-is! */
441 /* FALLTHRU */
442 default:
443 c = '\\';
444 goto jleave;
446 ++xs;
447 jleave:
448 *s = xs;
449 return c;
452 FL char *
453 getprompt(void)
455 static char buf[PROMPT_BUFFER_SIZE];
457 char *cp = buf;
458 char const *ccp;
460 if ((ccp = voption("prompt")) == NULL || *ccp == '\0')
461 goto jleave;
463 for (; PTRCMP(cp, <, buf + sizeof(buf) - 1); ++cp) {
464 char const *a;
465 size_t l;
466 int c = expand_shell_escape(&ccp, TRU1);
468 if (c > 0) {
469 *cp = (char)c;
470 continue;
472 if (c == 0 || c == PROMPT_STOP)
473 break;
475 a = (c == PROMPT_DOLLAR) ? account_name : displayname;
476 if (a == NULL)
477 a = "";
478 l = strlen(a);
479 if (PTRCMP(cp + l, >=, buf + sizeof(buf) - 1))
480 *cp++ = '?';
481 else {
482 memcpy(cp, a, l);
483 cp += --l;
486 jleave:
487 *cp = '\0';
488 return buf;
491 FL char *
492 nodename(int mayoverride)
494 static char *hostname;
495 struct utsname ut;
496 char *hn;
497 #ifdef HAVE_SOCKETS
498 # ifdef HAVE_IPV6
499 struct addrinfo hints, *res;
500 # else
501 struct hostent *hent;
502 # endif
503 #endif
505 if (mayoverride && (hn = value("hostname")) != NULL && *hn != '\0') {
506 if (hostname != NULL)
507 free(hostname);
508 hostname = sstrdup(hn);
509 } else if (hostname == NULL) {
510 uname(&ut);
511 hn = ut.nodename;
512 #ifdef HAVE_SOCKETS
513 # ifdef HAVE_IPV6
514 memset(&hints, 0, sizeof hints);
515 hints.ai_family = AF_UNSPEC;
516 hints.ai_socktype = SOCK_DGRAM; /* dummy */
517 hints.ai_flags = AI_CANONNAME;
518 if (getaddrinfo(hn, "0", &hints, &res) == 0) {
519 if (res->ai_canonname != NULL) {
520 size_t l = strlen(res->ai_canonname);
521 hn = ac_alloc(l + 1);
522 memcpy(hn, res->ai_canonname, l + 1);
524 freeaddrinfo(res);
526 # else
527 hent = gethostbyname(hn);
528 if (hent != NULL) {
529 hn = hent->h_name;
531 # endif
532 #endif
533 hostname = sstrdup(hn);
534 #if defined HAVE_SOCKETS && defined HAVE_IPV6
535 if (hn != ut.nodename)
536 ac_free(hn);
537 #endif
539 return (hostname);
542 FL char *
543 lookup_password_for_token(char const *token)
545 size_t tl;
546 char *var, *cp;
548 tl = strlen(token);
549 var = ac_alloc(tl + 10);
551 memcpy(var, "password-", 9);
552 memcpy(var + 9, token, tl);
553 var[tl + 9] = '\0';
555 if ((cp = value(var)) != NULL)
556 cp = savestr(cp);
557 ac_free(var);
558 return cp;
561 FL char *
562 getrandstring(size_t length)
564 static unsigned char nodedigest[16];
565 static pid_t pid;
566 struct str b64;
567 int fd = -1;
568 char *data, *cp;
569 size_t i;
570 #ifdef HAVE_MD5
571 md5_ctx ctx;
572 #else
573 size_t j;
574 #endif
576 data = ac_alloc(length);
577 if ((fd = open("/dev/urandom", O_RDONLY)) < 0 ||
578 length != (size_t)read(fd, data, length)) {
579 if (pid == 0) {
580 pid = getpid();
581 srand(pid);
582 cp = nodename(0);
583 #ifdef HAVE_MD5
584 md5_init(&ctx);
585 md5_update(&ctx, (unsigned char*)cp, strlen(cp));
586 md5_final(nodedigest, &ctx);
587 #else
588 /* In that case it's only used for boundaries and
589 * Message-Id:s so that srand(3) should suffice */
590 j = strlen(cp) + 1;
591 for (i = 0; i < sizeof(nodedigest); ++i)
592 nodedigest[i] = (unsigned char)(
593 cp[i % j] ^ rand());
594 #endif
596 for (i = 0; i < length; i++)
597 data[i] = (char)(
598 (int)(255 * (rand() / (RAND_MAX + 1.0))) ^
599 nodedigest[i % sizeof nodedigest]);
601 if (fd >= 0)
602 close(fd);
604 (void)b64_encode_buf(&b64, data, length, B64_SALLOC);
605 ac_free(data);
606 assert(length < b64.l);
607 b64.s[length] = '\0';
608 return b64.s;
611 #ifdef HAVE_MD5
612 FL char *
613 md5tohex(char hex[MD5TOHEX_SIZE], void const *vp)
615 char const *cp = vp;
616 size_t i, j;
618 for (i = 0; i < MD5TOHEX_SIZE / 2; i++) {
619 j = i << 1;
620 hex[j] = hexchar((cp[i] & 0xf0) >> 4);
621 hex[++j] = hexchar(cp[i] & 0x0f);
623 return hex;
626 FL char *
627 cram_md5_string(char const *user, char const *pass, char const *b64)
629 struct str in, out;
630 char digest[16], *cp;
631 size_t lu;
633 out.s = NULL;
634 in.s = UNCONST(b64);
635 in.l = strlen(in.s);
636 (void)b64_decode(&out, &in, NULL);
637 assert(out.s != NULL);
639 hmac_md5((unsigned char*)out.s, out.l, UNCONST(pass), strlen(pass),
640 digest);
641 free(out.s);
642 cp = md5tohex(salloc(MD5TOHEX_SIZE + 1), digest);
644 lu = strlen(user);
645 in.l = lu + MD5TOHEX_SIZE +1;
646 in.s = ac_alloc(lu + 1 + MD5TOHEX_SIZE +1);
647 memcpy(in.s, user, lu);
648 in.s[lu] = ' ';
649 memcpy(in.s + lu + 1, cp, MD5TOHEX_SIZE);
650 (void)b64_encode(&out, &in, B64_SALLOC|B64_CRLF);
651 ac_free(in.s);
652 return out.s;
654 #endif /* HAVE_MD5 */
656 FL enum okay
657 makedir(const char *name)
659 int e;
660 struct stat st;
662 if (mkdir(name, 0700) < 0) {
663 e = errno;
664 if ((e == EEXIST || e == ENOSYS) &&
665 stat(name, &st) == 0 &&
666 (st.st_mode&S_IFMT) == S_IFDIR)
667 return OKAY;
668 return STOP;
670 return OKAY;
673 #ifdef HAVE_FCHDIR
674 FL enum okay
675 cwget(struct cw *cw)
677 if ((cw->cw_fd = open(".", O_RDONLY)) < 0)
678 return STOP;
679 if (fchdir(cw->cw_fd) < 0) {
680 close(cw->cw_fd);
681 return STOP;
683 return OKAY;
686 FL enum okay
687 cwret(struct cw *cw)
689 if (fchdir(cw->cw_fd) < 0)
690 return STOP;
691 return OKAY;
694 FL void
695 cwrelse(struct cw *cw)
697 close(cw->cw_fd);
699 #else /* !HAVE_FCHDIR */
700 FL enum okay
701 cwget(struct cw *cw)
703 if (getcwd(cw->cw_wd, sizeof cw->cw_wd) == NULL || chdir(cw->cw_wd) < 0)
704 return STOP;
705 return OKAY;
708 FL enum okay
709 cwret(struct cw *cw)
711 if (chdir(cw->cw_wd) < 0)
712 return STOP;
713 return OKAY;
716 /*ARGSUSED*/
717 FL void
718 cwrelse(struct cw *cw)
720 (void)cw;
722 #endif /* !HAVE_FCHDIR */
724 FL void
725 makeprint(struct str const *in, struct str *out)
727 static int print_all_chars = -1;
728 char const *inp, *maxp;
729 char *outp;
730 size_t msz, dist;
732 if (print_all_chars == -1)
733 print_all_chars = (value("print-all-chars") != NULL);
735 msz = in->l + 1;
736 out->s = outp = smalloc(msz);
737 inp = in->s;
738 maxp = inp + in->l;
740 if (print_all_chars) {
741 out->l = in->l;
742 memcpy(outp, inp, out->l);
743 goto jleave;
746 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
747 if (mb_cur_max > 1) {
748 char mbb[MB_LEN_MAX + 1];
749 wchar_t wc;
750 int i, n;
751 out->l = 0;
752 while (inp < maxp) {
753 if (*inp & 0200)
754 n = mbtowc(&wc, inp, maxp - inp);
755 else {
756 wc = *inp;
757 n = 1;
759 if (n < 0) {
760 /* FIXME Why mbtowc() resetting here?
761 * FIXME what about ISO 2022-JP plus -- those
762 * FIXME will loose shifts, then!
763 * FIXME THUS - we'd need special "known points"
764 * FIXME to do so - say, after a newline!!
765 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
766 (void)mbtowc(&wc, NULL, mb_cur_max);
767 wc = utf8 ? 0xFFFD : '?';
768 n = 1;
769 } else if (n == 0)
770 n = 1;
771 inp += n;
772 if (!iswprint(wc) && wc != '\n' && wc != '\r' &&
773 wc != '\b' && wc != '\t') {
774 if ((wc & ~(wchar_t)037) == 0)
775 wc = utf8 ? 0x2400 | wc : '?';
776 else if (wc == 0177)
777 wc = utf8 ? 0x2421 : '?';
778 else
779 wc = utf8 ? 0x2426 : '?';
781 if ((n = wctomb(mbb, wc)) <= 0)
782 continue;
783 out->l += n;
784 if (out->l >= msz - 1) {
785 dist = outp - out->s;
786 out->s = srealloc(out->s, msz += 32);
787 outp = &out->s[dist];
789 for (i = 0; i < n; i++)
790 *outp++ = mbb[i];
792 } else
793 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
795 int c;
796 while (inp < maxp) {
797 c = *inp++ & 0377;
798 if (!isprint(c) && c != '\n' && c != '\r' &&
799 c != '\b' && c != '\t')
800 c = '?';
801 *outp++ = c;
803 out->l = in->l;
805 jleave:
806 out->s[out->l] = '\0';
809 FL char *
810 prstr(const char *s)
812 struct str in, out;
813 char *rp;
815 in.s = UNCONST(s);
816 in.l = strlen(s);
817 makeprint(&in, &out);
818 rp = salloc(out.l + 1);
819 memcpy(rp, out.s, out.l);
820 rp[out.l] = '\0';
821 free(out.s);
822 return rp;
825 FL int
826 prout(const char *s, size_t sz, FILE *fp)
828 struct str in, out;
829 int n;
831 in.s = UNCONST(s);
832 in.l = sz;
833 makeprint(&in, &out);
834 n = fwrite(out.s, 1, out.l, fp);
835 free(out.s);
836 return n;
839 FL size_t
840 putuc(int u, int c, FILE *fp)
842 size_t rv;
844 #if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
845 if (utf8 && u & ~(wchar_t)0177) {
846 char mbb[MB_LEN_MAX];
847 int i, n;
848 if ((n = wctomb(mbb, u)) > 0) {
849 rv = wcwidth(u);
850 for (i = 0; i < n; ++i)
851 if (putc(mbb[i] & 0377, fp) == EOF) {
852 rv = 0;
853 break;
855 } else if (n == 0)
856 rv = (putc('\0', fp) != EOF);
857 else
858 rv = 0;
859 } else
860 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
861 rv = (putc(c, fp) != EOF);
862 return rv;
865 FL void
866 time_current_update(struct time_current *tc, bool_t full_update)
868 tc->tc_time = time(NULL);
869 if (full_update) {
870 memcpy(&tc->tc_gm, gmtime(&tc->tc_time), sizeof tc->tc_gm);
871 memcpy(&tc->tc_local, localtime(&tc->tc_time),
872 sizeof tc->tc_local);
873 sstpcpy(tc->tc_ctime, ctime(&tc->tc_time));
877 static void
878 _out_of_memory(void)
880 panic("no memory");
883 FL void *
884 (smalloc_safe)(size_t s SMALLOC_DEBUG_ARGS)
886 void *rv;
888 hold_all_sigs();
889 rv = (smalloc)(s SMALLOC_DEBUG_ARGSCALL);
890 rele_all_sigs();
891 return rv;
894 FL void *
895 (srealloc_safe)(void *v, size_t s SMALLOC_DEBUG_ARGS)
897 void *rv;
899 hold_all_sigs();
900 rv = (srealloc)(v, s SMALLOC_DEBUG_ARGSCALL);
901 rele_all_sigs();
902 return rv;
905 #ifdef notyet
906 FL void *
907 (scalloc_safe)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
909 void *rv;
911 hold_all_sigs();
912 rv = (scalloc)(nmemb, size SMALLOC_DEBUG_ARGSCALL);
913 rele_all_sigs();
914 return rv;
916 #endif
918 #ifndef HAVE_DEBUG
919 FL void *
920 smalloc(size_t s SMALLOC_DEBUG_ARGS)
922 void *rv;
924 if (s == 0)
925 s = 1;
926 if ((rv = malloc(s)) == NULL)
927 _out_of_memory();
928 return rv;
931 FL void *
932 srealloc(void *v, size_t s SMALLOC_DEBUG_ARGS)
934 void *rv;
936 if (s == 0)
937 s = 1;
938 if (v == NULL)
939 rv = smalloc(s);
940 else if ((rv = realloc(v, s)) == NULL)
941 _out_of_memory();
942 return rv;
945 FL void *
946 scalloc(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
948 void *rv;
950 if (size == 0)
951 size = 1;
952 if ((rv = calloc(nmemb, size)) == NULL)
953 _out_of_memory();
954 return rv;
957 #else /* !HAVE_DEBUG */
958 CTA(sizeof(char) == sizeof(ui8_t));
960 # define _HOPE_SIZE (2 * 8 * sizeof(char))
961 # define _HOPE_SET(C) \
962 do {\
963 union ptr __xl, __xu;\
964 struct chunk *__xc;\
965 __xl.p = (C).p;\
966 __xc = __xl.c - 1;\
967 __xu.p = __xc;\
968 (C).cp += 8;\
969 __xl.ui8p[0]=0xDE; __xl.ui8p[1]=0xAA; __xl.ui8p[2]=0x55; __xl.ui8p[3]=0xAD;\
970 __xl.ui8p[4]=0xBE; __xl.ui8p[5]=0x55; __xl.ui8p[6]=0xAA; __xl.ui8p[7]=0xEF;\
971 __xu.ui8p += __xc->size - 8;\
972 __xu.ui8p[0]=0xDE; __xu.ui8p[1]=0xAA; __xu.ui8p[2]=0x55; __xu.ui8p[3]=0xAD;\
973 __xu.ui8p[4]=0xBE; __xu.ui8p[5]=0x55; __xu.ui8p[6]=0xAA; __xu.ui8p[7]=0xEF;\
974 } while (0)
975 # define _HOPE_GET_TRACE(C,BAD) do {(C).cp += 8; _HOPE_GET(C, BAD);} while(0)
976 # define _HOPE_GET(C,BAD) \
977 do {\
978 union ptr __xl, __xu;\
979 struct chunk *__xc;\
980 ui32_t __i;\
981 __xl.p = (C).p;\
982 __xl.cp -= 8;\
983 (C).cp = __xl.cp;\
984 __xc = __xl.c - 1;\
985 (BAD) = FAL0;\
986 __i = 0;\
987 if (__xl.ui8p[0] != 0xDE) __i |= 1<<0;\
988 if (__xl.ui8p[1] != 0xAA) __i |= 1<<1;\
989 if (__xl.ui8p[2] != 0x55) __i |= 1<<2;\
990 if (__xl.ui8p[3] != 0xAD) __i |= 1<<3;\
991 if (__xl.ui8p[4] != 0xBE) __i |= 1<<4;\
992 if (__xl.ui8p[5] != 0x55) __i |= 1<<5;\
993 if (__xl.ui8p[6] != 0xAA) __i |= 1<<6;\
994 if (__xl.ui8p[7] != 0xEF) __i |= 1<<7;\
995 if (__i != 0) {\
996 (BAD) = TRU1;\
997 warn("%p: corrupted lower canary: 0x%02X: %s, line %u",\
998 __xl.p, __i, mdbg_file, mdbg_line);\
1000 __xu.p = __xc;\
1001 __xu.ui8p += __xc->size - 8;\
1002 __i = 0;\
1003 if (__xu.ui8p[0] != 0xDE) __i |= 1<<0;\
1004 if (__xu.ui8p[1] != 0xAA) __i |= 1<<1;\
1005 if (__xu.ui8p[2] != 0x55) __i |= 1<<2;\
1006 if (__xu.ui8p[3] != 0xAD) __i |= 1<<3;\
1007 if (__xu.ui8p[4] != 0xBE) __i |= 1<<4;\
1008 if (__xu.ui8p[5] != 0x55) __i |= 1<<5;\
1009 if (__xu.ui8p[6] != 0xAA) __i |= 1<<6;\
1010 if (__xu.ui8p[7] != 0xEF) __i |= 1<<7;\
1011 if (__i != 0) {\
1012 (BAD) = TRU1;\
1013 warn("%p: corrupted upper canary: 0x%02X: %s, line %u",\
1014 __xl.p, __i, mdbg_file, mdbg_line);\
1016 if (BAD)\
1017 warn(" ..canary last seen: %s, line %u", __xc->file, __xc->line);\
1018 } while (0)
1020 struct chunk {
1021 struct chunk *prev;
1022 struct chunk *next;
1023 char const *file;
1024 ui16_t line;
1025 ui8_t isfree;
1026 ui8_t __dummy;
1027 ui32_t size;
1030 union ptr {
1031 void *p;
1032 struct chunk *c;
1033 char *cp;
1034 ui8_t *ui8p;
1037 struct chunk *_mlist, *_mfree;
1039 FL void *
1040 (smalloc)(size_t s SMALLOC_DEBUG_ARGS)
1042 union ptr p;
1044 if (s == 0)
1045 s = 1;
1046 s += sizeof(struct chunk) + _HOPE_SIZE;
1048 if ((p.p = (malloc)(s)) == NULL)
1049 _out_of_memory();
1050 p.c->prev = NULL;
1051 if ((p.c->next = _mlist) != NULL)
1052 _mlist->prev = p.c;
1053 p.c->file = mdbg_file;
1054 p.c->line = (ui16_t)mdbg_line;
1055 p.c->isfree = FAL0;
1056 p.c->size = (ui32_t)s;
1057 _mlist = p.c++;
1058 _HOPE_SET(p);
1059 return p.p;
1062 FL void *
1063 (srealloc)(void *v, size_t s SMALLOC_DEBUG_ARGS)
1065 union ptr p;
1066 bool_t isbad;
1068 if ((p.p = v) == NULL) {
1069 p.p = (smalloc)(s, mdbg_file, mdbg_line);
1070 goto jleave;
1073 _HOPE_GET(p, isbad);
1074 --p.c;
1075 if (p.c->isfree) {
1076 fprintf(stderr, "srealloc(): region freed! At %s, line %d\n"
1077 "\tLast seen: %s, line %d\n",
1078 mdbg_file, mdbg_line, p.c->file, p.c->line);
1079 goto jforce;
1082 if (p.c == _mlist)
1083 _mlist = p.c->next;
1084 else
1085 p.c->prev->next = p.c->next;
1086 if (p.c->next != NULL)
1087 p.c->next->prev = p.c->prev;
1089 jforce:
1090 if (s == 0)
1091 s = 1;
1092 s += sizeof(struct chunk) + _HOPE_SIZE;
1094 if ((p.p = (realloc)(p.c, s)) == NULL)
1095 _out_of_memory();
1096 p.c->prev = NULL;
1097 if ((p.c->next = _mlist) != NULL)
1098 _mlist->prev = p.c;
1099 p.c->file = mdbg_file;
1100 p.c->line = (ui16_t)mdbg_line;
1101 p.c->isfree = FAL0;
1102 p.c->size = (ui32_t)s;
1103 _mlist = p.c++;
1104 _HOPE_SET(p);
1105 jleave:
1106 return p.p;
1109 FL void *
1110 (scalloc)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1112 union ptr p;
1114 if (size == 0)
1115 size = 1;
1116 if (nmemb == 0)
1117 nmemb = 1;
1118 size *= nmemb;
1119 size += sizeof(struct chunk) + _HOPE_SIZE;
1121 if ((p.p = (malloc)(size)) == NULL)
1122 _out_of_memory();
1123 memset(p.p, 0, size);
1124 p.c->prev = NULL;
1125 if ((p.c->next = _mlist) != NULL)
1126 _mlist->prev = p.c;
1127 p.c->file = mdbg_file;
1128 p.c->line = (ui16_t)mdbg_line;
1129 p.c->isfree = FAL0;
1130 p.c->size = (ui32_t)size;
1131 _mlist = p.c++;
1132 _HOPE_SET(p);
1133 return p.p;
1136 FL void
1137 (sfree)(void *v SMALLOC_DEBUG_ARGS)
1139 union ptr p;
1140 bool_t isbad;
1142 if ((p.p = v) == NULL) {
1143 fprintf(stderr, "sfree(NULL) from %s, line %d\n", mdbg_file, mdbg_line);
1144 goto jleave;
1147 _HOPE_GET(p, isbad);
1148 --p.c;
1149 if (p.c->isfree) {
1150 fprintf(stderr, "sfree(): double-free avoided at %s, line %d\n"
1151 "\tLast seen: %s, line %d\n",
1152 mdbg_file, mdbg_line, p.c->file, p.c->line);
1153 goto jleave;
1156 if (p.c == _mlist)
1157 _mlist = p.c->next;
1158 else
1159 p.c->prev->next = p.c->next;
1160 if (p.c->next != NULL)
1161 p.c->next->prev = p.c->prev;
1162 p.c->isfree = TRU1;
1164 if (options & OPT_DEBUG) {
1165 p.c->next = _mfree;
1166 _mfree = p.c;
1167 } else
1168 (free)(p.c);
1169 jleave:
1173 FL void
1174 smemreset(void)
1176 union ptr p;
1177 size_t c = 0, s = 0;
1179 for (p.c = _mfree; p.c != NULL;) {
1180 void *vp = p.c;
1181 ++c;
1182 s += p.c->size;
1183 p.c = p.c->next;
1184 (free)(vp);
1186 _mfree = NULL;
1188 if (options & OPT_DEBUG)
1189 fprintf(stderr, "smemreset(): freed %" ZFMT " chunks/%" ZFMT " bytes\n",
1190 c, s);
1193 FL int
1194 smemtrace(void *v)
1196 /* For _HOPE_GET() */
1197 char const * const mdbg_file = "smemtrace()";
1198 int const mdbg_line = -1;
1200 FILE *fp;
1201 char *cp;
1202 union ptr p, xp;
1203 bool_t isbad;
1204 size_t lines;
1206 v = (void*)0x1;
1207 if ((fp = Ftemp(&cp, "Ra", "w+", 0600, 1)) == NULL) {
1208 perror("tmpfile");
1209 goto jleave;
1211 rm(cp);
1212 Ftfree(&cp);
1214 fprintf(fp, "Currently allocated memory chunks:\n");
1215 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1216 xp = p;
1217 ++xp.c;
1218 _HOPE_GET_TRACE(xp, isbad);
1219 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1220 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1221 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1224 if (options & OPT_DEBUG) {
1225 fprintf(fp, "sfree()d memory chunks awaiting free():\n");
1226 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1227 xp = p;
1228 ++xp.c;
1229 _HOPE_GET_TRACE(xp, isbad);
1230 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1231 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1232 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1236 page_or_print(fp, lines);
1237 Fclose(fp);
1238 v = NULL;
1239 jleave:
1240 return (v != NULL);
1243 # ifdef MEMCHECK
1244 FL bool_t
1245 _smemcheck(char const *mdbg_file, int mdbg_line)
1247 union ptr p, xp;
1248 bool_t anybad = FAL0, isbad;
1249 size_t lines;
1251 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1252 xp = p;
1253 ++xp.c;
1254 _HOPE_GET_TRACE(xp, isbad);
1255 if (isbad) {
1256 anybad = TRU1;
1257 fprintf(stderr,
1258 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1259 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1260 p.c->file, p.c->line);
1264 if (options & OPT_DEBUG) {
1265 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1266 xp = p;
1267 ++xp.c;
1268 _HOPE_GET_TRACE(xp, isbad);
1269 if (isbad) {
1270 anybad = TRU1;
1271 fprintf(stderr,
1272 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1273 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1274 p.c->file, p.c->line);
1278 return anybad;
1280 # endif /* MEMCHECK */
1281 #endif /* HAVE_DEBUG */
1283 /* vim:set fenc=utf-8:s-it-mode (TODO only partial true) */