]> diplodocus.org Git - nmh/blob - sbr/utils.c
158f998bf0050f4a527f332847d2f7819d8d2a71
[nmh] / sbr / utils.c
1 /*
2 * utils.c -- various utility routines
3 *
4 * This code is Copyright (c) 2006, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <h/utils.h>
11 #include <fcntl.h>
12
13 /* sbr/signals.c */
14 extern int setup_signal_handlers();
15
16 /* sbr/m_mktemp.c */
17 extern void remove_registered_files_atexit();
18
19 extern char *mhdocdir;
20
21 /*
22 * We allocate space for messages (msgs array)
23 * this number of elements at a time.
24 */
25 #define MAXMSGS 256
26
27 /* Call malloc(3), exiting on NULL return. */
28 void *mh_xmalloc(size_t size)
29 {
30 void *p;
31
32 if (size == 0)
33 size = 1; /* Some mallocs don't like 0. */
34 p = malloc(size);
35 if (!p)
36 adios(NULL, "malloc failed, size wanted: %zu", size);
37
38 return p;
39 }
40
41 /* Call realloc(3), exiting on NULL return. */
42 void *mh_xrealloc(void *ptr, size_t size)
43 {
44 void *new;
45
46 /* Copy POSIX behaviour, coping with non-POSIX systems. */
47 if (size == 0) {
48 mh_xfree(ptr);
49 return mh_xmalloc(1); /* Get a unique pointer. */
50 }
51 if (!ptr)
52 return mh_xmalloc(size);
53
54 new = realloc(ptr, size);
55 if (!new)
56 adios(NULL, "realloc failed, size wanted: %zu", size);
57
58 return new;
59 }
60
61 /* Call calloc(3), exiting on NULL return. */
62 void *mh_xcalloc(size_t nelem, size_t elsize)
63 {
64 void *p;
65
66 if (!nelem || !elsize)
67 return mh_xmalloc(1); /* Get a unique pointer. */
68
69 p = calloc(nelem, elsize);
70 if (!p)
71 adios(NULL, "calloc failed, size wanted: %zu * %zu", nelem, elsize);
72
73 return p;
74 }
75
76 /* Duplicate a NUL-terminated string, exit on failure. */
77 char *mh_xstrdup(const char *src)
78 {
79 size_t n;
80 char *dest;
81
82 n = strlen(src) + 1; /* Ignore possibility of overflow. */
83 dest = mh_xmalloc(n);
84 memcpy(dest, src, n);
85
86 return dest;
87 }
88
89 /* Call free(3), if ptr isn't NULL. */
90 void mh_xfree(void *ptr)
91 {
92 if (ptr)
93 free(ptr); /* Some very old platforms can't cope with NULL. */
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 /*
125 * add -- If "s1" is NULL, this routine just creates a
126 * -- copy of "s2" into newly malloc'ed memory.
127 * --
128 * -- If "s1" is not NULL, then copy the concatenation
129 * -- of "s1" and "s2" (note the order) into newly
130 * -- malloc'ed memory. Then free "s1".
131 */
132 char *
133 add (const char *s2, char *s1)
134 {
135 char *cp;
136 size_t len1 = 0, len2 = 0;
137
138 if (s1)
139 len1 = strlen (s1);
140 if (s2)
141 len2 = strlen (s2);
142
143 cp = mh_xmalloc (len1 + len2 + 1);
144
145 /* Copy s1 and free it */
146 if (s1) {
147 memcpy (cp, s1, len1);
148 free (s1);
149 }
150
151 /* Copy s2 */
152 if (s2)
153 memcpy (cp + len1, s2, len2);
154
155 /* Now NULL terminate the string */
156 cp[len1 + len2] = '\0';
157
158 return cp;
159 }
160
161 /*
162 * addlist
163 * Append an item to a comma separated list
164 */
165 char *
166 addlist (char *list, const char *item)
167 {
168 if (list)
169 list = add (", ", list);
170
171 return add (item, list);
172 }
173
174 /*
175 * folder_exists
176 * Check to see if a folder exists.
177 */
178 int folder_exists(const char *folder)
179 {
180 struct stat st;
181
182 return stat(folder, &st) != -1;
183 }
184
185 /*
186 * create_folder
187 * Check to see if a folder exists, if not, prompt the user to create
188 * it.
189 */
190 void create_folder(char *folder, int autocreate, void (*done_callback)(int))
191 {
192 struct stat st;
193 extern int errno;
194 char *cp;
195
196 if (stat (folder, &st) == -1) {
197 if (errno != ENOENT)
198 adios (folder, "error on folder");
199 if (autocreate == 0) {
200 /* ask before creating folder */
201 cp = concat ("Create folder \"", folder, "\"? ", NULL);
202 if (!read_yes_or_no_if_tty (cp))
203 done_callback (1);
204 free (cp);
205 } else if (autocreate == -1) {
206 /* do not create, so exit */
207 done_callback (1);
208 }
209 if (!makedir (folder))
210 adios (NULL, "unable to create folder %s", folder);
211 }
212 }
213
214 /*
215 * num_digits
216 * Return the number of digits in a nonnegative integer.
217 */
218 int
219 num_digits (int n)
220 {
221 int ndigits = 0;
222
223 /* Sanity check */
224 if (n < 0)
225 adios (NULL, "oops, num_digits called with negative value");
226
227 if (n == 0)
228 return 1;
229
230 while (n) {
231 n /= 10;
232 ndigits++;
233 }
234
235 return ndigits;
236 }
237
238 /*
239 * Append a message arg to an array of them, resizing it if necessary.
240 * Really a simple vector-of-(char *) maintenance routine.
241 */
242 void
243 app_msgarg(struct msgs_array *msgs, char *cp)
244 {
245 if(msgs->size >= msgs->max) {
246 msgs->max += MAXMSGS;
247 msgs->msgs = mh_xrealloc(msgs->msgs,
248 msgs->max * sizeof(*msgs->msgs));
249 }
250 msgs->msgs[msgs->size++] = cp;
251 }
252
253 /*
254 * Append a message number to an array of them, resizing it if necessary.
255 * Like app_msgarg, but with a vector-of-ints instead.
256 */
257
258 void
259 app_msgnum(struct msgnum_array *msgs, int msgnum)
260 {
261 if (msgs->size >= msgs->max) {
262 msgs->max += MAXMSGS;
263 msgs->msgnums = mh_xrealloc(msgs->msgnums,
264 msgs->max * sizeof(*msgs->msgnums));
265 }
266 msgs->msgnums[msgs->size++] = msgnum;
267 }
268
269 /* Open a form or components file */
270 int
271 open_form(char **form, char *def)
272 {
273 int in;
274 if (*form) {
275 if ((in = open (etcpath (*form), O_RDONLY)) == NOTOK)
276 adios (*form, "unable to open form file");
277 } else {
278 if ((in = open (etcpath (def), O_RDONLY)) == NOTOK)
279 adios (def, "unable to open default components file");
280 *form = def;
281 }
282 return in;
283 }
284
285
286 /*
287 * Finds first occurrence of str in buf. buf is not a C string but a
288 * byte array of length buflen. str is a null-terminated C string.
289 * find_str() does not modify buf but passes back a non-const char *
290 * pointer so that the caller can modify it.
291 */
292 char *
293 find_str (const char buf[], size_t buflen, const char *str) {
294 const size_t len = strlen (str);
295 size_t i;
296
297 for (i = 0; i + len <= buflen; ++i, ++buf) {
298 if (! memcmp (buf, str, len)) return (char *) buf;
299 }
300
301 return NULL;
302 }
303
304
305 /*
306 * Finds last occurrence of str in buf. buf is not a C string but a
307 * byte array of length buflen. str is a null-terminated C string.
308 * find_str() does not modify buf but passes back a non-const char *
309 * pointer so that the caller can modify it.
310 */
311 char *
312 rfind_str (const char buf[], size_t buflen, const char *str) {
313 const size_t len = strlen (str);
314 size_t i;
315
316 for (i = 0, buf += buflen - len; i + len <= buflen; ++i, --buf) {
317 if (! memcmp (buf, str, len)) return (char *) buf;
318 }
319
320 return NULL;
321 }
322
323
324 /* POSIX doesn't have strcasestr() so emulate it. */
325 char *
326 nmh_strcasestr (const char *s1, const char *s2) {
327 const size_t len = strlen (s2);
328
329 if (isupper ((unsigned char) s2[0]) || islower ((unsigned char)s2[0])) {
330 char first[3];
331 first[0] = (char) toupper ((unsigned char) s2[0]);
332 first[1] = (char) tolower ((unsigned char) s2[0]);
333 first[2] = '\0';
334
335 for (s1 = strpbrk (s1, first); s1; s1 = strpbrk (++s1, first)) {
336 if (! strncasecmp (s1, s2, len)) return (char *) s1;
337 }
338 } else {
339 for (s1 = strchr (s1, s2[0]); s1; s1 = strchr (++s1, s2[0])) {
340 if (! strncasecmp (s1, s2, len)) return (char *) s1;
341 }
342 }
343
344 return NULL;
345 }
346
347
348 /* truncpy copies at most size - 1 chars from non-NULL src to non-NULL,
349 * non-overlapping, dst, and ensures dst is NUL terminated. If size is
350 * zero then it aborts as dst cannot be NUL terminated.
351 *
352 * It's to be used when truncation is intended and correct, e.g.
353 * reporting a possibly very long external string back to the user. One
354 * of its advantages over strncpy(3) is it doesn't pad in the common
355 * case of no truncation. */
356 void trunccpy(char *dst, const char *src, size_t size)
357 {
358 if (!size) {
359 inform("trunccpy: zero-length destination: \"%.20s\"",
360 src ? src : "null");
361 abort();
362 }
363
364 if (strnlen(src, size) < size) {
365 strcpy(dst, src);
366 } else {
367 memcpy(dst, src, size - 1);
368 dst[size - 1] = '\0';
369 }
370 }
371
372
373 /* has_prefix returns true if non-NULL s starts with non-NULL prefix. */
374 bool has_prefix(const char *s, const char *prefix)
375 {
376 while (*s && *s == *prefix) {
377 s++;
378 prefix++;
379 }
380
381 return *prefix == '\0';
382 }
383
384
385 /* has_suffix returns true if non-NULL s ends with non-NULL suffix. */
386 bool 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 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 trim_suffix_c(char *s, int c)
408 {
409 if (!*s)
410 return;
411
412 s += strlen(s) - 1;
413 if (*s == c)
414 *s = '\0';
415 }
416
417
418 /* to_lower runs all of s through tolower(3). */
419 void to_lower(char *s)
420 {
421 unsigned char *b;
422
423 for (b = (unsigned char *)s; (*b = tolower(*b)); b++)
424 ;
425 }
426
427
428 /* to_upper runs all of s through toupper(3). */
429 void to_upper(char *s)
430 {
431 unsigned char *b;
432
433 for (b = (unsigned char *)s; (*b = toupper(*b)); b++)
434 ;
435 }
436
437
438 int
439 nmh_init(const char *argv0, int read_context) {
440 int status = OK;
441 char *locale;
442
443 invo_name = r1bindex ((char *) argv0, '/');
444
445 if (setup_signal_handlers()) {
446 admonish("sigaction", "unable to set up signal handlers");
447 }
448
449 /* POSIX atexit() does not define any error conditions. */
450 if (atexit(remove_registered_files_atexit)) {
451 admonish("atexit", "unable to register atexit function");
452 }
453
454 /* Read context, if supposed to. */
455 if (read_context) {
456 int allow_version_check = 1;
457 int check_older_version = 0;
458 char *cp;
459
460 context_read();
461
462 if (read_context != 1 ||
463 ((cp = context_find ("Welcome")) && strcasecmp (cp, "disable") == 0)) {
464 allow_version_check = 0;
465 } else if ((cp = getenv ("MHCONTEXT")) != NULL && *cp != '\0') {
466 /* Context file comes from $MHCONTEXT, so only print the message
467 if the context file has an older version. If it does, or if it
468 doesn't have a version at all, update the version. */
469 check_older_version = 1;
470 }
471
472 /* Check to see if the user is running a different (or older, if
473 specified) version of nmh than they had run bfore, and notify them
474 if so. But only if read_context was set to a value to enable. */
475 if (allow_version_check && isatty (fileno (stdin)) &&
476 isatty (fileno (stdout)) && isatty (fileno (stderr))) {
477 if (nmh_version_changed (check_older_version)) {
478 printf ("==================================================="
479 "=====================\n");
480 printf ("Welcome to nmh version %s\n\n", VERSION);
481 printf ("See the release notes in %s/NEWS\n\n",
482 mhdocdir);
483 print_intro (stdout, 1);
484 printf ("\nThis message will not be repeated until "
485 "nmh is next updated.\n");
486 printf ("==================================================="
487 "=====================\n\n");
488
489 fputs ("Press enter to continue: ", stdout);
490 (void) read_line ();
491 putchar ('\n');
492 }
493 }
494 } else {
495 if ((status = context_foil(NULL)) != OK) {
496 advise("", "failed to create minimal profile/context");
497 }
498 }
499
500 /* Allow the user to set a locale in their profile. Otherwise, use the
501 "" string to pull it from their environment, see setlocale(3). */
502 if ((locale = context_find ("locale")) == NULL) {
503 locale = "";
504 }
505
506 if (! setlocale (LC_ALL, locale)) {
507 inform("setlocale failed, check your LC_ALL, LC_CTYPE, and LANG "
508 "environment variables, continuing...");
509 }
510
511 return status;
512 }
513
514
515 /*
516 * Check stored version, and return 1 if out-of-date or non-existent.
517 * Because the output of "mhparam version" is prefixed with "nmh-",
518 * use that prefix here.
519 */
520 int
521 nmh_version_changed (int older) {
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 ? 1 : 0;
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 /* Returns copy of argument str with all characters converted to upper
550 case, and trimmed whitespace (see cpytrim()) . */
551 char *
552 upcase (const char *str) {
553 char *up = cpytrim (str);
554
555 to_upper(up);
556
557 return up;
558 }
559
560
561 /*
562 * Scan for any 8-bit characters. Return 1 if they exist.
563 *
564 * Scan up until the given endpoint (but not the actual endpoint itself).
565 * If the endpoint is NULL, scan until a '\0' is reached.
566 */
567
568 int
569 contains8bit(const char *start, const char *end)
570 {
571 if (! start)
572 return 0;
573
574 while (*start != '\0' && (!end || (start < end)))
575 if (! isascii((unsigned char) *start++))
576 return 1;
577
578 return 0;
579 }
580
581
582 /*
583 * See if input has any 8-bit bytes.
584 */
585 int
586 scan_input (int fd, int *eightbit) {
587 int state;
588 char buf[BUFSIZ];
589
590 *eightbit = 0;
591 lseek (fd, (off_t) 0, SEEK_SET);
592
593 while ((state = read (fd, buf, sizeof buf)) > 0) {
594 if (contains8bit (buf, buf + state)) {
595 *eightbit = 1;
596 return OK;
597 }
598 }
599
600 return state == NOTOK ? NOTOK : OK;
601 }