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