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