3 * utils.c -- various utility routines
5 * This code is Copyright (c) 2006, by the authors of nmh. See the
6 * COPYRIGHT file in the root directory of the nmh distribution for
7 * complete copyright information.
15 extern int setup_signal_handlers();
18 extern void remove_registered_files_atexit();
20 extern char *mhdocdir
;
23 * We allocate space for messages (msgs array)
24 * this number of elements at a time.
28 /* Call malloc(3), exiting on NULL return. */
29 void *mh_xmalloc(size_t size
)
34 size
= 1; /* Some mallocs don't like 0. */
37 adios(NULL
, "malloc failed, size wanted: %zu", size
);
42 /* Call realloc(3), exiting on NULL return. */
43 void *mh_xrealloc(void *ptr
, size_t size
)
47 /* Copy POSIX behaviour, coping with non-POSIX systems. */
50 return mh_xmalloc(1); /* Get a unique pointer. */
53 return mh_xmalloc(size
);
55 new = realloc(ptr
, size
);
57 adios(NULL
, "realloc failed, size wanted: %zu", size
);
62 /* Call calloc(3), exiting on NULL return. */
63 void *mh_xcalloc(size_t nelem
, size_t elsize
)
67 if (!nelem
|| !elsize
)
68 return mh_xmalloc(1); /* Get a unique pointer. */
70 p
= calloc(nelem
, elsize
);
72 adios(NULL
, "calloc failed, size wanted: %zu * %zu", nelem
, elsize
);
77 /* Duplicate a NUL-terminated string, exit on failure. */
78 char *mh_xstrdup(const char *src
)
83 n
= strlen(src
) + 1; /* Ignore possibility of overflow. */
90 /* Call free(3), if ptr isn't NULL. */
91 void mh_xfree(void *ptr
)
94 free(ptr
); /* Some very old platforms can't cope with NULL. */
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 admonish (NULL
, "unable to determine working directory");
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
== '/')
126 * add -- If "s1" is NULL, this routine just creates a
127 * -- copy of "s2" into newly malloc'ed memory.
129 * -- If "s1" is not NULL, then copy the concatenation
130 * -- of "s1" and "s2" (note the order) into newly
131 * -- malloc'ed memory. Then free "s1".
134 add (const char *s2
, char *s1
)
137 size_t len1
= 0, len2
= 0;
144 cp
= mh_xmalloc (len1
+ len2
+ 1);
146 /* Copy s1 and free it */
148 memcpy (cp
, s1
, len1
);
154 memcpy (cp
+ len1
, s2
, len2
);
156 /* Now NULL terminate the string */
157 cp
[len1
+ len2
] = '\0';
164 * Append an item to a comma separated list
167 addlist (char *list
, const char *item
)
170 list
= add (", ", list
);
172 return add (item
, list
);
177 * Check to see if a folder exists.
179 int folder_exists(const char *folder
)
183 return stat(folder
, &st
) != -1;
188 * Check to see if a folder exists, if not, prompt the user to create
191 void create_folder(char *folder
, int autocreate
, void (*done_callback
)(int))
197 if (stat (folder
, &st
) == -1) {
199 adios (folder
, "error on folder");
200 if (autocreate
== 0) {
201 /* ask before creating folder */
202 cp
= concat ("Create folder \"", folder
, "\"? ", NULL
);
203 if (!read_yes_or_no_if_tty (cp
))
206 } else if (autocreate
== -1) {
207 /* do not create, so exit */
210 if (!makedir (folder
))
211 adios (NULL
, "unable to create folder %s", folder
);
217 * Return the number of digits in a nonnegative integer.
226 adios (NULL
, "oops, num_digits called with negative value");
240 * Append a message arg to an array of them, resizing it if necessary.
241 * Really a simple vector-of-(char *) maintenance routine.
244 app_msgarg(struct msgs_array
*msgs
, char *cp
)
246 if(msgs
->size
>= msgs
->max
) {
247 msgs
->max
+= MAXMSGS
;
248 msgs
->msgs
= mh_xrealloc(msgs
->msgs
,
249 msgs
->max
* sizeof(*msgs
->msgs
));
251 msgs
->msgs
[msgs
->size
++] = cp
;
255 * Append a message number to an array of them, resizing it if necessary.
256 * Like app_msgarg, but with a vector-of-ints instead.
260 app_msgnum(struct msgnum_array
*msgs
, int msgnum
)
262 if (msgs
->size
>= msgs
->max
) {
263 msgs
->max
+= MAXMSGS
;
264 msgs
->msgnums
= mh_xrealloc(msgs
->msgnums
,
265 msgs
->max
* sizeof(*msgs
->msgnums
));
267 msgs
->msgnums
[msgs
->size
++] = msgnum
;
270 /* Open a form or components file */
272 open_form(char **form
, char *def
)
276 if ((in
= open (etcpath (*form
), O_RDONLY
)) == NOTOK
)
277 adios (*form
, "unable to open form file");
279 if ((in
= open (etcpath (def
), O_RDONLY
)) == NOTOK
)
280 adios (def
, "unable to open default components file");
288 * Finds first occurrence of str in buf. buf is not a C string but a
289 * byte array of length buflen. str is a null-terminated C string.
290 * find_str() does not modify buf but passes back a non-const char *
291 * pointer so that the caller can modify it.
294 find_str (const char buf
[], size_t buflen
, const char *str
) {
295 const size_t len
= strlen (str
);
298 for (i
= 0; i
+ len
<= buflen
; ++i
, ++buf
) {
299 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
307 * Finds last occurrence of str in buf. buf is not a C string but a
308 * byte array of length buflen. str is a null-terminated C string.
309 * find_str() does not modify buf but passes back a non-const char *
310 * pointer so that the caller can modify it.
313 rfind_str (const char buf
[], size_t buflen
, const char *str
) {
314 const size_t len
= strlen (str
);
317 for (i
= 0, buf
+= buflen
- len
; i
+ len
<= buflen
; ++i
, --buf
) {
318 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
325 /* POSIX doesn't have strcasestr() so emulate it. */
327 nmh_strcasestr (const char *s1
, const char *s2
) {
328 const size_t len
= strlen (s2
);
330 if (isupper ((unsigned char) s2
[0]) || islower ((unsigned char)s2
[0])) {
332 first
[0] = (char) toupper ((unsigned char) s2
[0]);
333 first
[1] = (char) tolower ((unsigned char) s2
[0]);
336 for (s1
= strpbrk (s1
, first
); s1
; s1
= strpbrk (++s1
, first
)) {
337 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
340 for (s1
= strchr (s1
, s2
[0]); s1
; s1
= strchr (++s1
, s2
[0])) {
341 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
349 /* truncpy copies at most size - 1 chars from non-NULL src to non-NULL,
350 * non-overlapping, dst, and ensures dst is NUL terminated. If size is
351 * zero then it aborts as dst cannot be NUL terminated.
353 * It's to be used when truncation is intended and correct, e.g.
354 * reporting a possibly very long external string back to the user. One
355 * of its advantages over strncpy(3) is it doesn't pad in the common
356 * case of no truncation. */
357 void trunccpy(char *dst
, const char *src
, size_t size
)
360 advise(NULL
, "trunccpy: zero-length destination: \"%.20s\"",
365 if (strnlen(src
, size
) < size
) {
368 memcpy(dst
, src
, size
- 1);
369 dst
[size
- 1] = '\0';
374 /* has_prefix returns true if non-NULL s starts with non-NULL prefix. */
375 bool has_prefix(const char *s
, const char *prefix
)
377 while (*s
&& *s
== *prefix
) {
382 return *prefix
== '\0';
386 /* has_suffix returns true if non-NULL s ends with non-NULL suffix. */
387 bool has_suffix(const char *s
, const char *suffix
)
392 lsuf
= strlen(suffix
);
394 return lsuf
<= ls
&& !strcmp(s
+ ls
- lsuf
, suffix
);
398 /* has_suffix_c returns true if non-NULL string s ends with a c before the
399 * terminating NUL. */
400 bool has_suffix_c(const char *s
, int c
)
402 return *s
&& s
[strlen(s
) - 1] == c
;
406 /* trim_suffix_c deletes c from the end of non-NULL string s if it's
407 * present, shortening s by 1. Only one instance of c is removed. */
408 void trim_suffix_c(char *s
, int c
)
419 /* to_lower runs all of s through tolower(3). */
420 void to_lower(char *s
)
424 for (b
= (unsigned char *)s
; (*b
= tolower(*b
)); b
++)
429 /* to_upper runs all of s through toupper(3). */
430 void to_upper(char *s
)
434 for (b
= (unsigned char *)s
; (*b
= toupper(*b
)); b
++)
440 nmh_init(const char *argv0
, int read_context
) {
444 invo_name
= r1bindex ((char *) argv0
, '/');
446 if (setup_signal_handlers()) {
447 admonish("sigaction", "unable to set up signal handlers");
450 /* POSIX atexit() does not define any error conditions. */
451 if (atexit(remove_registered_files_atexit
)) {
452 admonish("atexit", "unable to register atexit function");
455 /* Read context, if supposed to. */
457 int allow_version_check
= 1;
458 int check_older_version
= 0;
463 if (read_context
!= 1 ||
464 ((cp
= context_find ("Welcome")) && strcasecmp (cp
, "disable") == 0)) {
465 allow_version_check
= 0;
466 } else if ((cp
= getenv ("MHCONTEXT")) != NULL
&& *cp
!= '\0') {
467 /* Context file comes from $MHCONTEXT, so only print the message
468 if the context file has an older version. If it does, or if it
469 doesn't have a version at all, update the version. */
470 check_older_version
= 1;
473 /* Check to see if the user is running a different (or older, if
474 specified) version of nmh than they had run bfore, and notify them
475 if so. But only if read_context was set to a value to enable. */
476 if (allow_version_check
&& isatty (fileno (stdin
)) &&
477 isatty (fileno (stdout
)) && isatty (fileno (stderr
))) {
478 if (nmh_version_changed (check_older_version
)) {
479 printf ("==================================================="
480 "=====================\n");
481 printf ("Welcome to nmh version %s\n\n", VERSION
);
482 printf ("See the release notes in %s/NEWS\n\n",
484 print_intro (stdout
, 1);
485 printf ("\nThis message will not be repeated until "
486 "nmh is next updated.\n");
487 printf ("==================================================="
488 "=====================\n\n");
490 fputs ("Press enter to continue: ", stdout
);
496 if ((status
= context_foil(NULL
)) != OK
) {
497 advise("", "failed to create minimal profile/context");
501 /* Allow the user to set a locale in their profile. Otherwise, use the
502 "" string to pull it from their environment, see setlocale(3). */
503 if ((locale
= context_find ("locale")) == NULL
) {
507 if (! setlocale (LC_ALL
, locale
)) {
508 admonish (NULL
, "setlocale failed, check your LC_ALL, LC_CTYPE, and "
509 "LANG environment variables");
517 * Check stored version, and return 1 if out-of-date or non-existent.
518 * Because the output of "mhparam version" is prefixed with "nmh-",
519 * use that prefix here.
522 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
? 1 : 0;
541 if (context_version
== NULL
|| strcmp(context_version
, "nmh-" VERSION
) != 0) {
542 context_replace ("Version", "nmh-" VERSION
);
550 /* Returns copy of argument str with all characters converted to upper
551 case, and trimmed whitespace (see cpytrim()) . */
553 upcase (const char *str
) {
554 char *up
= cpytrim (str
);
563 * Scan for any 8-bit characters. Return 1 if they exist.
565 * Scan up until the given endpoint (but not the actual endpoint itself).
566 * If the endpoint is NULL, scan until a '\0' is reached.
570 contains8bit(const char *start
, const char *end
)
575 while (*start
!= '\0' && (!end
|| (start
< end
)))
576 if (! isascii((unsigned char) *start
++))
584 * See if input has any 8-bit bytes.
587 scan_input (int fd
, int *eightbit
) {
592 lseek (fd
, (off_t
) 0, SEEK_SET
);
594 while ((state
= read (fd
, buf
, sizeof buf
)) > 0) {
595 if (contains8bit (buf
, buf
+ state
)) {
601 return state
== NOTOK
? NOTOK
: OK
;