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