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