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>.
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
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
42 #include <sys/utsname.h>
50 # include <sys/socket.h>
60 /* {hold,rele}_all_sigs() */
61 static size_t _alls_depth
;
62 static sigset_t _alls_nset
, _alls_oset
;
65 panic(char const *format
, ...)
69 fprintf(stderr
, tr(1, "Panic: "));
72 vfprintf(stderr
, format
, ap
);
83 if (_alls_depth
++ == 0) {
84 sigfillset(&_alls_nset
);
85 sigdelset(&_alls_nset
, SIGKILL
);
86 sigdelset(&_alls_nset
, SIGSTOP
);
87 sigprocmask(SIG_BLOCK
, &_alls_nset
, &_alls_oset
);
94 if (--_alls_depth
== 0)
95 sigprocmask(SIG_SETMASK
, &_alls_oset
, (sigset_t
*)NULL
);
99 * Touch the named message by setting its MTOUCH flag.
100 * Touched messages have the effect of not being sent
101 * back to the system mailbox on exit.
104 touch(struct message
*mp
)
107 mp
->m_flag
|= MTOUCH
;
108 if ((mp
->m_flag
& MREAD
) == 0)
109 mp
->m_flag
|= MREAD
|MSTATUS
;
113 * Test to see if the passed file name is a directory.
114 * Return true if it is.
117 is_dir(char const *name
)
121 if (stat(name
, &sbuf
) < 0)
123 return(S_ISDIR(sbuf
.st_mode
));
127 * Count the number of arguments in the given string raw list.
130 argcount(char **argv
)
134 for (ap
= argv
; *ap
++ != NULL
;)
136 return ap
- argv
- 1;
140 colalign(const char *cp
, int col
, int fill
, int *cols_decr_used_or_null
)
142 int col_orig
= col
, n
, sz
;
145 np
= nb
= salloc(mb_cur_max
* strlen(cp
) + col
+ 1);
147 #if defined (HAVE_MBTOWC) && defined (HAVE_WCWIDTH)
148 if (mb_cur_max
> 1) {
151 if ((sz
= mbtowc(&wc
, cp
, mb_cur_max
)) < 0) {
154 if ((n
= wcwidth(wc
)) < 0)
158 #endif /* HAVE_MBTOWC && HAVE_WCWIDTH */
165 if (sz
== 1 && spacechar(*cp
)) {
173 if (fill
&& col
!= 0) {
175 memmove(nb
+ col
, nb
, (size_t)(np
- nb
));
176 memset(nb
, ' ', col
);
178 memset(np
, ' ', col
);
184 if (cols_decr_used_or_null
!= NULL
)
185 *cols_decr_used_or_null
-= col_orig
- col
;
190 paging_seems_sensible(void)
195 if (IS_TTY_SESSION() && (cp
= voption("crt")) != NULL
)
196 ret
= (*cp
!= '\0') ? (size_t)atol(cp
) : (size_t)scrnheight
;
201 page_or_print(FILE *fp
, size_t lines
)
208 if ((rows
= paging_seems_sensible()) != 0 && lines
== 0) {
209 while ((c
= getc(fp
)) != EOF
)
210 if (c
== '\n' && ++lines
> rows
)
215 if (rows
!= 0 && lines
>= rows
)
216 run_command(get_pager(), 0, fileno(fp
), -1, NULL
, NULL
, NULL
);
218 while ((c
= getc(fp
)) != EOF
)
223 which_protocol(const char *name
)
225 register const char *cp
;
231 if (name
[0] == '%' && name
[1] == ':')
233 for (cp
= name
; *cp
&& *cp
!= ':'; cp
++)
234 if (!alnumchar(*cp
&0377))
236 if (cp
[0] == ':' && cp
[1] == '/' && cp
[2] == '/') {
237 if (strncmp(name
, "pop3://", 7) == 0)
242 tr(216, "No POP3 support compiled in.\n"));
244 if (strncmp(name
, "pop3s://", 8) == 0)
249 tr(225, "No SSL support compiled in.\n"));
251 if (strncmp(name
, "imap://", 7) == 0)
256 tr(269, "No IMAP support compiled in.\n"));
258 if (strncmp(name
, "imaps://", 8) == 0)
263 tr(225, "No SSL support compiled in.\n"));
265 return PROTO_UNKNOWN
;
267 /* TODO This is the de facto maildir code and thus belongs
268 * TODO into maildir! */
269 file
: p
= PROTO_FILE
;
270 np
= ac_alloc((sz
= strlen(name
)) + 5);
271 memcpy(np
, name
, sz
+ 1);
272 if (stat(name
, &st
) == 0) {
273 if (S_ISDIR(st
.st_mode
)) {
274 strcpy(&np
[sz
], "/tmp");
275 if (stat(np
, &st
) == 0 && S_ISDIR(st
.st_mode
)) {
276 strcpy(&np
[sz
], "/new");
277 if (stat(np
, &st
) == 0 &&
278 S_ISDIR(st
.st_mode
)) {
279 strcpy(&np
[sz
], "/cur");
280 if (stat(np
, &st
) == 0 &&
287 strcpy(&np
[sz
], ".gz");
288 if (stat(np
, &st
) < 0) {
289 strcpy(&np
[sz
], ".bz2");
290 if (stat(np
, &st
) < 0) {
291 if ((cp
= value("newfolders")) != 0 &&
292 strcmp(cp
, "maildir") == 0)
309 h
= (h
<< 4 & 0xffffffff) + (*cp
&0377);
310 if ((g
= h
& 0xf0000000) != 0) {
321 const long primes
[] = {
322 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
323 131071, 262139, 524287, 1048573, 2097143, 4194301,
324 8388593, 16777213, 33554393, 67108859, 134217689,
325 268435399, 536870909, 1073741789, 2147483647
330 for (i
= 0; i
< sizeof primes
/ sizeof *primes
; i
++)
331 if ((mprime
= primes
[i
]) >= (n
< 65536 ? n
*4 :
332 n
< 262144 ? n
*2 : n
))
334 if (i
== sizeof primes
/ sizeof *primes
)
335 mprime
= n
; /* not so prime, but better than failure */
340 expand_shell_escape(char const **s
, bool_t use_nail_extensions
)
345 if ((c
= *xs
& 0xFF) == '\0')
351 switch ((c
= *xs
& 0xFF)) {
353 case 'a': c
= '\a'; break;
354 case 'b': c
= '\b'; break;
355 case 'c': c
= PROMPT_STOP
;break;
356 case 'f': c
= '\f'; break;
357 case 'n': c
= '\n'; break;
358 case 'r': c
= '\r'; break;
359 case 't': c
= '\t'; break;
360 case 'v': c
= '\v'; break;
362 for (++xs
, c
= 0, n
= 4; --n
> 0 && octalchar(*xs
); ++xs
) {
367 /* S-nail extension for nice (get)prompt(()) support */
371 if (use_nail_extensions
) {
374 c
= exec_last_comm_error
? '1' : '0';
387 /* A sole <backslash> at EOS is treated as-is! */
402 static char buf
[PROMPT_BUFFER_SIZE
];
406 if (options
& OPT_NOPROMPT
)
408 else if ((ccp
= value("prompt")) == NULL
) {
409 buf
[0] = value("bsdcompat") ? '&' : '?';
415 for (cp
= buf
; PTRCMP(cp
, <, buf
+ sizeof(buf
) - 1); ++cp
) {
418 int c
= expand_shell_escape(&ccp
, TRU1
);
423 if (c
== 0 || c
== PROMPT_STOP
)
426 a
= (c
== PROMPT_DOLLAR
) ? account_name
: displayname
;
430 if (PTRCMP(cp
+ l
, >=, buf
+ sizeof(buf
) - 1))
443 nodename(int mayoverride
)
445 static char *hostname
;
450 struct addrinfo hints
, *res
;
452 struct hostent
*hent
;
456 if (mayoverride
&& (hn
= value("hostname")) != NULL
&& *hn
!= '\0') {
457 if (hostname
!= NULL
)
459 hostname
= sstrdup(hn
);
460 } else if (hostname
== NULL
) {
465 memset(&hints
, 0, sizeof hints
);
466 hints
.ai_family
= AF_UNSPEC
;
467 hints
.ai_socktype
= SOCK_DGRAM
; /* dummy */
468 hints
.ai_flags
= AI_CANONNAME
;
469 if (getaddrinfo(hn
, "0", &hints
, &res
) == 0) {
470 if (res
->ai_canonname
!= NULL
) {
471 size_t l
= strlen(res
->ai_canonname
);
472 hn
= ac_alloc(l
+ 1);
473 memcpy(hn
, res
->ai_canonname
, l
+ 1);
478 hent
= gethostbyname(hn
);
484 hostname
= sstrdup(hn
);
485 #if defined HAVE_SOCKETS && defined HAVE_IPV6
486 if (hn
!= ut
.nodename
)
494 lookup_password_for_token(char const *token
)
500 var
= ac_alloc(tl
+ 10);
502 memcpy(var
, "password-", 9);
503 memcpy(var
+ 9, token
, tl
);
506 if ((cp
= value(var
)) != NULL
)
513 getrandstring(size_t length
)
515 static unsigned char nodedigest
[16];
527 data
= ac_alloc(length
);
528 if ((fd
= open("/dev/urandom", O_RDONLY
)) < 0 ||
529 length
!= (size_t)read(fd
, data
, length
)) {
536 MD5Update(&ctx
, (unsigned char *)cp
, strlen(cp
));
537 MD5Final(nodedigest
, &ctx
);
539 /* In that case it's only used for boundaries and
540 * Message-Id:s so that srand(3) should suffice */
542 for (i
= 0; i
< sizeof(nodedigest
); ++i
)
543 nodedigest
[i
] = (unsigned char)(
547 for (i
= 0; i
< length
; i
++)
549 (int)(255 * (rand() / (RAND_MAX
+ 1.0))) ^
550 nodedigest
[i
% sizeof nodedigest
]);
555 (void)b64_encode_buf(&b64
, data
, length
, B64_SALLOC
);
557 assert(length
< b64
.l
);
558 b64
.s
[length
] = '\0';
564 md5tohex(char hex
[MD5TOHEX_SIZE
], void const *vp
)
569 for (i
= 0; i
< MD5TOHEX_SIZE
/ 2; i
++) {
571 hex
[j
] = hexchar((cp
[i
] & 0xf0) >> 4);
572 hex
[++j
] = hexchar(cp
[i
] & 0x0f);
574 hex
[MD5TOHEX_SIZE
] = '\0';
579 cram_md5_string(char const *user
, char const *pass
, char const *b64
)
582 char digest
[16], *cp
;
588 (void)b64_decode(&out
, &in
, NULL
);
589 assert(out
.s
!= NULL
);
591 hmac_md5((unsigned char*)out
.s
, out
.l
, UNCONST(pass
), strlen(pass
),
594 cp
= md5tohex(salloc(MD5TOHEX_SIZE
+ 1), digest
);
597 in
.l
= lu
+ MD5TOHEX_SIZE
+1;
598 in
.s
= ac_alloc(lu
+ 1 + MD5TOHEX_SIZE
+1);
599 memcpy(in
.s
, user
, lu
);
601 memcpy(in
.s
+ lu
+ 1, cp
, MD5TOHEX_SIZE
);
602 (void)b64_encode(&out
, &in
, B64_SALLOC
|B64_CRLF
);
606 #endif /* HAVE_MD5 */
609 makedir(const char *name
)
614 if (mkdir(name
, 0700) < 0) {
616 if ((e
== EEXIST
|| e
== ENOSYS
) &&
617 stat(name
, &st
) == 0 &&
618 (st
.st_mode
&S_IFMT
) == S_IFDIR
)
629 if ((cw
->cw_fd
= open(".", O_RDONLY
)) < 0)
631 if (fchdir(cw
->cw_fd
) < 0) {
641 if (fchdir(cw
->cw_fd
) < 0)
647 cwrelse(struct cw
*cw
)
651 #else /* !HAVE_FCHDIR */
655 if (getcwd(cw
->cw_wd
, sizeof cw
->cw_wd
) == NULL
|| chdir(cw
->cw_wd
) < 0)
663 if (chdir(cw
->cw_wd
) < 0)
670 cwrelse(struct cw
*cw
)
674 #endif /* !HAVE_FCHDIR */
677 makeprint(struct str
const *in
, struct str
*out
)
679 static int print_all_chars
= -1;
680 char const *inp
, *maxp
;
684 if (print_all_chars
== -1)
685 print_all_chars
= (value("print-all-chars") != NULL
);
688 out
->s
= outp
= smalloc(msz
);
692 if (print_all_chars
) {
694 memcpy(outp
, inp
, out
->l
);
698 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
699 if (mb_cur_max
> 1) {
700 char mbb
[MB_LEN_MAX
+ 1];
706 n
= mbtowc(&wc
, inp
, maxp
- inp
);
712 /* FIXME Why mbtowc() resetting here?
713 * FIXME what about ISO 2022-JP plus -- those
714 * FIXME will loose shifts, then!
715 * FIXME THUS - we'd need special "known points"
716 * FIXME to do so - say, after a newline!!
717 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
718 (void)mbtowc(&wc
, NULL
, mb_cur_max
);
719 wc
= utf8
? 0xFFFD : '?';
724 if (!iswprint(wc
) && wc
!= '\n' && wc
!= '\r' &&
725 wc
!= '\b' && wc
!= '\t') {
726 if ((wc
& ~(wchar_t)037) == 0)
727 wc
= utf8
? 0x2400 | wc
: '?';
729 wc
= utf8
? 0x2421 : '?';
731 wc
= utf8
? 0x2426 : '?';
733 if ((n
= wctomb(mbb
, wc
)) <= 0)
736 if (out
->l
>= msz
- 1) {
737 dist
= outp
- out
->s
;
738 out
->s
= srealloc(out
->s
, msz
+= 32);
739 outp
= &out
->s
[dist
];
741 for (i
= 0; i
< n
; i
++)
745 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
750 if (!isprint(c
) && c
!= '\n' && c
!= '\r' &&
751 c
!= '\b' && c
!= '\t')
758 out
->s
[out
->l
] = '\0';
769 makeprint(&in
, &out
);
770 rp
= salloc(out
.l
+ 1);
771 memcpy(rp
, out
.s
, out
.l
);
778 prout(const char *s
, size_t sz
, FILE *fp
)
785 makeprint(&in
, &out
);
786 n
= fwrite(out
.s
, 1, out
.l
, fp
);
792 putuc(int u
, int c
, FILE *fp
)
796 #if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
797 if (utf8
&& u
& ~(wchar_t)0177) {
798 char mbb
[MB_LEN_MAX
];
800 if ((n
= wctomb(mbb
, u
)) > 0) {
802 for (i
= 0; i
< n
; ++i
)
803 if (putc(mbb
[i
] & 0377, fp
) == EOF
) {
808 rv
= (putc('\0', fp
) != EOF
);
812 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
813 rv
= (putc(c
, fp
) != EOF
);
818 time_current_update(struct time_current
*tc
, bool_t full_update
)
820 tc
->tc_time
= time(NULL
);
822 memcpy(&tc
->tc_gm
, gmtime(&tc
->tc_time
), sizeof tc
->tc_gm
);
823 memcpy(&tc
->tc_local
, localtime(&tc
->tc_time
),
824 sizeof tc
->tc_local
);
825 sstpcpy(tc
->tc_ctime
, ctime(&tc
->tc_time
));
831 int my_optind
= 1, /*my_opterr = 1,*/ my_optopt
;
834 my_getopt(int argc
, char *const argv
[], char const *optstring
) /* XXX */
836 static char const *lastp
;
840 if (optstring
[0] == ':') {
849 if (optind
>= argc
|| argv
[optind
] == 0 ||
850 argv
[optind
][0] != '-' ||
851 argv
[optind
][1] == '\0')
853 if (argv
[optind
][1] == '-' && argv
[optind
][2] == '\0') {
857 curp
= &argv
[optind
][1];
860 while (optstring
[0]) {
861 if (optstring
[0] == ':' || optstring
[0] != optopt
) {
865 if (optstring
[1] == ':') {
866 if (curp
[1] != '\0') {
867 optarg
= UNCONST(&curp
[1]);
870 if ((optind
+= 2) > argc
) {
871 if (!colon
/*&& opterr*/) {
872 fprintf(stderr
, tr(79,
873 "%s: option requires an argument -- %c\n"),
874 argv
[0], (char)optopt
);
876 return colon
? ':' : '?';
878 optarg
= argv
[optind
- 1];
889 if (!colon
/*&& opterr*/)
890 fprintf(stderr
, tr(78, "%s: illegal option -- %c\n"),
899 #endif /* HAVE_GETOPT */
908 (smalloc_safe
)(size_t s SMALLOC_DEBUG_ARGS
)
913 rv
= (smalloc
)(s SMALLOC_DEBUG_ARGSCALL
);
919 (srealloc_safe
)(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
924 rv
= (srealloc
)(v
, s SMALLOC_DEBUG_ARGSCALL
);
930 (scalloc_safe
)(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
935 rv
= (scalloc
)(nmemb
, size SMALLOC_DEBUG_ARGSCALL
);
942 smalloc(size_t s SMALLOC_DEBUG_ARGS
)
948 if ((p
= malloc(s
)) == NULL
)
954 srealloc(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
962 if ((r
= realloc(v
, s
)) == NULL
)
968 scalloc(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
974 if ((vp
= calloc(nmemb
, size
)) == NULL
)
979 #else /* !HAVE_ASSERTS */
995 struct chunk
*_mlist
, *_mfree
;
998 (smalloc
)(size_t s SMALLOC_DEBUG_ARGS
)
1004 s
+= sizeof(struct chunk
);
1006 if ((p
.p
= malloc(s
)) == NULL
)
1009 if ((p
.c
->next
= _mlist
) != NULL
)
1011 p
.c
->file
= mdbg_file
;
1012 p
.c
->line
= (us_it
)mdbg_line
;
1014 p
.c
->size
= (ui_it
)s
;
1020 (srealloc
)(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
1024 if ((p
.p
= v
) == NULL
) {
1025 p
.p
= (smalloc
)(s
, mdbg_file
, mdbg_line
);
1031 fprintf(stderr
, "srealloc(): region freed! At %s, line %d\n"
1032 "\tLast seen: %s, line %d\n",
1033 mdbg_file
, mdbg_line
, p
.c
->file
, p
.c
->line
);
1040 p
.c
->prev
->next
= p
.c
->next
;
1041 if (p
.c
->next
!= NULL
)
1042 p
.c
->next
->prev
= p
.c
->prev
;
1047 s
+= sizeof(struct chunk
);
1049 if ((p
.p
= realloc(p
.c
, s
)) == NULL
)
1052 if ((p
.c
->next
= _mlist
) != NULL
)
1054 p
.c
->file
= mdbg_file
;
1055 p
.c
->line
= (us_it
)mdbg_line
;
1057 p
.c
->size
= (ui_it
)s
;
1064 (scalloc
)(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
1073 size
+= sizeof(struct chunk
);
1075 if ((p
.p
= malloc(size
)) == NULL
)
1077 memset(p
.p
, 0, size
);
1079 if ((p
.c
->next
= _mlist
) != NULL
)
1081 p
.c
->file
= mdbg_file
;
1082 p
.c
->line
= (us_it
)mdbg_line
;
1084 p
.c
->size
= (ui_it
)size
;
1090 (sfree
)(void *v SMALLOC_DEBUG_ARGS
)
1094 if ((p
.p
= v
) == NULL
) {
1095 fprintf(stderr
, "sfree(NULL) from %s, line %d\n",
1096 mdbg_file
, mdbg_line
);
1102 fprintf(stderr
, "sfree(): double-free avoided at %s, line %d\n"
1103 "\tLast seen: %s, line %d\n",
1104 mdbg_file
, mdbg_line
, p
.c
->file
, p
.c
->line
);
1111 p
.c
->prev
->next
= p
.c
->next
;
1112 if (p
.c
->next
!= NULL
)
1113 p
.c
->next
->prev
= p
.c
->prev
;
1116 if (options
& OPT_DEBUG
) {
1130 for (p
.c
= _mfree
; p
.c
!= NULL
;) {
1139 if (options
& OPT_DEBUG
)
1140 fprintf(stderr
, "smemreset(): freed %lu regions/%lu bytes\n",
1145 (smemtrace
)(void *v
)
1153 if ((fp
= Ftemp(&cp
, "Ra", "w+", 0600, 1)) == NULL
) {
1160 fprintf(fp
, "Currently allocated memory chunks:\n");
1161 for (p
.c
= _mlist
; p
.c
!= NULL
; ++lines
, p
.c
= p
.c
->next
)
1162 fprintf(fp
, "%p (%5u bytes): %s, line %hu\n",
1164 (ui_it
)(p
.c
->size
- sizeof(struct chunk
)),
1165 p
.c
->file
, p
.c
->line
);
1167 if (options
& OPT_DEBUG
) {
1168 fprintf(fp
, "sfree()d memory chunks awaiting free():\n");
1169 for (p
.c
= _mfree
; p
.c
!= NULL
; ++lines
, p
.c
= p
.c
->next
)
1170 fprintf(fp
, "%p (%5u bytes): %s, line %hu\n",
1172 (ui_it
)(p
.c
->size
- sizeof(struct chunk
)),
1173 p
.c
->file
, p
.c
->line
);
1176 page_or_print(fp
, lines
);
1182 #endif /* HAVE_ASSERTS */