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.
13 extern int setup_signal_handlers();
16 extern void remove_registered_files_atexit();
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. */
32 void *mh_xmalloc(size_t size
)
37 size
= 1; /* Some mallocs don't like 0. */
40 adios(NULL
, "malloc failed, size wanted: %zu", size
);
45 /* Call realloc(3), exiting on NULL return. */
46 void *mh_xrealloc(void *ptr
, size_t size
)
50 /* Copy POSIX behaviour, coping with non-POSIX systems. */
53 return mh_xmalloc(1); /* Get a unique pointer. */
56 return mh_xmalloc(size
);
58 new = realloc(ptr
, size
);
60 adios(NULL
, "realloc failed, size wanted: %zu", size
);
65 /* Call calloc(3), exiting on NULL return. */
66 void *mh_xcalloc(size_t nelem
, size_t elsize
)
70 if (!nelem
|| !elsize
)
71 return mh_xmalloc(1); /* Get a unique pointer. */
73 p
= calloc(nelem
, elsize
);
75 adios(NULL
, "calloc failed, size wanted: %zu * %zu", nelem
, elsize
);
80 /* Duplicate a NUL-terminated string, exit on failure. */
81 char *mh_xstrdup(const char *src
)
86 n
= strlen(src
) + 1; /* Ignore possibility of overflow. */
93 /* Call free(3), if ptr isn't NULL. */
94 void mh_xfree(void *ptr
)
97 free(ptr
); /* Some very old platforms can't cope with NULL. */
101 * Return the present working directory, if the current directory does not
102 * exist, or is too long, make / the pwd.
108 static char curwd
[PATH_MAX
];
110 if (!getcwd (curwd
, PATH_MAX
)) {
111 inform("unable to determine working directory, continuing...");
112 if (!mypath
|| !*mypath
113 || (strcpy (curwd
, mypath
), chdir (curwd
)) == -1) {
115 if (chdir (curwd
) < 0) {
116 advise (curwd
, "chdir");
122 if ((cp
= curwd
+ strlen (curwd
) - 1) > curwd
&& *cp
== '/')
129 * add -- If "s1" is NULL, this routine just creates a
130 * -- copy of "s2" into newly malloc'ed memory.
132 * -- If "s1" is not NULL, then copy the concatenation
133 * -- of "s1" and "s2" (note the order) into newly
134 * -- malloc'ed memory. Then free "s1".
137 add (const char *s2
, char *s1
)
140 size_t len1
= 0, len2
= 0;
147 cp
= mh_xmalloc (len1
+ len2
+ 1);
149 /* Copy s1 and free it */
151 memcpy (cp
, s1
, len1
);
157 memcpy (cp
+ len1
, s2
, len2
);
159 /* Now NULL terminate the string */
160 cp
[len1
+ len2
] = '\0';
167 * Append an item to a comma separated list
170 addlist (char *list
, const char *item
)
173 list
= add (", ", list
);
175 return add (item
, list
);
180 * Check to see if a folder exists.
182 int 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
194 void create_folder(char *folder
, int autocreate
, void (*done_callback
)(int))
200 if (stat (folder
, &st
) == -1) {
202 adios (folder
, "error on folder");
203 if (autocreate
== 0) {
204 /* ask before creating folder */
205 cp
= concat ("Create folder \"", folder
, "\"? ", NULL
);
206 if (!read_yes_or_no_if_tty (cp
))
209 } else if (autocreate
== -1) {
210 /* do not create, so exit */
213 if (!makedir (folder
))
214 adios (NULL
, "unable to create folder %s", folder
);
220 * Return the number of digits in a nonnegative integer.
229 adios (NULL
, "oops, num_digits called with negative value");
243 * Append a message arg to an array of them, resizing it if necessary.
244 * Really a simple vector-of-(char *) maintenance routine.
247 app_msgarg(struct msgs_array
*msgs
, char *cp
)
249 if(msgs
->size
>= msgs
->max
) {
250 msgs
->max
+= MAXMSGS
;
251 msgs
->msgs
= mh_xrealloc(msgs
->msgs
,
252 msgs
->max
* sizeof(*msgs
->msgs
));
254 msgs
->msgs
[msgs
->size
++] = cp
;
258 * Append a message number to an array of them, resizing it if necessary.
259 * Like app_msgarg, but with a vector-of-ints instead.
263 app_msgnum(struct msgnum_array
*msgs
, int msgnum
)
265 if (msgs
->size
>= msgs
->max
) {
266 msgs
->max
+= MAXMSGS
;
267 msgs
->msgnums
= mh_xrealloc(msgs
->msgnums
,
268 msgs
->max
* sizeof(*msgs
->msgnums
));
270 msgs
->msgnums
[msgs
->size
++] = msgnum
;
273 /* Open a form or components file */
275 open_form(char **form
, char *def
)
279 if ((in
= open (etcpath (*form
), O_RDONLY
)) == NOTOK
)
280 adios (*form
, "unable to open form file");
282 if ((in
= open (etcpath (def
), O_RDONLY
)) == NOTOK
)
283 adios (def
, "unable to open default components file");
291 * Finds first occurrence of str in buf. buf is not a C string but a
292 * byte array of length buflen. str is a null-terminated C string.
293 * find_str() does not modify buf but passes back a non-const char *
294 * pointer so that the caller can modify it.
297 find_str (const char buf
[], size_t buflen
, const char *str
) {
298 const size_t len
= strlen (str
);
301 for (i
= 0; i
+ len
<= buflen
; ++i
, ++buf
) {
302 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
310 * Finds last occurrence of str in buf. buf is not a C string but a
311 * byte array of length buflen. str is a null-terminated C string.
312 * find_str() does not modify buf but passes back a non-const char *
313 * pointer so that the caller can modify it.
316 rfind_str (const char buf
[], size_t buflen
, const char *str
) {
317 const size_t len
= strlen (str
);
320 for (i
= 0, buf
+= buflen
- len
; i
+ len
<= buflen
; ++i
, --buf
) {
321 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
328 /* POSIX doesn't have strcasestr() so emulate it. */
330 nmh_strcasestr (const char *s1
, const char *s2
) {
331 const size_t len
= strlen (s2
);
333 if (isupper ((unsigned char) s2
[0]) || islower ((unsigned char)s2
[0])) {
335 first
[0] = (char) toupper ((unsigned char) s2
[0]);
336 first
[1] = (char) tolower ((unsigned char) s2
[0]);
339 for (s1
= strpbrk (s1
, first
); s1
; s1
= strpbrk (++s1
, first
)) {
340 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
343 for (s1
= strchr (s1
, s2
[0]); s1
; s1
= strchr (++s1
, s2
[0])) {
344 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
352 /* truncpy copies at most size - 1 chars from non-NULL src to non-NULL,
353 * non-overlapping, dst, and ensures dst is NUL terminated. If size is
354 * zero then it aborts as dst cannot be NUL terminated.
356 * It's to be used when truncation is intended and correct, e.g.
357 * reporting a possibly very long external string back to the user. One
358 * of its advantages over strncpy(3) is it doesn't pad in the common
359 * case of no truncation. */
360 void trunccpy(char *dst
, const char *src
, size_t size
)
363 inform("trunccpy: zero-length destination: \"%.20s\"",
368 if (strnlen(src
, size
) < size
) {
371 memcpy(dst
, src
, size
- 1);
372 dst
[size
- 1] = '\0';
377 /* has_prefix returns true if non-NULL s starts with non-NULL prefix. */
378 bool has_prefix(const char *s
, const char *prefix
)
380 while (*s
&& *s
== *prefix
) {
385 return *prefix
== '\0';
389 /* has_suffix returns true if non-NULL s ends with non-NULL suffix. */
390 bool has_suffix(const char *s
, const char *suffix
)
395 lsuf
= strlen(suffix
);
397 return lsuf
<= ls
&& !strcmp(s
+ ls
- lsuf
, suffix
);
401 /* has_suffix_c returns true if non-NULL string s ends with a c before the
402 * terminating NUL. */
403 bool has_suffix_c(const char *s
, int c
)
405 return *s
&& s
[strlen(s
) - 1] == c
;
409 /* trim_suffix_c deletes c from the end of non-NULL string s if it's
410 * present, shortening s by 1. Only one instance of c is removed. */
411 void trim_suffix_c(char *s
, int c
)
422 /* to_lower runs all of s through tolower(3). */
423 void to_lower(char *s
)
427 for (b
= (unsigned char *)s
; (*b
= tolower(*b
)); b
++)
432 /* to_upper runs all of s through toupper(3). */
433 void to_upper(char *s
)
437 for (b
= (unsigned char *)s
; (*b
= toupper(*b
)); b
++)
443 nmh_init(const char *argv0
, int read_context
) {
447 invo_name
= r1bindex ((char *) argv0
, '/');
449 if (setup_signal_handlers()) {
450 admonish("sigaction", "unable to set up signal handlers");
453 /* POSIX atexit() does not define any error conditions. */
454 if (atexit(remove_registered_files_atexit
)) {
455 admonish("atexit", "unable to register atexit function");
458 /* Read context, if supposed to. */
460 int allow_version_check
= 1;
461 int check_older_version
= 0;
466 if (read_context
!= 1 ||
467 ((cp
= context_find ("Welcome")) && strcasecmp (cp
, "disable") == 0)) {
468 allow_version_check
= 0;
469 } else if ((cp
= getenv ("MHCONTEXT")) != NULL
&& *cp
!= '\0') {
470 /* Context file comes from $MHCONTEXT, so only print the message
471 if the context file has an older version. If it does, or if it
472 doesn't have a version at all, update the version. */
473 check_older_version
= 1;
476 /* Check to see if the user is running a different (or older, if
477 specified) version of nmh than they had run before, and notify them
478 if so. But only if read_context was set to a value to enable. */
479 if (allow_version_check
&& isatty (fileno (stdin
)) &&
480 isatty (fileno (stdout
)) && isatty (fileno (stderr
))) {
481 if (nmh_version_changed (check_older_version
)) {
482 printf ("==================================================="
483 "=====================\n");
484 printf ("Welcome to nmh version %s\n\n", VERSION
);
485 printf ("See the release notes in %s/NEWS\n\n",
487 print_intro (stdout
, 1);
488 printf ("\nThis message will not be repeated until "
489 "nmh is next updated.\n");
490 printf ("==================================================="
491 "=====================\n\n");
493 fputs ("Press enter to continue: ", stdout
);
499 if ((status
= context_foil(NULL
)) != OK
) {
500 advise("", "failed to create minimal profile/context");
504 /* Allow the user to set a locale in their profile. Otherwise, use the
505 "" string to pull it from their environment, see setlocale(3). */
506 if ((locale
= context_find ("locale")) == NULL
) {
510 if (! setlocale (LC_ALL
, locale
)) {
511 inform("setlocale failed, check your LC_ALL, LC_CTYPE, and LANG "
512 "environment variables, continuing...");
520 * Check stored version, and return 1 if out-of-date or non-existent.
521 * Because the output of "mhparam version" is prefixed with "nmh-",
522 * use that prefix here.
525 nmh_version_changed (int older
) {
526 const char *const context_version
= context_find("Version");
529 /* Convert the version strings to floats and compare them. This will
530 break for versions with multiple decimal points, etc. */
531 const float current_version
= strtof (VERSION
, NULL
);
532 const float old_version
=
533 context_version
&& has_prefix(context_version
, "nmh-")
534 ? strtof (context_version
+ 4, NULL
)
537 if (context_version
== NULL
|| old_version
< current_version
) {
538 context_replace ("Version", "nmh-" VERSION
);
541 return old_version
< current_version
;
544 if (context_version
== NULL
|| strcmp(context_version
, "nmh-" VERSION
) != 0) {
545 context_replace ("Version", "nmh-" VERSION
);
553 /* Returns copy of argument str with all characters converted to upper
554 case, and trimmed whitespace (see cpytrim()) . */
556 upcase (const char *str
) {
557 char *up
= cpytrim (str
);
566 * Scan for any 8-bit characters. Return 1 if they exist.
568 * Scan up until the given endpoint (but not the actual endpoint itself).
569 * If the endpoint is NULL, scan until a '\0' is reached.
573 contains8bit(const char *start
, const char *end
)
578 while (*start
!= '\0' && (!end
|| (start
< end
)))
579 if (! isascii((unsigned char) *start
++))
587 * See if input has any 8-bit bytes.
590 scan_input (int fd
, int *eightbit
) {
595 lseek (fd
, (off_t
) 0, SEEK_SET
);
597 while ((state
= read (fd
, buf
, sizeof buf
)) > 0) {
598 if (contains8bit (buf
, buf
+ state
)) {
604 return state
== NOTOK
? NOTOK
: OK
;