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