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