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