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