Add configure checks for sys/socket.h
[deb_libnfs.git] / lib / socket.c
1 /*
2 Copyright (C) 2010 by Ronnie Sahlberg <ronniesahlberg@gmail.com>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as published by
6 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program; if not, see <http://www.gnu.org/licenses/>.
16 */
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20
21 #ifdef AROS
22 #include "aros_compat.h"
23 #endif
24
25 #ifdef WIN32
26 #include "win32_compat.h"
27 #else
28 #include <arpa/inet.h>
29 #include <netdb.h>
30 #endif/*WIN32*/
31
32 #ifdef HAVE_POLL_H
33 #include <poll.h>
34 #endif
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43
44 #ifdef HAVE_SYS_SOCKET_H
45 #include <sys/socket.h>
46 #endif
47
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <assert.h>
51 #include <fcntl.h>
52 #include <string.h>
53 #include <errno.h>
54 #ifdef HAVE_SYS_FILIO_H
55 #include <sys/filio.h>
56 #endif
57 #ifdef HAVE_SYS_SOCKIO_H
58 #include <sys/sockio.h>
59 #endif
60 #include <sys/types.h>
61 #include "libnfs-zdr.h"
62 #include "libnfs.h"
63 #include "libnfs-raw.h"
64 #include "libnfs-private.h"
65 #include "slist.h"
66
67 #ifdef WIN32
68 //has to be included after stdlib!!
69 #include "win32_errnowrapper.h"
70 #endif
71
72
73 static int rpc_reconnect_requeue(struct rpc_context *rpc);
74 static int rpc_connect_sockaddr_async(struct rpc_context *rpc, struct sockaddr_storage *s);
75
76 static void set_nonblocking(int fd)
77 {
78 int v = 0;
79 #if defined(WIN32)
80 long nonblocking=1;
81 v = ioctl(fd, FIONBIO, &nonblocking);
82 #else
83 v = fcntl(fd, F_GETFL, 0);
84 fcntl(fd, F_SETFL, v | O_NONBLOCK);
85 #endif //FIXME
86 }
87
88 int rpc_get_fd(struct rpc_context *rpc)
89 {
90 assert(rpc->magic == RPC_CONTEXT_MAGIC);
91
92 return rpc->fd;
93 }
94
95 int rpc_which_events(struct rpc_context *rpc)
96 {
97 int events;
98
99 assert(rpc->magic == RPC_CONTEXT_MAGIC);
100
101 events = rpc->is_connected ? POLLIN : POLLOUT;
102
103 if (rpc->is_udp != 0) {
104 /* for udp sockets we only wait for pollin */
105 return POLLIN;
106 }
107
108 if (rpc->outqueue) {
109 events |= POLLOUT;
110 }
111 return events;
112 }
113
114 static int rpc_write_to_socket(struct rpc_context *rpc)
115 {
116 int32_t count;
117
118 assert(rpc->magic == RPC_CONTEXT_MAGIC);
119
120 if (rpc->fd == -1) {
121 rpc_set_error(rpc, "trying to write but not connected");
122 return -1;
123 }
124
125 while (rpc->outqueue != NULL) {
126 int64_t total;
127
128 total = rpc->outqueue->outdata.size;
129
130 count = send(rpc->fd, rpc->outqueue->outdata.data + rpc->outqueue->written, total - rpc->outqueue->written, 0);
131 if (count == -1) {
132 if (errno == EAGAIN || errno == EWOULDBLOCK) {
133 return 0;
134 }
135 rpc_set_error(rpc, "Error when writing to socket :%s(%d)", strerror(errno), errno);
136 return -1;
137 }
138
139 rpc->outqueue->written += count;
140 if (rpc->outqueue->written == total) {
141 struct rpc_pdu *pdu = rpc->outqueue;
142
143 SLIST_REMOVE(&rpc->outqueue, pdu);
144 SLIST_ADD_END(&rpc->waitpdu, pdu);
145 }
146 }
147 return 0;
148 }
149
150 static int rpc_read_from_socket(struct rpc_context *rpc)
151 {
152 int available;
153 int size;
154 int pdu_size;
155 int32_t count;
156
157 assert(rpc->magic == RPC_CONTEXT_MAGIC);
158
159 assert(rpc->magic == RPC_CONTEXT_MAGIC);
160
161 if (ioctl(rpc->fd, FIONREAD, &available) != 0) {
162 rpc_set_error(rpc, "Ioctl FIONREAD returned error : %d. Closing socket.", errno);
163 return -1;
164 }
165
166 if (available == 0) {
167 rpc_set_error(rpc, "Socket has been closed");
168 return -1;
169 }
170
171 if (rpc->is_udp) {
172 char *buf;
173 socklen_t socklen = sizeof(rpc->udp_src);
174
175 buf = malloc(available);
176 if (buf == NULL) {
177 rpc_set_error(rpc, "Failed to malloc buffer for recvfrom");
178 return -1;
179 }
180 count = recvfrom(rpc->fd, buf, available, MSG_DONTWAIT, (struct sockaddr *)&rpc->udp_src, &socklen);
181 if (count < 0) {
182 rpc_set_error(rpc, "Failed recvfrom: %s", strerror(errno));
183 free(buf);
184 }
185 if (rpc_process_pdu(rpc, buf, count) != 0) {
186 rpc_set_error(rpc, "Invalid/garbage pdu received from server. Ignoring PDU");
187 free(buf);
188 return -1;
189 }
190 free(buf);
191 return 0;
192 }
193
194 /* read record marker, 4 bytes at the beginning of every pdu */
195 if (rpc->inbuf == NULL) {
196 rpc->insize = 4;
197 rpc->inbuf = malloc(rpc->insize);
198 if (rpc->inbuf == NULL) {
199 rpc_set_error(rpc, "Failed to allocate buffer for record marker, errno:%d. Closing socket.", errno);
200 return -1;
201 }
202 }
203 if (rpc->inpos < 4) {
204 size = 4 - rpc->inpos;
205
206 count = recv(rpc->fd, rpc->inbuf + rpc->inpos, size, 0);
207 if (count == -1) {
208 if (errno == EINTR) {
209 return 0;
210 }
211 rpc_set_error(rpc, "Read from socket failed, errno:%d. Closing socket.", errno);
212 return -1;
213 }
214 available -= count;
215 rpc->inpos += count;
216 }
217
218 if (available == 0) {
219 return 0;
220 }
221
222 pdu_size = rpc_get_pdu_size(rpc->inbuf);
223 if (rpc->insize < pdu_size) {
224 unsigned char *buf;
225
226 buf = malloc(pdu_size);
227 if (buf == NULL) {
228 rpc_set_error(rpc, "Failed to allocate buffer of %d bytes for pdu, errno:%d. Closing socket.", pdu_size, errno);
229 return -1;
230 }
231 memcpy(buf, rpc->inbuf, rpc->insize);
232 free(rpc->inbuf);
233 rpc->inbuf = buf;
234 rpc->insize = rpc_get_pdu_size(rpc->inbuf);
235 }
236
237 size = available;
238 if (size > rpc->insize - rpc->inpos) {
239 size = rpc->insize - rpc->inpos;
240 }
241
242 count = recv(rpc->fd, rpc->inbuf + rpc->inpos, size, 0);
243 if (count == -1) {
244 if (errno == EINTR) {
245 return 0;
246 }
247 rpc_set_error(rpc, "Read from socket failed, errno:%d. Closing socket.", errno);
248 return -1;
249 }
250 available -= count;
251 rpc->inpos += count;
252
253 if (rpc->inpos == rpc->insize) {
254 if (rpc_process_pdu(rpc, rpc->inbuf, pdu_size) != 0) {
255 rpc_set_error(rpc, "Invalid/garbage pdu received from server. Closing socket");
256 return -1;
257 }
258 free(rpc->inbuf);
259 rpc->inbuf = NULL;
260 rpc->insize = 0;
261 rpc->inpos = 0;
262 }
263
264 return 0;
265 }
266
267
268
269 int rpc_service(struct rpc_context *rpc, int revents)
270 {
271 assert(rpc->magic == RPC_CONTEXT_MAGIC);
272
273 if (revents & POLLERR) {
274 #ifdef WIN32
275 char err = 0;
276 #else
277 int err = 0;
278 #endif
279 socklen_t err_size = sizeof(err);
280
281 if (getsockopt(rpc->fd, SOL_SOCKET, SO_ERROR,
282 (char *)&err, &err_size) != 0 || err != 0) {
283 if (err == 0) {
284 err = errno;
285 }
286 rpc_set_error(rpc, "rpc_service: socket error "
287 "%s(%d).",
288 strerror(err), err);
289 } else {
290 rpc_set_error(rpc, "rpc_service: POLLERR, "
291 "Unknown socket error.");
292 }
293 if (rpc->connect_cb != NULL) {
294 rpc->connect_cb(rpc, RPC_STATUS_ERROR, rpc->error_string, rpc->connect_data);
295 }
296 return -1;
297 }
298 if (revents & POLLHUP) {
299 rpc_set_error(rpc, "Socket failed with POLLHUP");
300 if (rpc->connect_cb != NULL) {
301 rpc->connect_cb(rpc, RPC_STATUS_ERROR, rpc->error_string, rpc->connect_data);
302 }
303 return -1;
304 }
305
306 if (rpc->is_connected == 0 && rpc->fd != -1 && revents&POLLOUT) {
307 int err = 0;
308 socklen_t err_size = sizeof(err);
309
310 if (getsockopt(rpc->fd, SOL_SOCKET, SO_ERROR,
311 (char *)&err, &err_size) != 0 || err != 0) {
312 if (err == 0) {
313 err = errno;
314 }
315 rpc_set_error(rpc, "rpc_service: socket error "
316 "%s(%d) while connecting.",
317 strerror(err), err);
318 if (rpc->connect_cb != NULL) {
319 rpc->connect_cb(rpc, RPC_STATUS_ERROR,
320 NULL, rpc->connect_data);
321 }
322 return -1;
323 }
324
325 rpc->is_connected = 1;
326 if (rpc->connect_cb != NULL) {
327 rpc->connect_cb(rpc, RPC_STATUS_SUCCESS, NULL, rpc->connect_data);
328 }
329 return 0;
330 }
331
332 if (revents & POLLIN) {
333 if (rpc_read_from_socket(rpc) != 0) {
334 rpc_reconnect_requeue(rpc);
335 return 0;
336 }
337 }
338
339 if (revents & POLLOUT && rpc->outqueue != NULL) {
340 if (rpc_write_to_socket(rpc) != 0) {
341 rpc_set_error(rpc, "write to socket failed");
342 return -1;
343 }
344 }
345
346 return 0;
347 }
348
349 void rpc_set_autoreconnect(struct rpc_context *rpc)
350 {
351 assert(rpc->magic == RPC_CONTEXT_MAGIC);
352
353 rpc->auto_reconnect = 1;
354 }
355
356 void rpc_unset_autoreconnect(struct rpc_context *rpc)
357 {
358 assert(rpc->magic == RPC_CONTEXT_MAGIC);
359
360 rpc->auto_reconnect = 0;
361 }
362
363 static int rpc_connect_sockaddr_async(struct rpc_context *rpc, struct sockaddr_storage *s)
364 {
365 int socksize;
366
367 assert(rpc->magic == RPC_CONTEXT_MAGIC);
368
369 switch (s->ss_family) {
370 case AF_INET:
371 socksize = sizeof(struct sockaddr_in);
372 rpc->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
373 break;
374 default:
375 rpc_set_error(rpc, "Can not handle AF_FAMILY:%d", s->ss_family);
376 return -1;
377 }
378
379 if (rpc->fd == -1) {
380 rpc_set_error(rpc, "Failed to open socket");
381 return -1;
382 }
383
384 /* Some systems allow you to set capabilities on an executable
385 * to allow the file to be executed with privilege to bind to
386 * privileged system ports, even if the user is not root.
387 *
388 * Opportunistically try to bind the socket to a low numbered
389 * system port in the hope that the user is either root or the
390 * executable has the CAP_NET_BIND_SERVICE.
391 *
392 * As soon as we fail the bind() with EACCES we know we will never
393 * be able to bind to a system port so we terminate the loop.
394 *
395 * On linux, use
396 * sudo setcap 'cap_net_bind_service=+ep' /path/executable
397 * to make the executable able to bind to a system port.
398 *
399 * On Windows, there is no concept of privileged ports. Thus
400 * binding will usually succeed.
401 */
402 {
403 struct sockaddr_in sin;
404 static int portOfs = 0;
405 const int firstPort = 512; /* >= 512 according to Sun docs */
406 const int portCount = IPPORT_RESERVED - firstPort;
407 int startOfs, port, rc;
408
409 if (portOfs == 0) {
410 portOfs = time(NULL) % 400;
411 }
412 startOfs = portOfs;
413 do {
414 rc = -1;
415 port = htons(firstPort + portOfs);
416 portOfs = (portOfs + 1) % portCount;
417
418 /* skip well-known ports */
419 if (!getservbyport(port, "tcp")) {
420 memset(&sin, 0, sizeof(sin));
421 sin.sin_port = port;
422 sin.sin_family = AF_INET;
423 sin.sin_addr.s_addr = 0;
424
425 rc = bind(rpc->fd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in));
426 #if !defined(WIN32)
427 /* we got EACCES, so don't try again */
428 if (rc != 0 && errno == EACCES)
429 break;
430 #endif
431 }
432 } while (rc != 0 && portOfs != startOfs);
433 }
434
435 set_nonblocking(rpc->fd);
436
437 if (connect(rpc->fd, (struct sockaddr *)s, socksize) != 0 && errno != EINPROGRESS) {
438 rpc_set_error(rpc, "connect() to server failed. %s(%d)", strerror(errno), errno);
439 return -1;
440 }
441
442 return 0;
443 }
444
445 int rpc_connect_async(struct rpc_context *rpc, const char *server, int port, rpc_cb cb, void *private_data)
446 {
447 struct sockaddr_in *sin = (struct sockaddr_in *)&rpc->s;
448
449 assert(rpc->magic == RPC_CONTEXT_MAGIC);
450
451 if (rpc->fd != -1) {
452 rpc_set_error(rpc, "Trying to connect while already connected");
453 return -1;
454 }
455
456 if (rpc->is_udp != 0) {
457 rpc_set_error(rpc, "Trying to connect on UDP socket");
458 return -1;
459 }
460
461 rpc->auto_reconnect = 0;
462
463 sin->sin_family = AF_INET;
464 sin->sin_port = htons(port);
465 if (inet_pton(AF_INET, server, &sin->sin_addr) != 1) {
466 rpc_set_error(rpc, "Not a valid server ip address");
467 return -1;
468 }
469
470
471 switch (rpc->s.ss_family) {
472 case AF_INET:
473 #ifdef HAVE_SOCKADDR_LEN
474 sin->sin_len = sizeof(struct sockaddr_in);
475 #endif
476 break;
477 }
478
479 rpc->connect_cb = cb;
480 rpc->connect_data = private_data;
481
482 if (rpc_connect_sockaddr_async(rpc, &rpc->s) != 0) {
483 return -1;
484 }
485
486 return 0;
487 }
488
489 int rpc_disconnect(struct rpc_context *rpc, char *error)
490 {
491 assert(rpc->magic == RPC_CONTEXT_MAGIC);
492
493 rpc_unset_autoreconnect(rpc);
494
495 if (rpc->fd != -1) {
496 close(rpc->fd);
497 }
498 rpc->fd = -1;
499
500 rpc->is_connected = 0;
501
502 rpc_error_all_pdus(rpc, error);
503
504 return 0;
505 }
506
507 static void reconnect_cb(struct rpc_context *rpc, int status, void *data _U_, void *private_data)
508 {
509 assert(rpc->magic == RPC_CONTEXT_MAGIC);
510
511 if (status != RPC_STATUS_SUCCESS) {
512 rpc_error_all_pdus(rpc, "RPC ERROR: Failed to reconnect async");
513 return;
514 }
515
516 rpc->is_connected = 1;
517 rpc->connect_cb = NULL;
518 }
519
520 /* disconnect but do not error all PDUs, just move pdus in-flight back to the outqueue and reconnect */
521 static int rpc_reconnect_requeue(struct rpc_context *rpc)
522 {
523 struct rpc_pdu *pdu;
524
525 assert(rpc->magic == RPC_CONTEXT_MAGIC);
526
527 if (rpc->fd != -1) {
528 close(rpc->fd);
529 }
530 rpc->fd = -1;
531
532 rpc->is_connected = 0;
533
534 /* socket is closed so we will not get any replies to any commands
535 * in flight. Move them all over from the waitpdu queue back to the out queue
536 */
537 for (pdu=rpc->waitpdu; pdu; pdu=pdu->next) {
538 SLIST_REMOVE(&rpc->waitpdu, pdu);
539 SLIST_ADD(&rpc->outqueue, pdu);
540 /* we have to re-send the whole pdu again */
541 pdu->written = 0;
542 }
543
544 if (rpc->auto_reconnect != 0) {
545 rpc->connect_cb = reconnect_cb;
546
547 if (rpc_connect_sockaddr_async(rpc, &rpc->s) != 0) {
548 rpc_error_all_pdus(rpc, "RPC ERROR: Failed to reconnect async");
549 return -1;
550 }
551 }
552
553 return 0;
554 }
555
556
557 int rpc_bind_udp(struct rpc_context *rpc, char *addr, int port)
558 {
559 struct addrinfo *ai = NULL;
560 char service[6];
561
562 assert(rpc->magic == RPC_CONTEXT_MAGIC);
563
564 if (rpc->is_udp == 0) {
565 rpc_set_error(rpc, "Cant not bind UDP. Not UDP context");
566 return -1;
567 }
568
569 sprintf(service, "%d", port);
570 if (getaddrinfo(addr, service, NULL, &ai) != 0) {
571 rpc_set_error(rpc, "Invalid address:%s. "
572 "Can not resolv into IPv4/v6 structure.");
573 return -1;
574 }
575
576 switch(ai->ai_family) {
577 case AF_INET:
578 rpc->fd = socket(ai->ai_family, SOCK_DGRAM, 0);
579 if (rpc->fd == -1) {
580 rpc_set_error(rpc, "Failed to create UDP socket: %s", strerror(errno));
581 freeaddrinfo(ai);
582 return -1;
583 }
584
585 if (bind(rpc->fd, (struct sockaddr *)ai->ai_addr, sizeof(struct sockaddr_in)) != 0) {
586 rpc_set_error(rpc, "Failed to bind to UDP socket: %s",strerror(errno));
587 freeaddrinfo(ai);
588 return -1;
589 }
590 break;
591 default:
592 rpc_set_error(rpc, "Can not handle UPD sockets of family %d yet", ai->ai_family);
593 freeaddrinfo(ai);
594 return -1;
595 }
596
597 freeaddrinfo(ai);
598
599 return 0;
600 }
601
602 int rpc_set_udp_destination(struct rpc_context *rpc, char *addr, int port, int is_broadcast)
603 {
604 struct addrinfo *ai = NULL;
605 char service[6];
606
607 assert(rpc->magic == RPC_CONTEXT_MAGIC);
608
609 if (rpc->is_udp == 0) {
610 rpc_set_error(rpc, "Can not set destination sockaddr. Not UDP context");
611 return -1;
612 }
613
614 sprintf(service, "%d", port);
615 if (getaddrinfo(addr, service, NULL, &ai) != 0) {
616 rpc_set_error(rpc, "Invalid address:%s. "
617 "Can not resolv into IPv4/v6 structure.");
618 return -1;
619 }
620
621 if (rpc->udp_dest) {
622 free(rpc->udp_dest);
623 rpc->udp_dest = NULL;
624 }
625 rpc->udp_dest = malloc(ai->ai_addrlen);
626 if (rpc->udp_dest == NULL) {
627 rpc_set_error(rpc, "Out of memory. Failed to allocate sockaddr structure");
628 freeaddrinfo(ai);
629 return -1;
630 }
631 memcpy(rpc->udp_dest, ai->ai_addr, ai->ai_addrlen);
632 freeaddrinfo(ai);
633
634 rpc->is_broadcast = is_broadcast;
635 setsockopt(rpc->fd, SOL_SOCKET, SO_BROADCAST, (char *)&is_broadcast, sizeof(is_broadcast));
636
637 return 0;
638 }
639
640 struct sockaddr *rpc_get_recv_sockaddr(struct rpc_context *rpc)
641 {
642 assert(rpc->magic == RPC_CONTEXT_MAGIC);
643
644 return (struct sockaddr *)&rpc->udp_src;
645 }
646
647 int rpc_queue_length(struct rpc_context *rpc)
648 {
649 int i=0;
650 struct rpc_pdu *pdu;
651
652 assert(rpc->magic == RPC_CONTEXT_MAGIC);
653
654 for(pdu = rpc->outqueue; pdu; pdu = pdu->next) {
655 i++;
656 }
657 for(pdu = rpc->waitpdu; pdu; pdu = pdu->next) {
658 i++;
659 }
660 return i;
661 }