]> diplodocus.org Git - nmh/blob - sbr/utils.c
h/prototypes.h: Remove scan_reset_m_getfld_state() prototype.
[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 <fcntl.h>
11
12 /* sbr/signals.c */
13 extern int setup_signal_handlers();
14
15 /* sbr/m_mktemp.c */
16 extern void remove_registered_files_atexit();
17
18 extern char *mhdocdir;
19
20 /* plurals gives the letter ess to indicate a plural noun, or an empty
21 * string as plurals+1 for the singular noun. Used by the PLURALS
22 * macro. */
23 const char plurals[] = "s";
24
25 /*
26 * We allocate space for messages (msgs array)
27 * this number of elements at a time.
28 */
29 #define MAXMSGS 256
30
31 /* Call malloc(3), exiting on NULL return. */
32 void *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 adios(NULL, "malloc failed, size wanted: %zu", size);
41
42 return p;
43 }
44
45 /* Call realloc(3), exiting on NULL return. */
46 void *mh_xrealloc(void *ptr, size_t size)
47 {
48 void *new;
49
50 /* Copy POSIX behaviour, coping with non-POSIX systems. */
51 if (size == 0) {
52 mh_xfree(ptr);
53 return mh_xmalloc(1); /* Get a unique pointer. */
54 }
55 if (!ptr)
56 return mh_xmalloc(size);
57
58 new = realloc(ptr, size);
59 if (!new)
60 adios(NULL, "realloc failed, size wanted: %zu", size);
61
62 return new;
63 }
64
65 /* Call calloc(3), exiting on NULL return. */
66 void *mh_xcalloc(size_t nelem, size_t elsize)
67 {
68 void *p;
69
70 if (!nelem || !elsize)
71 return mh_xmalloc(1); /* Get a unique pointer. */
72
73 p = calloc(nelem, elsize);
74 if (!p)
75 adios(NULL, "calloc failed, size wanted: %zu * %zu", nelem, elsize);
76
77 return p;
78 }
79
80 /* Duplicate a NUL-terminated string, exit on failure. */
81 char *mh_xstrdup(const char *src)
82 {
83 size_t n;
84 char *dest;
85
86 n = strlen(src) + 1; /* Ignore possibility of overflow. */
87 dest = mh_xmalloc(n);
88 memcpy(dest, src, n);
89
90 return dest;
91 }
92
93 /* Call free(3), if ptr isn't NULL. */
94 void mh_xfree(void *ptr)
95 {
96 if (ptr)
97 free(ptr); /* Some very old platforms can't cope with NULL. */
98 }
99
100 /*
101 * Return the present working directory, if the current directory does not
102 * exist, or is too long, make / the pwd.
103 */
104 char *
105 pwd(void)
106 {
107 char *cp;
108 static char curwd[PATH_MAX];
109
110 if (!getcwd (curwd, PATH_MAX)) {
111 inform("unable to determine working directory, continuing...");
112 if (!mypath || !*mypath
113 || (strcpy (curwd, mypath), chdir (curwd)) == -1) {
114 strcpy (curwd, "/");
115 if (chdir (curwd) < 0) {
116 advise (curwd, "chdir");
117 }
118 }
119 return curwd;
120 }
121
122 if ((cp = curwd + strlen (curwd) - 1) > curwd && *cp == '/')
123 *cp = '\0';
124
125 return curwd;
126 }
127
128 /*
129 * add -- If "s1" is NULL, this routine just creates a
130 * -- copy of "s2" into newly malloc'ed memory.
131 * --
132 * -- If "s1" is not NULL, then copy the concatenation
133 * -- of "s1" and "s2" (note the order) into newly
134 * -- malloc'ed memory. Then free "s1".
135 */
136 char *
137 add (const char *s2, char *s1)
138 {
139 char *cp;
140 size_t len1 = 0, len2 = 0;
141
142 if (s1)
143 len1 = strlen (s1);
144 if (s2)
145 len2 = strlen (s2);
146
147 cp = mh_xmalloc (len1 + len2 + 1);
148
149 /* Copy s1 and free it */
150 if (s1) {
151 memcpy (cp, s1, len1);
152 free (s1);
153 }
154
155 /* Copy s2 */
156 if (s2)
157 memcpy (cp + len1, s2, len2);
158
159 /* Now NULL terminate the string */
160 cp[len1 + len2] = '\0';
161
162 return cp;
163 }
164
165 /*
166 * addlist
167 * Append an item to a comma separated list
168 */
169 char *
170 addlist (char *list, const char *item)
171 {
172 if (list)
173 list = add (", ", list);
174
175 return add (item, list);
176 }
177
178 /*
179 * folder_exists
180 * Check to see if a folder exists.
181 */
182 int folder_exists(const char *folder)
183 {
184 struct stat st;
185
186 return stat(folder, &st) != -1;
187 }
188
189 /*
190 * create_folder
191 * Check to see if a folder exists, if not, prompt the user to create
192 * it.
193 */
194 void 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 adios (NULL, "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 adios (NULL, "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 /* Open a form or components file */
274 int
275 open_form(char **form, char *def)
276 {
277 int in;
278 if (*form) {
279 if ((in = open (etcpath (*form), O_RDONLY)) == NOTOK)
280 adios (*form, "unable to open form file");
281 } else {
282 if ((in = open (etcpath (def), O_RDONLY)) == NOTOK)
283 adios (def, "unable to open default components file");
284 *form = def;
285 }
286 return in;
287 }
288
289
290 /*
291 * Finds first occurrence of str in buf. buf is not a C string but a
292 * byte array of length buflen. str is a null-terminated C string.
293 * find_str() does not modify buf but passes back a non-const char *
294 * pointer so that the caller can modify it.
295 */
296 char *
297 find_str (const char buf[], size_t buflen, const char *str) {
298 const size_t len = strlen (str);
299 size_t i;
300
301 for (i = 0; i + len <= buflen; ++i, ++buf) {
302 if (! memcmp (buf, str, len)) return (char *) buf;
303 }
304
305 return NULL;
306 }
307
308
309 /*
310 * Finds last occurrence of str in buf. buf is not a C string but a
311 * byte array of length buflen. str is a null-terminated C string.
312 * find_str() does not modify buf but passes back a non-const char *
313 * pointer so that the caller can modify it.
314 */
315 char *
316 rfind_str (const char buf[], size_t buflen, const char *str) {
317 const size_t len = strlen (str);
318 size_t i;
319
320 for (i = 0, buf += buflen - len; i + len <= buflen; ++i, --buf) {
321 if (! memcmp (buf, str, len)) return (char *) buf;
322 }
323
324 return NULL;
325 }
326
327
328 /* POSIX doesn't have strcasestr() so emulate it. */
329 char *
330 nmh_strcasestr (const char *s1, const char *s2) {
331 const size_t len = strlen (s2);
332
333 if (isupper ((unsigned char) s2[0]) || islower ((unsigned char)s2[0])) {
334 char first[3];
335 first[0] = (char) toupper ((unsigned char) s2[0]);
336 first[1] = (char) tolower ((unsigned char) s2[0]);
337 first[2] = '\0';
338
339 for (s1 = strpbrk (s1, first); s1; s1 = strpbrk (++s1, first)) {
340 if (! strncasecmp (s1, s2, len)) return (char *) s1;
341 }
342 } else {
343 for (s1 = strchr (s1, s2[0]); s1; s1 = strchr (++s1, s2[0])) {
344 if (! strncasecmp (s1, s2, len)) return (char *) s1;
345 }
346 }
347
348 return NULL;
349 }
350
351
352 /* truncpy copies at most size - 1 chars from non-NULL src to non-NULL,
353 * non-overlapping, dst, and ensures dst is NUL terminated. If size is
354 * zero then it aborts as dst cannot be NUL terminated.
355 *
356 * It's to be used when truncation is intended and correct, e.g.
357 * reporting a possibly very long external string back to the user. One
358 * of its advantages over strncpy(3) is it doesn't pad in the common
359 * case of no truncation. */
360 void trunccpy(char *dst, const char *src, size_t size)
361 {
362 if (!size) {
363 inform("trunccpy: zero-length destination: \"%.20s\"",
364 src ? src : "null");
365 abort();
366 }
367
368 if (strnlen(src, size) < size) {
369 strcpy(dst, src);
370 } else {
371 memcpy(dst, src, size - 1);
372 dst[size - 1] = '\0';
373 }
374 }
375
376
377 /* has_prefix returns true if non-NULL s starts with non-NULL prefix. */
378 bool has_prefix(const char *s, const char *prefix)
379 {
380 while (*s && *s == *prefix) {
381 s++;
382 prefix++;
383 }
384
385 return *prefix == '\0';
386 }
387
388
389 /* has_suffix returns true if non-NULL s ends with non-NULL suffix. */
390 bool has_suffix(const char *s, const char *suffix)
391 {
392 size_t ls, lsuf;
393
394 ls = strlen(s);
395 lsuf = strlen(suffix);
396
397 return lsuf <= ls && !strcmp(s + ls - lsuf, suffix);
398 }
399
400
401 /* has_suffix_c returns true if non-NULL string s ends with a c before the
402 * terminating NUL. */
403 bool has_suffix_c(const char *s, int c)
404 {
405 return *s && s[strlen(s) - 1] == c;
406 }
407
408
409 /* trim_suffix_c deletes c from the end of non-NULL string s if it's
410 * present, shortening s by 1. Only one instance of c is removed. */
411 void trim_suffix_c(char *s, int c)
412 {
413 if (!*s)
414 return;
415
416 s += strlen(s) - 1;
417 if (*s == c)
418 *s = '\0';
419 }
420
421
422 /* to_lower runs all of s through tolower(3). */
423 void to_lower(char *s)
424 {
425 unsigned char *b;
426
427 for (b = (unsigned char *)s; (*b = tolower(*b)); b++)
428 ;
429 }
430
431
432 /* to_upper runs all of s through toupper(3). */
433 void to_upper(char *s)
434 {
435 unsigned char *b;
436
437 for (b = (unsigned char *)s; (*b = toupper(*b)); b++)
438 ;
439 }
440
441
442 int
443 nmh_init(const char *argv0, int read_context) {
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 int allow_version_check = 1;
461 int check_older_version = 0;
462 char *cp;
463
464 context_read();
465
466 if (read_context != 1 ||
467 ((cp = context_find ("Welcome")) && strcasecmp (cp, "disable") == 0)) {
468 allow_version_check = 0;
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 = 1;
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. But only if read_context was set to a value to enable. */
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 const char *const context_version = context_find("Version");
527
528 if (older) {
529 /* Convert the version strings to floats and compare them. This will
530 break for versions with multiple decimal points, etc. */
531 const float current_version = strtof (VERSION, NULL);
532 const float old_version =
533 context_version && has_prefix(context_version, "nmh-")
534 ? strtof (context_version + 4, NULL)
535 : 99999999;
536
537 if (context_version == NULL || old_version < current_version) {
538 context_replace ("Version", "nmh-" VERSION);
539 }
540
541 return old_version < current_version;
542 }
543
544 if (context_version == NULL || strcmp(context_version, "nmh-" VERSION) != 0) {
545 context_replace ("Version", "nmh-" VERSION);
546 return 1;
547 }
548
549 return 0;
550 }
551
552
553 /* Returns copy of argument str with all characters converted to upper
554 case, and trimmed whitespace (see cpytrim()) . */
555 char *
556 upcase (const char *str) {
557 char *up = cpytrim (str);
558
559 to_upper(up);
560
561 return up;
562 }
563
564
565 /*
566 * Scan for any 8-bit characters. Return 1 if they exist.
567 *
568 * Scan up until the given endpoint (but not the actual endpoint itself).
569 * If the endpoint is NULL, scan until a '\0' is reached.
570 */
571
572 int
573 contains8bit(const char *start, const char *end)
574 {
575 if (! start)
576 return 0;
577
578 while (*start != '\0' && (!end || (start < end)))
579 if (! isascii((unsigned char) *start++))
580 return 1;
581
582 return 0;
583 }
584
585
586 /*
587 * See if input has any 8-bit bytes.
588 */
589 int
590 scan_input (int fd, int *eightbit) {
591 int state;
592 char buf[BUFSIZ];
593
594 *eightbit = 0;
595 lseek (fd, (off_t) 0, SEEK_SET);
596
597 while ((state = read (fd, buf, sizeof buf)) > 0) {
598 if (contains8bit (buf, buf + state)) {
599 *eightbit = 1;
600 return OK;
601 }
602 }
603
604 return state == NOTOK ? NOTOK : OK;
605 }