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