5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2007 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
25 #define SIZEOF_SOCKADDR(so) ((so).sa.sa_family == AF_INET6 ? \
26 sizeof(so.sin6) : sizeof(so.sin))
28 #define SIZEOF_SOCKADDR(so) (sizeof(so.sin))
33 struct sockaddr_in sin;
35 struct sockaddr_in6 sin6;
39 static SilcBool silc_net_set_sockaddr(SilcSockaddr *addr, const char *ip_addr,
44 memset(addr, 0, sizeof(*addr));
46 /* Check for IPv4 and IPv6 addresses */
48 if (!silc_net_is_ip(ip_addr)) {
49 SILC_LOG_ERROR(("%s is not IP address", ip_addr));
53 if (silc_net_is_ip4(ip_addr)) {
55 len = sizeof(addr->sin.sin_addr);
56 silc_net_addr2bin(ip_addr,
57 (unsigned char *)&addr->sin.sin_addr.s_addr, len);
58 addr->sin.sin_family = AF_INET;
59 addr->sin.sin_port = port ? htons(port) : 0;
63 len = sizeof(addr->sin6.sin6_addr);
64 silc_net_addr2bin(ip_addr,
65 (unsigned char *)&addr->sin6.sin6_addr, len);
66 addr->sin6.sin6_family = AF_INET6;
67 addr->sin6.sin6_port = port ? htons(port) : 0;
69 SILC_LOG_ERROR(("IPv6 support is not compiled in"));
75 addr->sin.sin_family = AF_INET;
76 addr->sin.sin_addr.s_addr = INADDR_ANY;
78 addr->sin.sin_port = htons(port);
84 /* Deliver new stream to upper layer */
86 static void silc_net_accept_stream(SilcSocketStreamStatus status,
87 SilcStream stream, void *context)
89 SilcNetListener listener = context;
91 if (status != SILC_SOCKET_OK)
94 listener->callback(SILC_NET_OK, stream, listener->context);
97 /* Accept incoming connection and notify upper layer */
99 SILC_TASK_CALLBACK(silc_net_accept)
101 SilcNetListener listener = context;
104 SILC_LOG_DEBUG(("Accepting new connection"));
106 sock = silc_net_accept_connection(fd);
110 /* Set socket options */
111 silc_net_set_socket_nonblock(sock);
112 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
114 /* Create socket stream */
115 silc_socket_tcp_stream_create(sock, listener->lookup,
116 listener->require_fqdn, schedule,
117 silc_net_accept_stream, listener);
120 /* Create TCP network listener */
123 silc_net_tcp_create_listener(const char **local_ip_addr,
124 SilcUInt32 local_ip_count, int port,
125 SilcBool lookup, SilcBool require_fqdn,
126 SilcSchedule schedule,
127 SilcNetCallback callback, void *context)
129 SilcNetListener listener = NULL;
132 const char *ipany = "0.0.0.0";
134 SILC_LOG_DEBUG(("Creating TCP listener"));
136 if (port < 0 || !schedule || !callback)
139 listener = silc_calloc(1, sizeof(*listener));
142 listener->schedule = schedule;
143 listener->callback = callback;
144 listener->context = context;
145 listener->require_fqdn = require_fqdn;
146 listener->lookup = lookup;
148 if (local_ip_count > 0) {
149 listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
150 if (!listener->socks)
153 listener->socks = silc_calloc(1, sizeof(*listener->socks));
154 if (!listener->socks)
160 /* Bind to local addresses */
161 for (i = 0; i < local_ip_count; i++) {
162 SILC_LOG_DEBUG(("Binding to local address %s",
163 local_ip_addr ? local_ip_addr[i] : ipany));
165 /* Set sockaddr for server */
166 if (!silc_net_set_sockaddr(&server,
167 local_ip_addr ? local_ip_addr[i] : ipany,
171 /* Create the socket */
172 sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
174 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
178 /* Set the socket options */
179 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
181 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
185 /* Bind the listener socket */
186 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
188 SILC_LOG_ERROR(("Cannot bind socket: %s", strerror(errno)));
192 /* Specify that we are listenning */
193 rval = listen(sock, 64);
195 SILC_LOG_ERROR(("Cannot set socket listenning: %s", strerror(errno)));
199 /* Set the server socket to non-blocking mode */
200 silc_net_set_socket_nonblock(sock);
202 /* Schedule for incoming connections */
203 silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
205 SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
206 listener->socks[i] = sock;
207 listener->socks_count++;
214 silc_net_close_listener(listener);
218 /* Close network listener */
220 void silc_net_close_listener(SilcNetListener listener)
224 SILC_LOG_DEBUG(("Closing network listener"));
226 for (i = 0; i < listener->socks_count; i++) {
227 silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
228 shutdown(listener->socks[i], 2);
229 close(listener->socks[i]);
232 silc_free(listener->socks);
236 /* Create UDP stream */
239 silc_net_udp_connect(const char *local_ip_addr, int local_port,
240 const char *remote_ip_addr, int remote_port,
241 SilcSchedule schedule)
246 const char *ipany = "0.0.0.0";
248 SILC_LOG_DEBUG(("Creating UDP stream"));
253 /* Bind to local addresses */
254 SILC_LOG_DEBUG(("Binding to local address %s",
255 local_ip_addr ? local_ip_addr : ipany));
257 /* Set sockaddr for server */
258 if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
262 /* Create the socket */
263 sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
265 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
269 /* Set the socket options */
270 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
272 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
276 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
278 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
281 #endif /* SO_REUSEPORT */
283 /* Bind the listener socket */
284 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
286 SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
290 /* Set socket to non-blocking mode */
291 silc_net_set_socket_nonblock(sock);
293 /* Set to connected state if remote address is provided. */
294 if (remote_ip_addr && remote_port) {
295 if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
298 rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
300 SILC_LOG_DEBUG(("Cannot connect UDP stream: %s", strerror(errno)));
305 /* Set send and receive buffer size */
307 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 65535);
309 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
312 #endif /* SO_SNDBUF */
314 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 65535);
316 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
319 #endif /* SO_RCVBUF */
321 /* Encapsulate into socket stream */
323 silc_socket_udp_stream_create(sock, local_ip_addr ?
324 silc_net_is_ip6(local_ip_addr) : FALSE,
325 remote_ip_addr ? TRUE : FALSE, schedule);
329 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
338 /* Receive UDP packet */
340 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
341 SilcUInt32 remote_ip_addr_size, int *remote_port,
342 unsigned char *ret_data, SilcUInt32 data_size)
344 SilcSocketStream sock = stream;
346 struct sockaddr *from;
349 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
351 if (remote_ip_addr && remote_port) {
353 from = (struct sockaddr *)&s.sin6;
354 flen = sizeof(s.sin6);
356 from = (struct sockaddr *)&s.sin;
357 flen = sizeof(s.sin);
359 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
361 len = recv(sock->sock, ret_data, data_size, 0);
364 if (errno == EAGAIN || errno == EINTR) {
365 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
366 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
367 SILC_TASK_READ, FALSE);
370 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d:%s",
371 sock->sock, strerror(errno)));
372 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
373 sock->sock_error = errno;
377 SILC_LOG_DEBUG(("Read %d bytes", len));
380 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
382 /* Return remote address */
383 if (remote_ip_addr && remote_port) {
385 *remote_port = ntohs(s.sin6.sin6_port);
386 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
387 remote_ip_addr_size);
389 *remote_port = ntohs(s.sin.sin_port);
390 inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
391 remote_ip_addr_size);
394 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
400 /* Send UDP packet */
402 int silc_net_udp_send(SilcStream stream,
403 const char *remote_ip_addr, int remote_port,
404 const unsigned char *data, SilcUInt32 data_len)
406 SilcSocketStream sock = stream;
410 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
413 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
417 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
418 SIZEOF_SOCKADDR(remote));
420 if (errno == EAGAIN || errno == EINTR) {
421 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
422 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
423 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
426 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
427 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
428 sock->sock_error = errno;
432 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
433 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
435 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
436 SILC_TASK_READ, FALSE);
441 /* Asynchronous TCP/IP connecting */
444 SilcNetStatus status;
445 SilcSocketStreamStatus stream_status;
448 SilcFSMEventStruct event;
449 SilcAsyncOperation op;
450 SilcAsyncOperation sop;
455 SilcNetCallback callback;
457 unsigned int port : 24;
458 unsigned int retry : 7;
459 unsigned int aborted : 1;
462 SILC_FSM_STATE(silc_net_connect_st_start);
463 SILC_FSM_STATE(silc_net_connect_st_connected);
464 SILC_FSM_STATE(silc_net_connect_st_stream);
465 SILC_FSM_STATE(silc_net_connect_st_finish);
467 SILC_TASK_CALLBACK(silc_net_connect_wait)
469 SilcNetConnect conn = context;
470 SILC_FSM_EVENT_SIGNAL(&conn->event);
473 SILC_FSM_STATE(silc_net_connect_st_start)
475 SilcNetConnect conn = fsm_context;
477 SilcSockaddr desthost;
478 SilcBool prefer_ipv6 = TRUE;
482 silc_fsm_next(fsm, silc_net_connect_st_finish);
483 return SILC_FSM_CONTINUE;
488 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
489 conn->ip_addr, sizeof(conn->ip_addr))) {
490 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
491 "host", conn->remote));
493 /** Network unreachable */
494 conn->status = SILC_NET_HOST_UNREACHABLE;
495 silc_fsm_next(fsm, silc_net_connect_st_finish);
496 return SILC_FSM_CONTINUE;
499 /* Set sockaddr for this connection */
500 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port)) {
501 /** Sockaddr failed */
502 silc_fsm_next(fsm, silc_net_connect_st_finish);
503 return SILC_FSM_CONTINUE;
506 /* Create the connection socket */
507 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
509 /* If address is IPv6, then fallback to IPv4 and see whether we can do
510 better with that on socket creation. */
511 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
516 /** Cannot create socket */
517 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
518 silc_fsm_next(fsm, silc_net_connect_st_finish);
519 return SILC_FSM_CONTINUE;
522 /* Bind to the local address if provided */
523 if (conn->local_ip) {
526 /* Set sockaddr for local listener, and try to bind it. */
527 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
528 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
531 /* Set the socket to non-blocking mode */
532 silc_net_set_socket_nonblock(sock);
534 /* Connect to the host */
535 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
537 if (errno != EINPROGRESS) {
538 /* retry using an IPv4 adress, if IPv6 didn't work */
539 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
550 /** Cannot connect to remote host */
551 SILC_LOG_ERROR(("Cannot connect to remote host: %s", strerror(errno)));
552 silc_fsm_next(fsm, silc_net_connect_st_finish);
553 return SILC_FSM_CONTINUE;
557 /* Set appropriate options */
558 #if defined(TCP_NODELAY)
559 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
561 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
563 SILC_LOG_DEBUG(("Connection operation in progress"));
567 /** Wait for connection */
568 silc_fsm_next(fsm, silc_net_connect_st_connected);
569 silc_fsm_event_init(&conn->event, fsm);
570 silc_schedule_task_add_fd(silc_fsm_get_schedule(fsm), sock,
571 silc_net_connect_wait, conn);
572 silc_schedule_set_listen_fd(silc_fsm_get_schedule(fsm), sock,
573 SILC_TASK_WRITE, FALSE);
574 SILC_FSM_EVENT_WAIT(&conn->event);
575 return SILC_FSM_CONTINUE;
578 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
579 SilcStream stream, void *context)
581 SilcNetConnect conn = context;
582 conn->stream_status = status;
583 conn->stream = stream;
584 SILC_FSM_CALL_CONTINUE(&conn->fsm);
587 SILC_FSM_STATE(silc_net_connect_st_connected)
589 SilcNetConnect conn = fsm_context;
590 SilcSchedule schedule = silc_fsm_get_schedule(fsm);
591 int opt = EINVAL, optlen = sizeof(opt), ret;
595 silc_schedule_unset_listen_fd(schedule, conn->sock);
596 silc_schedule_task_del_by_fd(schedule, conn->sock);
597 silc_fsm_next(fsm, silc_net_connect_st_finish);
598 return SILC_FSM_CONTINUE;
601 ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
604 silc_schedule_unset_listen_fd(schedule, conn->sock);
605 silc_schedule_task_del_by_fd(schedule, conn->sock);
607 if (ret != 0 || opt != 0) {
609 /** Retry connecting */
610 SILC_LOG_DEBUG(("Retry connecting"));
612 silc_net_close_connection(conn->sock);
613 silc_fsm_next(fsm, silc_net_connect_st_start);
614 return SILC_FSM_CONTINUE;
617 #if defined(ECONNREFUSED)
618 if (errno == ECONNREFUSED)
619 conn->status = SILC_NET_CONNECTION_REFUSED;
620 #endif /* ECONNREFUSED */
621 #if defined(ETIMEDOUT)
622 if (errno == ETIMEDOUT)
623 conn->status = SILC_NET_CONNECTION_TIMEOUT;
624 #endif /* ETIMEDOUT */
625 #if defined(ENETUNREACH)
626 if (errno == ENETUNREACH)
627 conn->status = SILC_NET_HOST_UNREACHABLE;
628 #endif /* ENETUNREACH */
630 /** Connecting failed */
631 SILC_LOG_DEBUG(("Connecting failed"));
632 silc_fsm_next(fsm, silc_net_connect_st_finish);
633 return SILC_FSM_CONTINUE;
636 SILC_LOG_DEBUG(("TCP connection established"));
638 /** Connection created */
639 silc_fsm_next(fsm, silc_net_connect_st_stream);
640 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
641 conn->sock, FALSE, FALSE,
643 silc_net_connect_wait_stream, conn)));
646 SILC_FSM_STATE(silc_net_connect_st_stream)
648 SilcNetConnect conn = fsm_context;
652 silc_fsm_next(fsm, silc_net_connect_st_finish);
653 return SILC_FSM_CONTINUE;
656 if (conn->stream_status != SILC_SOCKET_OK) {
657 /** Stream creation failed */
658 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
659 conn->status = SILC_NET_UNKNOWN_IP;
660 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
661 conn->status = SILC_NET_UNKNOWN_HOST;
663 conn->status = SILC_NET_ERROR;
664 silc_fsm_next(fsm, silc_net_connect_st_finish);
665 return SILC_FSM_CONTINUE;
668 /* Set stream information */
669 silc_socket_stream_set_info(conn->stream,
670 !silc_net_is_ip(conn->remote) ? conn->remote :
671 conn->ip_addr, conn->ip_addr, conn->port);
673 /** Stream created successfully */
674 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
675 conn->status = SILC_NET_OK;
676 silc_fsm_next(fsm, silc_net_connect_st_finish);
677 return SILC_FSM_CONTINUE;
680 SILC_FSM_STATE(silc_net_connect_st_finish)
682 SilcNetConnect conn = fsm_context;
684 /* Deliver error or new stream */
685 if (!conn->aborted) {
686 conn->callback(conn->status, conn->stream, conn->context);
688 silc_async_free(conn->op);
690 silc_async_free(conn->sop);
693 return SILC_FSM_FINISH;
696 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
698 SilcNetConnect conn = context;
699 conn->aborted = TRUE;
701 /* Abort underlaying stream creation too */
703 silc_async_abort(conn->op, NULL, NULL);
706 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
707 void *destructor_context)
709 SilcNetConnect conn = fsm_context;
710 silc_free(conn->local_ip);
711 silc_free(conn->remote);
715 /* Create asynchronous TCP/IP connection. */
717 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
718 const char *remote_ip_addr,
720 SilcSchedule schedule,
721 SilcNetCallback callback,
726 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
729 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
730 remote_ip_addr, remote_port));
732 conn = silc_calloc(1, sizeof(*conn));
734 callback(SILC_NET_NO_MEMORY, NULL, context);
738 /* Start async operation */
739 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
742 callback(SILC_NET_NO_MEMORY, NULL, context);
747 conn->local_ip = strdup(local_ip_addr);
748 conn->remote = strdup(remote_ip_addr);
750 silc_async_free(conn->op);
751 silc_free(conn->local_ip);
753 callback(SILC_NET_NO_MEMORY, NULL, context);
756 conn->port = remote_port;
757 conn->callback = callback;
758 conn->context = context;
760 conn->status = SILC_NET_ERROR;
762 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
763 silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
768 /* Closes the connection by closing the socket connection. */
770 void silc_net_close_connection(int sock)
772 SILC_LOG_DEBUG(("Closing sock %d", sock));
776 /* Set's the socket to non-blocking mode. */
778 int silc_net_set_socket_nonblock(SilcSocket sock)
780 return fcntl((int)sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
783 /* Converts the IP number string from numbers-and-dots notation to
786 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
790 if (silc_net_is_ip4(addr)) {
793 ret = inet_aton(addr, &tmp);
797 memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
800 struct addrinfo hints, *ai;
807 memset(&hints, 0, sizeof(hints));
808 hints.ai_family = AF_INET6;
809 if (getaddrinfo(addr, NULL, &hints, &ai))
813 s = (SilcSockaddr *)ai->ai_addr;
814 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
819 #endif /* HAVE_IPV6 */