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