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
43 #include <sys/utsname.h>
61 # include <sys/socket.h>
71 /* {hold,rele}_all_sigs() */
72 static size_t _alls_depth
;
73 static sigset_t _alls_nset
, _alls_oset
;
76 panic(char const *format
, ...)
80 fprintf(stderr
, tr(1, "Panic: "));
83 vfprintf(stderr
, format
, ap
);
94 if (_alls_depth
++ == 0) {
95 sigfillset(&_alls_nset
);
96 sigdelset(&_alls_nset
, SIGKILL
);
97 sigdelset(&_alls_nset
, SIGSTOP
);
98 sigprocmask(SIG_BLOCK
, &_alls_nset
, &_alls_oset
);
105 if (--_alls_depth
== 0)
106 sigprocmask(SIG_SETMASK
, &_alls_oset
, (sigset_t
*)NULL
);
110 * Touch the named message by setting its MTOUCH flag.
111 * Touched messages have the effect of not being sent
112 * back to the system mailbox on exit.
115 touch(struct message
*mp
)
118 mp
->m_flag
|= MTOUCH
;
119 if ((mp
->m_flag
& MREAD
) == 0)
120 mp
->m_flag
|= MREAD
|MSTATUS
;
124 * Test to see if the passed file name is a directory.
125 * Return true if it is.
128 is_dir(char const *name
)
132 if (stat(name
, &sbuf
) < 0)
134 return(S_ISDIR(sbuf
.st_mode
));
138 * Count the number of arguments in the given string raw list.
141 argcount(char **argv
)
145 for (ap
= argv
; *ap
++ != NULL
;)
147 return ap
- argv
- 1;
151 colalign(const char *cp
, int col
, int fill
, int *cols_decr_used_or_null
)
153 int col_orig
= col
, n
, sz
;
156 np
= nb
= salloc(mb_cur_max
* strlen(cp
) + col
+ 1);
158 #if defined (HAVE_MBTOWC) && defined (HAVE_WCWIDTH)
159 if (mb_cur_max
> 1) {
162 if ((sz
= mbtowc(&wc
, cp
, mb_cur_max
)) < 0) {
165 if ((n
= wcwidth(wc
)) < 0)
169 #endif /* HAVE_MBTOWC && HAVE_WCWIDTH */
176 if (sz
== 1 && spacechar(*cp
)) {
184 if (fill
&& col
!= 0) {
186 memmove(nb
+ col
, nb
, (size_t)(np
- nb
));
187 memset(nb
, ' ', col
);
189 memset(np
, ' ', col
);
195 if (cols_decr_used_or_null
!= NULL
)
196 *cols_decr_used_or_null
-= col_orig
- col
;
201 paging_seems_sensible(void)
206 if (IS_TTY_SESSION() && (cp
= voption("crt")) != NULL
)
207 ret
= (*cp
!= '\0') ? (size_t)atol(cp
) : (size_t)scrnheight
;
212 page_or_print(FILE *fp
, size_t lines
)
219 if ((rows
= paging_seems_sensible()) != 0 && lines
== 0) {
220 while ((c
= getc(fp
)) != EOF
)
221 if (c
== '\n' && ++lines
> rows
)
226 if (rows
!= 0 && lines
>= rows
)
227 run_command(get_pager(), 0, fileno(fp
), -1, NULL
, NULL
, NULL
);
229 while ((c
= getc(fp
)) != EOF
)
234 which_protocol(const char *name
)
236 register const char *cp
;
242 if (name
[0] == '%' && name
[1] == ':')
244 for (cp
= name
; *cp
&& *cp
!= ':'; cp
++)
245 if (!alnumchar(*cp
&0377))
247 if (cp
[0] == ':' && cp
[1] == '/' && cp
[2] == '/') {
248 if (strncmp(name
, "pop3://", 7) == 0)
253 tr(216, "No POP3 support compiled in.\n"));
255 if (strncmp(name
, "pop3s://", 8) == 0)
260 tr(225, "No SSL support compiled in.\n"));
262 if (strncmp(name
, "imap://", 7) == 0)
267 tr(269, "No IMAP support compiled in.\n"));
269 if (strncmp(name
, "imaps://", 8) == 0)
274 tr(225, "No SSL support compiled in.\n"));
276 return PROTO_UNKNOWN
;
278 /* TODO This is the de facto maildir code and thus belongs
279 * TODO into maildir! */
280 file
: p
= PROTO_FILE
;
281 np
= ac_alloc((sz
= strlen(name
)) + 5);
282 memcpy(np
, name
, sz
+ 1);
283 if (stat(name
, &st
) == 0) {
284 if (S_ISDIR(st
.st_mode
)) {
285 strcpy(&np
[sz
], "/tmp");
286 if (stat(np
, &st
) == 0 && S_ISDIR(st
.st_mode
)) {
287 strcpy(&np
[sz
], "/new");
288 if (stat(np
, &st
) == 0 &&
289 S_ISDIR(st
.st_mode
)) {
290 strcpy(&np
[sz
], "/cur");
291 if (stat(np
, &st
) == 0 &&
298 strcpy(&np
[sz
], ".gz");
299 if (stat(np
, &st
) < 0) {
300 strcpy(&np
[sz
], ".bz2");
301 if (stat(np
, &st
) < 0) {
302 if ((cp
= value("newfolders")) != 0 &&
303 strcmp(cp
, "maildir") == 0)
320 h
= (h
<< 4 & 0xffffffff) + (*cp
&0377);
321 if ((g
= h
& 0xf0000000) != 0) {
332 const long primes
[] = {
333 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
334 131071, 262139, 524287, 1048573, 2097143, 4194301,
335 8388593, 16777213, 33554393, 67108859, 134217689,
336 268435399, 536870909, 1073741789, 2147483647
341 for (i
= 0; i
< sizeof primes
/ sizeof *primes
; i
++)
342 if ((mprime
= primes
[i
]) >= (n
< 65536 ? n
*4 :
343 n
< 262144 ? n
*2 : n
))
345 if (i
== sizeof primes
/ sizeof *primes
)
346 mprime
= n
; /* not so prime, but better than failure */
351 expand_shell_escape(char const **s
, bool_t use_nail_extensions
)
356 if ((c
= *xs
& 0xFF) == '\0')
362 switch ((c
= *xs
& 0xFF)) {
364 case 'a': c
= '\a'; break;
365 case 'b': c
= '\b'; break;
366 case 'c': c
= -1; break;
367 case 'f': c
= '\f'; break;
368 case 'n': c
= '\n'; break;
369 case 'r': c
= '\r'; break;
370 case 't': c
= '\t'; break;
371 case 'v': c
= '\v'; break;
373 for (++xs
, c
= 0, n
= 4; --n
> 0 && octalchar(*xs
); ++xs
) {
378 /* S-nail extension for nice prompt support */
380 if (use_nail_extensions
) {
381 c
= exec_last_comm_error
? '1' : '0';
386 /* A sole <backslash> at EOS is treated as-is! */
404 if ((ccp
= value("prompt")) == NULL
) {
405 buf
[0] = value("bsdcompat") ? '&' : '?';
411 for (cp
= buf
; cp
< buf
+ sizeof(buf
) - 1; ++cp
) {
412 int c
= expand_shell_escape(&ccp
, TRU1
);
425 struct passwd
*pw
= getpwuid(uid
);
427 return pw
== NULL
? NULL
: pw
->pw_name
;
436 if ((np
= getenv("USER")) != NULL
)
438 if ((np
= getname(uid
= getuid())) != NULL
)
440 panic(tr(201, "Cannot associate a name with uid %d\n"), (int)uid
);
446 nodename(int mayoverride
)
448 static char *hostname
;
453 struct addrinfo hints
, *res
;
455 struct hostent
*hent
;
459 if (mayoverride
&& (hn
= value("hostname")) != NULL
&& *hn
!= '\0') {
460 if (hostname
!= NULL
)
462 hostname
= sstrdup(hn
);
463 } else if (hostname
== NULL
) {
468 memset(&hints
, 0, sizeof hints
);
469 hints
.ai_family
= AF_UNSPEC
;
470 hints
.ai_socktype
= SOCK_DGRAM
; /* dummy */
471 hints
.ai_flags
= AI_CANONNAME
;
472 if (getaddrinfo(hn
, "0", &hints
, &res
) == 0) {
473 if (res
->ai_canonname
!= NULL
) {
474 size_t l
= strlen(res
->ai_canonname
);
475 hn
= ac_alloc(l
+ 1);
476 memcpy(hn
, res
->ai_canonname
, l
+ 1);
481 hent
= gethostbyname(hn
);
487 hostname
= sstrdup(hn
);
488 #if defined HAVE_SOCKETS && defined HAVE_IPV6
489 if (hn
!= ut
.nodename
)
497 lookup_password_for_token(char const *token
)
503 var
= ac_alloc(tl
+ 10);
505 memcpy(var
, "password-", 9);
506 memcpy(var
+ 9, token
, tl
);
509 if ((cp
= value(var
)) != NULL
)
516 getrandstring(size_t length
)
518 static unsigned char nodedigest
[16];
530 data
= ac_alloc(length
);
531 if ((fd
= open("/dev/urandom", O_RDONLY
)) < 0 ||
532 length
!= (size_t)read(fd
, data
, length
)) {
539 MD5Update(&ctx
, (unsigned char *)cp
, strlen(cp
));
540 MD5Final(nodedigest
, &ctx
);
542 /* In that case it's only used for boundaries and
543 * Message-Id:s so that srand(3) should suffice */
545 for (i
= 0; i
< sizeof(nodedigest
); ++i
)
546 nodedigest
[i
] = (unsigned char)(
550 for (i
= 0; i
< length
; i
++)
552 (int)(255 * (rand() / (RAND_MAX
+ 1.0))) ^
553 nodedigest
[i
% sizeof nodedigest
]);
558 (void)b64_encode_buf(&b64
, data
, length
, B64_SALLOC
);
560 assert(length
< b64
.l
);
561 b64
.s
[length
] = '\0';
567 md5tohex(char hex
[MD5TOHEX_SIZE
], void const *vp
)
572 for (i
= 0; i
< MD5TOHEX_SIZE
/ 2; i
++) {
574 hex
[j
] = hexchar((cp
[i
] & 0xf0) >> 4);
575 hex
[++j
] = hexchar(cp
[i
] & 0x0f);
577 hex
[MD5TOHEX_SIZE
] = '\0';
582 cram_md5_string(char const *user
, char const *pass
, char const *b64
)
585 char digest
[16], *cp
;
591 (void)b64_decode(&out
, &in
, NULL
);
592 assert(out
.s
!= NULL
);
594 hmac_md5((unsigned char*)out
.s
, out
.l
, UNCONST(pass
), strlen(pass
),
597 cp
= md5tohex(salloc(MD5TOHEX_SIZE
+ 1), digest
);
600 in
.l
= lu
+ MD5TOHEX_SIZE
+1;
601 in
.s
= ac_alloc(lu
+ 1 + MD5TOHEX_SIZE
+1);
602 memcpy(in
.s
, user
, lu
);
604 memcpy(in
.s
+ lu
+ 1, cp
, MD5TOHEX_SIZE
);
605 (void)b64_encode(&out
, &in
, B64_SALLOC
|B64_CRLF
);
609 #endif /* HAVE_MD5 */
612 makedir(const char *name
)
617 if (mkdir(name
, 0700) < 0) {
619 if ((e
== EEXIST
|| e
== ENOSYS
) &&
620 stat(name
, &st
) == 0 &&
621 (st
.st_mode
&S_IFMT
) == S_IFDIR
)
632 if ((cw
->cw_fd
= open(".", O_RDONLY
)) < 0)
634 if (fchdir(cw
->cw_fd
) < 0) {
644 if (fchdir(cw
->cw_fd
) < 0)
650 cwrelse(struct cw
*cw
)
654 #else /* !HAVE_FCHDIR */
658 if (getcwd(cw
->cw_wd
, sizeof cw
->cw_wd
) == NULL
|| chdir(cw
->cw_wd
) < 0)
666 if (chdir(cw
->cw_wd
) < 0)
673 cwrelse(struct cw
*cw
)
677 #endif /* !HAVE_FCHDIR */
680 makeprint(struct str
const *in
, struct str
*out
)
682 static int print_all_chars
= -1;
683 char const *inp
, *maxp
;
687 if (print_all_chars
== -1)
688 print_all_chars
= (value("print-all-chars") != NULL
);
691 out
->s
= outp
= smalloc(msz
);
695 if (print_all_chars
) {
697 memcpy(outp
, inp
, out
->l
);
701 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
702 if (mb_cur_max
> 1) {
703 char mbb
[MB_LEN_MAX
+ 1];
709 n
= mbtowc(&wc
, inp
, maxp
- inp
);
715 /* FIXME Why mbtowc() resetting here?
716 * FIXME what about ISO 2022-JP plus -- those
717 * FIXME will loose shifts, then!
718 * FIXME THUS - we'd need special "known points"
719 * FIXME to do so - say, after a newline!!
720 * FIXME WE NEED TO CHANGE ALL USES +MBLEN! */
721 (void)mbtowc(&wc
, NULL
, mb_cur_max
);
722 wc
= utf8
? 0xFFFD : '?';
727 if (!iswprint(wc
) && wc
!= '\n' && wc
!= '\r' &&
728 wc
!= '\b' && wc
!= '\t') {
729 if ((wc
& ~(wchar_t)037) == 0)
730 wc
= utf8
? 0x2400 | wc
: '?';
732 wc
= utf8
? 0x2421 : '?';
734 wc
= utf8
? 0x2426 : '?';
736 if ((n
= wctomb(mbb
, wc
)) <= 0)
739 if (out
->l
>= msz
- 1) {
740 dist
= outp
- out
->s
;
741 out
->s
= srealloc(out
->s
, msz
+= 32);
742 outp
= &out
->s
[dist
];
744 for (i
= 0; i
< n
; i
++)
748 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
753 if (!isprint(c
) && c
!= '\n' && c
!= '\r' &&
754 c
!= '\b' && c
!= '\t')
761 out
->s
[out
->l
] = '\0';
772 makeprint(&in
, &out
);
773 rp
= salloc(out
.l
+ 1);
774 memcpy(rp
, out
.s
, out
.l
);
781 prout(const char *s
, size_t sz
, FILE *fp
)
788 makeprint(&in
, &out
);
789 n
= fwrite(out
.s
, 1, out
.l
, fp
);
795 putuc(int u
, int c
, FILE *fp
)
799 #if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
800 if (utf8
&& u
& ~(wchar_t)0177) {
801 char mbb
[MB_LEN_MAX
];
803 if ((n
= wctomb(mbb
, u
)) > 0) {
805 for (i
= 0; i
< n
; ++i
)
806 if (putc(mbb
[i
] & 0377, fp
) == EOF
) {
811 rv
= (putc('\0', fp
) != EOF
);
815 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
816 rv
= (putc(c
, fp
) != EOF
);
821 time_current_update(struct time_current
*tc
, bool_t full_update
)
823 tc
->tc_time
= time(NULL
);
825 memcpy(&tc
->tc_gm
, gmtime(&tc
->tc_time
), sizeof tc
->tc_gm
);
826 memcpy(&tc
->tc_local
, localtime(&tc
->tc_time
),
827 sizeof tc
->tc_local
);
828 sstpcpy(tc
->tc_ctime
, ctime(&tc
->tc_time
));
834 int my_optind
= 1, /*my_opterr = 1,*/ my_optopt
;
837 my_getopt(int argc
, char *const argv
[], char const *optstring
) /* XXX */
839 static char const *lastp
;
843 if (optstring
[0] == ':') {
852 if (optind
>= argc
|| argv
[optind
] == 0 ||
853 argv
[optind
][0] != '-' ||
854 argv
[optind
][1] == '\0')
856 if (argv
[optind
][1] == '-' && argv
[optind
][2] == '\0') {
860 curp
= &argv
[optind
][1];
863 while (optstring
[0]) {
864 if (optstring
[0] == ':' || optstring
[0] != optopt
) {
868 if (optstring
[1] == ':') {
869 if (curp
[1] != '\0') {
870 optarg
= UNCONST(&curp
[1]);
873 if ((optind
+= 2) > argc
) {
874 if (!colon
/*&& opterr*/) {
875 fprintf(stderr
, tr(79,
876 "%s: option requires an argument -- %c\n"),
877 argv
[0], (char)optopt
);
879 return colon
? ':' : '?';
881 optarg
= argv
[optind
- 1];
892 if (!colon
/*&& opterr*/)
893 fprintf(stderr
, tr(78, "%s: illegal option -- %c\n"),
902 #endif /* HAVE_GETOPT */
912 smalloc(size_t s SMALLOC_DEBUG_ARGS
)
918 if ((p
= malloc(s
)) == NULL
)
924 srealloc(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
932 if ((r
= realloc(v
, s
)) == NULL
)
938 scalloc(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
944 if ((vp
= calloc(nmemb
, size
)) == NULL
)
949 #else /* !HAVE_ASSERTS */
965 struct chunk
*_mlist
, *_mfree
;
968 (smalloc
)(size_t s SMALLOC_DEBUG_ARGS
)
974 s
+= sizeof(struct chunk
);
976 if ((p
.p
= malloc(s
)) == NULL
)
979 if ((p
.c
->next
= _mlist
) != NULL
)
981 p
.c
->file
= mdbg_file
;
982 p
.c
->line
= (us_it
)mdbg_line
;
984 p
.c
->size
= (ui_it
)s
;
990 (srealloc
)(void *v
, size_t s SMALLOC_DEBUG_ARGS
)
994 if ((p
.p
= v
) == NULL
) {
995 p
.p
= (smalloc
)(s
, mdbg_file
, mdbg_line
);
1001 fprintf(stderr
, "srealloc(): region freed! At %s, line %d\n"
1002 "\tLast seen: %s, line %d\n",
1003 mdbg_file
, mdbg_line
, p
.c
->file
, p
.c
->line
);
1010 p
.c
->prev
->next
= p
.c
->next
;
1011 if (p
.c
->next
!= NULL
)
1012 p
.c
->next
->prev
= p
.c
->prev
;
1017 s
+= sizeof(struct chunk
);
1019 if ((p
.p
= realloc(p
.c
, s
)) == NULL
)
1022 if ((p
.c
->next
= _mlist
) != NULL
)
1024 p
.c
->file
= mdbg_file
;
1025 p
.c
->line
= (us_it
)mdbg_line
;
1027 p
.c
->size
= (ui_it
)s
;
1034 (scalloc
)(size_t nmemb
, size_t size SMALLOC_DEBUG_ARGS
)
1043 size
+= sizeof(struct chunk
);
1045 if ((p
.p
= malloc(size
)) == NULL
)
1047 memset(p
.p
, 0, size
);
1049 if ((p
.c
->next
= _mlist
) != NULL
)
1051 p
.c
->file
= mdbg_file
;
1052 p
.c
->line
= (us_it
)mdbg_line
;
1054 p
.c
->size
= (ui_it
)size
;
1060 (sfree
)(void *v SMALLOC_DEBUG_ARGS
)
1064 if ((p
.p
= v
) == NULL
) {
1065 fprintf(stderr
, "sfree(NULL) from %s, line %d\n",
1066 mdbg_file
, mdbg_line
);
1072 fprintf(stderr
, "sfree(): double-free avoided at %s, line %d\n"
1073 "\tLast seen: %s, line %d\n",
1074 mdbg_file
, mdbg_line
, p
.c
->file
, p
.c
->line
);
1081 p
.c
->prev
->next
= p
.c
->next
;
1082 if (p
.c
->next
!= NULL
)
1083 p
.c
->next
->prev
= p
.c
->prev
;
1086 if (options
& OPT_DEBUG
) {
1100 for (p
.c
= _mfree
; p
.c
!= NULL
;) {
1109 if (options
& OPT_DEBUG
)
1110 fprintf(stderr
, "smemreset(): freed %lu regions/%lu bytes\n",
1115 (smemtrace
)(void *v
)
1123 if ((fp
= Ftemp(&cp
, "Ra", "w+", 0600, 1)) == NULL
) {
1130 fprintf(fp
, "Currently allocated memory chunks:\n");
1131 for (p
.c
= _mlist
; p
.c
!= NULL
; ++lines
, p
.c
= p
.c
->next
)
1132 fprintf(fp
, "%p (%5u bytes): %s, line %hu\n",
1134 (ui_it
)(p
.c
->size
- sizeof(struct chunk
)),
1135 p
.c
->file
, p
.c
->line
);
1137 if (options
& OPT_DEBUG
) {
1138 fprintf(fp
, "sfree()d memory chunks awaiting free():\n");
1139 for (p
.c
= _mfree
; p
.c
!= NULL
; ++lines
, p
.c
= p
.c
->next
)
1140 fprintf(fp
, "%p (%5u bytes): %s, line %hu\n",
1142 (ui_it
)(p
.c
->size
- sizeof(struct chunk
)),
1143 p
.c
->file
, p
.c
->line
);
1146 page_or_print(fp
, lines
);
1152 #endif /* HAVE_ASSERTS */