Fixed make_bcc_file () to use contents of From: in draft, if draft_from masquerade...
[mmh] / sbr / utils.c
1
2 /*
3  * utils.c -- various utility routines
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2006, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 #include <h/mh.h>
13 #include <h/utils.h>
14 #include <stdlib.h>
15
16 /*
17  * Safely call malloc
18  */
19 void *
20 mh_xmalloc(size_t size)
21 {
22     void *memory;
23
24     if (size == 0)
25         adios(NULL, "Tried to malloc 0 bytes");
26
27     memory = malloc(size);
28     if (!memory)
29         adios(NULL, "Malloc failed");
30
31     return memory;
32 }
33
34 /*
35  * Safely call realloc
36  */
37 void *
38 mh_xrealloc(void *ptr, size_t size)
39 {
40     void *memory;
41
42     if (size == 0)
43         adios(NULL, "Tried to realloc 0bytes");
44
45     memory = realloc(ptr, size);
46     if (!memory)
47         adios(NULL, "Realloc failed");
48
49     return memory;
50 }
51
52 /*
53  * Return the present working directory, if the current directory does not
54  * exist, or is too long, make / the pwd.
55  */
56 char *
57 pwd(void)
58 {
59     register char *cp;
60     static char curwd[PATH_MAX];
61
62     if (!getcwd (curwd, PATH_MAX)) {
63         admonish (NULL, "unable to determine working directory");
64         if (!mypath || !*mypath
65                 || (strcpy (curwd, mypath), chdir (curwd)) == -1) {
66             strcpy (curwd, "/");
67             chdir (curwd);
68         }
69         return curwd;
70     }
71
72     if ((cp = curwd + strlen (curwd) - 1) > curwd && *cp == '/')
73         *cp = '\0';
74
75     return curwd;
76 }
77
78 /*
79  * add   -- If "s1" is NULL, this routine just creates a
80  *       -- copy of "s2" into newly malloc'ed memory.
81  *       --
82  *       -- If "s1" is not NULL, then copy the concatenation
83  *       -- of "s1" and "s2" (note the order) into newly
84  *       -- malloc'ed memory.  Then free "s1".
85  */
86 char *
87 add (char *s2, char *s1)
88 {
89     char *cp;
90     size_t len1 = 0, len2 = 0;
91
92     if (s1)
93         len1 = strlen (s1);
94     if (s2)
95         len2 = strlen (s2);
96
97     cp = mh_xmalloc (len1 + len2 + 1);
98
99     /* Copy s1 and free it */
100     if (s1) {
101         memcpy (cp, s1, len1);
102         free (s1);
103     }
104
105     /* Copy s2 */
106     if (s2)
107         memcpy (cp + len1, s2, len2);
108
109     /* Now NULL terminate the string */
110     cp[len1 + len2] = '\0';
111
112     return cp;
113 }