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