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