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));
141 callback(SILC_NET_NO_MEMORY, NULL, context);
144 listener->schedule = schedule;
145 listener->callback = callback;
146 listener->context = context;
147 listener->require_fqdn = require_fqdn;
148 listener->lookup = lookup;
150 if (local_ip_count > 0) {
151 listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
152 if (!listener->socks) {
153 callback(SILC_NET_NO_MEMORY, NULL, context);
157 listener->socks = silc_calloc(1, sizeof(*listener->socks));
158 if (!listener->socks) {
159 callback(SILC_NET_NO_MEMORY, NULL, context);
166 /* Bind to local addresses */
167 for (i = 0; i < local_ip_count; i++) {
168 SILC_LOG_DEBUG(("Binding to local address %s",
169 local_ip_addr ? local_ip_addr[i] : ipany));
171 /* Set sockaddr for server */
172 if (!silc_net_set_sockaddr(&server,
173 local_ip_addr ? local_ip_addr[i] : ipany,
177 /* Create the socket */
178 sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
180 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
184 /* Set the socket options */
185 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
187 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
191 /* Bind the listener socket */
192 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
194 SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
198 /* Specify that we are listenning */
199 rval = listen(sock, 64);
201 SILC_LOG_ERROR(("Cannot set socket listenning: %s", strerror(errno)));
205 /* Set the server socket to non-blocking mode */
206 silc_net_set_socket_nonblock(sock);
208 /* Schedule for incoming connections */
209 silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
211 SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
212 listener->socks[i] = sock;
213 listener->socks_count++;
220 callback(SILC_NET_ERROR, NULL, context);
222 silc_net_close_listener(listener);
226 /* Close network listener */
228 void silc_net_close_listener(SilcNetListener listener)
232 SILC_LOG_DEBUG(("Closing network listener"));
234 for (i = 0; i < listener->socks_count; i++) {
235 silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
236 shutdown(listener->socks[i], 2);
237 close(listener->socks[i]);
240 silc_free(listener->socks);
244 /* Create UDP stream */
247 silc_net_udp_connect(const char *local_ip_addr, int local_port,
248 const char *remote_ip_addr, int remote_port,
249 SilcSchedule schedule)
254 const char *ipany = "0.0.0.0";
256 SILC_LOG_DEBUG(("Creating UDP stream"));
261 /* Bind to local addresses */
262 SILC_LOG_DEBUG(("Binding to local address %s",
263 local_ip_addr ? local_ip_addr : ipany));
265 /* Set sockaddr for server */
266 if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
270 /* Create the socket */
271 sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
273 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
277 /* Set the socket options */
278 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
280 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
284 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
286 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
289 #endif /* SO_REUSEPORT */
291 /* Bind the listener socket */
292 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
294 SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
298 /* Set socket to non-blocking mode */
299 silc_net_set_socket_nonblock(sock);
301 /* Set to connected state if remote address is provided. */
302 if (remote_ip_addr && remote_port) {
303 if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
306 rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
308 SILC_LOG_DEBUG(("Cannot connect UDP stream: %s", strerror(errno)));
313 /* Set send and receive buffer size */
315 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 65535);
317 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
320 #endif /* SO_SNDBUF */
322 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 65535);
324 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
327 #endif /* SO_RCVBUF */
329 /* Encapsulate into socket stream */
331 silc_socket_udp_stream_create(sock, local_ip_addr ?
332 silc_net_is_ip6(local_ip_addr) : FALSE,
333 remote_ip_addr ? TRUE : FALSE, schedule);
337 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
346 /* Receive UDP packet */
348 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
349 SilcUInt32 remote_ip_addr_size, int *remote_port,
350 unsigned char *ret_data, SilcUInt32 data_size)
352 SilcSocketStream sock = stream;
354 struct sockaddr *from;
357 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
359 if (remote_ip_addr && remote_port) {
361 from = (struct sockaddr *)&s.sin6;
362 flen = sizeof(s.sin6);
364 from = (struct sockaddr *)&s.sin;
365 flen = sizeof(s.sin);
367 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
369 len = recv(sock->sock, ret_data, data_size, 0);
372 if (errno == EAGAIN || errno == EINTR) {
373 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
374 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
375 SILC_TASK_READ, FALSE);
378 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d:%s",
379 sock->sock, strerror(errno)));
380 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
381 sock->sock_error = errno;
385 SILC_LOG_DEBUG(("Read %d bytes", len));
388 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
390 /* Return remote address */
391 if (remote_ip_addr && remote_port) {
393 *remote_port = ntohs(s.sin6.sin6_port);
394 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
395 remote_ip_addr_size);
397 *remote_port = ntohs(s.sin.sin_port);
398 inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
399 remote_ip_addr_size);
402 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
408 /* Send UDP packet */
410 int silc_net_udp_send(SilcStream stream,
411 const char *remote_ip_addr, int remote_port,
412 const unsigned char *data, SilcUInt32 data_len)
414 SilcSocketStream sock = stream;
418 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
421 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
425 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
426 SIZEOF_SOCKADDR(remote));
428 if (errno == EAGAIN || errno == EINTR) {
429 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
430 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
431 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
434 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
435 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
436 sock->sock_error = errno;
440 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
441 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
443 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
444 SILC_TASK_READ, FALSE);
449 /* Asynchronous TCP/IP connecting */
452 SilcNetStatus status;
453 SilcSocketStreamStatus stream_status;
456 SilcFSMEventStruct event;
457 SilcAsyncOperation op;
458 SilcAsyncOperation sop;
463 SilcNetCallback callback;
465 unsigned int port : 24;
466 unsigned int retry : 7;
467 unsigned int aborted : 1;
470 SILC_FSM_STATE(silc_net_connect_st_start);
471 SILC_FSM_STATE(silc_net_connect_st_connected);
472 SILC_FSM_STATE(silc_net_connect_st_stream);
473 SILC_FSM_STATE(silc_net_connect_st_finish);
475 SILC_TASK_CALLBACK(silc_net_connect_wait)
477 SilcNetConnect conn = context;
478 SILC_FSM_EVENT_SIGNAL(&conn->event);
481 SILC_FSM_STATE(silc_net_connect_st_start)
483 SilcNetConnect conn = fsm_context;
485 SilcSockaddr desthost;
486 SilcBool prefer_ipv6 = TRUE;
490 silc_fsm_next(fsm, silc_net_connect_st_finish);
491 return SILC_FSM_CONTINUE;
496 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
497 conn->ip_addr, sizeof(conn->ip_addr))) {
498 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
499 "host", conn->remote));
501 /** Network unreachable */
502 conn->status = SILC_NET_HOST_UNREACHABLE;
503 silc_fsm_next(fsm, silc_net_connect_st_finish);
504 return SILC_FSM_CONTINUE;
507 /* Set sockaddr for this connection */
508 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port)) {
509 /** Sockaddr failed */
510 silc_fsm_next(fsm, silc_net_connect_st_finish);
511 return SILC_FSM_CONTINUE;
514 /* Create the connection socket */
515 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
517 /* If address is IPv6, then fallback to IPv4 and see whether we can do
518 better with that on socket creation. */
519 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
524 /** Cannot create socket */
525 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
526 silc_fsm_next(fsm, silc_net_connect_st_finish);
527 return SILC_FSM_CONTINUE;
530 /* Bind to the local address if provided */
531 if (conn->local_ip) {
534 /* Set sockaddr for local listener, and try to bind it. */
535 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
536 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
539 /* Set the socket to non-blocking mode */
540 silc_net_set_socket_nonblock(sock);
542 /* Connect to the host */
543 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
545 if (errno != EINPROGRESS) {
546 /* retry using an IPv4 adress, if IPv6 didn't work */
547 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
558 /** Cannot connect to remote host */
559 SILC_LOG_ERROR(("Cannot connect to remote host: %s", strerror(errno)));
560 silc_fsm_next(fsm, silc_net_connect_st_finish);
561 return SILC_FSM_CONTINUE;
565 /* Set appropriate options */
566 #if defined(TCP_NODELAY)
567 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
569 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
571 SILC_LOG_DEBUG(("Connection operation in progress"));
575 /** Wait for connection */
576 silc_fsm_next(fsm, silc_net_connect_st_connected);
577 silc_fsm_event_init(&conn->event, fsm);
578 silc_schedule_task_add_fd(silc_fsm_get_schedule(fsm), sock,
579 silc_net_connect_wait, conn);
580 silc_schedule_set_listen_fd(silc_fsm_get_schedule(fsm), sock,
581 SILC_TASK_WRITE, FALSE);
582 SILC_FSM_EVENT_WAIT(&conn->event);
583 return SILC_FSM_CONTINUE;
586 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
587 SilcStream stream, void *context)
589 SilcNetConnect conn = context;
590 conn->stream_status = status;
591 conn->stream = stream;
592 SILC_FSM_CALL_CONTINUE(&conn->fsm);
595 SILC_FSM_STATE(silc_net_connect_st_connected)
597 SilcNetConnect conn = fsm_context;
598 SilcSchedule schedule = silc_fsm_get_schedule(fsm);
599 int opt = EINVAL, optlen = sizeof(opt), ret;
603 silc_schedule_unset_listen_fd(schedule, conn->sock);
604 silc_schedule_task_del_by_fd(schedule, conn->sock);
605 silc_fsm_next(fsm, silc_net_connect_st_finish);
606 return SILC_FSM_CONTINUE;
609 ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
612 silc_schedule_unset_listen_fd(schedule, conn->sock);
613 silc_schedule_task_del_by_fd(schedule, conn->sock);
615 if (ret != 0 || opt != 0) {
617 /** Retry connecting */
618 SILC_LOG_DEBUG(("Retry connecting"));
620 silc_net_close_connection(conn->sock);
621 silc_fsm_next(fsm, silc_net_connect_st_start);
622 return SILC_FSM_CONTINUE;
625 #if defined(ECONNREFUSED)
626 if (errno == ECONNREFUSED)
627 conn->status = SILC_NET_CONNECTION_REFUSED;
628 #endif /* ECONNREFUSED */
629 #if defined(ETIMEDOUT)
630 if (errno == ETIMEDOUT)
631 conn->status = SILC_NET_CONNECTION_TIMEOUT;
632 #endif /* ETIMEDOUT */
633 #if defined(ENETUNREACH)
634 if (errno == ENETUNREACH)
635 conn->status = SILC_NET_HOST_UNREACHABLE;
636 #endif /* ENETUNREACH */
638 /** Connecting failed */
639 SILC_LOG_DEBUG(("Connecting failed"));
640 silc_fsm_next(fsm, silc_net_connect_st_finish);
641 return SILC_FSM_CONTINUE;
644 SILC_LOG_DEBUG(("TCP connection established"));
646 /** Connection created */
647 silc_fsm_next(fsm, silc_net_connect_st_stream);
648 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
649 conn->sock, FALSE, FALSE,
651 silc_net_connect_wait_stream, conn)));
654 SILC_FSM_STATE(silc_net_connect_st_stream)
656 SilcNetConnect conn = fsm_context;
660 silc_fsm_next(fsm, silc_net_connect_st_finish);
661 return SILC_FSM_CONTINUE;
664 if (conn->stream_status != SILC_SOCKET_OK) {
665 /** Stream creation failed */
666 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
667 conn->status = SILC_NET_UNKNOWN_IP;
668 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
669 conn->status = SILC_NET_UNKNOWN_HOST;
671 conn->status = SILC_NET_ERROR;
672 silc_fsm_next(fsm, silc_net_connect_st_finish);
673 return SILC_FSM_CONTINUE;
676 /* Set stream information */
677 silc_socket_stream_set_info(conn->stream,
678 !silc_net_is_ip(conn->remote) ? conn->remote :
679 conn->ip_addr, conn->ip_addr, conn->port);
681 /** Stream created successfully */
682 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
683 conn->status = SILC_NET_OK;
684 silc_fsm_next(fsm, silc_net_connect_st_finish);
685 return SILC_FSM_CONTINUE;
688 SILC_FSM_STATE(silc_net_connect_st_finish)
690 SilcNetConnect conn = fsm_context;
692 /* Deliver error or new stream */
693 if (!conn->aborted) {
694 conn->callback(conn->status, conn->stream, conn->context);
696 silc_async_free(conn->op);
698 silc_async_free(conn->sop);
701 return SILC_FSM_FINISH;
704 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
706 SilcNetConnect conn = context;
707 conn->aborted = TRUE;
709 /* Abort underlaying stream creation too */
711 silc_async_abort(conn->op, NULL, NULL);
714 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
715 void *destructor_context)
717 SilcNetConnect conn = fsm_context;
718 silc_free(conn->local_ip);
719 silc_free(conn->remote);
723 /* Create asynchronous TCP/IP connection. */
725 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
726 const char *remote_ip_addr,
728 SilcSchedule schedule,
729 SilcNetCallback callback,
734 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
737 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
738 remote_ip_addr, remote_port));
740 conn = silc_calloc(1, sizeof(*conn));
742 callback(SILC_NET_NO_MEMORY, NULL, context);
746 /* Start async operation */
747 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
750 callback(SILC_NET_NO_MEMORY, NULL, context);
755 conn->local_ip = strdup(local_ip_addr);
756 conn->remote = strdup(remote_ip_addr);
758 silc_async_free(conn->op);
759 silc_free(conn->local_ip);
761 callback(SILC_NET_NO_MEMORY, NULL, context);
764 conn->port = remote_port;
765 conn->callback = callback;
766 conn->context = context;
768 conn->status = SILC_NET_ERROR;
770 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
771 silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
776 /* Closes the connection by closing the socket connection. */
778 void silc_net_close_connection(int sock)
780 SILC_LOG_DEBUG(("Closing sock %d", sock));
784 /* Set's the socket to non-blocking mode. */
786 int silc_net_set_socket_nonblock(SilcSocket sock)
788 return fcntl((int)sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
791 /* Converts the IP number string from numbers-and-dots notation to
794 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
798 if (silc_net_is_ip4(addr)) {
801 ret = inet_aton(addr, &tmp);
805 memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
808 struct addrinfo hints, *ai;
815 memset(&hints, 0, sizeof(hints));
816 hints.ai_family = AF_INET6;
817 if (getaddrinfo(addr, NULL, &hints, &ai))
821 s = (SilcSockaddr *)ai->ai_addr;
822 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
827 #endif /* HAVE_IPV6 */