2 * utils.c -- various utility routines
4 * This code is Copyright (c) 2006, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
14 extern int setup_signal_handlers();
17 extern void remove_registered_files_atexit();
19 extern char *mhdocdir
;
22 * We allocate space for messages (msgs array)
23 * this number of elements at a time.
27 /* Call malloc(3), exiting on NULL return. */
28 void *mh_xmalloc(size_t size
)
33 size
= 1; /* Some mallocs don't like 0. */
36 adios(NULL
, "malloc failed, size wanted: %zu", size
);
41 /* Call realloc(3), exiting on NULL return. */
42 void *mh_xrealloc(void *ptr
, size_t size
)
46 /* Copy POSIX behaviour, coping with non-POSIX systems. */
49 return mh_xmalloc(1); /* Get a unique pointer. */
52 return mh_xmalloc(size
);
54 new = realloc(ptr
, size
);
56 adios(NULL
, "realloc failed, size wanted: %zu", size
);
61 /* Call calloc(3), exiting on NULL return. */
62 void *mh_xcalloc(size_t nelem
, size_t elsize
)
66 if (!nelem
|| !elsize
)
67 return mh_xmalloc(1); /* Get a unique pointer. */
69 p
= calloc(nelem
, elsize
);
71 adios(NULL
, "calloc failed, size wanted: %zu * %zu", nelem
, elsize
);
76 /* Duplicate a NUL-terminated string, exit on failure. */
77 char *mh_xstrdup(const char *src
)
82 n
= strlen(src
) + 1; /* Ignore possibility of overflow. */
89 /* Call free(3), if ptr isn't NULL. */
90 void mh_xfree(void *ptr
)
93 free(ptr
); /* Some very old platforms can't cope with NULL. */
97 * Return the present working directory, if the current directory does not
98 * exist, or is too long, make / the pwd.
104 static char curwd
[PATH_MAX
];
106 if (!getcwd (curwd
, PATH_MAX
)) {
107 inform("unable to determine working directory, continuing...");
108 if (!mypath
|| !*mypath
109 || (strcpy (curwd
, mypath
), chdir (curwd
)) == -1) {
111 if (chdir (curwd
) < 0) {
112 advise (curwd
, "chdir");
118 if ((cp
= curwd
+ strlen (curwd
) - 1) > curwd
&& *cp
== '/')
125 * add -- If "s1" is NULL, this routine just creates a
126 * -- copy of "s2" into newly malloc'ed memory.
128 * -- If "s1" is not NULL, then copy the concatenation
129 * -- of "s1" and "s2" (note the order) into newly
130 * -- malloc'ed memory. Then free "s1".
133 add (const char *s2
, char *s1
)
136 size_t len1
= 0, len2
= 0;
143 cp
= mh_xmalloc (len1
+ len2
+ 1);
145 /* Copy s1 and free it */
147 memcpy (cp
, s1
, len1
);
153 memcpy (cp
+ len1
, s2
, len2
);
155 /* Now NULL terminate the string */
156 cp
[len1
+ len2
] = '\0';
163 * Append an item to a comma separated list
166 addlist (char *list
, const char *item
)
169 list
= add (", ", list
);
171 return add (item
, list
);
176 * Check to see if a folder exists.
178 int folder_exists(const char *folder
)
182 return stat(folder
, &st
) != -1;
187 * Check to see if a folder exists, if not, prompt the user to create
190 void create_folder(char *folder
, int autocreate
, void (*done_callback
)(int))
196 if (stat (folder
, &st
) == -1) {
198 adios (folder
, "error on folder");
199 if (autocreate
== 0) {
200 /* ask before creating folder */
201 cp
= concat ("Create folder \"", folder
, "\"? ", NULL
);
202 if (!read_yes_or_no_if_tty (cp
))
205 } else if (autocreate
== -1) {
206 /* do not create, so exit */
209 if (!makedir (folder
))
210 adios (NULL
, "unable to create folder %s", folder
);
216 * Return the number of digits in a nonnegative integer.
225 adios (NULL
, "oops, num_digits called with negative value");
239 * Append a message arg to an array of them, resizing it if necessary.
240 * Really a simple vector-of-(char *) maintenance routine.
243 app_msgarg(struct msgs_array
*msgs
, char *cp
)
245 if(msgs
->size
>= msgs
->max
) {
246 msgs
->max
+= MAXMSGS
;
247 msgs
->msgs
= mh_xrealloc(msgs
->msgs
,
248 msgs
->max
* sizeof(*msgs
->msgs
));
250 msgs
->msgs
[msgs
->size
++] = cp
;
254 * Append a message number to an array of them, resizing it if necessary.
255 * Like app_msgarg, but with a vector-of-ints instead.
259 app_msgnum(struct msgnum_array
*msgs
, int msgnum
)
261 if (msgs
->size
>= msgs
->max
) {
262 msgs
->max
+= MAXMSGS
;
263 msgs
->msgnums
= mh_xrealloc(msgs
->msgnums
,
264 msgs
->max
* sizeof(*msgs
->msgnums
));
266 msgs
->msgnums
[msgs
->size
++] = msgnum
;
269 /* Open a form or components file */
271 open_form(char **form
, char *def
)
275 if ((in
= open (etcpath (*form
), O_RDONLY
)) == NOTOK
)
276 adios (*form
, "unable to open form file");
278 if ((in
= open (etcpath (def
), O_RDONLY
)) == NOTOK
)
279 adios (def
, "unable to open default components file");
287 * Finds first occurrence of str in buf. buf is not a C string but a
288 * byte array of length buflen. str is a null-terminated C string.
289 * find_str() does not modify buf but passes back a non-const char *
290 * pointer so that the caller can modify it.
293 find_str (const char buf
[], size_t buflen
, const char *str
) {
294 const size_t len
= strlen (str
);
297 for (i
= 0; i
+ len
<= buflen
; ++i
, ++buf
) {
298 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
306 * Finds last occurrence of str in buf. buf is not a C string but a
307 * byte array of length buflen. str is a null-terminated C string.
308 * find_str() does not modify buf but passes back a non-const char *
309 * pointer so that the caller can modify it.
312 rfind_str (const char buf
[], size_t buflen
, const char *str
) {
313 const size_t len
= strlen (str
);
316 for (i
= 0, buf
+= buflen
- len
; i
+ len
<= buflen
; ++i
, --buf
) {
317 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
324 /* POSIX doesn't have strcasestr() so emulate it. */
326 nmh_strcasestr (const char *s1
, const char *s2
) {
327 const size_t len
= strlen (s2
);
329 if (isupper ((unsigned char) s2
[0]) || islower ((unsigned char)s2
[0])) {
331 first
[0] = (char) toupper ((unsigned char) s2
[0]);
332 first
[1] = (char) tolower ((unsigned char) s2
[0]);
335 for (s1
= strpbrk (s1
, first
); s1
; s1
= strpbrk (++s1
, first
)) {
336 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
339 for (s1
= strchr (s1
, s2
[0]); s1
; s1
= strchr (++s1
, s2
[0])) {
340 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
348 /* truncpy copies at most size - 1 chars from non-NULL src to non-NULL,
349 * non-overlapping, dst, and ensures dst is NUL terminated. If size is
350 * zero then it aborts as dst cannot be NUL terminated.
352 * It's to be used when truncation is intended and correct, e.g.
353 * reporting a possibly very long external string back to the user. One
354 * of its advantages over strncpy(3) is it doesn't pad in the common
355 * case of no truncation. */
356 void trunccpy(char *dst
, const char *src
, size_t size
)
359 inform("trunccpy: zero-length destination: \"%.20s\"",
364 if (strnlen(src
, size
) < size
) {
367 memcpy(dst
, src
, size
- 1);
368 dst
[size
- 1] = '\0';
373 /* has_prefix returns true if non-NULL s starts with non-NULL prefix. */
374 bool has_prefix(const char *s
, const char *prefix
)
376 while (*s
&& *s
== *prefix
) {
381 return *prefix
== '\0';
385 /* has_suffix returns true if non-NULL s ends with non-NULL suffix. */
386 bool has_suffix(const char *s
, const char *suffix
)
391 lsuf
= strlen(suffix
);
393 return lsuf
<= ls
&& !strcmp(s
+ ls
- lsuf
, suffix
);
397 /* has_suffix_c returns true if non-NULL string s ends with a c before the
398 * terminating NUL. */
399 bool has_suffix_c(const char *s
, int c
)
401 return *s
&& s
[strlen(s
) - 1] == c
;
405 /* trim_suffix_c deletes c from the end of non-NULL string s if it's
406 * present, shortening s by 1. Only one instance of c is removed. */
407 void trim_suffix_c(char *s
, int c
)
418 /* to_lower runs all of s through tolower(3). */
419 void to_lower(char *s
)
423 for (b
= (unsigned char *)s
; (*b
= tolower(*b
)); b
++)
428 /* to_upper runs all of s through toupper(3). */
429 void to_upper(char *s
)
433 for (b
= (unsigned char *)s
; (*b
= toupper(*b
)); b
++)
439 nmh_init(const char *argv0
, int read_context
) {
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. */
456 int allow_version_check
= 1;
457 int check_older_version
= 0;
462 if (read_context
!= 1 ||
463 ((cp
= context_find ("Welcome")) && strcasecmp (cp
, "disable") == 0)) {
464 allow_version_check
= 0;
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
= 1;
472 /* Check to see if the user is running a different (or older, if
473 specified) version of nmh than they had run bfore, and notify them
474 if so. But only if read_context was set to a value to enable. */
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
) {
522 const char *const context_version
= context_find("Version");
525 /* Convert the version strings to floats and compare them. This will
526 break for versions with multiple decimal points, etc. */
527 const float current_version
= strtof (VERSION
, NULL
);
528 const float old_version
=
529 context_version
&& has_prefix(context_version
, "nmh-")
530 ? strtof (context_version
+ 4, NULL
)
533 if (context_version
== NULL
|| old_version
< current_version
) {
534 context_replace ("Version", "nmh-" VERSION
);
537 return old_version
< current_version
? 1 : 0;
540 if (context_version
== NULL
|| strcmp(context_version
, "nmh-" VERSION
) != 0) {
541 context_replace ("Version", "nmh-" VERSION
);
549 /* Returns copy of argument str with all characters converted to upper
550 case, and trimmed whitespace (see cpytrim()) . */
552 upcase (const char *str
) {
553 char *up
= cpytrim (str
);
562 * Scan for any 8-bit characters. Return 1 if they exist.
564 * Scan up until the given endpoint (but not the actual endpoint itself).
565 * If the endpoint is NULL, scan until a '\0' is reached.
569 contains8bit(const char *start
, const char *end
)
574 while (*start
!= '\0' && (!end
|| (start
< end
)))
575 if (! isascii((unsigned char) *start
++))
583 * See if input has any 8-bit bytes.
586 scan_input (int fd
, int *eightbit
) {
591 lseek (fd
, (off_t
) 0, SEEK_SET
);
593 while ((state
= read (fd
, buf
, sizeof buf
)) > 0) {
594 if (contains8bit (buf
, buf
+ state
)) {
600 return state
== NOTOK
? NOTOK
: OK
;