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