]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/socket.c
c7ef534a7e556567bda75e22eb3048a4616816ae
[netatalk.git] / libatalk / util / socket.c
1 /*
2    Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2 of the License, or
7    (at your option) any later version.
8  
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 */
14
15 /*!
16  * @file
17  * Netatalk utility functions
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif /* HAVE_CONFIG_H */
23
24 #include <atalk/standards.h>
25
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <sys/uio.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <errno.h>
36 #include <sys/time.h>
37 #include <time.h>
38 #include <sys/ioctl.h>
39
40 #include <atalk/logger.h>
41 #include <atalk/util.h>
42 #include <atalk/errchk.h>
43
44 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
45
46 /*!
47  * @brief set or unset non-blocking IO on a fd
48  *
49  * @param     fd         (r) File descriptor
50  * @param     cmd        (r) 0: disable non-blocking IO, ie block\n
51  *                           <>0: enable non-blocking IO
52  *
53  * @returns   0 on success, -1 on failure
54  */
55 int setnonblock(int fd, int cmd)
56 {
57     int ofdflags;
58     int fdflags;
59
60     if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
61         return -1;
62
63     if (cmd)
64         fdflags |= O_NONBLOCK;
65     else
66         fdflags &= ~O_NONBLOCK;
67
68     if (fdflags != ofdflags)
69         if (fcntl(fd, F_SETFL, fdflags) == -1)
70             return -1;
71
72     return 0;
73 }
74
75 /*!
76  * non-blocking drop-in replacement for read with timeout using select
77  *
78  * @param socket          (r)  socket, if in blocking mode, pass "setnonblocking" arg as 1
79  * @param data            (rw) buffer for the read data
80  * @param lenght          (r)  how many bytes to read
81  * @param setnonblocking  (r)  when non-zero this func will enable and disable non blocking
82  *                             io mode for the socket
83  * @param timeout         (r)  number of seconds to try reading, 0 means no timeout
84  *
85  * @returns number of bytes actually read or -1 on timeout or error
86  */
87 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
88 {
89     size_t stored = 0;
90     ssize_t len = 0;
91     struct timeval now, end, tv;
92     fd_set rfds;
93     int ret;
94
95     FD_ZERO(&rfds);
96
97     if (setnonblocking) {
98         if (setnonblock(socket, 1) != 0)
99             return -1;
100     }
101
102     /* Calculate end time */
103     if (timeout) {
104         (void)gettimeofday(&now, NULL);
105         end = now;
106         end.tv_sec += timeout;
107     }
108
109     while (stored < length) {
110         len = recv(socket, (char *) data + stored, length - stored, 0);
111         if (len == -1) {
112             switch (errno) {
113             case EINTR:
114                 continue;
115             case EAGAIN:
116                 FD_SET(socket, &rfds);
117                 if (timeout) {
118                     tv.tv_usec = 0;
119                     tv.tv_sec  = timeout;
120                 }
121
122                 while ((ret = select(socket + 1, &rfds, NULL, NULL, timeout ? &tv : NULL)) < 1) {
123                     switch (ret) {
124                     case 0:
125                         LOG(log_debug, logtype_dsi, "select timeout %d s", timeout);
126                         errno = EAGAIN;
127                         goto exit;
128
129                     default: /* -1 */
130                         switch (errno) {
131                         case EINTR:
132                             if (timeout) {
133                                 (void)gettimeofday(&now, NULL);
134                                 if (now.tv_sec > end.tv_sec
135                                     ||
136                                     (now.tv_sec == end.tv_sec && now.tv_usec >= end.tv_usec)) {
137                                     LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
138                                     goto exit;
139                                 }
140                                 if (now.tv_usec > end.tv_usec) {
141                                     tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
142                                     tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
143                                 } else {
144                                     tv.tv_usec = end.tv_usec - now.tv_usec;
145                                     tv.tv_sec  = end.tv_sec - now.tv_sec;
146                                 }
147                             }
148                             FD_SET(socket, &rfds);
149                             continue;
150                         case EBADF:
151                             /* possibly entered disconnected state, don't spam log here */
152                             LOG(log_debug, logtype_afpd, "select: %s", strerror(errno));
153                             stored = -1;
154                             goto exit;
155                         default:
156                             LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
157                             stored = -1;
158                             goto exit;
159                         }
160                     }
161                 } /* while (select) */
162                 continue;
163             } /* switch (errno) */
164             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
165             stored = -1;
166             goto exit;
167         } /* (len == -1) */
168         else if (len > 0)
169             stored += len;
170         else
171             break;
172     } /* while (stored < length) */
173
174 exit:
175     if (setnonblocking) {
176         if (setnonblock(socket, 0) != 0)
177             return -1;
178     }
179
180     if (len == -1 && stored == 0)
181         /* last read or select got an error and we haven't got yet anything => return -1*/
182         return -1;
183     return stored;
184 }
185
186 /*!
187  * non-blocking drop-in replacement for read with timeout using select
188  *
189  * @param socket          (r)  socket, if in blocking mode, pass "setnonblocking" arg as 1
190  * @param data            (rw) buffer for the read data
191  * @param lenght          (r)  how many bytes to read
192  * @param setnonblocking  (r)  when non-zero this func will enable and disable non blocking
193  *                             io mode for the socket
194  * @param timeout         (r)  number of seconds to try reading
195  *
196  * @returns number of bytes actually read or -1 on fatal error
197  */
198 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
199 {
200     size_t stored = 0;
201     ssize_t len = 0;
202     struct timeval now, end, tv;
203     fd_set rfds;
204     int ret;
205
206     if (setnonblocking) {
207         if (setnonblock(socket, 1) != 0)
208             return -1;
209     }
210
211     /* Calculate end time */
212     (void)gettimeofday(&now, NULL);
213     end = now;
214     end.tv_sec += timeout;
215
216     while (stored < length) {
217         len = write(socket, (char *) data + stored, length - stored);
218         if (len == -1) {
219             switch (errno) {
220             case EINTR:
221                 continue;
222             case EAGAIN:
223                 FD_ZERO(&rfds);
224                 FD_SET(socket, &rfds);
225                 tv.tv_usec = 0;
226                 tv.tv_sec  = timeout;
227                         
228                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
229                     switch (ret) {
230                     case 0:
231                         LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
232                         goto exit;
233
234                     default: /* -1 */
235                         if (errno == EINTR) {
236                             (void)gettimeofday(&now, NULL);
237                             if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
238                                 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
239                                 goto exit;
240                             }
241                             if (now.tv_usec > end.tv_usec) {
242                                 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
243                                 tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
244                             } else {
245                                 tv.tv_usec = end.tv_usec - now.tv_usec;
246                                 tv.tv_sec  = end.tv_sec - now.tv_sec;
247                             }
248                             FD_ZERO(&rfds);
249                             FD_SET(socket, &rfds);
250                             continue;
251                         }
252                         LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
253                         stored = -1;
254                         goto exit;
255                     }
256                 } /* while (select) */
257                 continue;
258             } /* switch (errno) */
259             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
260             stored = -1;
261             goto exit;
262         } /* (len == -1) */
263         else if (len > 0)
264             stored += len;
265         else
266             break;
267     } /* while (stored < length) */
268
269 exit:
270     if (setnonblocking) {
271         if (setnonblock(socket, 0) != 0)
272             return -1;
273     }
274
275     if (len == -1 && stored == 0)
276         /* last read or select got an error and we haven't got yet anything => return -1*/
277         return -1;
278     return stored;
279 }
280
281 /*!
282  * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
283  *
284  * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
285  * ::ffff:10.0.0.0 is returned as "10.0.0.0".
286  *
287  * @param  sa        (r) pointer to an struct sockaddr
288  *
289  * @returns pointer to a static string cotaining the converted address as string.\n
290  *          On error pointers to "0.0.0.0" or "::0" are returned.
291  */
292 const char *getip_string(const struct sockaddr *sa)
293 {
294     static char ip4[INET_ADDRSTRLEN];
295     static char ip6[INET6_ADDRSTRLEN];
296
297     switch (sa->sa_family) {
298
299     case AF_INET: {
300         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
301         if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
302             return "0.0.0.0";
303         return ip4;
304     }
305     case AF_INET6: {
306         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
307         if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
308             return "::0";
309
310         /* Deal with IPv6 mapped IPv4 addresses*/
311         if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
312             return (strrchr(ip6, ':') + 1);
313         return ip6;
314     }
315     default:
316         return "getip_string ERROR";
317     }
318
319     /* We never get here */
320 }
321
322 /*!
323  * @brief return port number from struct sockaddr
324  *
325  * @param  sa        (r) pointer to an struct sockaddr
326  *
327  * @returns port as unsigned int
328  */
329 unsigned int getip_port(const struct sockaddr  *sa)
330 {
331     if (sa->sa_family == AF_INET) { /* IPv4 */
332         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
333         return ntohs(sai4->sin_port);
334     } else {                       /* IPv6 */
335         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
336         return ntohs(sai6->sin6_port);
337     }
338
339     /* We never get here */
340 }
341
342 /*!
343  * @brief apply netmask to IP (v4 or v6)
344  *
345  * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
346  * for passing a value for mask that is sensible to the passed address,
347  * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
348  * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
349  *
350  * @param  ai        (rw) pointer to an struct sockaddr
351  * @parma  mask      (r) number of maskbits
352  */
353 void apply_ip_mask(struct sockaddr *sa, int mask)
354 {
355
356     switch (sa->sa_family) {
357     case AF_INET: {
358         if (mask >= 32)
359             return;
360
361         struct sockaddr_in *si = (struct sockaddr_in *)sa;
362         uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
363         si->sin_addr.s_addr &= htonl(nmask);
364         break;
365     }
366     case AF_INET6: {
367         if (mask >= 128)
368             return;
369
370         int i, maskbytes, maskbits;
371         struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
372
373         /* Deal with IPv6 mapped IPv4 addresses*/
374         if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
375             mask += 96;
376             if (mask >= 128)
377                 return;
378         }
379
380         maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
381         maskbits = mask % 8;
382
383         for (i = maskbytes - 1; i >= 0; i--)
384             si6->sin6_addr.s6_addr[15 - i] = 0;
385         if (maskbits)
386             si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
387         break;
388     }
389     default:
390         break;
391     }
392 }
393
394 /*!
395  * @brief compare IP addresses for equality
396  *
397  * @param  sa1       (r) pointer to an struct sockaddr
398  * @param  sa2       (r) pointer to an struct sockaddr
399  *
400  * @returns Addresses are converted to strings and compared with strcmp and
401  *          the result of strcmp is returned.
402  *
403  * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
404  */
405 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
406 {
407     int ret;
408     char *ip1;
409     const char *ip2;
410
411     ip1 = strdup(getip_string(sa1));
412     ip2 = getip_string(sa2);
413
414     ret = strcmp(ip1, ip2);
415
416     free(ip1);
417
418     return ret;
419 }
420
421 /*!
422  * Tokenize IP(4/6) addresses with an optional port into address and port
423  *
424  * @param ipurl    (r) IP URL string
425  * @param address  (w) IP address
426  * @param port     (w) IP port
427  *
428  * @returns 0 on success, -1 on failure
429  *
430  * Tokenize IPv4, IPv4:port, IPv6, [IPv6] or [IPv6:port] URL into address and
431  * port and return two allocated strings with the address and the port.
432  *
433  * If the function returns 0, then address point to a newly allocated
434  * valid address string, port may either be NULL or point to a newly
435  * allocated port number.
436  *
437  * If the function returns -1, then the contents of address and port are
438  * undefined.
439  */
440 int tokenize_ip_port(const char *ipurl, char **address, char **port)
441 {
442     EC_INIT;
443     char *p = NULL;
444     char *s;
445
446     AFP_ASSERT(ipurl && address && port);
447     EC_NULL( p = strdup(ipurl));
448
449     /* Either ipv4, ipv4:port, ipv6, [ipv6] or [ipv6]:port */
450
451     if (!strchr(p, ':')) {
452         /* IPv4 address without port */
453         *address = p;
454         p = NULL;  /* prevent free() */
455         *port = NULL;
456         EC_EXIT_STATUS(0);
457     }
458
459     /* Either ipv4:port, ipv6, [ipv6] or [ipv6]:port */
460
461     if (strchr(p, '.')) {
462         /* ipv4:port */
463         *address = p;
464         p = strchr(p, ':');
465         *p = '\0';
466         EC_NULL( *port = strdup(p + 1));
467         p = NULL; /* prevent free() */
468         EC_EXIT_STATUS(0);
469     }
470
471     /* Either ipv6, [ipv6] or [ipv6]:port */
472
473     if (p[0] != '[') {
474         /* ipv6 */
475         *address = p;
476         p = NULL;  /* prevent free() */
477         *port = NULL;
478         EC_EXIT_STATUS(0);
479     }
480
481     /* [ipv6] or [ipv6]:port */
482
483     EC_NULL( *address = strdup(p + 1) );
484
485     if ((s = strchr(*address, ']')) == NULL) {
486         LOG(log_error, logtype_dsi, "tokenize_ip_port: malformed ipv6 address %s\n", ipurl);
487         EC_FAIL;
488     }
489     *s = '\0';
490     /* address now points to the ipv6 address without [] */
491
492     if (s[1] == ':') {
493         /* [ipv6]:port */
494         EC_NULL( *port = strdup(s + 2) );
495     } else {
496         /* [ipv6] */
497         *port = NULL;
498     }
499
500 EC_CLEANUP:
501     if (p)
502         free(p);
503     EC_EXIT;
504 }
505
506 /*!
507  * Add a fd to a dynamic pollfd array that is allocated and grown as needed
508  *
509  * This uses an additional array of struct polldata which stores type information
510  * (enum fdtype) and a pointer to anciliary user data.
511  *
512  * 1. Allocate the arrays with the size of "maxconns" if *fdsetp is NULL.
513  * 2. Fill in both array elements and increase count of used elements
514  * 
515  * @param maxconns    (r)  maximum number of connections, determines array size
516  * @param fdsetp      (rw) pointer to callers pointer to the pollfd array
517  * @param polldatap   (rw) pointer to callers pointer to the polldata array
518  * @param fdset_usedp (rw) pointer to an int with the number of used elements
519  * @param fdset_sizep (rw) pointer to an int which stores the array sizes
520  * @param fd          (r)  file descriptor to add to the arrays
521  * @param fdtype      (r)  type of fd, currently IPC_FD or LISTEN_FD
522  * @param data        (rw) pointer to data the caller want to associate with an fd
523  */
524 void fdset_add_fd(int maxconns,
525                   struct pollfd **fdsetp,
526                   struct polldata **polldatap,
527                   int *fdset_usedp,
528                   int *fdset_sizep,
529                   int fd,
530                   enum fdtype fdtype,
531                   void *data)
532 {
533     struct pollfd *fdset = *fdsetp;
534     struct polldata *polldata = *polldatap;
535     int fdset_size = *fdset_sizep;
536
537     LOG(log_debug, logtype_default, "fdset_add_fd: adding fd %i in slot %i", fd, *fdset_usedp);
538
539     if (fdset == NULL) { /* 1 */
540         /* Initialize with space for all possibly active fds */
541         fdset = calloc(maxconns, sizeof(struct pollfd));
542         if (! fdset)
543             exit(EXITERR_SYS);
544
545         polldata = calloc(maxconns, sizeof(struct polldata));
546         if (! polldata)
547             exit(EXITERR_SYS);
548
549         fdset_size = maxconns;
550
551         *fdset_sizep = fdset_size;
552         *fdsetp = fdset;
553         *polldatap = polldata;
554
555         LOG(log_debug, logtype_default, "fdset_add_fd: initialized with space for %i conncections", 
556             maxconns);
557     }
558
559     /* 2 */
560     fdset[*fdset_usedp].fd = fd;
561     fdset[*fdset_usedp].events = POLLIN;
562     polldata[*fdset_usedp].fdtype = fdtype;
563     polldata[*fdset_usedp].data = data;
564     (*fdset_usedp)++;
565 }
566
567 /*!
568  * Remove a fd from our pollfd array
569  *
570  * 1. Search fd
571  * 2a Matched last (or only) in the set ? null it and return
572  * 2b If we remove the last array elemnt, just decrease count
573  * 3. If found move all following elements down by one
574  * 4. Decrease count of used elements in array
575  *
576  * This currently doesn't shrink the allocated storage of the array.
577  *
578  * @param fdsetp      (rw) pointer to callers pointer to the pollfd array
579  * @param polldatap   (rw) pointer to callers pointer to the polldata array
580  * @param fdset_usedp (rw) pointer to an int with the number of used elements
581  * @param fdset_sizep (rw) pointer to an int which stores the array sizes
582  * @param fd          (r)  file descriptor to remove from the arrays
583  */
584 void fdset_del_fd(struct pollfd **fdsetp,
585                   struct polldata **polldatap,
586                   int *fdset_usedp,
587                   int *fdset_sizep _U_,
588                   int fd)
589 {
590     struct pollfd *fdset = *fdsetp;
591     struct polldata *polldata = *polldatap;
592
593     if (*fdset_usedp < 1)
594         return;
595
596     for (int i = 0; i < *fdset_usedp; i++) {
597         if (fdset[i].fd == fd) { /* 1 */
598             if ((i + 1) == *fdset_usedp) { /* 2a */
599                 fdset[i].fd = -1;
600                 memset(&polldata[i], 0, sizeof(struct polldata));
601             } else if (i < (*fdset_usedp - 1)) { /* 2b */
602                 memmove(&fdset[i],
603                         &fdset[i+1],
604                         (*fdset_usedp - i - 1) * sizeof(struct pollfd)); /* 3 */
605                 memmove(&polldata[i],
606                         &polldata[i+1],
607                         (*fdset_usedp - i - 1) * sizeof(struct polldata)); /* 3 */
608             }
609             (*fdset_usedp)--;
610             break;
611         }
612     }
613 }
614
615 /* Length of the space taken up by a padded control message of length len */
616 #ifndef CMSG_SPACE
617 #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len))
618 #endif
619
620 /*
621  * Receive a fd on a suitable socket
622  * @args fd          (r) PF_UNIX socket to receive on
623  * @args nonblocking (r) 0: fd is in blocking mode - 1: fd is nonblocking, poll for 1 sec
624  * @returns fd on success, -1 on error
625  */
626 int recv_fd(int fd, int nonblocking)
627 {
628     int ret;
629     struct msghdr msgh;
630     struct iovec iov[1];
631     struct cmsghdr *cmsgp = NULL;
632     char buf[CMSG_SPACE(sizeof(int))];
633     char dbuf[80];
634     struct pollfd pollfds[1];
635
636     pollfds[0].fd = fd;
637     pollfds[0].events = POLLIN;
638
639     memset(&msgh,0,sizeof(msgh));
640     memset(buf,0,sizeof(buf));
641
642     msgh.msg_name = NULL;
643     msgh.msg_namelen = 0;
644
645     msgh.msg_iov = iov;
646     msgh.msg_iovlen = 1;
647
648     iov[0].iov_base = dbuf;
649     iov[0].iov_len = sizeof(dbuf);
650
651     msgh.msg_control = buf;
652     msgh.msg_controllen = sizeof(buf);
653
654     if (nonblocking) {
655         do {
656             ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
657         } while ( ret == -1 && errno == EINTR );
658         if (ret != 1)
659             return -1;
660         ret = recvmsg(fd, &msgh, 0);
661     } else {
662         do  {
663             ret = recvmsg(fd, &msgh, 0);
664         } while ( ret == -1 && errno == EINTR );
665     }
666
667     if ( ret == -1 ) {
668         return -1;
669     }
670
671     for ( cmsgp = CMSG_FIRSTHDR(&msgh); cmsgp != NULL; cmsgp = CMSG_NXTHDR(&msgh,cmsgp) ) {
672         if ( cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_RIGHTS ) {
673             return *(int *) CMSG_DATA(cmsgp);
674         }
675     }
676
677     if ( ret == sizeof (int) )
678         errno = *(int *)dbuf; /* Rcvd errno */
679     else
680         errno = ENOENT;    /* Default errno */
681
682     return -1;
683 }
684
685 /*
686  * Send a fd across a suitable socket
687  */
688 int send_fd(int socket, int fd)
689 {
690     int ret;
691     struct msghdr msgh;
692     struct iovec iov[1];
693     struct cmsghdr *cmsgp = NULL;
694     char *buf;
695     size_t size;
696     int er=0;
697
698     size = CMSG_SPACE(sizeof fd);
699     buf = malloc(size);
700     if (!buf) {
701         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
702         return -1;
703     }
704
705     memset(&msgh,0,sizeof (msgh));
706     memset(buf,0, size);
707
708     msgh.msg_name = NULL;
709     msgh.msg_namelen = 0;
710
711     msgh.msg_iov = iov;
712     msgh.msg_iovlen = 1;
713
714     iov[0].iov_base = &er;
715     iov[0].iov_len = sizeof(er);
716
717     msgh.msg_control = buf;
718     msgh.msg_controllen = size;
719
720     cmsgp = CMSG_FIRSTHDR(&msgh);
721     cmsgp->cmsg_level = SOL_SOCKET;
722     cmsgp->cmsg_type = SCM_RIGHTS;
723     cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
724
725     *((int *)CMSG_DATA(cmsgp)) = fd;
726     msgh.msg_controllen = cmsgp->cmsg_len;
727
728     do  {
729         ret = sendmsg(socket,&msgh, 0);
730     } while ( ret == -1 && errno == EINTR );
731     if (ret == -1) {
732         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
733         free(buf);
734         return -1;
735     }
736     free(buf);
737     return 0;
738 }