]> diplodocus.org Git - nmh/blob - sbr/utils.c
Don't need to cast to `char *' for free(3) these days.
[nmh] / sbr / utils.c
1
2 /*
3 * utils.c -- various utility routines
4 *
5 * This code is Copyright (c) 2006, by the authors of nmh. See the
6 * COPYRIGHT file in the root directory of the nmh distribution for
7 * complete copyright information.
8 */
9
10 #include <h/mh.h>
11 #include <h/utils.h>
12 #include <fcntl.h>
13
14 /* sbr/signals.c */
15 extern int setup_signal_handlers();
16
17 /* sbr/m_mktemp.c */
18 extern void remove_registered_files_atexit();
19
20 extern char *mhdocdir;
21
22 /*
23 * We allocate space for messages (msgs array)
24 * this number of elements at a time.
25 */
26 #define MAXMSGS 256
27
28 /* Call malloc(3), exiting on NULL return. */
29 void *mh_xmalloc(size_t size)
30 {
31 void *p;
32
33 if (size == 0)
34 size = 1; /* Some mallocs don't like 0. */
35 p = malloc(size);
36 if (!p)
37 adios(NULL, "malloc failed, size wanted: %zu", size);
38
39 return p;
40 }
41
42 /* Call realloc(3), exiting on NULL return. */
43 void *mh_xrealloc(void *ptr, size_t size)
44 {
45 void *new;
46
47 /* Copy POSIX behaviour, coping with non-POSIX systems. */
48 if (size == 0) {
49 mh_xfree(ptr);
50 return mh_xmalloc(1); /* Get a unique pointer. */
51 }
52 if (!ptr)
53 return mh_xmalloc(size);
54
55 new = realloc(ptr, size);
56 if (!new)
57 adios(NULL, "realloc failed, size wanted: %zu", size);
58
59 return new;
60 }
61
62 /* Call calloc(3), exiting on NULL return. */
63 void *mh_xcalloc(size_t nelem, size_t elsize)
64 {
65 void *p;
66
67 if (!nelem || !elsize)
68 return mh_xmalloc(1); /* Get a unique pointer. */
69
70 p = calloc(nelem, elsize);
71 if (!p)
72 adios(NULL, "calloc failed, size wanted: %zu * %zu", nelem, elsize);
73
74 return p;
75 }
76
77 /* Duplicate a NUL-terminated string, exit on failure. */
78 char *mh_xstrdup(const char *src)
79 {
80 size_t n;
81 char *dest;
82
83 n = strlen(src) + 1; /* Ignore possibility of overflow. */
84 dest = mh_xmalloc(n);
85 memcpy(dest, src, n);
86
87 return dest;
88 }
89
90 /* Call free(3), if ptr isn't NULL. */
91 void mh_xfree(void *ptr)
92 {
93 if (ptr)
94 free(ptr); /* Some very old platforms can't cope with NULL. */
95 }
96
97 /*
98 * Return the present working directory, if the current directory does not
99 * exist, or is too long, make / the pwd.
100 */
101 char *
102 pwd(void)
103 {
104 char *cp;
105 static char curwd[PATH_MAX];
106
107 if (!getcwd (curwd, PATH_MAX)) {
108 admonish (NULL, "unable to determine working directory");
109 if (!mypath || !*mypath
110 || (strcpy (curwd, mypath), chdir (curwd)) == -1) {
111 strcpy (curwd, "/");
112 if (chdir (curwd) < 0) {
113 advise (curwd, "chdir");
114 }
115 }
116 return curwd;
117 }
118
119 if ((cp = curwd + strlen (curwd) - 1) > curwd && *cp == '/')
120 *cp = '\0';
121
122 return curwd;
123 }
124
125 /*
126 * add -- If "s1" is NULL, this routine just creates a
127 * -- copy of "s2" into newly malloc'ed memory.
128 * --
129 * -- If "s1" is not NULL, then copy the concatenation
130 * -- of "s1" and "s2" (note the order) into newly
131 * -- malloc'ed memory. Then free "s1".
132 */
133 char *
134 add (const char *s2, char *s1)
135 {
136 char *cp;
137 size_t len1 = 0, len2 = 0;
138
139 if (s1)
140 len1 = strlen (s1);
141 if (s2)
142 len2 = strlen (s2);
143
144 cp = mh_xmalloc (len1 + len2 + 1);
145
146 /* Copy s1 and free it */
147 if (s1) {
148 memcpy (cp, s1, len1);
149 free (s1);
150 }
151
152 /* Copy s2 */
153 if (s2)
154 memcpy (cp + len1, s2, len2);
155
156 /* Now NULL terminate the string */
157 cp[len1 + len2] = '\0';
158
159 return cp;
160 }
161
162 /*
163 * addlist
164 * Append an item to a comma separated list
165 */
166 char *
167 addlist (char *list, const char *item)
168 {
169 if (list)
170 list = add (", ", list);
171
172 return add (item, list);
173 }
174
175 /*
176 * folder_exists
177 * Check to see if a folder exists.
178 */
179 int folder_exists(const char *folder)
180 {
181 struct stat st;
182 int exists = 0;
183
184 if (stat (folder, &st) == -1) {
185 /* The folder either doesn't exist, or we hit an error. Either way
186 * return a failure.
187 */
188 exists = 0;
189 } else {
190 /* We can see a folder with the right name */
191 exists = 1;
192 }
193
194 return exists;
195 }
196
197
198 /*
199 * create_folder
200 * Check to see if a folder exists, if not, prompt the user to create
201 * it.
202 */
203 void create_folder(char *folder, int autocreate, void (*done_callback)(int))
204 {
205 struct stat st;
206 extern int errno;
207 char *cp;
208
209 if (stat (folder, &st) == -1) {
210 if (errno != ENOENT)
211 adios (folder, "error on folder");
212 if (autocreate == 0) {
213 /* ask before creating folder */
214 cp = concat ("Create folder \"", folder, "\"? ", NULL);
215 if (!read_yes_or_no_if_tty (cp))
216 done_callback (1);
217 free (cp);
218 } else if (autocreate == -1) {
219 /* do not create, so exit */
220 done_callback (1);
221 }
222 if (!makedir (folder))
223 adios (NULL, "unable to create folder %s", folder);
224 }
225 }
226
227 /*
228 * num_digits
229 * Return the number of digits in a nonnegative integer.
230 */
231 int
232 num_digits (int n)
233 {
234 int ndigits = 0;
235
236 /* Sanity check */
237 if (n < 0)
238 adios (NULL, "oops, num_digits called with negative value");
239
240 if (n == 0)
241 return 1;
242
243 while (n) {
244 n /= 10;
245 ndigits++;
246 }
247
248 return ndigits;
249 }
250
251 /*
252 * Append a message arg to an array of them, resizing it if necessary.
253 * Really a simple vector-of-(char *) maintenance routine.
254 */
255 void
256 app_msgarg(struct msgs_array *msgs, char *cp)
257 {
258 if(msgs->size >= msgs->max) {
259 msgs->max += MAXMSGS;
260 msgs->msgs = mh_xrealloc(msgs->msgs,
261 msgs->max * sizeof(*msgs->msgs));
262 }
263 msgs->msgs[msgs->size++] = cp;
264 }
265
266 /*
267 * Append a message number to an array of them, resizing it if necessary.
268 * Like app_msgarg, but with a vector-of-ints instead.
269 */
270
271 void
272 app_msgnum(struct msgnum_array *msgs, int msgnum)
273 {
274 if (msgs->size >= msgs->max) {
275 msgs->max += MAXMSGS;
276 msgs->msgnums = mh_xrealloc(msgs->msgnums,
277 msgs->max * sizeof(*msgs->msgnums));
278 }
279 msgs->msgnums[msgs->size++] = msgnum;
280 }
281
282 /* Open a form or components file */
283 int
284 open_form(char **form, char *def)
285 {
286 int in;
287 if (*form) {
288 if ((in = open (etcpath (*form), O_RDONLY)) == NOTOK)
289 adios (*form, "unable to open form file");
290 } else {
291 if ((in = open (etcpath (def), O_RDONLY)) == NOTOK)
292 adios (def, "unable to open default components file");
293 *form = def;
294 }
295 return in;
296 }
297
298
299 /*
300 * Finds first occurrence of str in buf. buf is not a C string but a
301 * byte array of length buflen. str is a null-terminated C string.
302 * find_str() does not modify buf but passes back a non-const char *
303 * pointer so that the caller can modify it.
304 */
305 char *
306 find_str (const char buf[], size_t buflen, const char *str) {
307 const size_t len = strlen (str);
308 size_t i;
309
310 for (i = 0; i + len <= buflen; ++i, ++buf) {
311 if (! memcmp (buf, str, len)) return (char *) buf;
312 }
313
314 return NULL;
315 }
316
317
318 /*
319 * Finds last occurrence of str in buf. buf is not a C string but a
320 * byte array of length buflen. str is a null-terminated C string.
321 * find_str() does not modify buf but passes back a non-const char *
322 * pointer so that the caller can modify it.
323 */
324 char *
325 rfind_str (const char buf[], size_t buflen, const char *str) {
326 const size_t len = strlen (str);
327 size_t i;
328
329 for (i = 0, buf += buflen - len; i + len <= buflen; ++i, --buf) {
330 if (! memcmp (buf, str, len)) return (char *) buf;
331 }
332
333 return NULL;
334 }
335
336
337 /* POSIX doesn't have strcasestr() so emulate it. */
338 char *
339 nmh_strcasestr (const char *s1, const char *s2) {
340 const size_t len = strlen (s2);
341
342 if (isupper ((unsigned char) s2[0]) || islower ((unsigned char)s2[0])) {
343 char first[3];
344 first[0] = (char) toupper ((unsigned char) s2[0]);
345 first[1] = (char) tolower ((unsigned char) s2[0]);
346 first[2] = '\0';
347
348 for (s1 = strpbrk (s1, first); s1; s1 = strpbrk (++s1, first)) {
349 if (! strncasecmp (s1, s2, len)) return (char *) s1;
350 }
351 } else {
352 for (s1 = strchr (s1, s2[0]); s1; s1 = strchr (++s1, s2[0])) {
353 if (! strncasecmp (s1, s2, len)) return (char *) s1;
354 }
355 }
356
357 return NULL;
358 }
359
360
361 /* EndsWithC returns true if non-NULL string s ends with a c before the
362 * terminating NUL. */
363 bool EndsWithC(char *s, int c)
364 {
365 return *s && s[strlen(s) - 1] == c;
366 }
367
368
369 /* TrimSuffixC deletes c from the end of non-NULL string s if it's
370 * present, shortening s by 1. Only one instance of c is removed. */
371 void TrimSuffixC(char *s, int c)
372 {
373 if (!*s)
374 return;
375
376 s += strlen(s) - 1;
377 if (*s == c)
378 *s = '\0';
379 }
380
381
382 int
383 nmh_init(const char *argv0, int read_context) {
384 int status = OK;
385 char *locale;
386
387 invo_name = r1bindex ((char *) argv0, '/');
388
389 if (setup_signal_handlers()) {
390 admonish("sigaction", "unable to set up signal handlers");
391 }
392
393 /* POSIX atexit() does not define any error conditions. */
394 if (atexit(remove_registered_files_atexit)) {
395 admonish("atexit", "unable to register atexit function");
396 }
397
398 /* Read context, if supposed to. */
399 if (read_context) {
400 int allow_version_check = 1;
401 int check_older_version = 0;
402 char *cp;
403
404 context_read();
405
406 if (read_context != 1 ||
407 ((cp = context_find ("Welcome")) && strcasecmp (cp, "disable") == 0)) {
408 allow_version_check = 0;
409 } else if ((cp = getenv ("MHCONTEXT")) != NULL && *cp != '\0') {
410 /* Context file comes from $MHCONTEXT, so only print the message
411 if the context file has an older version. If it does, or if it
412 doesn't have a version at all, update the version. */
413 check_older_version = 1;
414 }
415
416 /* Check to see if the user is running a different (or older, if
417 specified) version of nmh than they had run bfore, and notify them
418 if so. But only if read_context was set to a value to enable. */
419 if (allow_version_check && isatty (fileno (stdin)) &&
420 isatty (fileno (stdout)) && isatty (fileno (stderr))) {
421 if (nmh_version_changed (check_older_version)) {
422 printf ("==================================================="
423 "=====================\n");
424 printf ("Welcome to nmh version %s\n\n", VERSION);
425 printf ("See the release notes in %s/NEWS\n\n",
426 mhdocdir);
427 print_intro (stdout, 1);
428 printf ("\nThis message will not be repeated until "
429 "nmh is next updated.\n");
430 printf ("==================================================="
431 "=====================\n\n");
432
433 fputs ("Press enter to continue: ", stdout);
434 (void) read_line ();
435 putchar ('\n');
436 }
437 }
438 } else {
439 if ((status = context_foil(NULL)) != OK) {
440 advise("", "failed to create minimal profile/context");
441 }
442 }
443
444 /* Allow the user to set a locale in their profile. Otherwise, use the
445 "" string to pull it from their environment, see setlocale(3). */
446 if ((locale = context_find ("locale")) == NULL) {
447 locale = "";
448 }
449
450 if (! setlocale (LC_ALL, locale)) {
451 admonish (NULL, "setlocale failed, check your LC_ALL, LC_CTYPE, and "
452 "LANG environment variables");
453 }
454
455 return status;
456 }
457
458
459 /*
460 * Check stored version, and return 1 if out-of-date or non-existent.
461 * Because the output of "mhparam version" is prefixed with "nmh-",
462 * use that prefix here.
463 */
464 int
465 nmh_version_changed (int older) {
466 const char *const context_version = context_find("Version");
467
468 if (older) {
469 /* Convert the version strings to floats and compare them. This will
470 break for versions with multiple decimal points, etc. */
471 const float current_version = strtof (VERSION, NULL);
472 const float old_version =
473 context_version && strncmp (context_version, "nmh-", 4) == 0
474 ? strtof (context_version + 4, NULL)
475 : 99999999;
476
477 if (context_version == NULL || old_version < current_version) {
478 context_replace ("Version", "nmh-" VERSION);
479 }
480
481 return old_version < current_version ? 1 : 0;
482 }
483
484 if (context_version == NULL || strcmp(context_version, "nmh-" VERSION) != 0) {
485 context_replace ("Version", "nmh-" VERSION);
486 return 1;
487 }
488
489 return 0;
490 }
491
492
493 /* Returns copy of argument str with all characters converted to upper
494 case, and trimmed whitespace (see cpytrim()) . */
495 char *
496 upcase (const char *str) {
497 char *up = cpytrim (str);
498 char *cp;
499
500 for (cp = up; *cp; ++cp) { *cp = toupper ((unsigned char) *cp); }
501
502 return up;
503 }
504
505
506 /*
507 * Scan for any 8-bit characters. Return 1 if they exist.
508 *
509 * Scan up until the given endpoint (but not the actual endpoint itself).
510 * If the endpoint is NULL, scan until a '\0' is reached.
511 */
512
513 int
514 contains8bit(const char *start, const char *end)
515 {
516 if (! start)
517 return 0;
518
519 while (*start != '\0' && (!end || (start < end)))
520 if (! isascii((unsigned char) *start++))
521 return 1;
522
523 return 0;
524 }
525
526
527 /*
528 * See if input has any 8-bit bytes.
529 */
530 int
531 scan_input (int fd, int *eightbit) {
532 int state;
533 char buf[BUFSIZ];
534
535 *eightbit = 0;
536 lseek (fd, (off_t) 0, SEEK_SET);
537
538 while ((state = read (fd, buf, sizeof buf)) > 0) {
539 if (contains8bit (buf, buf + state)) {
540 *eightbit = 1;
541 return OK;
542 }
543 }
544
545 return state == NOTOK ? NOTOK : OK;
546 }