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. */
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
);
80 * Return the present working directory, if the current directory does not
81 * exist, or is too long, make / the pwd.
87 static char curwd
[PATH_MAX
];
89 if (!getcwd (curwd
, PATH_MAX
)) {
90 admonish (NULL
, "unable to determine working directory");
91 if (!mypath
|| !*mypath
92 || (strcpy (curwd
, mypath
), chdir (curwd
)) == -1) {
94 if (chdir (curwd
) < 0) {
95 advise (curwd
, "chdir");
101 if ((cp
= curwd
+ strlen (curwd
) - 1) > curwd
&& *cp
== '/')
108 * add -- If "s1" is NULL, this routine just creates a
109 * -- copy of "s2" into newly malloc'ed memory.
111 * -- If "s1" is not NULL, then copy the concatenation
112 * -- of "s1" and "s2" (note the order) into newly
113 * -- malloc'ed memory. Then free "s1".
116 add (const char *s2
, char *s1
)
119 size_t len1
= 0, len2
= 0;
126 cp
= mh_xmalloc (len1
+ len2
+ 1);
128 /* Copy s1 and free it */
130 memcpy (cp
, s1
, len1
);
136 memcpy (cp
+ len1
, s2
, len2
);
138 /* Now NULL terminate the string */
139 cp
[len1
+ len2
] = '\0';
146 * Append an item to a comma separated list
149 addlist (char *list
, const char *item
)
152 list
= add (", ", list
);
154 return add (item
, list
);
159 * Check to see if a folder exists.
161 int folder_exists(const char *folder
)
166 if (stat (folder
, &st
) == -1) {
167 /* The folder either doesn't exist, or we hit an error. Either way
172 /* We can see a folder with the right name */
182 * Check to see if a folder exists, if not, prompt the user to create
185 void create_folder(char *folder
, int autocreate
, void (*done_callback
)(int))
191 if (stat (folder
, &st
) == -1) {
193 adios (folder
, "error on folder");
194 if (autocreate
== 0) {
195 /* ask before creating folder */
196 cp
= concat ("Create folder \"", folder
, "\"? ", NULL
);
197 if (!read_yes_or_no_if_tty (cp
))
200 } else if (autocreate
== -1) {
201 /* do not create, so exit */
204 if (!makedir (folder
))
205 adios (NULL
, "unable to create folder %s", folder
);
211 * Return the number of digits in a nonnegative integer.
220 adios (NULL
, "oops, num_digits called with negative value");
234 * Append a message arg to an array of them, resizing it if necessary.
235 * Really a simple vector-of-(char *) maintenance routine.
238 app_msgarg(struct msgs_array
*msgs
, char *cp
)
240 if(msgs
->size
>= msgs
->max
) {
241 msgs
->max
+= MAXMSGS
;
242 msgs
->msgs
= mh_xrealloc(msgs
->msgs
,
243 msgs
->max
* sizeof(*msgs
->msgs
));
245 msgs
->msgs
[msgs
->size
++] = cp
;
249 * Append a message number to an array of them, resizing it if necessary.
250 * Like app_msgarg, but with a vector-of-ints instead.
254 app_msgnum(struct msgnum_array
*msgs
, int msgnum
)
256 if (msgs
->size
>= msgs
->max
) {
257 msgs
->max
+= MAXMSGS
;
258 msgs
->msgnums
= mh_xrealloc(msgs
->msgnums
,
259 msgs
->max
* sizeof(*msgs
->msgnums
));
261 msgs
->msgnums
[msgs
->size
++] = msgnum
;
264 /* Open a form or components file */
266 open_form(char **form
, char *def
)
270 if ((in
= open (etcpath (*form
), O_RDONLY
)) == NOTOK
)
271 adios (*form
, "unable to open form file");
273 if ((in
= open (etcpath (def
), O_RDONLY
)) == NOTOK
)
274 adios (def
, "unable to open default components file");
282 * Finds first occurrence of str in buf. buf is not a C string but a
283 * byte array of length buflen. str is a null-terminated C string.
284 * find_str() does not modify buf but passes back a non-const char *
285 * pointer so that the caller can modify it.
288 find_str (const char buf
[], size_t buflen
, const char *str
) {
289 const size_t len
= strlen (str
);
292 for (i
= 0; i
+ len
<= buflen
; ++i
, ++buf
) {
293 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
301 * Finds last occurrence of str in buf. buf is not a C string but a
302 * byte array of length buflen. str is a null-terminated C string.
303 * find_str() does not modify buf but passes back a non-const char *
304 * pointer so that the caller can modify it.
307 rfind_str (const char buf
[], size_t buflen
, const char *str
) {
308 const size_t len
= strlen (str
);
311 for (i
= 0, buf
+= buflen
- len
; i
+ len
<= buflen
; ++i
, --buf
) {
312 if (! memcmp (buf
, str
, len
)) return (char *) buf
;
319 /* POSIX doesn't have strcasestr() so emulate it. */
321 nmh_strcasestr (const char *s1
, const char *s2
) {
322 const size_t len
= strlen (s2
);
324 if (isupper ((unsigned char) s2
[0]) || islower ((unsigned char)s2
[0])) {
326 first
[0] = (char) toupper ((unsigned char) s2
[0]);
327 first
[1] = (char) tolower ((unsigned char) s2
[0]);
330 for (s1
= strpbrk (s1
, first
); s1
; s1
= strpbrk (++s1
, first
)) {
331 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
334 for (s1
= strchr (s1
, s2
[0]); s1
; s1
= strchr (++s1
, s2
[0])) {
335 if (! strncasecmp (s1
, s2
, len
)) return (char *) s1
;
344 nmh_init(const char *argv0
, int read_context
) {
345 if (! setlocale(LC_ALL
, "")) {
346 admonish(NULL
, "setlocale failed, check your LC_ALL, LC_CTYPE, and "
347 "LANG environment variables");
350 invo_name
= r1bindex ((char *) argv0
, '/');
352 if (setup_signal_handlers()) {
353 admonish("sigaction", "unable to set up signal handlers");
356 /* POSIX atexit() does not define any error conditions. */
357 if (atexit(remove_registered_files_atexit
)) {
358 admonish("atexit", "unable to register atexit function");
361 /* Read context, if supposed to. */
363 int allow_version_check
= 1;
364 int check_older_version
= 0;
369 if (read_context
!= 1 ||
370 ((cp
= context_find ("Welcome")) && strcasecmp (cp
, "disable") == 0)) {
371 allow_version_check
= 0;
372 } else if ((cp
= getenv ("MHCONTEXT")) != NULL
&& *cp
!= '\0') {
373 /* Context file comes from $MHCONTEXT, so only print the message
374 if the context file has an older version. If it does, or if it
375 doesn't have a version at all, update the version. */
376 check_older_version
= 1;
379 /* Check to see if the user is running a different (or older, if
380 specified) version of nmh than they had run bfore, and notify them
381 if so. But only if read_context was set to a value to enable. */
382 if (allow_version_check
&& isatty (fileno (stdin
)) &&
383 isatty (fileno (stdout
)) && isatty (fileno (stderr
))) {
384 if (nmh_version_changed (check_older_version
)) {
385 printf ("==================================================="
386 "=====================\n");
387 printf ("Welcome to nmh version %s\n\n", VERSION
);
388 printf ("See the release notes in %s/NEWS\n\n",
390 print_intro (stdout
, 1);
391 printf ("\nThis message will not be repeated until "
392 "nmh is next updated.\n");
393 printf ("==================================================="
394 "=====================\n\n");
396 fputs ("Press enter to continue: ", stdout
);
404 int status
= context_foil(NULL
);
406 advise("", "failed to create minimal profile/context");
414 * Check stored version, and return 1 if out-of-date or non-existent.
415 * Because the output of "mhparam version" is prefixed with "nmh-",
416 * use that prefix here.
419 nmh_version_changed (int older
) {
420 const char *const context_version
= context_find("Version");
423 /* Convert the version strings to floats and compare them. This will
424 break for versions with multiple decimal points, etc. */
425 const float current_version
= strtof (VERSION
, NULL
);
426 const float old_version
=
427 context_version
&& strncmp (context_version
, "nmh-", 4) == 0
428 ? strtof (context_version
+ 4, NULL
)
431 if (context_version
== NULL
|| old_version
< current_version
) {
432 context_replace ("Version", "nmh-" VERSION
);
435 return old_version
< current_version
? 1 : 0;
437 if (context_version
== NULL
|| strcmp(context_version
, "nmh-" VERSION
) != 0) {
438 context_replace ("Version", "nmh-" VERSION
);
448 /* Returns copy of argument str with all characters converted to upper
449 case, and trimmed whitespace (see cpytrim()) . */
451 upcase (const char *str
) {
452 char *up
= cpytrim (str
);
455 for (cp
= up
; *cp
; ++cp
) { *cp
= toupper ((unsigned char) *cp
); }
462 * Scan for any 8-bit characters. Return 1 if they exist.
464 * Scan up until the given endpoint (but not the actual endpoint itself).
465 * If the endpoint is NULL, scan until a '\0' is reached.
469 contains8bit(const char *start
, const char *end
)
474 while (*start
!= '\0' && (!end
|| (start
< end
)))
475 if (! isascii((unsigned char) *start
++))
483 * See if input has any 8-bit bytes.
486 scan_input (int fd
, int *eightbit
) {
491 lseek (fd
, (off_t
) 0, SEEK_SET
);
493 while ((state
= read (fd
, buf
, sizeof buf
)) > 0) {
494 if (contains8bit (buf
, buf
+ state
)) {
500 return state
== NOTOK
? NOTOK
: OK
;