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