65ef20049d26748ef54b6fd60068e7492b159beb
[dss.git] / ipc.c
1 #include <sys/wait.h>
2 #include <stdio.h>
3 #include <inttypes.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <sys/types.h>
8 #include <sys/ipc.h>
9 #include <sys/sem.h>
10 #include <string.h>
11 #include <assert.h>
12 #include <sys/stat.h>
13 #include <stddef.h>
14 #include <limits.h>
15 #include <sys/param.h>
16
17 #include "gcc-compat.h"
18 #include "str.h"
19 #include "log.h"
20 #include "gcc-compat.h"
21 #include "err.h"
22 #include "ipc.h"
23
24 #if (defined(__GNUC__) && defined(__i386__))
25 #define get16bits(d) (*((const uint16_t *) (d)))
26 #else
27 #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
28                 +(uint32_t)(((const uint8_t *)(d))[0]) )
29 #endif
30
31 /*
32  * SuperFastHash, by Paul Hsieh.
33  * http://www.azillionmonkeys.com/qed/hash.html
34  */
35 static uint32_t super_fast_hash(const uint8_t *data, uint32_t len, uint32_t hash)
36 {
37         uint32_t tmp;
38         int rem = len & 3;
39
40         len >>= 2;
41
42         for (;len > 0; len--) {
43                 hash  += get16bits (data);
44                 tmp    = (get16bits (data+2) << 11) ^ hash;
45                 hash   = (hash << 16) ^ tmp;
46                 data  += 2*sizeof (uint16_t);
47                 hash  += hash >> 11;
48         }
49
50         /* Handle end cases */
51         switch (rem) {
52         case 3:
53                 hash += get16bits (data);
54                 hash ^= hash << 16;
55                 hash ^= data[sizeof (uint16_t)] << 18;
56                 hash += hash >> 11;
57                 break;
58         case 2:
59                 hash += get16bits (data);
60                 hash ^= hash << 11;
61                 hash += hash >> 17;
62                 break;
63         case 1:
64                 hash += *data;
65                 hash ^= hash << 10;
66                 hash += hash >> 1;
67         }
68         /* Force "avalanching" of final 127 bits */
69         hash ^= hash << 3;
70         hash += hash >> 5;
71         hash ^= hash << 4;
72         hash += hash >> 17;
73         hash ^= hash << 25;
74         hash += hash >> 6;
75         return hash;
76 }
77
78 /*
79  * Return the canonical absolute name of a given file name.
80  *
81  * Slightly modified version of glibc's realpath, Copyright (C)
82  * 1996-2002,2004,2005,2006,2008 Free Software Foundation, Inc.
83  *
84  * A canonical name does not contain any `.', `..' components nor any repeated
85  * path separators ('/') or symlinks. All path components must exist. The
86  * result is malloc'd and must be freed by the caller.
87  */
88 static int dss_realpath(const char *name, char **resolved_path)
89 {
90         char *rpath = NULL, *dest, *extra_buf = NULL;
91         const char *start, *end, *rpath_limit;
92         long int path_max;
93         int ret, num_links = 0;
94
95         if (name[0] == '\0') {
96                 /*
97                  * As per Single Unix Specification V2 we must return an error
98                  * if the name argument points to an empty string.
99                  */
100                 ret = -ERRNO_TO_DSS_ERROR(ENOENT);
101                 goto error;
102         }
103 #ifdef PATH_MAX
104         path_max = PATH_MAX;
105 #else
106         /*
107          * From realpath(3): Asking pathconf(3) does not really help, since on
108          * the one hand POSIX warns that the result of pathconf(3) may be
109          * huge and unsuitable for mallocing memory. And on the other hand
110          * pathconf(3) may return -1 to signify that PATH_MAX is not bounded.
111          */
112         path_max = pathconf(name, _PC_PATH_MAX);
113         if (path_max <= 0 || path_max >= 4096)
114                 path_max = 4096;
115 #endif
116         rpath = dss_malloc(path_max);
117         rpath_limit = rpath + path_max;
118
119         if (name[0] != '/') {
120                 if (!getcwd(rpath, path_max)) {
121                         ret = -ERRNO_TO_DSS_ERROR(errno);
122                         goto error;
123                 }
124                 dest = memchr(rpath, '\0', path_max);
125         } else {
126                 rpath[0] = '/';
127                 dest = rpath + 1;
128         }
129
130         for (start = end = name; *start; start = end) {
131                 struct stat st;
132                 int n;
133
134                 /* Skip sequence of multiple path-separators.  */
135                 while (*start == '/')
136                         ++start;
137
138                 /* Find end of path component.  */
139                 for (end = start; *end && *end != '/'; ++end)
140                         /* Nothing.  */ ;
141
142                 if (end - start == 0)
143                         break;
144                 else if (end - start == 1 && start[0] == '.')
145                         /* nothing */ ;
146                 else if (end - start == 2 && start[0] == '.' && start[1] == '.') {
147                         /* Back up to previous component, ignore if at root already.  */
148                         if (dest > rpath + 1)
149                                 while ((--dest)[-1] != '/') ;
150                 } else {
151                         size_t new_size;
152
153                         if (dest[-1] != '/')
154                                 *dest++ = '/';
155
156                         if (dest + (end - start) >= rpath_limit) {
157                                 ptrdiff_t dest_offset = dest - rpath;
158
159                                 new_size = rpath_limit - rpath;
160                                 if (end - start + 1 > path_max)
161                                         new_size += end - start + 1;
162                                 else
163                                         new_size += path_max;
164                                 rpath = dss_realloc(rpath, new_size);
165                                 rpath_limit = rpath + new_size;
166                                 dest = rpath + dest_offset;
167                         }
168
169                         memcpy(dest, start, end - start);
170                         dest += end - start;
171                         *dest = '\0';
172
173                         if (stat(rpath, &st) < 0) {
174                                 ret = -ERRNO_TO_DSS_ERROR(errno);
175                                 goto error;
176                         }
177
178                         if (S_ISLNK(st.st_mode)) {
179                                 char *buf = alloca(path_max);
180                                 size_t len;
181
182                                 if (++num_links > MAXSYMLINKS) {
183                                         ret = -ERRNO_TO_DSS_ERROR(ELOOP);
184                                         goto error;
185                                 }
186
187                                 n = readlink(rpath, buf, path_max - 1);
188                                 if (n < 0) {
189                                         ret = -ERRNO_TO_DSS_ERROR(errno);
190                                         goto error;
191                                 }
192                                 buf[n] = '\0';
193
194                                 if (!extra_buf)
195                                         extra_buf = alloca(path_max);
196
197                                 len = strlen(end);
198                                 if ((long int) (n + len) >= path_max) {
199                                         ret = -ERRNO_TO_DSS_ERROR(ENAMETOOLONG);
200                                         goto error;
201                                 }
202
203                                 /* Careful here, end may be a pointer into extra_buf... */
204                                 memmove(&extra_buf[n], end, len + 1);
205                                 name = end = memcpy(extra_buf, buf, n);
206
207                                 if (buf[0] == '/') /* It's an absolute symlink */
208                                         dest = rpath + 1;
209                                 else /* Back up to previous component, ignore if at root already: */
210                                         if (dest > rpath + 1)
211                                                 while ((--dest)[-1] != '/')
212                                                         ; /* nothing */
213                         } else if (!S_ISDIR(st.st_mode) && *end != '\0') {
214                                 ret = -ERRNO_TO_DSS_ERROR(ENOTDIR);
215                                 goto error;
216                         }
217                 }
218         }
219         if (dest > rpath + 1 && dest[-1] == '/')
220                 --dest;
221         *dest = '\0';
222         *resolved_path = rpath;
223         return 1;
224 error:
225         free(rpath);
226         *resolved_path = NULL;
227         return ret;
228 }
229
230 static inline int get_key_or_die(char *config_file)
231 {
232         int ret;
233         struct stat statbuf;
234         char *rpath;
235
236         assert(config_file);
237         if (stat(config_file, &statbuf) == 0) {
238                 ret = dss_realpath(config_file, &rpath);
239                 if (ret < 0) {
240                         DSS_EMERG_LOG(("could not resolve path %s: %s\n", config_file,
241                                 dss_strerror(-ret)));
242                         exit(EXIT_FAILURE);
243                 }
244                 DSS_DEBUG_LOG(("resolved path: %s\n", rpath));
245         } else
246                 /*
247                  * This happens if the user did not specify a config file, and
248                  * the default config file does not exist.  Another (unlikely)
249                  * possibility is that the config file was removed between
250                  * startup and this call. We don't care about these corner
251                  * cases too much and just use the unresolved path in this
252                  * case.
253                  */
254                 rpath = dss_strdup(config_file);
255         ret = super_fast_hash((uint8_t *)rpath, strlen(rpath), 0) >> 1;
256         free(rpath);
257         return ret;
258 }
259
260 static int mutex_get(int key, int flags)
261 {
262         int ret;
263
264         DSS_DEBUG_LOG(("getting semaphore 0x%x\n", key));
265         ret = semget(key, 2, flags);
266         if (ret < 0)
267                 return -ERRNO_TO_DSS_ERROR(errno);
268         return ret;
269 }
270
271 static int do_semop(int id, struct sembuf *sops, int num)
272 {
273         int ret;
274
275         DSS_DEBUG_LOG(("calling semop\n"));
276         do {
277                 ret = semop(id, sops, num);
278                 if (ret >= 0)
279                         return 1;
280         } while (errno == EINTR);
281         return -ERRNO_TO_DSS_ERROR(errno);
282 }
283
284 static int mutex_lock(int id)
285 {
286         struct sembuf sops[4];
287         int ret;
288
289         DSS_DEBUG_LOG(("locking\n"));
290
291         sops[0].sem_num = 0;
292         sops[0].sem_op = 0;
293         sops[0].sem_flg = SEM_UNDO | IPC_NOWAIT;
294
295         sops[1].sem_num = 0;
296         sops[1].sem_op = 1;
297         sops[1].sem_flg = SEM_UNDO | IPC_NOWAIT;
298
299         sops[2].sem_num = 1;
300         sops[2].sem_op = 0;
301         sops[2].sem_flg = SEM_UNDO | IPC_NOWAIT;
302
303         sops[3].sem_num = 1;
304         sops[3].sem_op = 1;
305         sops[3].sem_flg = SEM_UNDO | IPC_NOWAIT;
306
307         ret = do_semop(id, sops, 4);
308         if (ret < 0)
309                 return -ERRNO_TO_DSS_ERROR(errno);
310         return 1;
311 }
312
313 static int mutex_try_lock(int id)
314 {
315         struct sembuf sops[2];
316         int ret;
317
318         DSS_DEBUG_LOG(("trying to lock\n"));
319
320         sops[0].sem_num = 0;
321         sops[0].sem_op = 0;
322         sops[0].sem_flg = SEM_UNDO | IPC_NOWAIT;
323
324         sops[1].sem_num = 0;
325         sops[1].sem_op = 1;
326         sops[1].sem_flg = SEM_UNDO | IPC_NOWAIT;
327
328         ret = do_semop(id, sops, 2);
329         if (ret < 0)
330                 return -ERRNO_TO_DSS_ERROR(errno);
331         return 1;
332 }
333
334 int lock_dss(char *config_file)
335 {
336         int ret, key = get_key_or_die(config_file);
337
338         ret = mutex_get(key, IPC_CREAT | 0600);
339         if (ret < 0)
340                 return ret;
341         return mutex_lock(ret);
342 }
343
344 int get_dss_pid(char *config_file, pid_t *pid)
345 {
346         int ret, semid, key = get_key_or_die(config_file);
347
348         ret = mutex_get(key, 0);
349         if (ret < 0)
350                 return ret;
351         semid = ret;
352         ret = semctl(semid, 1, GETPID);
353         if (ret < 0)
354                 return -E_NOT_RUNNING;
355         *pid = ret;
356         ret = mutex_try_lock(semid);
357         if (ret >= 0)
358                 return -E_NOT_RUNNING;
359         return 1;
360 }