Separate out uevent parsing functions
[multipath-tools/.git] / libmultipath / uevent.c
1 /*
2  * uevent.c - trigger upon netlink uevents from the kernel
3  *
4  *      Only kernels from version 2.6.10* on provide the uevent netlink socket.
5  *      Until the libc-kernel-headers are updated, you need to compile with:
6  *
7  *        gcc -I /lib/modules/`uname -r`/build/include -o uevent_listen uevent_listen.c
8  *
9  * Copyright (C) 2004 Kay Sievers <kay.sievers@vrfy.org>
10  *
11  *      This program is free software; you can redistribute it and/or modify it
12  *      under the terms of the GNU General Public License as published by the
13  *      Free Software Foundation version 2 of the License.
14  *
15  *      This program is distributed in the hope that it will be useful, but
16  *      WITHOUT ANY WARRANTY; without even the implied warranty of
17  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  *      General Public License for more details.
19  *
20  *      You should have received a copy of the GNU General Public License along
21  *      with this program; if not, write to the Free Software Foundation, Inc.,
22  *      675 Mass Ave, Cambridge, MA 02139, USA.
23  *
24  */
25
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <stdlib.h>
30 #include <stddef.h>
31 #include <string.h>
32 #include <fcntl.h>
33 #include <time.h>
34 #include <sys/socket.h>
35 #include <sys/user.h>
36 #include <sys/un.h>
37 #include <linux/types.h>
38 #include <linux/netlink.h>
39 #include <pthread.h>
40 #include <limits.h>
41 #include <sys/mman.h>
42 #include <libudev.h>
43 #include <errno.h>
44
45 #include "memory.h"
46 #include "debug.h"
47 #include "list.h"
48 #include "uevent.h"
49 #include "vector.h"
50
51 typedef int (uev_trigger)(struct uevent *, void * trigger_data);
52
53 pthread_t uevq_thr;
54 LIST_HEAD(uevq);
55 pthread_mutex_t uevq_lock = PTHREAD_MUTEX_INITIALIZER;
56 pthread_mutex_t *uevq_lockp = &uevq_lock;
57 pthread_cond_t uev_cond = PTHREAD_COND_INITIALIZER;
58 pthread_cond_t *uev_condp = &uev_cond;
59 uev_trigger *my_uev_trigger;
60 void * my_trigger_data;
61 int servicing_uev;
62
63 int is_uevent_busy(void)
64 {
65         int empty;
66
67         pthread_mutex_lock(uevq_lockp);
68         empty = list_empty(&uevq);
69         pthread_mutex_unlock(uevq_lockp);
70         return (!empty || servicing_uev);
71 }
72
73 struct uevent * alloc_uevent (void)
74 {
75         struct uevent *uev = MALLOC(sizeof(struct uevent));
76
77         if (uev)
78                 INIT_LIST_HEAD(&uev->node);
79
80         return uev;
81 }
82
83 void
84 setup_thread_attr(pthread_attr_t *attr, size_t stacksize, int detached)
85 {
86         if (pthread_attr_init(attr)) {
87                 fprintf(stderr, "can't initialize thread attr: %s\n",
88                         strerror(errno));
89                 exit(1);
90         }
91         if (stacksize < PTHREAD_STACK_MIN)
92                 stacksize = PTHREAD_STACK_MIN;
93
94         if (pthread_attr_setstacksize(attr, stacksize)) {
95                 fprintf(stderr, "can't set thread stack size to %lu: %s\n",
96                         (unsigned long)stacksize, strerror(errno));
97                 exit(1);
98         }
99         if (detached && pthread_attr_setdetachstate(attr,
100                                                     PTHREAD_CREATE_DETACHED)) {
101                 fprintf(stderr, "can't set thread to detached: %s\n",
102                         strerror(errno));
103                 exit(1);
104         }
105 }
106
107 /*
108  * Called with uevq_lockp held
109  */
110 void
111 service_uevq(struct list_head *tmpq)
112 {
113         struct uevent *uev, *tmp;
114
115         list_for_each_entry_safe(uev, tmp, tmpq, node) {
116                 list_del_init(&uev->node);
117
118                 if (my_uev_trigger && my_uev_trigger(uev, my_trigger_data))
119                         condlog(0, "uevent trigger error");
120
121                 if (uev->udev)
122                         udev_device_unref(uev->udev);
123                 FREE(uev);
124         }
125 }
126
127 static void uevq_stop(void *arg)
128 {
129         struct udev *udev = arg;
130
131         condlog(3, "Stopping uev queue");
132         pthread_mutex_lock(uevq_lockp);
133         my_uev_trigger = NULL;
134         pthread_cond_signal(uev_condp);
135         pthread_mutex_unlock(uevq_lockp);
136         udev_unref(udev);
137 }
138
139 void
140 uevq_cleanup(struct list_head *tmpq)
141 {
142         struct uevent *uev, *tmp;
143
144         list_for_each_entry_safe(uev, tmp, tmpq, node) {
145                 list_del_init(&uev->node);
146                 FREE(uev);
147         }
148 }
149
150 /*
151  * Service the uevent queue.
152  */
153 int uevent_dispatch(int (*uev_trigger)(struct uevent *, void * trigger_data),
154                     void * trigger_data)
155 {
156         my_uev_trigger = uev_trigger;
157         my_trigger_data = trigger_data;
158
159         mlockall(MCL_CURRENT | MCL_FUTURE);
160
161         while (1) {
162                 LIST_HEAD(uevq_tmp);
163
164                 pthread_mutex_lock(uevq_lockp);
165                 servicing_uev = 0;
166                 /*
167                  * Condition signals are unreliable,
168                  * so make sure we only wait if we have to.
169                  */
170                 if (list_empty(&uevq)) {
171                         pthread_cond_wait(uev_condp, uevq_lockp);
172                 }
173                 servicing_uev = 1;
174                 list_splice_init(&uevq, &uevq_tmp);
175                 pthread_mutex_unlock(uevq_lockp);
176                 if (!my_uev_trigger)
177                         break;
178                 service_uevq(&uevq_tmp);
179         }
180         condlog(3, "Terminating uev service queue");
181         uevq_cleanup(&uevq);
182         return 0;
183 }
184
185 struct uevent *uevent_from_buffer(char *buf, ssize_t buflen)
186 {
187         struct uevent *uev;
188         char *buffer;
189         size_t bufpos;
190         int i;
191         char *pos;
192
193         uev = alloc_uevent();
194         if (!uev) {
195                 condlog(1, "lost uevent, oom");
196                 return NULL;
197         }
198
199         if ((size_t)buflen > sizeof(buf)-1)
200                 buflen = sizeof(buf)-1;
201
202         /*
203          * Copy the shared receive buffer contents to buffer private
204          * to this uevent so we can immediately reuse the shared buffer.
205          */
206         memcpy(uev->buffer, buf, HOTPLUG_BUFFER_SIZE + OBJECT_SIZE);
207         buffer = uev->buffer;
208         buffer[buflen] = '\0';
209
210         /* save start of payload */
211         bufpos = strlen(buffer) + 1;
212
213         /* action string */
214         uev->action = buffer;
215         pos = strchr(buffer, '@');
216         if (!pos) {
217                 condlog(3, "bad action string '%s'", buffer);
218                 FREE(uev);
219                 return NULL;
220         }
221         pos[0] = '\0';
222
223         /* sysfs path */
224         uev->devpath = &pos[1];
225
226         /* hotplug events have the environment attached - reconstruct envp[] */
227         for (i = 0; (bufpos < (size_t)buflen) && (i < HOTPLUG_NUM_ENVP-1); i++) {
228                 int keylen;
229                 char *key;
230
231                 key = &buffer[bufpos];
232                 keylen = strlen(key);
233                 uev->envp[i] = key;
234                 /* Filter out sequence number */
235                 if (strncmp(key, "SEQNUM=", 7) == 0) {
236                         char *eptr;
237
238                         uev->seqnum = strtoul(key + 7, &eptr, 10);
239                         if (eptr == key + 7)
240                                 uev->seqnum = -1;
241                 }
242                 bufpos += keylen + 1;
243         }
244         uev->envp[i] = NULL;
245
246         condlog(3, "uevent %ld '%s' from '%s'", uev->seqnum,
247                 uev->action, uev->devpath);
248         uev->kernel = strrchr(uev->devpath, '/');
249         if (uev->kernel)
250                 uev->kernel++;
251
252         /* print payload environment */
253         for (i = 0; uev->envp[i] != NULL; i++)
254                 condlog(5, "%s", uev->envp[i]);
255
256         return uev;
257 }
258
259 int failback_listen(void)
260 {
261         int sock;
262         struct sockaddr_nl snl;
263         struct sockaddr_un sun;
264         socklen_t addrlen;
265         int retval;
266         int rcvbufsz = 128*1024;
267         int rcvsz = 0;
268         int rcvszsz = sizeof(rcvsz);
269         unsigned int *prcvszsz = (unsigned int *)&rcvszsz;
270         const int feature_on = 1;
271         /*
272          * First check whether we have a udev socket
273          */
274         memset(&sun, 0x00, sizeof(struct sockaddr_un));
275         sun.sun_family = AF_LOCAL;
276         strcpy(&sun.sun_path[1], "/org/kernel/dm/multipath_event");
277         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(sun.sun_path+1) + 1;
278
279         sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
280         if (sock >= 0) {
281
282                 condlog(3, "reading events from udev socket.");
283
284                 /* the bind takes care of ensuring only one copy running */
285                 retval = bind(sock, (struct sockaddr *) &sun, addrlen);
286                 if (retval < 0) {
287                         condlog(0, "bind failed, exit");
288                         goto exit;
289                 }
290
291                 /* enable receiving of the sender credentials */
292                 setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
293                            &feature_on, sizeof(feature_on));
294
295         } else {
296                 /* Fallback to read kernel netlink events */
297                 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
298                 snl.nl_family = AF_NETLINK;
299                 snl.nl_pid = getpid();
300                 snl.nl_groups = 0x01;
301
302                 sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
303                 if (sock == -1) {
304                         condlog(0, "error getting socket, exit");
305                         return 1;
306                 }
307
308                 condlog(3, "reading events from kernel.");
309
310                 /*
311                  * try to avoid dropping uevents, even so, this is not a guarantee,
312                  * but it does help to change the netlink uevent socket's
313                  * receive buffer threshold from the default value of 106,496 to
314                  * the maximum value of 262,142.
315                  */
316                 retval = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbufsz,
317                                     sizeof(rcvbufsz));
318
319                 if (retval < 0) {
320                         condlog(0, "error setting receive buffer size for socket, exit");
321                         exit(1);
322                 }
323                 retval = getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvsz, prcvszsz);
324                 if (retval < 0) {
325                         condlog(0, "error setting receive buffer size for socket, exit");
326                         exit(1);
327                 }
328                 condlog(3, "receive buffer size for socket is %u.", rcvsz);
329
330                 /* enable receiving of the sender credentials */
331                 setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
332                            &feature_on, sizeof(feature_on));
333
334                 retval = bind(sock, (struct sockaddr *) &snl,
335                               sizeof(struct sockaddr_nl));
336                 if (retval < 0) {
337                         condlog(0, "bind failed, exit");
338                         goto exit;
339                 }
340         }
341
342         while (1) {
343                 size_t bufpos;
344                 ssize_t buflen;
345                 struct uevent *uev;
346                 struct msghdr smsg;
347                 struct iovec iov;
348                 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
349                 struct cmsghdr *cmsg;
350                 struct ucred *cred;
351                 static char buf[HOTPLUG_BUFFER_SIZE + OBJECT_SIZE];
352
353                 memset(buf, 0x00, sizeof(buf));
354                 iov.iov_base = &buf;
355                 iov.iov_len = sizeof(buf);
356                 memset (&smsg, 0x00, sizeof(struct msghdr));
357                 smsg.msg_iov = &iov;
358                 smsg.msg_iovlen = 1;
359                 smsg.msg_control = cred_msg;
360                 smsg.msg_controllen = sizeof(cred_msg);
361
362                 buflen = recvmsg(sock, &smsg, 0);
363                 if (buflen < 0) {
364                         if (errno != EINTR)
365                                 condlog(0, "error receiving message, errno %d", errno);
366                         continue;
367                 }
368
369                 cmsg = CMSG_FIRSTHDR(&smsg);
370                 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
371                         condlog(3, "no sender credentials received, message ignored");
372                         continue;
373                 }
374
375                 cred = (struct ucred *)CMSG_DATA(cmsg);
376                 if (cred->uid != 0) {
377                         condlog(3, "sender uid=%d, message ignored", cred->uid);
378                         continue;
379                 }
380
381                 /* skip header */
382                 bufpos = strlen(buf) + 1;
383                 if (bufpos < sizeof("a@/d") || bufpos >= sizeof(buf)) {
384                         condlog(3, "invalid message length");
385                         continue;
386                 }
387
388                 /* check message header */
389                 if (strstr(buf, "@/") == NULL) {
390                         condlog(3, "unrecognized message header");
391                         continue;
392                 }
393                 if ((size_t)buflen > sizeof(buf)-1) {
394                         condlog(2, "buffer overflow for received uevent");
395                         buflen = sizeof(buf)-1;
396                 }
397
398                 uev = uevent_from_buffer(buf, buflen);
399                 if (!uev)
400                         continue;
401                 /*
402                  * Queue uevent and poke service pthread.
403                  */
404                 pthread_mutex_lock(uevq_lockp);
405                 list_add_tail(&uev->node, &uevq);
406                 pthread_cond_signal(uev_condp);
407                 pthread_mutex_unlock(uevq_lockp);
408         }
409
410 exit:
411         close(sock);
412         return 1;
413 }
414
415 struct uevent *uevent_from_udev_device(struct udev_device *dev)
416 {
417         struct uevent *uev;
418         int i = 0;
419         char *pos, *end;
420         struct udev_list_entry *list_entry;
421
422         uev = alloc_uevent();
423         if (!uev) {
424                 udev_device_unref(dev);
425                 condlog(1, "lost uevent, oom");
426                 return NULL;
427         }
428         pos = uev->buffer;
429         end = pos + HOTPLUG_BUFFER_SIZE + OBJECT_SIZE - 1;
430         udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(dev)) {
431                 const char *name, *value;
432                 int bytes;
433
434                 name = udev_list_entry_get_name(list_entry);
435                 if (!name)
436                         name = "(null)";
437                 value = udev_list_entry_get_value(list_entry);
438                 if (!value)
439                         value = "(null)";
440                 bytes = snprintf(pos, end - pos, "%s=%s", name, value);
441                 if (pos + bytes >= end) {
442                         condlog(2, "buffer overflow for uevent");
443                         break;
444                 }
445                 uev->envp[i] = pos;
446                 pos += bytes;
447                 *pos = '\0';
448                 pos++;
449                 if (strcmp(name, "DEVPATH") == 0)
450                         uev->devpath = uev->envp[i] + 8;
451                 if (strcmp(name, "ACTION") == 0)
452                         uev->action = uev->envp[i] + 7;
453                 i++;
454                 if (i == HOTPLUG_NUM_ENVP - 1)
455                         break;
456         }
457         uev->udev = dev;
458         uev->envp[i] = NULL;
459
460         condlog(3, "uevent '%s' from '%s'", uev->action, uev->devpath);
461         uev->kernel = strrchr(uev->devpath, '/');
462         if (uev->kernel)
463                 uev->kernel++;
464
465         /* print payload environment */
466         for (i = 0; uev->envp[i] != NULL; i++)
467                 condlog(5, "%s", uev->envp[i]);
468         return uev;
469 }
470
471 int uevent_listen(struct udev *udev)
472 {
473         int err;
474         struct udev_monitor *monitor = NULL;
475         int fd, socket_flags;
476         int need_failback = 1;
477         /*
478          * Queue uevents for service by dedicated thread so that the uevent
479          * listening thread does not block on multipathd locks (vecs->lock)
480          * thereby not getting to empty the socket's receive buffer queue
481          * often enough.
482          */
483         if (!udev) {
484                 condlog(1, "no udev context");
485                 return 1;
486         }
487         udev_ref(udev);
488         pthread_cleanup_push(uevq_stop, udev);
489
490         monitor = udev_monitor_new_from_netlink(udev, "udev");
491         if (!monitor) {
492                 condlog(2, "failed to create udev monitor");
493                 err = 2;
494                 goto out;
495         }
496 #ifdef LIBUDEV_API_RECVBUF
497         if (udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024))
498                 condlog(2, "failed to increase buffer size");
499 #endif
500         fd = udev_monitor_get_fd(monitor);
501         if (fd < 0) {
502                 condlog(2, "failed to get monitor fd");
503                 goto out;
504         }
505         socket_flags = fcntl(fd, F_GETFL);
506         if (socket_flags < 0) {
507                 condlog(2, "failed to get monitor socket flags : %s",
508                         strerror(errno));
509                 goto out;
510         }
511         if (fcntl(fd, F_SETFL, socket_flags & ~O_NONBLOCK) < 0) {
512                 condlog(2, "failed to set monitor socket flags : %s",
513                         strerror(errno));
514                 goto out;
515         }
516         err = udev_monitor_filter_add_match_subsystem_devtype(monitor, "block",
517                                                               NULL);
518         if (err)
519                 condlog(2, "failed to create filter : %s", strerror(-err));
520         err = udev_monitor_enable_receiving(monitor);
521         if (err) {
522                 condlog(2, "failed to enable receiving : %s", strerror(-err));
523                 goto out;
524         }
525         while (1) {
526                 struct uevent *uev;
527                 struct udev_device *dev;
528
529                 dev = udev_monitor_receive_device(monitor);
530                 if (!dev) {
531                         condlog(0, "failed getting udev device");
532                         continue;
533                 }
534                 uev = uevent_from_udev_device(dev);
535                 if (!uev)
536                         continue;
537                 /*
538                  * Queue uevent and poke service pthread.
539                  */
540                 pthread_mutex_lock(uevq_lockp);
541                 list_add_tail(&uev->node, &uevq);
542                 pthread_cond_signal(uev_condp);
543                 pthread_mutex_unlock(uevq_lockp);
544         }
545         need_failback = 0;
546 out:
547         if (monitor)
548                 udev_monitor_unref(monitor);
549         if (need_failback)
550                 err = failback_listen();
551         pthread_cleanup_pop(1);
552         return err;
553 }
554
555 extern int
556 uevent_get_major(struct uevent *uev)
557 {
558         char *p, *q;
559         int i, major = -1;
560
561         for (i = 0; uev->envp[i] != NULL; i++) {
562                 if (!strncmp(uev->envp[i], "MAJOR", 5) && strlen(uev->envp[i]) > 6) {
563                         p = uev->envp[i] + 6;
564                         major = strtoul(p, &q, 10);
565                         if (p == q) {
566                                 condlog(2, "invalid major '%s'", p);
567                                 major = -1;
568                         }
569                         break;
570                 }
571         }
572         return major;
573 }
574
575 extern int
576 uevent_get_minor(struct uevent *uev)
577 {
578         char *p, *q;
579         int i, minor = -1;
580
581         for (i = 0; uev->envp[i] != NULL; i++) {
582                 if (!strncmp(uev->envp[i], "MINOR", 5) && strlen(uev->envp[i]) > 6) {
583                         p = uev->envp[i] + 6;
584                         minor = strtoul(p, &q, 10);
585                         if (p == q) {
586                                 condlog(2, "invalid minor '%s'", p);
587                                 minor = -1;
588                         }
589                         break;
590                 }
591         }
592         return minor;
593 }
594
595 extern int
596 uevent_get_disk_ro(struct uevent *uev)
597 {
598         char *p, *q;
599         int i, ro = -1;
600
601         for (i = 0; uev->envp[i] != NULL; i++) {
602                 if (!strncmp(uev->envp[i], "DISK_RO", 6) && strlen(uev->envp[i]) > 7) {
603                         p = uev->envp[i] + 8;
604                         ro = strtoul(p, &q, 10);
605                         if (p == q) {
606                                 condlog(2, "invalid read_only setting '%s'", p);
607                                 ro = -1;
608                         }
609                         break;
610                 }
611         }
612         return ro;
613 }
614
615 extern char *
616 uevent_get_dm_name(struct uevent *uev)
617 {
618         char *p = NULL;
619         int i;
620
621         for (i = 0; uev->envp[i] != NULL; i++) {
622                 if (!strncmp(uev->envp[i], "DM_NAME", 6) &&
623                     strlen(uev->envp[i]) > 7) {
624                         p = MALLOC(strlen(uev->envp[i] + 8) + 1);
625                         strcpy(p, uev->envp[i] + 8);
626                         break;
627                 }
628         }
629         return p;
630 }