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