Drop all catgets() in favour of tr()
[s-mailx.git] / auxlily.c
blob8df2c8c152dcdefbe5770070ba90a21ae9870947
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 #include "nail.h"
42 #include <sys/utsname.h>
44 #include <ctype.h>
45 #include <dirent.h>
46 #include <fcntl.h>
47 #include <pwd.h>
49 #ifdef HAVE_SOCKETS
50 # ifdef HAVE_IPV6
51 # include <sys/socket.h>
52 # endif
54 # include <netdb.h>
55 #endif
57 #ifdef HAVE_MD5
58 # include "md5.h"
59 #endif
61 /* {hold,rele}_all_sigs() */
62 static size_t _alls_depth;
63 static sigset_t _alls_nset, _alls_oset;
65 void
66 panic(char const *format, ...)
68 va_list ap;
70 fprintf(stderr, tr(1, "Panic: "));
72 va_start(ap, format);
73 vfprintf(stderr, format, ap);
74 va_end(ap);
76 fputs("\n", stderr);
77 fflush(stderr);
78 abort();
81 void
82 hold_all_sigs(void)
84 if (_alls_depth++ == 0) {
85 sigfillset(&_alls_nset);
86 sigdelset(&_alls_nset, SIGKILL);
87 sigdelset(&_alls_nset, SIGSTOP);
88 sigprocmask(SIG_BLOCK, &_alls_nset, &_alls_oset);
92 void
93 rele_all_sigs(void)
95 if (--_alls_depth == 0)
96 sigprocmask(SIG_SETMASK, &_alls_oset, (sigset_t*)NULL);
100 * Touch the named message by setting its MTOUCH flag.
101 * Touched messages have the effect of not being sent
102 * back to the system mailbox on exit.
104 void
105 touch(struct message *mp)
108 mp->m_flag |= MTOUCH;
109 if ((mp->m_flag & MREAD) == 0)
110 mp->m_flag |= MREAD|MSTATUS;
114 * Test to see if the passed file name is a directory.
115 * Return true if it is.
117 int
118 is_dir(char const *name)
120 struct stat sbuf;
122 if (stat(name, &sbuf) < 0)
123 return(0);
124 return(S_ISDIR(sbuf.st_mode));
128 * Count the number of arguments in the given string raw list.
130 int
131 argcount(char **argv)
133 char **ap;
135 for (ap = argv; *ap++ != NULL;)
137 return ap - argv - 1;
140 char *
141 colalign(const char *cp, int col, int fill, int *cols_decr_used_or_null)
143 int col_orig = col, n, sz;
144 char *nb, *np;
146 np = nb = salloc(mb_cur_max * strlen(cp) + col + 1);
147 while (*cp) {
148 #if defined (HAVE_MBTOWC) && defined (HAVE_WCWIDTH)
149 if (mb_cur_max > 1) {
150 wchar_t wc;
152 if ((sz = mbtowc(&wc, cp, mb_cur_max)) < 0) {
153 n = sz = 1;
154 } else {
155 if ((n = wcwidth(wc)) < 0)
156 n = 1;
158 } else
159 #endif /* HAVE_MBTOWC && HAVE_WCWIDTH */
161 n = sz = 1;
163 if (n > col)
164 break;
165 col -= n;
166 if (sz == 1 && spacechar(*cp)) {
167 *np++ = ' ';
168 cp++;
169 } else
170 while (sz--)
171 *np++ = *cp++;
174 if (fill && col != 0) {
175 if (fill > 0) {
176 memmove(nb + col, nb, (size_t)(np - nb));
177 memset(nb, ' ', col);
178 } else
179 memset(np, ' ', col);
180 np += col;
181 col = 0;
184 *np = '\0';
185 if (cols_decr_used_or_null != NULL)
186 *cols_decr_used_or_null -= col_orig - col;
187 return nb;
190 size_t
191 paging_seems_sensible(void)
193 size_t ret = 0;
194 char const *cp;
196 if (IS_TTY_SESSION() && (cp = voption("crt")) != NULL)
197 ret = (*cp != '\0') ? (size_t)atol(cp) : (size_t)scrnheight;
198 return ret;
201 void
202 page_or_print(FILE *fp, size_t lines)
204 size_t rows;
205 int c;
207 fflush_rewind(fp);
209 if ((rows = paging_seems_sensible()) != 0 && lines == 0) {
210 while ((c = getc(fp)) != EOF)
211 if (c == '\n' && ++lines > rows)
212 break;
213 rewind(fp);
216 if (rows != 0 && lines >= rows)
217 run_command(get_pager(), 0, fileno(fp), -1, NULL, NULL, NULL);
218 else
219 while ((c = getc(fp)) != EOF)
220 putchar(c);
223 enum protocol
224 which_protocol(const char *name)
226 register const char *cp;
227 char *np;
228 size_t sz;
229 struct stat st;
230 enum protocol p;
232 if (name[0] == '%' && name[1] == ':')
233 name += 2;
234 for (cp = name; *cp && *cp != ':'; cp++)
235 if (!alnumchar(*cp&0377))
236 goto file;
237 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
238 if (strncmp(name, "pop3://", 7) == 0)
239 #ifdef HAVE_POP3
240 return PROTO_POP3;
241 #else
242 fprintf(stderr,
243 tr(216, "No POP3 support compiled in.\n"));
244 #endif
245 if (strncmp(name, "pop3s://", 8) == 0)
246 #ifdef HAVE_SSL
247 return PROTO_POP3;
248 #else
249 fprintf(stderr,
250 tr(225, "No SSL support compiled in.\n"));
251 #endif
252 if (strncmp(name, "imap://", 7) == 0)
253 #ifdef HAVE_IMAP
254 return PROTO_IMAP;
255 #else
256 fprintf(stderr,
257 tr(269, "No IMAP support compiled in.\n"));
258 #endif
259 if (strncmp(name, "imaps://", 8) == 0)
260 #ifdef HAVE_SSL
261 return PROTO_IMAP;
262 #else
263 fprintf(stderr,
264 tr(225, "No SSL support compiled in.\n"));
265 #endif
266 return PROTO_UNKNOWN;
267 } else {
268 /* TODO This is the de facto maildir code and thus belongs
269 * TODO into maildir! */
270 file: p = PROTO_FILE;
271 np = ac_alloc((sz = strlen(name)) + 5);
272 memcpy(np, name, sz + 1);
273 if (stat(name, &st) == 0) {
274 if (S_ISDIR(st.st_mode)) {
275 strcpy(&np[sz], "/tmp");
276 if (stat(np, &st) == 0 && S_ISDIR(st.st_mode)) {
277 strcpy(&np[sz], "/new");
278 if (stat(np, &st) == 0 &&
279 S_ISDIR(st.st_mode)) {
280 strcpy(&np[sz], "/cur");
281 if (stat(np, &st) == 0 &&
282 S_ISDIR(st.st_mode))
283 p = PROTO_MAILDIR;
287 } else {
288 strcpy(&np[sz], ".gz");
289 if (stat(np, &st) < 0) {
290 strcpy(&np[sz], ".bz2");
291 if (stat(np, &st) < 0) {
292 if ((cp = value("newfolders")) != 0 &&
293 strcmp(cp, "maildir") == 0)
294 p = PROTO_MAILDIR;
298 ac_free(np);
299 return p;
303 unsigned
304 pjw(const char *cp)
306 unsigned h = 0, g;
308 cp--;
309 while (*++cp) {
310 h = (h << 4 & 0xffffffff) + (*cp&0377);
311 if ((g = h & 0xf0000000) != 0) {
312 h = h ^ g >> 24;
313 h = h ^ g;
316 return h;
319 long
320 nextprime(long n)
322 const long primes[] = {
323 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
324 131071, 262139, 524287, 1048573, 2097143, 4194301,
325 8388593, 16777213, 33554393, 67108859, 134217689,
326 268435399, 536870909, 1073741789, 2147483647
328 long mprime = 7;
329 size_t i;
331 for (i = 0; i < sizeof primes / sizeof *primes; i++)
332 if ((mprime = primes[i]) >= (n < 65536 ? n*4 :
333 n < 262144 ? n*2 : n))
334 break;
335 if (i == sizeof primes / sizeof *primes)
336 mprime = n; /* not so prime, but better than failure */
337 return mprime;
341 expand_shell_escape(char const **s, bool_t use_nail_extensions)
343 char const *xs = *s;
344 int c, n;
346 if ((c = *xs & 0xFF) == '\0')
347 goto jleave;
348 ++xs;
349 if (c != '\\')
350 goto jleave;
352 switch ((c = *xs & 0xFF)) {
353 case '\\': break;
354 case 'a': c = '\a'; break;
355 case 'b': c = '\b'; break;
356 case 'c': c = -1; break;
357 case 'f': c = '\f'; break;
358 case 'n': c = '\n'; break;
359 case 'r': c = '\r'; break;
360 case 't': c = '\t'; break;
361 case 'v': c = '\v'; break;
362 case '0':
363 for (++xs, c = 0, n = 4; --n > 0 && octalchar(*xs); ++xs) {
364 c <<= 3;
365 c |= *xs - '0';
367 goto jleave;
368 /* S-nail extension for nice prompt support */
369 case '?':
370 if (use_nail_extensions) {
371 c = exec_last_comm_error ? '1' : '0';
372 break;
374 /* FALLTHRU */
375 case '\0':
376 /* A sole <backslash> at EOS is treated as-is! */
377 /* FALLTHRU */
378 default:
379 c = '\\';
380 goto jleave;
382 ++xs;
383 jleave:
384 *s = xs;
385 return c;
388 char *
389 getprompt(void)
391 static char buf[64];
392 char const *ccp;
394 if ((ccp = value("prompt")) == NULL) {
395 buf[0] = value("bsdcompat") ? '&' : '?';
396 buf[1] = ' ';
397 buf[2] = '\0';
398 } else {
399 char *cp;
401 for (cp = buf; cp < buf + sizeof(buf) - 1; ++cp) {
402 int c = expand_shell_escape(&ccp, TRU1);
403 if (c <= 0)
404 break;
405 *cp = (char)c;
407 *cp = '\0';
409 return buf;
412 char *
413 getname(int uid)
415 struct passwd *pw = getpwuid(uid);
417 return pw == NULL ? NULL : pw->pw_name;
420 char *
421 username(void)
423 char *np;
424 uid_t uid;
426 if ((np = getenv("USER")) != NULL)
427 goto jleave;
428 if ((np = getname(uid = getuid())) != NULL)
429 goto jleave;
430 panic(tr(201, "Cannot associate a name with uid %d\n"), (int)uid);
431 jleave:
432 return (np);
435 char *
436 nodename(int mayoverride)
438 static char *hostname;
439 struct utsname ut;
440 char *hn;
441 #ifdef HAVE_SOCKETS
442 # ifdef HAVE_IPV6
443 struct addrinfo hints, *res;
444 # else
445 struct hostent *hent;
446 # endif
447 #endif
449 if (mayoverride && (hn = value("hostname")) != NULL && *hn != '\0') {
450 if (hostname != NULL)
451 free(hostname);
452 hostname = sstrdup(hn);
453 } else if (hostname == NULL) {
454 uname(&ut);
455 hn = ut.nodename;
456 #ifdef HAVE_SOCKETS
457 # ifdef HAVE_IPV6
458 memset(&hints, 0, sizeof hints);
459 hints.ai_family = AF_UNSPEC;
460 hints.ai_socktype = SOCK_DGRAM; /* dummy */
461 hints.ai_flags = AI_CANONNAME;
462 if (getaddrinfo(hn, "0", &hints, &res) == 0) {
463 if (res->ai_canonname != NULL) {
464 size_t l = strlen(res->ai_canonname);
465 hn = ac_alloc(l + 1);
466 memcpy(hn, res->ai_canonname, l + 1);
468 freeaddrinfo(res);
470 # else
471 hent = gethostbyname(hn);
472 if (hent != NULL) {
473 hn = hent->h_name;
475 # endif
476 #endif
477 hostname = sstrdup(hn);
478 #if defined HAVE_SOCKETS && defined HAVE_IPV6
479 if (hn != ut.nodename)
480 ac_free(hn);
481 #endif
483 return (hostname);
486 char *
487 lookup_password_for_token(char const *token)
489 size_t tl;
490 char *var, *cp;
492 tl = strlen(token);
493 var = ac_alloc(tl + 10);
495 memcpy(var, "password-", 9);
496 memcpy(var + 9, token, tl);
497 var[tl + 9] = '\0';
499 if ((cp = value(var)) != NULL)
500 cp = savestr(cp);
501 ac_free(var);
502 return cp;
505 char *
506 getrandstring(size_t length)
508 static unsigned char nodedigest[16];
509 static pid_t pid;
510 struct str b64;
511 int fd = -1;
512 char *data, *cp;
513 size_t i;
514 #ifdef HAVE_MD5
515 MD5_CTX ctx;
516 #else
517 size_t j;
518 #endif
520 data = ac_alloc(length);
521 if ((fd = open("/dev/urandom", O_RDONLY)) < 0 ||
522 length != (size_t)read(fd, data, length)) {
523 if (pid == 0) {
524 pid = getpid();
525 srand(pid);
526 cp = nodename(0);
527 #ifdef HAVE_MD5
528 MD5Init(&ctx);
529 MD5Update(&ctx, (unsigned char *)cp, strlen(cp));
530 MD5Final(nodedigest, &ctx);
531 #else
532 /* In that case it's only used for boundaries and
533 * Message-Id:s so that srand(3) should suffice */
534 j = strlen(cp) + 1;
535 for (i = 0; i < sizeof(nodedigest); ++i)
536 nodedigest[i] = (unsigned char)(
537 cp[i % j] ^ rand());
538 #endif
540 for (i = 0; i < length; i++)
541 data[i] = (char)(
542 (int)(255 * (rand() / (RAND_MAX + 1.0))) ^
543 nodedigest[i % sizeof nodedigest]);
545 if (fd >= 0)
546 close(fd);
548 (void)b64_encode_buf(&b64, data, length, B64_SALLOC);
549 ac_free(data);
550 assert(length < b64.l);
551 b64.s[length] = '\0';
552 return b64.s;
555 #ifdef HAVE_MD5
556 char *
557 md5tohex(char hex[MD5TOHEX_SIZE], void const *vp)
559 char const *cp = vp;
560 size_t i, j;
562 for (i = 0; i < MD5TOHEX_SIZE / 2; i++) {
563 j = i << 1;
564 hex[j] = hexchar((cp[i] & 0xf0) >> 4);
565 hex[++j] = hexchar(cp[i] & 0x0f);
567 hex[MD5TOHEX_SIZE] = '\0';
568 return hex;
571 char *
572 cram_md5_string(char const *user, char const *pass, char const *b64)
574 struct str in, out;
575 char digest[16], *cp;
576 size_t lu;
578 out.s = NULL;
579 in.s = UNCONST(b64);
580 in.l = strlen(in.s);
581 (void)b64_decode(&out, &in, NULL);
582 assert(out.s != NULL);
584 hmac_md5((unsigned char*)out.s, out.l, UNCONST(pass), strlen(pass),
585 digest);
586 free(out.s);
587 cp = md5tohex(salloc(MD5TOHEX_SIZE + 1), digest);
589 lu = strlen(user);
590 in.l = lu + MD5TOHEX_SIZE +1;
591 in.s = ac_alloc(lu + 1 + MD5TOHEX_SIZE +1);
592 memcpy(in.s, user, lu);
593 in.s[lu] = ' ';
594 memcpy(in.s + lu + 1, cp, MD5TOHEX_SIZE);
595 (void)b64_encode(&out, &in, B64_SALLOC|B64_CRLF);
596 ac_free(in.s);
597 return out.s;
599 #endif /* HAVE_MD5 */
601 enum okay
602 makedir(const char *name)
604 int e;
605 struct stat st;
607 if (mkdir(name, 0700) < 0) {
608 e = errno;
609 if ((e == EEXIST || e == ENOSYS) &&
610 stat(name, &st) == 0 &&
611 (st.st_mode&S_IFMT) == S_IFDIR)
612 return OKAY;
613 return STOP;
615 return OKAY;
618 #ifdef HAVE_FCHDIR
619 enum okay
620 cwget(struct cw *cw)
622 if ((cw->cw_fd = open(".", O_RDONLY)) < 0)
623 return STOP;
624 if (fchdir(cw->cw_fd) < 0) {
625 close(cw->cw_fd);
626 return STOP;
628 return OKAY;
631 enum okay
632 cwret(struct cw *cw)
634 if (fchdir(cw->cw_fd) < 0)
635 return STOP;
636 return OKAY;
639 void
640 cwrelse(struct cw *cw)
642 close(cw->cw_fd);
644 #else /* !HAVE_FCHDIR */
645 enum okay
646 cwget(struct cw *cw)
648 if (getcwd(cw->cw_wd, sizeof cw->cw_wd) == NULL || chdir(cw->cw_wd) < 0)
649 return STOP;
650 return OKAY;
653 enum okay
654 cwret(struct cw *cw)
656 if (chdir(cw->cw_wd) < 0)
657 return STOP;
658 return OKAY;
661 /*ARGSUSED*/
662 void
663 cwrelse(struct cw *cw)
665 (void)cw;
667 #endif /* !HAVE_FCHDIR */
669 void
670 makeprint(struct str const *in, struct str *out)
672 static int print_all_chars = -1;
673 char const *inp, *maxp;
674 char *outp;
675 size_t msz, dist;
677 if (print_all_chars == -1)
678 print_all_chars = (value("print-all-chars") != NULL);
680 msz = in->l + 1;
681 out->s = outp = smalloc(msz);
682 inp = in->s;
683 maxp = inp + in->l;
685 if (print_all_chars) {
686 out->l = in->l;
687 memcpy(outp, inp, out->l);
688 goto jleave;
691 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
692 if (mb_cur_max > 1) {
693 char mbb[MB_LEN_MAX + 1];
694 wchar_t wc;
695 int i, n;
696 out->l = 0;
697 while (inp < maxp) {
698 if (*inp & 0200)
699 n = mbtowc(&wc, inp, maxp - inp);
700 else {
701 wc = *inp;
702 n = 1;
704 if (n < 0) {
705 /* FIXME Why mbtowc() resetting here?
706 * FIXME what about ISO 2022-JP plus -- those
707 * FIXME will loose shifts, then!
708 * FIXME THUS - we'd need special "known points"
709 * FIXME to do so - say, after a newline!!
710 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
711 (void)mbtowc(&wc, NULL, mb_cur_max);
712 wc = utf8 ? 0xFFFD : '?';
713 n = 1;
714 } else if (n == 0)
715 n = 1;
716 inp += n;
717 if (!iswprint(wc) && wc != '\n' && wc != '\r' &&
718 wc != '\b' && wc != '\t') {
719 if ((wc & ~(wchar_t)037) == 0)
720 wc = utf8 ? 0x2400 | wc : '?';
721 else if (wc == 0177)
722 wc = utf8 ? 0x2421 : '?';
723 else
724 wc = utf8 ? 0x2426 : '?';
726 if ((n = wctomb(mbb, wc)) <= 0)
727 continue;
728 out->l += n;
729 if (out->l >= msz - 1) {
730 dist = outp - out->s;
731 out->s = srealloc(out->s, msz += 32);
732 outp = &out->s[dist];
734 for (i = 0; i < n; i++)
735 *outp++ = mbb[i];
737 } else
738 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
740 int c;
741 while (inp < maxp) {
742 c = *inp++ & 0377;
743 if (!isprint(c) && c != '\n' && c != '\r' &&
744 c != '\b' && c != '\t')
745 c = '?';
746 *outp++ = c;
748 out->l = in->l;
750 jleave:
751 out->s[out->l] = '\0';
754 char *
755 prstr(const char *s)
757 struct str in, out;
758 char *rp;
760 in.s = UNCONST(s);
761 in.l = strlen(s);
762 makeprint(&in, &out);
763 rp = salloc(out.l + 1);
764 memcpy(rp, out.s, out.l);
765 rp[out.l] = '\0';
766 free(out.s);
767 return rp;
771 prout(const char *s, size_t sz, FILE *fp)
773 struct str in, out;
774 int n;
776 in.s = UNCONST(s);
777 in.l = sz;
778 makeprint(&in, &out);
779 n = fwrite(out.s, 1, out.l, fp);
780 free(out.s);
781 return n;
784 size_t
785 putuc(int u, int c, FILE *fp)
787 size_t rv;
789 #if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
790 if (utf8 && u & ~(wchar_t)0177) {
791 char mbb[MB_LEN_MAX];
792 int i, n;
793 if ((n = wctomb(mbb, u)) > 0) {
794 rv = wcwidth(u);
795 for (i = 0; i < n; ++i)
796 if (putc(mbb[i] & 0377, fp) == EOF) {
797 rv = 0;
798 break;
800 } else if (n == 0)
801 rv = (putc('\0', fp) != EOF);
802 else
803 rv = 0;
804 } else
805 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
806 rv = (putc(c, fp) != EOF);
807 return rv;
810 void
811 time_current_update(struct time_current *tc, bool_t full_update)
813 tc->tc_time = time(NULL);
814 if (full_update) {
815 memcpy(&tc->tc_gm, gmtime(&tc->tc_time), sizeof tc->tc_gm);
816 memcpy(&tc->tc_local, localtime(&tc->tc_time),
817 sizeof tc->tc_local);
818 sstpcpy(tc->tc_ctime, ctime(&tc->tc_time));
822 #ifndef HAVE_GETOPT
823 char *my_optarg;
824 int my_optind = 1, /*my_opterr = 1,*/ my_optopt;
827 my_getopt(int argc, char *const argv[], char const *optstring) /* XXX */
829 static char const *lastp;
830 int colon;
831 char const *curp;
833 if (optstring[0] == ':') {
834 colon = 1;
835 optstring++;
836 } else
837 colon = 0;
838 if (lastp) {
839 curp = lastp;
840 lastp = 0;
841 } else {
842 if (optind >= argc || argv[optind] == 0 ||
843 argv[optind][0] != '-' ||
844 argv[optind][1] == '\0')
845 return -1;
846 if (argv[optind][1] == '-' && argv[optind][2] == '\0') {
847 optind++;
848 return -1;
850 curp = &argv[optind][1];
852 optopt = curp[0];
853 while (optstring[0]) {
854 if (optstring[0] == ':' || optstring[0] != optopt) {
855 optstring++;
856 continue;
858 if (optstring[1] == ':') {
859 if (curp[1] != '\0') {
860 optarg = UNCONST(&curp[1]);
861 optind++;
862 } else {
863 if ((optind += 2) > argc) {
864 if (!colon /*&& opterr*/) {
865 fprintf(stderr, tr(79,
866 "%s: option requires an argument -- %c\n"),
867 argv[0], (char)optopt);
869 return colon ? ':' : '?';
871 optarg = argv[optind - 1];
873 } else {
874 if (curp[1] != '\0')
875 lastp = &curp[1];
876 else
877 optind++;
878 optarg = 0;
880 return optopt;
882 if (!colon /*&& opterr*/)
883 fprintf(stderr, tr(78, "%s: illegal option -- %c\n"),
884 argv[0], optopt);
885 if (curp[1] != '\0')
886 lastp = &curp[1];
887 else
888 optind++;
889 optarg = 0;
890 return '?';
892 #endif /* HAVE_GETOPT */
894 static void
895 out_of_memory(void)
897 panic("no memory");
900 void *
901 (smalloc_safe)(size_t s SMALLOC_DEBUG_ARGS)
903 void *rv;
905 hold_all_sigs();
906 rv = (smalloc)(s SMALLOC_DEBUG_ARGSCALL);
907 rele_all_sigs();
908 return rv;
911 void *
912 (srealloc_safe)(void *v, size_t s SMALLOC_DEBUG_ARGS)
914 void *rv;
916 hold_all_sigs();
917 rv = (srealloc)(v, s SMALLOC_DEBUG_ARGSCALL);
918 rele_all_sigs();
919 return rv;
922 void *
923 (scalloc_safe)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
925 void *rv;
927 hold_all_sigs();
928 rv = (scalloc)(nmemb, size SMALLOC_DEBUG_ARGSCALL);
929 rele_all_sigs();
930 return rv;
933 #ifndef HAVE_ASSERTS
934 void *
935 smalloc(size_t s SMALLOC_DEBUG_ARGS)
937 void *p;
939 if (s == 0)
940 s = 1;
941 if ((p = malloc(s)) == NULL)
942 out_of_memory();
943 return p;
946 void *
947 srealloc(void *v, size_t s SMALLOC_DEBUG_ARGS)
949 void *r;
951 if (s == 0)
952 s = 1;
953 if (v == NULL)
954 return smalloc(s);
955 if ((r = realloc(v, s)) == NULL)
956 out_of_memory();
957 return r;
960 void *
961 scalloc(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
963 void *vp;
965 if (size == 0)
966 size = 1;
967 if ((vp = calloc(nmemb, size)) == NULL)
968 out_of_memory();
969 return vp;
972 #else /* !HAVE_ASSERTS */
973 struct chunk {
974 struct chunk *prev;
975 struct chunk *next;
976 char const *file;
977 us_it line;
978 uc_it isfree;
979 sc_it __dummy;
980 ui_it size;
983 union ptr {
984 struct chunk *c;
985 void *p;
988 struct chunk *_mlist, *_mfree;
990 void *
991 (smalloc)(size_t s SMALLOC_DEBUG_ARGS)
993 union ptr p;
995 if (s == 0)
996 s = 1;
997 s += sizeof(struct chunk);
999 if ((p.p = malloc(s)) == NULL)
1000 out_of_memory();
1001 p.c->prev = NULL;
1002 if ((p.c->next = _mlist) != NULL)
1003 _mlist->prev = p.c;
1004 p.c->file = mdbg_file;
1005 p.c->line = (us_it)mdbg_line;
1006 p.c->isfree = 0;
1007 p.c->size = (ui_it)s;
1008 _mlist = p.c++;
1009 return (p.p);
1012 void *
1013 (srealloc)(void *v, size_t s SMALLOC_DEBUG_ARGS)
1015 union ptr p;
1017 if ((p.p = v) == NULL) {
1018 p.p = (smalloc)(s, mdbg_file, mdbg_line);
1019 goto jleave;
1022 --p.c;
1023 if (p.c->isfree) {
1024 fprintf(stderr, "srealloc(): region freed! At %s, line %d\n"
1025 "\tLast seen: %s, line %d\n",
1026 mdbg_file, mdbg_line, p.c->file, p.c->line);
1027 goto jforce;
1030 if (p.c == _mlist)
1031 _mlist = p.c->next;
1032 else
1033 p.c->prev->next = p.c->next;
1034 if (p.c->next != NULL)
1035 p.c->next->prev = p.c->prev;
1037 jforce:
1038 if (s == 0)
1039 s = 1;
1040 s += sizeof(struct chunk);
1042 if ((p.p = realloc(p.c, s)) == NULL)
1043 out_of_memory();
1044 p.c->prev = NULL;
1045 if ((p.c->next = _mlist) != NULL)
1046 _mlist->prev = p.c;
1047 p.c->file = mdbg_file;
1048 p.c->line = (us_it)mdbg_line;
1049 p.c->isfree = 0;
1050 p.c->size = (ui_it)s;
1051 _mlist = p.c++;
1052 jleave:
1053 return (p.p);
1056 void *
1057 (scalloc)(size_t nmemb, size_t size SMALLOC_DEBUG_ARGS)
1059 union ptr p;
1061 if (size == 0)
1062 size = 1;
1063 if (nmemb == 0)
1064 nmemb = 1;
1065 size *= nmemb;
1066 size += sizeof(struct chunk);
1068 if ((p.p = malloc(size)) == NULL)
1069 out_of_memory();
1070 memset(p.p, 0, size);
1071 p.c->prev = NULL;
1072 if ((p.c->next = _mlist) != NULL)
1073 _mlist->prev = p.c;
1074 p.c->file = mdbg_file;
1075 p.c->line = (us_it)mdbg_line;
1076 p.c->isfree = 0;
1077 p.c->size = (ui_it)size;
1078 _mlist = p.c++;
1079 return (p.p);
1082 void
1083 (sfree)(void *v SMALLOC_DEBUG_ARGS)
1085 union ptr p;
1087 if ((p.p = v) == NULL) {
1088 fprintf(stderr, "sfree(NULL) from %s, line %d\n",
1089 mdbg_file, mdbg_line);
1090 goto jleave;
1093 --p.c;
1094 if (p.c->isfree) {
1095 fprintf(stderr, "sfree(): double-free avoided at %s, line %d\n"
1096 "\tLast seen: %s, line %d\n",
1097 mdbg_file, mdbg_line, p.c->file, p.c->line);
1098 goto jleave;
1101 if (p.c == _mlist)
1102 _mlist = p.c->next;
1103 else
1104 p.c->prev->next = p.c->next;
1105 if (p.c->next != NULL)
1106 p.c->next->prev = p.c->prev;
1107 p.c->isfree = 1;
1109 if (options & OPT_DEBUG) {
1110 p.c->next = _mfree;
1111 _mfree = p.c;
1112 } else
1113 (free)(p.c);
1114 jleave: ;
1117 void
1118 smemreset(void)
1120 union ptr p;
1121 ul_it c = 0, s = 0;
1123 for (p.c = _mfree; p.c != NULL;) {
1124 void *vp = p.c;
1125 ++c;
1126 s += p.c->size;
1127 p.c = p.c->next;
1128 (free)(vp);
1130 _mfree = NULL;
1132 if (options & OPT_DEBUG)
1133 fprintf(stderr, "smemreset(): freed %lu regions/%lu bytes\n",
1134 c, s);
1138 (smemtrace)(void *v)
1140 FILE *fp;
1141 char *cp;
1142 union ptr p;
1143 size_t lines = 0;
1145 v = (void*)0x1;
1146 if ((fp = Ftemp(&cp, "Ra", "w+", 0600, 1)) == NULL) {
1147 perror("tmpfile");
1148 goto jleave;
1150 rm(cp);
1151 Ftfree(&cp);
1153 fprintf(fp, "Currently allocated memory chunks:\n");
1154 for (p.c = _mlist; p.c != NULL; ++lines, p.c = p.c->next)
1155 fprintf(fp, "%p (%5u bytes): %s, line %hu\n",
1156 (void*)(p.c + 1),
1157 (ui_it)(p.c->size - sizeof(struct chunk)),
1158 p.c->file, p.c->line);
1160 if (options & OPT_DEBUG) {
1161 fprintf(fp, "sfree()d memory chunks awaiting free():\n");
1162 for (p.c = _mfree; p.c != NULL; ++lines, p.c = p.c->next)
1163 fprintf(fp, "%p (%5u bytes): %s, line %hu\n",
1164 (void*)(p.c + 1),
1165 (ui_it)(p.c->size - sizeof(struct chunk)),
1166 p.c->file, p.c->line);
1169 page_or_print(fp, lines);
1170 Fclose(fp);
1171 v = NULL;
1172 jleave:
1173 return (v != NULL);
1175 #endif /* HAVE_ASSERTS */