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.
10 #include <h/signals.h>
15 #include "read_line.h"
17 extern char *mhdocdir
;
19 /* plurals gives the letter ess to indicate a plural noun, or an empty
20 * string as plurals+1 for the singular noun. Used by the PLURALS
22 const char plurals
[] = "s";
25 * We allocate space for messages (msgs array)
26 * this number of elements at a time.
30 /* Call malloc(3), exiting on NULL return. */
31 void *mh_xmalloc(size_t size
)
36 size
= 1; /* Some mallocs don't like 0. */
39 adios(NULL
, "malloc failed, size wanted: %zu", size
);
44 /* Call realloc(3), exiting on NULL return. */
45 void *mh_xrealloc(void *ptr
, size_t size
)
49 /* Copy POSIX behaviour, coping with non-POSIX systems. */
52 return mh_xmalloc(1); /* Get a unique pointer. */
55 return mh_xmalloc(size
);
57 new = realloc(ptr
, size
);
59 adios(NULL
, "realloc failed, size wanted: %zu", size
);
64 /* Call calloc(3), exiting on NULL return. */
65 void *mh_xcalloc(size_t nelem
, size_t elsize
)
69 if (!nelem
|| !elsize
)
70 return mh_xmalloc(1); /* Get a unique pointer. */
72 p
= calloc(nelem
, elsize
);
74 adios(NULL
, "calloc failed, size wanted: %zu * %zu", nelem
, elsize
);
79 /* Duplicate a NUL-terminated string, exit on failure. */
80 char *mh_xstrdup(const char *src
)
85 n
= strlen(src
) + 1; /* Ignore possibility of overflow. */
93 * Return the present working directory, if the current directory does not
94 * exist, or is too long, make / the pwd.
100 static char curwd
[PATH_MAX
];
102 if (!getcwd (curwd
, PATH_MAX
)) {
103 inform("unable to determine working directory, continuing...");
104 if (!mypath
|| !*mypath
105 || (strcpy (curwd
, mypath
), chdir (curwd
)) == -1) {
107 if (chdir (curwd
) < 0) {
108 advise (curwd
, "chdir");
114 if ((cp
= curwd
+ strlen (curwd
) - 1) > curwd
&& *cp
== '/')
121 * add -- If "s1" is NULL, this routine just creates a
122 * -- copy of "s2" into newly malloc'ed memory.
124 * -- If "s1" is not NULL, then copy the concatenation
125 * -- of "s1" and "s2" (note the order) into newly
126 * -- malloc'ed memory. Then free "s1".
129 add (const char *s2
, char *s1
)
132 size_t len1
= 0, len2
= 0;
139 cp
= mh_xmalloc (len1
+ len2
+ 1);
141 /* Copy s1 and free it */
143 memcpy (cp
, s1
, len1
);
149 memcpy (cp
+ len1
, s2
, len2
);
151 /* Now NULL terminate the string */
152 cp
[len1
+ len2
] = '\0';
159 * Append an item to a comma separated list
162 addlist (char *list
, const char *item
)
165 list
= add (", ", list
);
167 return add (item
, list
);
172 * Check to see if a folder exists.
174 int folder_exists(const char *folder
)
178 return stat(folder
, &st
) != -1;
183 * Check to see if a folder exists, if not, prompt the user to create
186 void create_folder(char *folder
, int autocreate
, void (*done_callback
)(int))
192 if (stat (folder
, &st
) == -1) {
194 adios (folder
, "error on folder");
195 if (autocreate
== 0) {
196 /* ask before creating folder */
197 cp
= concat ("Create folder \"", folder
, "\"? ", NULL
);
198 if (!read_yes_or_no_if_tty (cp
))
201 } else if (autocreate
== -1) {
202 /* do not create, so exit */
205 if (!makedir (folder
))
206 adios (NULL
, "unable to create folder %s", folder
);
212 * Return the number of digits in a nonnegative integer.
221 adios (NULL
, "oops, num_digits called with negative value");
235 * Append a message arg to an array of them, resizing it if necessary.
236 * Really a simple vector-of-(char *) maintenance routine.
239 app_msgarg(struct msgs_array
*msgs
, char *cp
)
241 if(msgs
->size
>= msgs
->max
) {
242 msgs
->max
+= MAXMSGS
;
243 msgs
->msgs
= mh_xrealloc(msgs
->msgs
,
244 msgs
->max
* sizeof(*msgs
->msgs
));
246 msgs
->msgs
[msgs
->size
++] = cp
;
250 * Append a message number to an array of them, resizing it if necessary.
251 * Like app_msgarg, but with a vector-of-ints instead.
255 app_msgnum(struct msgnum_array
*msgs
, int msgnum
)
257 if (msgs
->size
>= msgs
->max
) {
258 msgs
->max
+= MAXMSGS
;
259 msgs
->msgnums
= mh_xrealloc(msgs
->msgnums
,
260 msgs
->max
* sizeof(*msgs
->msgnums
));
262 msgs
->msgnums
[msgs
->size
++] = msgnum
;
267 * Finds first occurrence of str in buf. buf is not a C string but a
268 * byte array of length buflen. str is a null-terminated C string.
269 * find_str() does not modify buf but passes back a non-const char *
270 * pointer so that the caller can modify it.
273 find_str (const char buf
[], size_t buflen
, const char *str
) {
274 const size_t len
= strlen (str
);
277 for (i
= 0; i
+ len
<= buflen
; ++i
, ++buf
) {
278 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
286 * Finds last occurrence of str in buf. buf is not a C string but a
287 * byte array of length buflen. str is a null-terminated C string.
288 * find_str() does not modify buf but passes back a non-const char *
289 * pointer so that the caller can modify it.
292 rfind_str (const char buf
[], size_t buflen
, const char *str
) {
293 const size_t len
= strlen (str
);
296 for (i
= 0, buf
+= buflen
- len
; i
+ len
<= buflen
; ++i
, --buf
) {
297 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
304 /* POSIX doesn't have strcasestr() so emulate it. */
306 nmh_strcasestr (const char *s1
, const char *s2
) {
307 const size_t len
= strlen (s2
);
309 if (isupper ((unsigned char) s2
[0]) || islower ((unsigned char)s2
[0])) {
311 first
[0] = (char) toupper ((unsigned char) s2
[0]);
312 first
[1] = (char) tolower ((unsigned char) s2
[0]);
315 for (s1
= strpbrk (s1
, first
); s1
; s1
= strpbrk (++s1
, first
)) {
316 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
319 for (s1
= strchr (s1
, s2
[0]); s1
; s1
= strchr (++s1
, s2
[0])) {
320 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
328 /* truncpy copies at most size - 1 chars from non-NULL src to non-NULL,
329 * non-overlapping, dst, and ensures dst is NUL terminated. If size is
330 * zero then it aborts as dst cannot be NUL terminated.
332 * It's to be used when truncation is intended and correct, e.g.
333 * reporting a possibly very long external string back to the user. One
334 * of its advantages over strncpy(3) is it doesn't pad in the common
335 * case of no truncation. */
336 void trunccpy(char *dst
, const char *src
, size_t size
)
339 inform("trunccpy: zero-length destination: \"%.20s\"",
344 if (strnlen(src
, size
) < size
) {
347 memcpy(dst
, src
, size
- 1);
348 dst
[size
- 1] = '\0';
353 /* has_prefix returns true if non-NULL s starts with non-NULL prefix. */
354 bool has_prefix(const char *s
, const char *prefix
)
356 while (*s
&& *s
== *prefix
) {
361 return *prefix
== '\0';
365 /* has_suffix returns true if non-NULL s ends with non-NULL suffix. */
366 bool has_suffix(const char *s
, const char *suffix
)
371 lsuf
= strlen(suffix
);
373 return lsuf
<= ls
&& !strcmp(s
+ ls
- lsuf
, suffix
);
377 /* has_suffix_c returns true if non-NULL string s ends with a c before the
378 * terminating NUL. */
379 bool has_suffix_c(const char *s
, int c
)
381 return *s
&& s
[strlen(s
) - 1] == c
;
385 /* trim_suffix_c deletes c from the end of non-NULL string s if it's
386 * present, shortening s by 1. Only one instance of c is removed. */
387 void trim_suffix_c(char *s
, int c
)
398 /* to_lower runs all of s through tolower(3). */
399 void to_lower(char *s
)
403 for (b
= (unsigned char *)s
; (*b
= tolower(*b
)); b
++)
408 /* to_upper runs all of s through toupper(3). */
409 void to_upper(char *s
)
413 for (b
= (unsigned char *)s
; (*b
= toupper(*b
)); b
++)
419 nmh_init(const char *argv0
, int read_context
) {
423 invo_name
= r1bindex ((char *) argv0
, '/');
425 if (setup_signal_handlers()) {
426 admonish("sigaction", "unable to set up signal handlers");
429 /* POSIX atexit() does not define any error conditions. */
430 if (atexit(remove_registered_files_atexit
)) {
431 admonish("atexit", "unable to register atexit function");
434 /* Read context, if supposed to. */
436 int allow_version_check
= 1;
437 int check_older_version
= 0;
442 if (read_context
!= 1 ||
443 ((cp
= context_find ("Welcome")) && strcasecmp (cp
, "disable") == 0)) {
444 allow_version_check
= 0;
445 } else if ((cp
= getenv ("MHCONTEXT")) != NULL
&& *cp
!= '\0') {
446 /* Context file comes from $MHCONTEXT, so only print the message
447 if the context file has an older version. If it does, or if it
448 doesn't have a version at all, update the version. */
449 check_older_version
= 1;
452 /* Check to see if the user is running a different (or older, if
453 specified) version of nmh than they had run before, and notify them
454 if so. But only if read_context was set to a value to enable. */
455 if (allow_version_check
&& isatty (fileno (stdin
)) &&
456 isatty (fileno (stdout
)) && isatty (fileno (stderr
))) {
457 if (nmh_version_changed (check_older_version
)) {
458 printf ("==================================================="
459 "=====================\n");
460 printf ("Welcome to nmh version %s\n\n", VERSION
);
461 printf ("See the release notes in %s/NEWS\n\n",
463 print_intro (stdout
, 1);
464 printf ("\nThis message will not be repeated until "
465 "nmh is next updated.\n");
466 printf ("==================================================="
467 "=====================\n\n");
469 fputs ("Press enter to continue: ", stdout
);
475 if ((status
= context_foil(NULL
)) != OK
) {
476 advise("", "failed to create minimal profile/context");
480 /* Allow the user to set a locale in their profile. Otherwise, use the
481 "" string to pull it from their environment, see setlocale(3). */
482 if ((locale
= context_find ("locale")) == NULL
) {
486 if (! setlocale (LC_ALL
, locale
)) {
487 inform("setlocale failed, check your LC_ALL, LC_CTYPE, and LANG "
488 "environment variables, continuing...");
496 * Check stored version, and return 1 if out-of-date or non-existent.
497 * Because the output of "mhparam version" is prefixed with "nmh-",
498 * use that prefix here.
501 nmh_version_changed (int older
) {
502 const char *const context_version
= context_find("Version");
505 /* Convert the version strings to floats and compare them. This will
506 break for versions with multiple decimal points, etc. */
507 const float current_version
= strtof (VERSION
, NULL
);
508 const float old_version
=
509 context_version
&& has_prefix(context_version
, "nmh-")
510 ? strtof (context_version
+ 4, NULL
)
513 if (context_version
== NULL
|| old_version
< current_version
) {
514 context_replace ("Version", "nmh-" VERSION
);
517 return old_version
< current_version
;
520 if (context_version
== NULL
|| strcmp(context_version
, "nmh-" VERSION
) != 0) {
521 context_replace ("Version", "nmh-" VERSION
);
529 /* contains8bit returns true if any byte from start onwards fails
530 * isascii(3), i.e. is outside [0, 0x7f]. If start is NULL it returns
531 * false. Bytes are examined until a NUL byte, or, if end is not NULL,
532 * whilst start is before end. */
533 bool contains8bit(const char *start
, const char *end
)
543 while (p
< end
&& (c
= (*p
++)))
544 if (!isascii((unsigned char)c
))
548 if (!isascii((unsigned char)c
))
557 * See if input has any 8-bit bytes.
560 scan_input (int fd
, int *eightbit
) {
565 lseek(fd
, 0, SEEK_SET
);
567 while ((state
= read (fd
, buf
, sizeof buf
)) > 0) {
568 if (contains8bit (buf
, buf
+ state
)) {
574 return state
== NOTOK
? NOTOK
: OK
;
579 * Convert an int to a char string.
583 return m_strn(value
, 0);
588 * Convert an int to a char string, of limited width if > 0.
591 /* SIZE(n) includes NUL. n must just be digits, not an equation. */
592 #define SIZE(n) (sizeof STR(n))
595 m_strn(int value
, unsigned int width
) {
596 /* Need to include space for negative sign. But don't use INT_MIN
597 because it could be a macro that would fool SIZE(n). */
598 static char buffer
[SIZE(-INT_MAX
)];
599 const int num_chars
= snprintf(buffer
, sizeof buffer
, "%d", value
);
601 return num_chars
> 0 && (width
== 0 || (unsigned int) num_chars
<= width
)