1 /* utils.c -- various utility routines
3 * This code is Copyright (c) 2006, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
11 #include <h/signals.h>
16 #include "read_line.h"
18 extern char *mhdocdir
;
20 /* plurals gives the letter ess to indicate a plural noun, or an empty
21 * string as plurals+1 for the singular noun. Used by the PLURALS
23 const char plurals
[] = "s";
26 * We allocate space for messages (msgs array)
27 * this number of elements at a time.
31 /* Call malloc(3), exiting on NULL return. */
33 mh_xmalloc(size_t size
)
38 size
= 1; /* Some mallocs don't like 0. */
41 die("malloc failed, size wanted: %zu", size
);
46 /* Call realloc(3), exiting on NULL return. */
48 mh_xrealloc(void *ptr
, size_t size
)
52 /* Copy POSIX behaviour, coping with non-POSIX systems. */
55 return mh_xmalloc(1); /* Get a unique pointer. */
58 return mh_xmalloc(size
);
60 new = realloc(ptr
, size
);
62 die("realloc failed, size wanted: %zu", size
);
67 /* Call calloc(3), exiting on NULL return. */
69 mh_xcalloc(size_t nelem
, size_t elsize
)
73 if (!nelem
|| !elsize
)
74 return mh_xmalloc(1); /* Get a unique pointer. */
76 p
= calloc(nelem
, elsize
);
78 die("calloc failed, size wanted: %zu * %zu", nelem
, elsize
);
83 /* Duplicate a NUL-terminated string, exit on failure. */
85 mh_xstrdup(const char *src
)
90 n
= strlen(src
) + 1; /* Ignore possibility of overflow. */
98 * Return the present working directory, if the current directory does not
99 * exist, or is too long, make / the pwd.
105 static char curwd
[PATH_MAX
];
107 if (!getcwd (curwd
, PATH_MAX
)) {
108 inform("unable to determine working directory, continuing...");
109 if (!mypath
|| !*mypath
110 || (strcpy (curwd
, mypath
), chdir (curwd
)) == -1) {
112 if (chdir (curwd
) < 0) {
113 advise (curwd
, "chdir");
119 if ((cp
= curwd
+ strlen (curwd
) - 1) > curwd
&& *cp
== '/')
125 /* add returns a newly malloc'd string, exiting on failure. The order
126 * of the parameters is unusual. A NULL parameter is treated as an
127 * empty string. s1 is free'd. Use mh_xstrdup(s) rather than add(s,
128 * NULL), with FENDNULL() if s might be NULL.
130 * add(NULL, NULL) -> ""
131 * add(NULL, "foo") -> "foo"
132 * add("bar", NULL) -> "bar"
133 * add("bar", "foo") -> "foobar"
136 add (const char *s2
, char *s1
)
139 size_t len1
= 0, len2
= 0;
146 cp
= mh_xmalloc (len1
+ len2
+ 1);
148 /* Copy s1 and free it */
150 memcpy (cp
, s1
, len1
);
156 memcpy (cp
+ len1
, s2
, len2
);
158 /* Now NULL terminate the string */
159 cp
[len1
+ len2
] = '\0';
166 * Append an item to a comma separated list
169 addlist (char *list
, const char *item
)
172 list
= add (", ", list
);
174 return add (item
, list
);
179 * Check to see if a folder exists.
182 folder_exists(const char *folder
)
186 return stat(folder
, &st
) != -1;
191 * Check to see if a folder exists, if not, prompt the user to create
195 create_folder(char *folder
, int autocreate
, void (*done_callback
)(int))
201 if (stat (folder
, &st
) == -1) {
203 adios (folder
, "error on folder");
204 if (autocreate
== 0) {
205 /* ask before creating folder */
206 cp
= concat ("Create folder \"", folder
, "\"? ", NULL
);
207 if (!read_yes_or_no_if_tty (cp
))
210 } else if (autocreate
== -1) {
211 /* do not create, so exit */
214 if (!makedir (folder
))
215 die("unable to create folder %s", folder
);
221 * Return the number of digits in a nonnegative integer.
230 die("oops, num_digits called with negative value");
244 * Append a message arg to an array of them, resizing it if necessary.
245 * Really a simple vector-of-(char *) maintenance routine.
248 app_msgarg(struct msgs_array
*msgs
, char *cp
)
250 if(msgs
->size
>= msgs
->max
) {
251 msgs
->max
+= MAXMSGS
;
252 msgs
->msgs
= mh_xrealloc(msgs
->msgs
,
253 msgs
->max
* sizeof(*msgs
->msgs
));
255 msgs
->msgs
[msgs
->size
++] = cp
;
259 * Append a message number to an array of them, resizing it if necessary.
260 * Like app_msgarg, but with a vector-of-ints instead.
264 app_msgnum(struct msgnum_array
*msgs
, int msgnum
)
266 if (msgs
->size
>= msgs
->max
) {
267 msgs
->max
+= MAXMSGS
;
268 msgs
->msgnums
= mh_xrealloc(msgs
->msgnums
,
269 msgs
->max
* sizeof(*msgs
->msgnums
));
271 msgs
->msgnums
[msgs
->size
++] = msgnum
;
276 * Finds first occurrence of str in buf. buf is not a C string but a
277 * byte array of length buflen. str is a null-terminated C string.
278 * find_str() does not modify buf but passes back a non-const char *
279 * pointer so that the caller can modify it.
282 find_str (const char buf
[], size_t buflen
, const char *str
)
284 const size_t len
= strlen (str
);
287 for (i
= 0; i
+ len
<= buflen
; ++i
, ++buf
) {
288 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
296 * Finds last occurrence of str in buf. buf is not a C string but a
297 * byte array of length buflen. str is a null-terminated C string.
298 * find_str() does not modify buf but passes back a non-const char *
299 * pointer so that the caller can modify it.
302 rfind_str (const char buf
[], size_t buflen
, const char *str
)
304 const size_t len
= strlen (str
);
307 for (i
= 0, buf
+= buflen
- len
; i
+ len
<= buflen
; ++i
, --buf
) {
308 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
315 /* POSIX doesn't have strcasestr() so emulate it. */
317 nmh_strcasestr (const char *s1
, const char *s2
)
319 const size_t len
= strlen (s2
);
321 if (isupper ((unsigned char) s2
[0]) || islower ((unsigned char)s2
[0])) {
323 first
[0] = (char) toupper ((unsigned char) s2
[0]);
324 first
[1] = (char) tolower ((unsigned char) s2
[0]);
327 for (s1
= strpbrk (s1
, first
); s1
; s1
= strpbrk (++s1
, first
)) {
328 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
331 for (s1
= strchr (s1
, s2
[0]); s1
; s1
= strchr (++s1
, s2
[0])) {
332 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
340 /* truncpy copies at most size - 1 chars from non-NULL src to non-NULL,
341 * non-overlapping, dst, and ensures dst is NUL terminated. If size is
342 * zero then it aborts as dst cannot be NUL terminated.
344 * It's to be used when truncation is intended and correct, e.g.
345 * reporting a possibly very long external string back to the user. One
346 * of its advantages over strncpy(3) is it doesn't pad in the common
347 * case of no truncation. */
349 trunccpy(char *dst
, const char *src
, size_t size
)
352 inform("trunccpy: zero-length destination: \"%.20s\"",
357 if (strnlen(src
, size
) < size
) {
360 memcpy(dst
, src
, size
- 1);
361 dst
[size
- 1] = '\0';
366 /* has_prefix returns true if non-NULL s starts with non-NULL prefix. */
368 has_prefix(const char *s
, const char *prefix
)
370 while (*s
&& *s
== *prefix
) {
375 return *prefix
== '\0';
379 /* has_suffix returns true if non-NULL s ends with non-NULL suffix. */
381 has_suffix(const char *s
, const char *suffix
)
386 lsuf
= strlen(suffix
);
388 return lsuf
<= ls
&& !strcmp(s
+ ls
- lsuf
, suffix
);
392 /* has_suffix_c returns true if non-NULL string s ends with a c before the
393 * terminating NUL. */
395 has_suffix_c(const char *s
, int c
)
397 return *s
&& s
[strlen(s
) - 1] == c
;
401 /* trim_suffix_c deletes c from the end of non-NULL string s if it's
402 * present, shortening s by 1. Only one instance of c is removed. */
404 trim_suffix_c(char *s
, int c
)
415 /* to_lower runs all of s through tolower(3). */
421 for (b
= (unsigned char *)s
; (*b
= tolower(*b
)); b
++)
426 /* to_upper runs all of s through toupper(3). */
432 for (b
= (unsigned char *)s
; (*b
= toupper(*b
)); b
++)
438 nmh_init(const char *argv0
, bool read_context
, bool check_version
)
443 invo_name
= r1bindex ((char *) argv0
, '/');
445 if (setup_signal_handlers()) {
446 admonish("sigaction", "unable to set up signal handlers");
449 /* POSIX atexit() does not define any error conditions. */
450 if (atexit(remove_registered_files_atexit
)) {
451 admonish("atexit", "unable to register atexit function");
454 /* Read context, if supposed to. */
460 bool allow_version_check
= true;
461 bool check_older_version
= false;
462 if (!check_version
||
463 ((cp
= context_find ("Welcome")) && strcasecmp (cp
, "disable") == 0)) {
464 allow_version_check
= false;
465 } else if ((cp
= getenv ("MHCONTEXT")) != NULL
&& *cp
!= '\0') {
466 /* Context file comes from $MHCONTEXT, so only print the message
467 if the context file has an older version. If it does, or if it
468 doesn't have a version at all, update the version. */
469 check_older_version
= true;
472 /* Check to see if the user is running a different (or older, if
473 specified) version of nmh than they had run before, and notify them
475 if (allow_version_check
&& isatty (fileno (stdin
)) &&
476 isatty (fileno (stdout
)) && isatty (fileno (stderr
))) {
477 if (nmh_version_changed (check_older_version
)) {
478 printf ("==================================================="
479 "=====================\n");
480 printf ("Welcome to nmh version %s\n\n", VERSION
);
481 printf ("See the release notes in %s/NEWS\n\n",
483 print_intro (stdout
, 1);
484 printf ("\nThis message will not be repeated until "
485 "nmh is next updated.\n");
486 printf ("==================================================="
487 "=====================\n\n");
489 fputs ("Press enter to continue: ", stdout
);
495 if ((status
= context_foil(NULL
)) != OK
) {
496 advise("", "failed to create minimal profile/context");
500 /* Allow the user to set a locale in their profile. Otherwise, use the
501 "" string to pull it from their environment, see setlocale(3). */
502 if ((locale
= context_find ("locale")) == NULL
) {
506 if (! setlocale (LC_ALL
, locale
)) {
507 inform("setlocale failed, check your LC_ALL, LC_CTYPE, and LANG "
508 "environment variables, continuing...");
516 * Check stored version, and return 1 if out-of-date or non-existent.
517 * Because the output of "mhparam version" is prefixed with "nmh-",
518 * use that prefix here.
521 nmh_version_changed (int older
)
523 const char *const context_version
= context_find("Version");
526 /* Convert the version strings to floats and compare them. This will
527 break for versions with multiple decimal points, etc. */
528 const float current_version
= strtof (VERSION
, NULL
);
529 const float old_version
=
530 context_version
&& has_prefix(context_version
, "nmh-")
531 ? strtof (context_version
+ 4, NULL
)
534 if (context_version
== NULL
|| old_version
< current_version
) {
535 context_replace ("Version", "nmh-" VERSION
);
538 return old_version
< current_version
;
541 if (context_version
== NULL
|| strcmp(context_version
, "nmh-" VERSION
) != 0) {
542 context_replace ("Version", "nmh-" VERSION
);
550 /* contains8bit returns true if any byte from start onwards fails
551 * isascii(3), i.e. is outside [0, 0x7f]. If start is NULL it returns
552 * false. Bytes are examined until a NUL byte, or, if end is not NULL,
553 * whilst start is before end. */
555 contains8bit(const char *start
, const char *end
)
565 while (p
< end
&& (c
= (*p
++)))
566 if (!isascii((unsigned char)c
))
570 if (!isascii((unsigned char)c
))
579 * See if input has any 8-bit bytes.
582 scan_input (int fd
, int *eightbit
)
588 lseek(fd
, 0, SEEK_SET
);
590 while ((state
= read (fd
, buf
, sizeof buf
)) > 0) {
591 if (contains8bit (buf
, buf
+ state
)) {
597 return state
== NOTOK
? NOTOK
: OK
;
602 * Convert an int to a char string.
607 return m_strn(value
, 0);
612 * Convert an int to a char string, of limited width if > 0.
615 /* SIZE(n) includes NUL. n must just be digits, not an equation. */
616 #define SIZE(n) (sizeof STR(n))
619 m_strn(int value
, unsigned int width
)
621 /* Need to include space for negative sign. But don't use INT_MIN
622 because it could be a macro that would fool SIZE(n). */
623 static char buffer
[SIZE(-INT_MAX
)];
624 const int num_chars
= snprintf(buffer
, sizeof buffer
, "%d", value
);
626 return num_chars
> 0 && (width
== 0 || (unsigned int) num_chars
<= width
)