Add vok_*() family, backed by (non-final) _var_vok*()
[s-mailx.git] / auxlily.c
blob9243446dce1f5feaeae43ecdbe2ad0ad6b3df828
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 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 = ok_blook(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 = ok_vlook(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 = ok_vlook(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;
732 if (print_all_chars == -1)
733 print_all_chars = ok_blook(print_all_chars);
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 #ifdef HAVE_C90AMEND1
747 if (mb_cur_max > 1) {
748 char mbb[MB_LEN_MAX + 1];
749 wchar_t wc;
750 int i, n;
751 size_t dist;
753 out->l = 0;
754 while (inp < maxp) {
755 if (*inp & 0200)
756 n = mbtowc(&wc, inp, maxp - inp);
757 else {
758 wc = *inp;
759 n = 1;
761 if (n < 0) {
762 /* FIXME Why mbtowc() resetting here?
763 * FIXME what about ISO 2022-JP plus -- those
764 * FIXME will loose shifts, then!
765 * FIXME THUS - we'd need special "known points"
766 * FIXME to do so - say, after a newline!!
767 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
768 (void)mbtowc(&wc, NULL, mb_cur_max);
769 wc = utf8 ? 0xFFFD : '?';
770 n = 1;
771 } else if (n == 0)
772 n = 1;
773 inp += n;
774 if (!iswprint(wc) && wc != '\n' && wc != '\r' &&
775 wc != '\b' && wc != '\t') {
776 if ((wc & ~(wchar_t)037) == 0)
777 wc = utf8 ? 0x2400 | wc : '?';
778 else if (wc == 0177)
779 wc = utf8 ? 0x2421 : '?';
780 else
781 wc = utf8 ? 0x2426 : '?';
783 if ((n = wctomb(mbb, wc)) <= 0)
784 continue;
785 out->l += n;
786 if (out->l >= msz - 1) {
787 dist = outp - out->s;
788 out->s = srealloc(out->s, msz += 32);
789 outp = &out->s[dist];
791 for (i = 0; i < n; i++)
792 *outp++ = mbb[i];
794 } else
795 #endif /* C90AMEND1 */
797 int c;
798 while (inp < maxp) {
799 c = *inp++ & 0377;
800 if (!isprint(c) && c != '\n' && c != '\r' &&
801 c != '\b' && c != '\t')
802 c = '?';
803 *outp++ = c;
805 out->l = in->l;
807 jleave:
808 out->s[out->l] = '\0';
811 FL char *
812 prstr(const char *s)
814 struct str in, out;
815 char *rp;
817 in.s = UNCONST(s);
818 in.l = strlen(s);
819 makeprint(&in, &out);
820 rp = salloc(out.l + 1);
821 memcpy(rp, out.s, out.l);
822 rp[out.l] = '\0';
823 free(out.s);
824 return rp;
827 FL int
828 prout(const char *s, size_t sz, FILE *fp)
830 struct str in, out;
831 int n;
833 in.s = UNCONST(s);
834 in.l = sz;
835 makeprint(&in, &out);
836 n = fwrite(out.s, 1, out.l, fp);
837 free(out.s);
838 return n;
841 FL size_t
842 putuc(int u, int c, FILE *fp)
844 size_t rv;
845 UNUSED(u);
847 #ifdef HAVE_C90AMEND1
848 if (utf8 && (u & ~(wchar_t)0177)) {
849 char mbb[MB_LEN_MAX];
850 int i, n;
851 if ((n = wctomb(mbb, u)) > 0) {
852 rv = wcwidth(u);
853 for (i = 0; i < n; ++i)
854 if (putc(mbb[i] & 0377, fp) == EOF) {
855 rv = 0;
856 break;
858 } else if (n == 0)
859 rv = (putc('\0', fp) != EOF);
860 else
861 rv = 0;
862 } else
863 #endif
864 rv = (putc(c, fp) != EOF);
865 return rv;
868 FL void
869 time_current_update(struct time_current *tc, bool_t full_update)
871 tc->tc_time = time(NULL);
872 if (full_update) {
873 memcpy(&tc->tc_gm, gmtime(&tc->tc_time), sizeof tc->tc_gm);
874 memcpy(&tc->tc_local, localtime(&tc->tc_time),
875 sizeof tc->tc_local);
876 sstpcpy(tc->tc_ctime, ctime(&tc->tc_time));
880 static void
881 _out_of_memory(void)
883 panic("no memory");
886 FL void *
887 (smalloc_safe)(size_t s SMALLOC_DEBUG_ARGS)
889 void *rv;
891 hold_all_sigs();
892 rv = (smalloc)(s SMALLOC_DEBUG_ARGSCALL);
893 rele_all_sigs();
894 return rv;
897 FL void *
898 (srealloc_safe)(void *v, size_t s SMALLOC_DEBUG_ARGS)
900 void *rv;
902 hold_all_sigs();
903 rv = (srealloc)(v, s SMALLOC_DEBUG_ARGSCALL);
904 rele_all_sigs();
905 return rv;
908 #ifdef notyet
909 FL void *
910 (scalloc_safe)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
912 void *rv;
914 hold_all_sigs();
915 rv = (scalloc)(nmemb, size SMALLOC_DEBUG_ARGSCALL);
916 rele_all_sigs();
917 return rv;
919 #endif
921 #ifndef HAVE_DEBUG
922 FL void *
923 smalloc(size_t s SMALLOC_DEBUG_ARGS)
925 void *rv;
927 if (s == 0)
928 s = 1;
929 if ((rv = malloc(s)) == NULL)
930 _out_of_memory();
931 return rv;
934 FL void *
935 srealloc(void *v, size_t s SMALLOC_DEBUG_ARGS)
937 void *rv;
939 if (s == 0)
940 s = 1;
941 if (v == NULL)
942 rv = smalloc(s);
943 else if ((rv = realloc(v, s)) == NULL)
944 _out_of_memory();
945 return rv;
948 FL void *
949 scalloc(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
951 void *rv;
953 if (size == 0)
954 size = 1;
955 if ((rv = calloc(nmemb, size)) == NULL)
956 _out_of_memory();
957 return rv;
960 #else /* !HAVE_DEBUG */
961 CTA(sizeof(char) == sizeof(ui8_t));
963 # define _HOPE_SIZE (2 * 8 * sizeof(char))
964 # define _HOPE_SET(C) \
965 do {\
966 union ptr __xl, __xu;\
967 struct chunk *__xc;\
968 __xl.p = (C).p;\
969 __xc = __xl.c - 1;\
970 __xu.p = __xc;\
971 (C).cp += 8;\
972 __xl.ui8p[0]=0xDE; __xl.ui8p[1]=0xAA; __xl.ui8p[2]=0x55; __xl.ui8p[3]=0xAD;\
973 __xl.ui8p[4]=0xBE; __xl.ui8p[5]=0x55; __xl.ui8p[6]=0xAA; __xl.ui8p[7]=0xEF;\
974 __xu.ui8p += __xc->size - 8;\
975 __xu.ui8p[0]=0xDE; __xu.ui8p[1]=0xAA; __xu.ui8p[2]=0x55; __xu.ui8p[3]=0xAD;\
976 __xu.ui8p[4]=0xBE; __xu.ui8p[5]=0x55; __xu.ui8p[6]=0xAA; __xu.ui8p[7]=0xEF;\
977 } while (0)
978 # define _HOPE_GET_TRACE(C,BAD) do {(C).cp += 8; _HOPE_GET(C, BAD);} while(0)
979 # define _HOPE_GET(C,BAD) \
980 do {\
981 union ptr __xl, __xu;\
982 struct chunk *__xc;\
983 ui32_t __i;\
984 __xl.p = (C).p;\
985 __xl.cp -= 8;\
986 (C).cp = __xl.cp;\
987 __xc = __xl.c - 1;\
988 (BAD) = FAL0;\
989 __i = 0;\
990 if (__xl.ui8p[0] != 0xDE) __i |= 1<<0;\
991 if (__xl.ui8p[1] != 0xAA) __i |= 1<<1;\
992 if (__xl.ui8p[2] != 0x55) __i |= 1<<2;\
993 if (__xl.ui8p[3] != 0xAD) __i |= 1<<3;\
994 if (__xl.ui8p[4] != 0xBE) __i |= 1<<4;\
995 if (__xl.ui8p[5] != 0x55) __i |= 1<<5;\
996 if (__xl.ui8p[6] != 0xAA) __i |= 1<<6;\
997 if (__xl.ui8p[7] != 0xEF) __i |= 1<<7;\
998 if (__i != 0) {\
999 (BAD) = TRU1;\
1000 warn("%p: corrupted lower canary: 0x%02X: %s, line %u",\
1001 __xl.p, __i, mdbg_file, mdbg_line);\
1003 __xu.p = __xc;\
1004 __xu.ui8p += __xc->size - 8;\
1005 __i = 0;\
1006 if (__xu.ui8p[0] != 0xDE) __i |= 1<<0;\
1007 if (__xu.ui8p[1] != 0xAA) __i |= 1<<1;\
1008 if (__xu.ui8p[2] != 0x55) __i |= 1<<2;\
1009 if (__xu.ui8p[3] != 0xAD) __i |= 1<<3;\
1010 if (__xu.ui8p[4] != 0xBE) __i |= 1<<4;\
1011 if (__xu.ui8p[5] != 0x55) __i |= 1<<5;\
1012 if (__xu.ui8p[6] != 0xAA) __i |= 1<<6;\
1013 if (__xu.ui8p[7] != 0xEF) __i |= 1<<7;\
1014 if (__i != 0) {\
1015 (BAD) = TRU1;\
1016 warn("%p: corrupted upper canary: 0x%02X: %s, line %u",\
1017 __xl.p, __i, mdbg_file, mdbg_line);\
1019 if (BAD)\
1020 warn(" ..canary last seen: %s, line %u", __xc->file, __xc->line);\
1021 } while (0)
1023 struct chunk {
1024 struct chunk *prev;
1025 struct chunk *next;
1026 char const *file;
1027 ui16_t line;
1028 ui8_t isfree;
1029 ui8_t __dummy;
1030 ui32_t size;
1033 union ptr {
1034 void *p;
1035 struct chunk *c;
1036 char *cp;
1037 ui8_t *ui8p;
1040 struct chunk *_mlist, *_mfree;
1042 FL void *
1043 (smalloc)(size_t s SMALLOC_DEBUG_ARGS)
1045 union ptr p;
1047 if (s == 0)
1048 s = 1;
1049 s += sizeof(struct chunk) + _HOPE_SIZE;
1051 if ((p.p = (malloc)(s)) == NULL)
1052 _out_of_memory();
1053 p.c->prev = NULL;
1054 if ((p.c->next = _mlist) != NULL)
1055 _mlist->prev = p.c;
1056 p.c->file = mdbg_file;
1057 p.c->line = (ui16_t)mdbg_line;
1058 p.c->isfree = FAL0;
1059 p.c->size = (ui32_t)s;
1060 _mlist = p.c++;
1061 _HOPE_SET(p);
1062 return p.p;
1065 FL void *
1066 (srealloc)(void *v, size_t s SMALLOC_DEBUG_ARGS)
1068 union ptr p;
1069 bool_t isbad;
1071 if ((p.p = v) == NULL) {
1072 p.p = (smalloc)(s, mdbg_file, mdbg_line);
1073 goto jleave;
1076 _HOPE_GET(p, isbad);
1077 --p.c;
1078 if (p.c->isfree) {
1079 fprintf(stderr, "srealloc(): region freed! At %s, line %d\n"
1080 "\tLast seen: %s, line %d\n",
1081 mdbg_file, mdbg_line, p.c->file, p.c->line);
1082 goto jforce;
1085 if (p.c == _mlist)
1086 _mlist = p.c->next;
1087 else
1088 p.c->prev->next = p.c->next;
1089 if (p.c->next != NULL)
1090 p.c->next->prev = p.c->prev;
1092 jforce:
1093 if (s == 0)
1094 s = 1;
1095 s += sizeof(struct chunk) + _HOPE_SIZE;
1097 if ((p.p = (realloc)(p.c, s)) == NULL)
1098 _out_of_memory();
1099 p.c->prev = NULL;
1100 if ((p.c->next = _mlist) != NULL)
1101 _mlist->prev = p.c;
1102 p.c->file = mdbg_file;
1103 p.c->line = (ui16_t)mdbg_line;
1104 p.c->isfree = FAL0;
1105 p.c->size = (ui32_t)s;
1106 _mlist = p.c++;
1107 _HOPE_SET(p);
1108 jleave:
1109 return p.p;
1112 FL void *
1113 (scalloc)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1115 union ptr p;
1117 if (size == 0)
1118 size = 1;
1119 if (nmemb == 0)
1120 nmemb = 1;
1121 size *= nmemb;
1122 size += sizeof(struct chunk) + _HOPE_SIZE;
1124 if ((p.p = (malloc)(size)) == NULL)
1125 _out_of_memory();
1126 memset(p.p, 0, size);
1127 p.c->prev = NULL;
1128 if ((p.c->next = _mlist) != NULL)
1129 _mlist->prev = p.c;
1130 p.c->file = mdbg_file;
1131 p.c->line = (ui16_t)mdbg_line;
1132 p.c->isfree = FAL0;
1133 p.c->size = (ui32_t)size;
1134 _mlist = p.c++;
1135 _HOPE_SET(p);
1136 return p.p;
1139 FL void
1140 (sfree)(void *v SMALLOC_DEBUG_ARGS)
1142 union ptr p;
1143 bool_t isbad;
1145 if ((p.p = v) == NULL) {
1146 fprintf(stderr, "sfree(NULL) from %s, line %d\n", mdbg_file, mdbg_line);
1147 goto jleave;
1150 _HOPE_GET(p, isbad);
1151 --p.c;
1152 if (p.c->isfree) {
1153 fprintf(stderr, "sfree(): double-free avoided at %s, line %d\n"
1154 "\tLast seen: %s, line %d\n",
1155 mdbg_file, mdbg_line, p.c->file, p.c->line);
1156 goto jleave;
1159 if (p.c == _mlist)
1160 _mlist = p.c->next;
1161 else
1162 p.c->prev->next = p.c->next;
1163 if (p.c->next != NULL)
1164 p.c->next->prev = p.c->prev;
1165 p.c->isfree = TRU1;
1167 if (options & OPT_DEBUG) {
1168 p.c->next = _mfree;
1169 _mfree = p.c;
1170 } else
1171 (free)(p.c);
1172 jleave:
1176 FL void
1177 smemreset(void)
1179 union ptr p;
1180 size_t c = 0, s = 0;
1182 for (p.c = _mfree; p.c != NULL;) {
1183 void *vp = p.c;
1184 ++c;
1185 s += p.c->size;
1186 p.c = p.c->next;
1187 (free)(vp);
1189 _mfree = NULL;
1191 if (options & OPT_DEBUG)
1192 fprintf(stderr, "smemreset(): freed %" ZFMT " chunks/%" ZFMT " bytes\n",
1193 c, s);
1196 FL int
1197 smemtrace(void *v)
1199 /* For _HOPE_GET() */
1200 char const * const mdbg_file = "smemtrace()";
1201 int const mdbg_line = -1;
1203 FILE *fp;
1204 char *cp;
1205 union ptr p, xp;
1206 bool_t isbad;
1207 size_t lines;
1209 v = (void*)0x1;
1210 if ((fp = Ftemp(&cp, "Ra", "w+", 0600, 1)) == NULL) {
1211 perror("tmpfile");
1212 goto jleave;
1214 rm(cp);
1215 Ftfree(&cp);
1217 fprintf(fp, "Currently allocated memory chunks:\n");
1218 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1219 xp = p;
1220 ++xp.c;
1221 _HOPE_GET_TRACE(xp, isbad);
1222 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1223 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1224 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1227 if (options & OPT_DEBUG) {
1228 fprintf(fp, "sfree()d memory chunks awaiting free():\n");
1229 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1230 xp = p;
1231 ++xp.c;
1232 _HOPE_GET_TRACE(xp, isbad);
1233 fprintf(fp, "%s%p (%5" ZFMT " bytes): %s, line %u\n",
1234 (isbad ? "! CANARY ERROR: " : ""), xp.p,
1235 (size_t)(p.c->size - sizeof(struct chunk)), p.c->file, p.c->line);
1239 page_or_print(fp, lines);
1240 Fclose(fp);
1241 v = NULL;
1242 jleave:
1243 return (v != NULL);
1246 # ifdef MEMCHECK
1247 FL bool_t
1248 _smemcheck(char const *mdbg_file, int mdbg_line)
1250 union ptr p, xp;
1251 bool_t anybad = FAL0, isbad;
1252 size_t lines;
1254 for (lines = 0, p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next) {
1255 xp = p;
1256 ++xp.c;
1257 _HOPE_GET_TRACE(xp, isbad);
1258 if (isbad) {
1259 anybad = TRU1;
1260 fprintf(stderr,
1261 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1262 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1263 p.c->file, p.c->line);
1267 if (options & OPT_DEBUG) {
1268 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next) {
1269 xp = p;
1270 ++xp.c;
1271 _HOPE_GET_TRACE(xp, isbad);
1272 if (isbad) {
1273 anybad = TRU1;
1274 fprintf(stderr,
1275 "! CANARY ERROR: %p (%5" ZFMT " bytes): %s, line %u\n",
1276 xp.p, (size_t)(p.c->size - sizeof(struct chunk)),
1277 p.c->file, p.c->line);
1281 return anybad;
1283 # endif /* MEMCHECK */
1284 #endif /* HAVE_DEBUG */
1286 /* vim:set fenc=utf-8:s-it-mode (TODO only partial true) */