xref: /plan9-contrib/sys/src/cmd/ip/imap4d/utils.c (revision 80ee5cbfe36716af62da8896207e9763b8e3d760)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include "imap4d.h"
5 
6 /*
7  * reverse string [s:e) in place
8  */
9 void
10 strrev(char *s, char *e)
11 {
12 	int c;
13 
14 	while(--e > s){
15 		c = *s;
16 		*s++ = *e;
17 		*e = c;
18 	}
19 }
20 
21 int
22 isdotdot(char *s)
23 {
24 	return s[0] == '.' && s[1] == '.' && (s[2] == '/' || s[2] == '\0');
25 }
26 
27 int
28 issuffix(char *suf, char *s)
29 {
30 	int n;
31 
32 	n = strlen(s) - strlen(suf);
33 	if(n < 0)
34 		return 0;
35 	return strcmp(s + n, suf) == 0;
36 }
37 
38 int
39 isprefix(char *pre, char *s)
40 {
41 	return strncmp(pre, s, strlen(pre)) == 0;
42 }
43 
44 int
45 ciisprefix(char *pre, char *s)
46 {
47 	return cistrncmp(pre, s, strlen(pre)) == 0;
48 }
49 
50 char*
51 readFile(int fd)
52 {
53 	Dir d;
54 	char *s;
55 
56 	if(dirfstat(fd, &d) < 0)
57 		return nil;
58 	s = binalloc(&parseBin, d.length + 1, 0);
59 	if(s == nil || read(fd, s, d.length) != d.length)
60 		return nil;
61 	s[d.length] = '\0';
62 	return s;
63 }
64 
65 /*
66  * create the imap tmp file.
67  * it just happens that we don't need multiple temporary files.
68  */
69 int
70 imapTmp(void)
71 {
72 	char buf[ERRLEN], name[5*NAMELEN];
73 	int tries, fd;
74 
75 	snprint(name, sizeof(name), "/mail/box/%s/mbox.tmp.imp", username);
76 	for(tries = 0; tries < LockSecs*2; tries++){
77 		fd = create(name, ORDWR|ORCLOSE|OCEXEC, CHEXCL|0600);
78 		if(fd >= 0)
79 			return fd;
80 		errstr(buf);
81 		if(cistrstr(buf, "locked") == nil)
82 			break;
83 		sleep(500);
84 	}
85 	return -1;
86 }
87 
88 /*
89  * open a file which might be locked.
90  * if it is, spin until available
91  */
92 int
93 openLocked(char *dir, char *file, int mode)
94 {
95 	char buf[ERRLEN];
96 	int tries, fd;
97 
98 	for(tries = 0; tries < LockSecs*2; tries++){
99 		fd = cdOpen(dir, file, mode);
100 		if(fd >= 0)
101 			return fd;
102 		errstr(buf);
103 		if(cistrstr(buf, "locked") == nil)
104 			break;
105 		sleep(500);
106 	}
107 	return -1;
108 }
109 
110 ulong
111 mapInt(NamedInt *map, char *name)
112 {
113 	int i;
114 
115 	for(i = 0; map[i].name != nil; i++)
116 		if(cistrcmp(map[i].name, name) == 0)
117 			break;
118 	return map[i].v;
119 }
120 
121 char*
122 estrdup(char *s)
123 {
124 	char *t;
125 
126 	t = emalloc(strlen(s) + 1);
127 	strcpy(t, s);
128 	return t;
129 }
130 
131 void*
132 emalloc(ulong n)
133 {
134 	void *p;
135 
136 	p = malloc(n);
137 	if(p == nil)
138 		bye("server out of memory");
139 	return p;
140 }
141 
142 void*
143 ezmalloc(ulong n)
144 {
145 	void *p;
146 
147 	p = malloc(n);
148 	if(p == nil)
149 		bye("server out of memory");
150 	memset(p, 0, n);
151 	return p;
152 }
153 
154 void*
155 erealloc(void *p, ulong n)
156 {
157 	p = realloc(p, n);
158 	if(p == nil)
159 		bye("server out of memory");
160 	return p;
161 }
162