1 /* utils.c -- various utility routines
2  *
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.
6  */
7 
8 #include <h/mh.h>
9 #include <h/utils.h>
10 #include <h/signals.h>
11 #include "m_mktemp.h"
12 #include "makedir.h"
13 #include <fcntl.h>
14 #include <limits.h>
15 
16 extern char *mhdocdir;
17 
18 /* plurals gives the letter ess to indicate a plural noun, or an empty
19  * string as plurals+1 for the singular noun.  Used by the PLURALS
20  * macro. */
21 const char plurals[] = "s";
22 
23 /*
24  * We allocate space for messages (msgs array)
25  * this number of elements at a time.
26  */
27 #define MAXMSGS 256
28 
29 /* Call malloc(3), exiting on NULL return. */
mh_xmalloc(size_t size)30 void *mh_xmalloc(size_t size)
31 {
32     void *p;
33 
34     if (size == 0)
35         size = 1; /* Some mallocs don't like 0. */
36     p = malloc(size);
37     if (!p)
38         adios(NULL, "malloc failed, size wanted: %zu", size);
39 
40     return p;
41 }
42 
43 /* Call realloc(3), exiting on NULL return. */
mh_xrealloc(void * ptr,size_t size)44 void *mh_xrealloc(void *ptr, size_t size)
45 {
46     void *new;
47 
48     /* Copy POSIX behaviour, coping with non-POSIX systems. */
49     if (size == 0) {
50         mh_xfree(ptr);
51         return mh_xmalloc(1); /* Get a unique pointer. */
52     }
53     if (!ptr)
54         return mh_xmalloc(size);
55 
56     new = realloc(ptr, size);
57     if (!new)
58         adios(NULL, "realloc failed, size wanted: %zu", size);
59 
60     return new;
61 }
62 
63 /* Call calloc(3), exiting on NULL return. */
mh_xcalloc(size_t nelem,size_t elsize)64 void *mh_xcalloc(size_t nelem, size_t elsize)
65 {
66     void *p;
67 
68     if (!nelem || !elsize)
69         return mh_xmalloc(1); /* Get a unique pointer. */
70 
71     p = calloc(nelem, elsize);
72     if (!p)
73         adios(NULL, "calloc failed, size wanted: %zu * %zu", nelem, elsize);
74 
75     return p;
76 }
77 
78 /* Duplicate a NUL-terminated string, exit on failure. */
mh_xstrdup(const char * src)79 char *mh_xstrdup(const char *src)
80 {
81     size_t n;
82     char *dest;
83 
84     n = strlen(src) + 1; /* Ignore possibility of overflow. */
85     dest = mh_xmalloc(n);
86     memcpy(dest, src, n);
87 
88     return dest;
89 }
90 
91 /* Call free(3), if ptr isn't NULL. */
mh_xfree(void * ptr)92 void mh_xfree(void *ptr)
93 {
94     if (ptr)
95         free(ptr); /* Some very old platforms can't cope with NULL. */
96 }
97 
98 /*
99  * Return the present working directory, if the current directory does not
100  * exist, or is too long, make / the pwd.
101  */
102 char *
pwd(void)103 pwd(void)
104 {
105     char *cp;
106     static char curwd[PATH_MAX];
107 
108     if (!getcwd (curwd, PATH_MAX)) {
109         inform("unable to determine working directory, continuing...");
110         if (!mypath || !*mypath
111                 || (strcpy (curwd, mypath), chdir (curwd)) == -1) {
112             strcpy (curwd, "/");
113             if (chdir (curwd) < 0) {
114                 advise (curwd, "chdir");
115             }
116         }
117         return curwd;
118     }
119 
120     if ((cp = curwd + strlen (curwd) - 1) > curwd && *cp == '/')
121         *cp = '\0';
122 
123     return curwd;
124 }
125 
126 /*
127  * add   -- If "s1" is NULL, this routine just creates a
128  *       -- copy of "s2" into newly malloc'ed memory.
129  *       --
130  *       -- If "s1" is not NULL, then copy the concatenation
131  *       -- of "s1" and "s2" (note the order) into newly
132  *       -- malloc'ed memory.  Then free "s1".
133  */
134 char *
add(const char * s2,char * s1)135 add (const char *s2, char *s1)
136 {
137     char *cp;
138     size_t len1 = 0, len2 = 0;
139 
140     if (s1)
141         len1 = strlen (s1);
142     if (s2)
143         len2 = strlen (s2);
144 
145     cp = mh_xmalloc (len1 + len2 + 1);
146 
147     /* Copy s1 and free it */
148     if (s1) {
149         memcpy (cp, s1, len1);
150         free (s1);
151     }
152 
153     /* Copy s2 */
154     if (s2)
155         memcpy (cp + len1, s2, len2);
156 
157     /* Now NULL terminate the string */
158     cp[len1 + len2] = '\0';
159 
160     return cp;
161 }
162 
163 /*
164  * addlist
165  *	Append an item to a comma separated list
166  */
167 char *
addlist(char * list,const char * item)168 addlist (char *list, const char *item)
169 {
170     if (list)
171     	list = add (", ", list);
172 
173     return add (item, list);
174 }
175 
176 /*
177  * folder_exists
178  *      Check to see if a folder exists.
179  */
folder_exists(const char * folder)180 int folder_exists(const char *folder)
181 {
182     struct stat st;
183 
184     return stat(folder, &st) != -1;
185 }
186 
187 /*
188  * create_folder
189  *      Check to see if a folder exists, if not, prompt the user to create
190  *      it.
191  */
create_folder(char * folder,int autocreate,void (* done_callback)(int))192 void create_folder(char *folder, int autocreate, void (*done_callback)(int))
193 {
194     struct stat st;
195     extern int errno;
196     char *cp;
197 
198     if (stat (folder, &st) == -1) {
199         if (errno != ENOENT)
200             adios (folder, "error on folder");
201         if (autocreate == 0) {
202             /* ask before creating folder */
203             cp = concat ("Create folder \"", folder, "\"? ", NULL);
204             if (!read_yes_or_no_if_tty (cp))
205                 done_callback (1);
206             free (cp);
207         } else if (autocreate == -1) {
208             /* do not create, so exit */
209             done_callback (1);
210         }
211         if (!makedir (folder))
212             adios (NULL, "unable to create folder %s", folder);
213     }
214 }
215 
216 /*
217  * num_digits
218  *      Return the number of digits in a nonnegative integer.
219  */
220 int
num_digits(int n)221 num_digits (int n)
222 {
223     int ndigits = 0;
224 
225     /* Sanity check */
226     if (n < 0)
227         adios (NULL, "oops, num_digits called with negative value");
228 
229     if (n == 0)
230         return 1;
231 
232     while (n) {
233         n /= 10;
234         ndigits++;
235     }
236 
237     return ndigits;
238 }
239 
240 /*
241  * Append a message arg to an array of them, resizing it if necessary.
242  * Really a simple vector-of-(char *) maintenance routine.
243  */
244 void
app_msgarg(struct msgs_array * msgs,char * cp)245 app_msgarg(struct msgs_array *msgs, char *cp)
246 {
247 	if(msgs->size >= msgs->max) {
248 		msgs->max += MAXMSGS;
249 		msgs->msgs = mh_xrealloc(msgs->msgs,
250 			msgs->max * sizeof(*msgs->msgs));
251 	}
252 	msgs->msgs[msgs->size++] = cp;
253 }
254 
255 /*
256  * Append a message number to an array of them, resizing it if necessary.
257  * Like app_msgarg, but with a vector-of-ints instead.
258  */
259 
260 void
app_msgnum(struct msgnum_array * msgs,int msgnum)261 app_msgnum(struct msgnum_array *msgs, int msgnum)
262 {
263 	if (msgs->size >= msgs->max) {
264 		msgs->max += MAXMSGS;
265 		msgs->msgnums = mh_xrealloc(msgs->msgnums,
266 			msgs->max * sizeof(*msgs->msgnums));
267 	}
268 	msgs->msgnums[msgs->size++] = msgnum;
269 }
270 
271 
272 /*
273  * Finds first occurrence of str in buf.  buf is not a C string but a
274  * byte array of length buflen.  str is a null-terminated C string.
275  * find_str() does not modify buf but passes back a non-const char *
276  * pointer so that the caller can modify it.
277  */
278 char *
find_str(const char buf[],size_t buflen,const char * str)279 find_str (const char buf[], size_t buflen, const char *str) {
280     const size_t len = strlen (str);
281     size_t i;
282 
283     for (i = 0; i + len <= buflen; ++i, ++buf) {
284         if (! memcmp (buf, str, len)) return (char *) buf;
285     }
286 
287     return NULL;
288 }
289 
290 
291 /*
292  * Finds last occurrence of str in buf.  buf is not a C string but a
293  * byte array of length buflen.  str is a null-terminated C string.
294  * find_str() does not modify buf but passes back a non-const char *
295  * pointer so that the caller can modify it.
296  */
297 char *
rfind_str(const char buf[],size_t buflen,const char * str)298 rfind_str (const char buf[], size_t buflen, const char *str) {
299     const size_t len = strlen (str);
300     size_t i;
301 
302     for (i = 0, buf += buflen - len; i + len <= buflen; ++i, --buf) {
303         if (! memcmp (buf, str, len)) return (char *) buf;
304     }
305 
306     return NULL;
307 }
308 
309 
310 /* POSIX doesn't have strcasestr() so emulate it. */
311 char *
nmh_strcasestr(const char * s1,const char * s2)312 nmh_strcasestr (const char *s1, const char *s2) {
313     const size_t len = strlen (s2);
314 
315     if (isupper ((unsigned char) s2[0])  ||  islower ((unsigned char)s2[0])) {
316         char first[3];
317         first[0] = (char) toupper ((unsigned char) s2[0]);
318         first[1] = (char) tolower ((unsigned char) s2[0]);
319         first[2] = '\0';
320 
321         for (s1 = strpbrk (s1, first); s1; s1 = strpbrk (++s1, first)) {
322             if (! strncasecmp (s1, s2, len)) return (char *) s1;
323         }
324     } else {
325         for (s1 = strchr (s1, s2[0]); s1; s1 = strchr (++s1, s2[0])) {
326             if (! strncasecmp (s1, s2, len)) return (char *) s1;
327         }
328     }
329 
330     return NULL;
331 }
332 
333 
334 /* truncpy copies at most size - 1 chars from non-NULL src to non-NULL,
335  * non-overlapping, dst, and ensures dst is NUL terminated.  If size is
336  * zero then it aborts as dst cannot be NUL terminated.
337  *
338  * It's to be used when truncation is intended and correct, e.g.
339  * reporting a possibly very long external string back to the user.  One
340  * of its advantages over strncpy(3) is it doesn't pad in the common
341  * case of no truncation. */
trunccpy(char * dst,const char * src,size_t size)342 void trunccpy(char *dst, const char *src, size_t size)
343 {
344     if (!size) {
345         inform("trunccpy: zero-length destination: \"%.20s\"",
346             src ? src : "null");
347         abort();
348     }
349 
350     if (strnlen(src, size) < size) {
351         strcpy(dst, src);
352     } else {
353         memcpy(dst, src, size - 1);
354         dst[size - 1] = '\0';
355     }
356 }
357 
358 
359 /* has_prefix returns true if non-NULL s starts with non-NULL prefix. */
has_prefix(const char * s,const char * prefix)360 bool has_prefix(const char *s, const char *prefix)
361 {
362     while (*s && *s == *prefix) {
363         s++;
364         prefix++;
365     }
366 
367     return *prefix == '\0';
368 }
369 
370 
371 /* has_suffix returns true if non-NULL s ends with non-NULL suffix. */
has_suffix(const char * s,const char * suffix)372 bool has_suffix(const char *s, const char *suffix)
373 {
374     size_t ls, lsuf;
375 
376     ls = strlen(s);
377     lsuf = strlen(suffix);
378 
379     return lsuf <= ls && !strcmp(s + ls - lsuf, suffix);
380 }
381 
382 
383 /* has_suffix_c returns true if non-NULL string s ends with a c before the
384  * terminating NUL. */
has_suffix_c(const char * s,int c)385 bool has_suffix_c(const char *s, int c)
386 {
387     return *s && s[strlen(s) - 1] == c;
388 }
389 
390 
391 /* trim_suffix_c deletes c from the end of non-NULL string s if it's
392  * present, shortening s by 1.  Only one instance of c is removed. */
trim_suffix_c(char * s,int c)393 void trim_suffix_c(char *s, int c)
394 {
395     if (!*s)
396         return;
397 
398     s += strlen(s) - 1;
399     if (*s == c)
400         *s = '\0';
401 }
402 
403 
404 /* to_lower runs all of s through tolower(3). */
to_lower(char * s)405 void to_lower(char *s)
406 {
407     unsigned char *b;
408 
409     for (b = (unsigned char *)s; (*b = tolower(*b)); b++)
410         ;
411 }
412 
413 
414 /* to_upper runs all of s through toupper(3). */
to_upper(char * s)415 void to_upper(char *s)
416 {
417     unsigned char *b;
418 
419     for (b = (unsigned char *)s; (*b = toupper(*b)); b++)
420         ;
421 }
422 
423 
424 int
nmh_init(const char * argv0,int read_context)425 nmh_init(const char *argv0, int read_context) {
426     int status = OK;
427     char *locale;
428 
429     invo_name = r1bindex ((char *) argv0, '/');
430 
431     if (setup_signal_handlers()) {
432         admonish("sigaction", "unable to set up signal handlers");
433     }
434 
435     /* POSIX atexit() does not define any error conditions. */
436     if (atexit(remove_registered_files_atexit)) {
437         admonish("atexit", "unable to register atexit function");
438     }
439 
440     /* Read context, if supposed to. */
441     if (read_context) {
442         int allow_version_check = 1;
443         int check_older_version = 0;
444         char *cp;
445 
446         context_read();
447 
448         if (read_context != 1  ||
449             ((cp = context_find ("Welcome")) && strcasecmp (cp, "disable") == 0)) {
450             allow_version_check = 0;
451         } else if ((cp = getenv ("MHCONTEXT")) != NULL && *cp != '\0') {
452             /* Context file comes from $MHCONTEXT, so only print the message
453                if the context file has an older version.  If it does, or if it
454                doesn't have a version at all, update the version. */
455             check_older_version = 1;
456         }
457 
458         /* Check to see if the user is running a different (or older, if
459            specified) version of nmh than they had run before, and notify them
460            if so.  But only if read_context was set to a value to enable. */
461         if (allow_version_check  &&  isatty (fileno (stdin))  &&
462             isatty (fileno (stdout))  &&  isatty (fileno (stderr))) {
463             if (nmh_version_changed (check_older_version)) {
464                 printf ("==================================================="
465                         "=====================\n");
466                 printf ("Welcome to nmh version %s\n\n", VERSION);
467                 printf ("See the release notes in %s/NEWS\n\n",
468                          mhdocdir);
469                 print_intro (stdout, 1);
470                 printf ("\nThis message will not be repeated until "
471                         "nmh is next updated.\n");
472                 printf ("==================================================="
473                         "=====================\n\n");
474 
475                 fputs ("Press enter to continue: ", stdout);
476                 (void) read_line ();
477                 putchar ('\n');
478             }
479         }
480     } else {
481         if ((status = context_foil(NULL)) != OK) {
482             advise("", "failed to create minimal profile/context");
483         }
484     }
485 
486     /* Allow the user to set a locale in their profile.  Otherwise, use the
487        "" string to pull it from their environment, see setlocale(3). */
488     if ((locale = context_find ("locale")) == NULL) {
489         locale = "";
490     }
491 
492     if (! setlocale (LC_ALL, locale)) {
493         inform("setlocale failed, check your LC_ALL, LC_CTYPE, and LANG "
494 	    "environment variables, continuing...");
495     }
496 
497     return status;
498 }
499 
500 
501 /*
502  * Check stored version, and return 1 if out-of-date or non-existent.
503  * Because the output of "mhparam version" is prefixed with "nmh-",
504  * use that prefix here.
505  */
506 int
nmh_version_changed(int older)507 nmh_version_changed (int older) {
508     const char *const context_version = context_find("Version");
509 
510     if (older) {
511         /* Convert the version strings to floats and compare them.  This will
512            break for versions with multiple decimal points, etc. */
513         const float current_version = strtof (VERSION, NULL);
514         const float old_version =
515             context_version  &&  has_prefix(context_version, "nmh-")
516             ?  strtof (context_version + 4, NULL)
517             :  99999999;
518 
519         if (context_version == NULL  ||  old_version < current_version) {
520             context_replace ("Version", "nmh-" VERSION);
521         }
522 
523         return old_version < current_version;
524     }
525 
526     if (context_version == NULL  ||  strcmp(context_version, "nmh-" VERSION) != 0) {
527         context_replace ("Version", "nmh-" VERSION);
528         return 1;
529     }
530 
531     return 0;
532 }
533 
534 
535 /*
536  * Scan for any 8-bit characters.  Return 1 if they exist.
537  *
538  * Scan up until the given endpoint (but not the actual endpoint itself).
539  * If the endpoint is NULL, scan until a '\0' is reached.
540  */
541 
542 int
contains8bit(const char * start,const char * end)543 contains8bit(const char *start, const char *end)
544 {
545     if (! start)
546 	return 0;
547 
548     while (*start != '\0' && (!end || (start < end)))
549 	if (! isascii((unsigned char) *start++))
550 	    return 1;
551 
552     return 0;
553 }
554 
555 
556 /*
557  * See if input has any 8-bit bytes.
558  */
559 int
scan_input(int fd,int * eightbit)560 scan_input (int fd, int *eightbit) {
561     int state;
562     char buf[BUFSIZ];
563 
564     *eightbit = 0;
565     lseek(fd, 0, SEEK_SET);
566 
567     while ((state = read (fd, buf, sizeof buf)) > 0) {
568         if (contains8bit (buf, buf + state)) {
569             *eightbit = 1;
570             return OK;
571         }
572     }
573 
574     return state == NOTOK  ?  NOTOK  :  OK;
575 }
576 
577 
578 /*
579  * Convert an int to a char string.
580  */
581 char *
m_str(int value)582 m_str(int value) {
583     return m_strn(value, 0);
584 }
585 
586 
587 /*
588  * Convert an int to a char string, of limited width if > 0.
589  */
590 #define STR(s) #s
591 /* SIZE(n) includes NUL.  n must just be digits, not an equation. */
592 #define SIZE(n) (sizeof STR(n))
593 
594 char *
m_strn(int value,unsigned int width)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);
600 
601     return num_chars > 0  &&  (width == 0 || (unsigned int) num_chars <= width)
602         ? buffer
603         : "?";
604 }
605