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