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