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.
24 /************************** Types and definitions ***************************/
27 #define SIZEOF_SOCKADDR(so) ((so).sa.sa_family == AF_INET6 ? \
28 sizeof(so.sin6) : sizeof(so.sin))
30 #define SIZEOF_SOCKADDR(so) (sizeof(so.sin))
35 struct sockaddr_in sin;
37 struct sockaddr_in6 sin6;
41 /************************ Static utility functions **************************/
43 static SilcBool silc_net_set_sockaddr(SilcSockaddr *addr, const char *ip_addr,
48 memset(addr, 0, sizeof(*addr));
50 /* Check for IPv4 and IPv6 addresses */
52 if (!silc_net_is_ip(ip_addr)) {
53 SILC_LOG_ERROR(("%s is not IP address", ip_addr));
57 if (silc_net_is_ip4(ip_addr)) {
59 len = sizeof(addr->sin.sin_addr);
60 silc_net_addr2bin(ip_addr,
61 (unsigned char *)&addr->sin.sin_addr.s_addr, len);
62 addr->sin.sin_family = AF_INET;
63 addr->sin.sin_port = port ? htons(port) : 0;
67 len = sizeof(addr->sin6.sin6_addr);
68 silc_net_addr2bin(ip_addr,
69 (unsigned char *)&addr->sin6.sin6_addr, len);
70 addr->sin6.sin6_family = AF_INET6;
71 addr->sin6.sin6_port = port ? htons(port) : 0;
73 SILC_LOG_ERROR(("IPv6 support is not compiled in"));
79 addr->sin.sin_family = AF_INET;
80 addr->sin.sin_addr.s_addr = INADDR_ANY;
82 addr->sin.sin_port = htons(port);
88 /****************************** TCP Listener ********************************/
90 /* Deliver new stream to upper layer */
92 static void silc_net_accept_stream(SilcSocketStreamStatus status,
93 SilcStream stream, void *context)
95 SilcNetListener listener = context;
97 if (status != SILC_SOCKET_OK)
100 listener->callback(SILC_NET_OK, stream, listener->context);
103 /* Accept incoming connection and notify upper layer */
105 SILC_TASK_CALLBACK(silc_net_accept)
107 SilcNetListener listener = context;
110 SILC_LOG_DEBUG(("Accepting new connection"));
112 sock = silc_net_accept_connection(fd);
116 /* Set socket options */
117 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
118 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
120 /* Create socket stream */
121 silc_socket_tcp_stream_create(sock, listener->lookup,
122 listener->require_fqdn, schedule,
123 silc_net_accept_stream, listener);
126 /* Create TCP network listener */
129 silc_net_tcp_create_listener(const char **local_ip_addr,
130 SilcUInt32 local_ip_count, int port,
131 SilcBool lookup, SilcBool require_fqdn,
132 SilcSchedule schedule,
133 SilcNetCallback callback, void *context)
135 SilcNetListener listener = NULL;
138 const char *ipany = "0.0.0.0";
140 SILC_LOG_DEBUG(("Creating TCP listener"));
142 if (port < 0 || !schedule || !callback)
145 listener = silc_calloc(1, sizeof(*listener));
148 listener->schedule = schedule;
149 listener->callback = callback;
150 listener->context = context;
151 listener->require_fqdn = require_fqdn;
152 listener->lookup = lookup;
154 if (local_ip_count > 0) {
155 listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
156 if (!listener->socks)
159 listener->socks = silc_calloc(1, sizeof(*listener->socks));
160 if (!listener->socks)
166 /* Bind to local addresses */
167 for (i = 0; i < local_ip_count; i++) {
168 SILC_LOG_DEBUG(("Binding to local address %s:%d",
169 local_ip_addr ? local_ip_addr[i] : ipany, port));
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)));
192 /* Bind the listener socket */
193 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
195 SILC_LOG_ERROR(("Cannot bind socket: %s", strerror(errno)));
200 /* Specify that we are listenning */
201 rval = listen(sock, 64);
203 SILC_LOG_ERROR(("Cannot set socket listenning: %s", strerror(errno)));
208 /* Set the server socket to non-blocking mode */
209 silc_net_set_socket_nonblock(sock);
211 /* Schedule for incoming connections */
212 silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
214 SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
215 listener->socks[i] = sock;
216 listener->socks_count++;
223 silc_net_close_listener(listener);
227 /* Close network listener */
229 void silc_net_close_listener(SilcNetListener listener)
233 SILC_LOG_DEBUG(("Closing network listener"));
235 for (i = 0; i < listener->socks_count; i++) {
236 silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
237 shutdown(listener->socks[i], 2);
238 close(listener->socks[i]);
241 silc_free(listener->socks);
245 /******************************* UDP Stream *********************************/
247 /* Create UDP stream */
250 silc_net_udp_connect(const char *local_ip_addr, int local_port,
251 const char *remote_ip_addr, int remote_port,
252 SilcSchedule schedule)
257 const char *ipany = "0.0.0.0";
259 SILC_LOG_DEBUG(("Creating UDP stream"));
264 /* Bind to local addresses */
265 SILC_LOG_DEBUG(("Binding to local address %s",
266 local_ip_addr ? local_ip_addr : ipany));
268 /* Set sockaddr for server */
269 if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
273 /* Create the socket */
274 sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
276 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
280 /* Set the socket options */
281 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
283 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
287 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
289 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
292 #endif /* SO_REUSEPORT */
294 /* Bind the listener socket */
295 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
297 SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
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, 765535);
317 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 65535);
319 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
323 #endif /* SO_SNDBUF */
325 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 765535);
327 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 65535);
329 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
333 #endif /* SO_RCVBUF */
335 /* Encapsulate into socket stream */
337 silc_socket_udp_stream_create(sock, local_ip_addr ?
338 silc_net_is_ip6(local_ip_addr) : FALSE,
339 remote_ip_addr ? TRUE : FALSE, schedule);
343 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
352 /* Receive UDP packet */
354 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
355 SilcUInt32 remote_ip_addr_size, int *remote_port,
356 unsigned char *ret_data, SilcUInt32 data_size)
358 SilcSocketStream sock = stream;
360 struct sockaddr *from;
363 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
365 if (remote_ip_addr && remote_port) {
368 from = (struct sockaddr *)&s.sin6;
369 flen = sizeof(s.sin6);
370 #endif /* HAVE_IPV6 */
372 from = (struct sockaddr *)&s.sin;
373 flen = sizeof(s.sin);
375 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
377 len = recv(sock->sock, ret_data, data_size, 0);
380 if (errno == EAGAIN || errno == EINTR) {
381 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
382 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
383 SILC_TASK_READ, FALSE);
386 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d:%s",
387 sock->sock, strerror(errno)));
388 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
389 sock->sock_error = errno;
393 SILC_LOG_DEBUG(("Read %d bytes", len));
396 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
398 /* Return remote address */
399 if (remote_ip_addr && remote_port) {
402 *remote_port = ntohs(s.sin6.sin6_port);
403 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
404 remote_ip_addr_size);
407 #endif /* HAVE_IPV6 */
409 *remote_port = ntohs(s.sin.sin_port);
410 inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
411 remote_ip_addr_size);
414 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
420 /* Send UDP packet */
422 int silc_net_udp_send(SilcStream stream,
423 const char *remote_ip_addr, int remote_port,
424 const unsigned char *data, SilcUInt32 data_len)
426 SilcSocketStream sock = stream;
430 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
433 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
437 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
438 SIZEOF_SOCKADDR(remote));
440 if (errno == EAGAIN || errno == EINTR) {
441 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
442 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
443 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
446 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
447 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
448 sock->sock_error = errno;
452 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
453 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
455 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
456 SILC_TASK_READ, FALSE);
461 /******************************* TCP Stream *********************************/
463 /* Asynchronous TCP/IP connecting */
466 SilcNetStatus status;
467 SilcSocketStreamStatus stream_status;
470 SilcFSMEventStruct event;
471 SilcAsyncOperation op;
472 SilcAsyncOperation sop;
477 SilcNetCallback callback;
479 unsigned int port : 24;
480 unsigned int retry : 7;
481 unsigned int aborted : 1;
484 SILC_FSM_STATE(silc_net_connect_st_start);
485 SILC_FSM_STATE(silc_net_connect_st_connected);
486 SILC_FSM_STATE(silc_net_connect_st_stream);
487 SILC_FSM_STATE(silc_net_connect_st_finish);
489 SILC_TASK_CALLBACK(silc_net_connect_wait)
491 SilcNetConnect conn = context;
492 SILC_FSM_EVENT_SIGNAL(&conn->event);
495 SILC_FSM_STATE(silc_net_connect_st_start)
497 SilcNetConnect conn = fsm_context;
499 SilcSockaddr desthost;
500 SilcBool prefer_ipv6 = TRUE;
504 silc_fsm_next(fsm, silc_net_connect_st_finish);
505 return SILC_FSM_CONTINUE;
510 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
511 conn->ip_addr, sizeof(conn->ip_addr))) {
512 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
513 "host", conn->remote));
515 /** Network unreachable */
516 conn->status = SILC_NET_HOST_UNREACHABLE;
517 silc_fsm_next(fsm, silc_net_connect_st_finish);
518 return SILC_FSM_CONTINUE;
521 /* Set sockaddr for this connection */
522 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port)) {
523 /** Sockaddr failed */
524 silc_fsm_next(fsm, silc_net_connect_st_finish);
525 return SILC_FSM_CONTINUE;
528 /* Create the connection socket */
529 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
531 /* If address is IPv6, then fallback to IPv4 and see whether we can do
532 better with that on socket creation. */
533 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
538 /** Cannot create socket */
539 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
540 silc_fsm_next(fsm, silc_net_connect_st_finish);
541 return SILC_FSM_CONTINUE;
544 /* Bind to the local address if provided */
545 if (conn->local_ip) {
548 /* Set sockaddr for local listener, and try to bind it. */
549 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
550 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
553 /* Set the socket to non-blocking mode */
554 silc_net_set_socket_nonblock(sock);
556 /* Connect to the host */
557 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
559 if (errno != EINPROGRESS) {
563 /* Retry using an IPv4 adress, if IPv6 didn't work */
564 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
569 /** Cannot connect to remote host */
570 SILC_LOG_ERROR(("Cannot connect to remote host: %s", strerror(errno)));
571 silc_fsm_next(fsm, silc_net_connect_st_finish);
572 return SILC_FSM_CONTINUE;
576 /* Set appropriate options */
577 #if defined(TCP_NODELAY)
578 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
580 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
582 SILC_LOG_DEBUG(("Connection operation in progress"));
586 /** Wait for connection */
587 silc_fsm_next(fsm, silc_net_connect_st_connected);
588 silc_fsm_event_init(&conn->event, fsm);
589 silc_schedule_task_add_fd(silc_fsm_get_schedule(fsm), sock,
590 silc_net_connect_wait, conn);
591 silc_schedule_set_listen_fd(silc_fsm_get_schedule(fsm), sock,
592 SILC_TASK_WRITE, FALSE);
593 SILC_FSM_EVENT_WAIT(&conn->event);
594 return SILC_FSM_CONTINUE;
597 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
598 SilcStream stream, void *context)
600 SilcNetConnect conn = context;
602 conn->stream_status = status;
603 conn->stream = stream;
604 SILC_FSM_CALL_CONTINUE(&conn->fsm);
607 SILC_FSM_STATE(silc_net_connect_st_connected)
609 SilcNetConnect conn = fsm_context;
610 SilcSchedule schedule = silc_fsm_get_schedule(fsm);
611 int opt = EINVAL, optlen = sizeof(opt), ret;
615 silc_schedule_unset_listen_fd(schedule, conn->sock);
616 silc_schedule_task_del_by_fd(schedule, conn->sock);
617 silc_fsm_next(fsm, silc_net_connect_st_finish);
618 return SILC_FSM_CONTINUE;
621 ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
624 silc_schedule_unset_listen_fd(schedule, conn->sock);
625 silc_schedule_task_del_by_fd(schedule, conn->sock);
627 if (ret != 0 || opt != 0) {
629 /** Retry connecting */
630 SILC_LOG_DEBUG(("Retry connecting"));
632 silc_net_close_connection(conn->sock);
633 silc_fsm_next(fsm, silc_net_connect_st_start);
634 return SILC_FSM_CONTINUE;
637 #if defined(ECONNREFUSED)
638 if (opt == ECONNREFUSED)
639 conn->status = SILC_NET_CONNECTION_REFUSED;
640 #endif /* ECONNREFUSED */
641 #if defined(ETIMEDOUT)
642 if (opt == ETIMEDOUT)
643 conn->status = SILC_NET_CONNECTION_TIMEOUT;
644 #endif /* ETIMEDOUT */
645 #if defined(ENETUNREACH)
646 if (opt == ENETUNREACH)
647 conn->status = SILC_NET_HOST_UNREACHABLE;
648 #endif /* ENETUNREACH */
650 /** Connecting failed */
651 SILC_LOG_DEBUG(("Connecting failed, error %s", strerror(opt)));
652 silc_fsm_next(fsm, silc_net_connect_st_finish);
653 return SILC_FSM_CONTINUE;
656 SILC_LOG_DEBUG(("TCP connection established"));
658 /** Connection created */
659 silc_fsm_next(fsm, silc_net_connect_st_stream);
660 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
661 conn->sock, TRUE, FALSE, schedule,
662 silc_net_connect_wait_stream, conn)));
665 SILC_FSM_STATE(silc_net_connect_st_stream)
667 SilcNetConnect conn = fsm_context;
671 silc_fsm_next(fsm, silc_net_connect_st_finish);
672 return SILC_FSM_CONTINUE;
675 if (conn->stream_status != SILC_SOCKET_OK) {
676 /** Stream creation failed */
677 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
678 conn->status = SILC_NET_UNKNOWN_IP;
679 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
680 conn->status = SILC_NET_UNKNOWN_HOST;
682 conn->status = SILC_NET_ERROR;
683 silc_fsm_next(fsm, silc_net_connect_st_finish);
684 return SILC_FSM_CONTINUE;
687 /** Stream created successfully */
688 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
689 conn->status = SILC_NET_OK;
690 silc_fsm_next(fsm, silc_net_connect_st_finish);
691 return SILC_FSM_CONTINUE;
694 SILC_FSM_STATE(silc_net_connect_st_finish)
696 SilcNetConnect conn = fsm_context;
698 /* Deliver error or new stream */
699 if (!conn->aborted) {
700 conn->callback(conn->status, conn->stream, conn->context);
702 silc_async_free(conn->op);
705 if (conn->sock && conn->status != SILC_NET_OK)
706 silc_net_close_connection(conn->sock);
708 return SILC_FSM_FINISH;
711 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
713 SilcNetConnect conn = context;
714 conn->aborted = TRUE;
716 /* Abort underlaying stream creation too */
718 silc_async_abort(conn->sop, NULL, NULL);
723 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
724 void *destructor_context)
726 SilcNetConnect conn = fsm_context;
727 silc_free(conn->local_ip);
728 silc_free(conn->remote);
732 /* Create asynchronous TCP/IP connection. */
734 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
735 const char *remote_ip_addr,
737 SilcSchedule schedule,
738 SilcNetCallback callback,
743 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
746 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
747 remote_ip_addr, remote_port));
749 conn = silc_calloc(1, sizeof(*conn));
751 callback(SILC_NET_NO_MEMORY, NULL, context);
755 /* Start async operation */
756 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
759 callback(SILC_NET_NO_MEMORY, NULL, context);
764 conn->local_ip = strdup(local_ip_addr);
765 conn->remote = strdup(remote_ip_addr);
767 silc_async_free(conn->op);
768 silc_free(conn->local_ip);
770 callback(SILC_NET_NO_MEMORY, NULL, context);
773 conn->port = remote_port;
774 conn->callback = callback;
775 conn->context = context;
777 conn->status = SILC_NET_ERROR;
779 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
780 silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
785 /* Closes the connection by closing the socket connection. */
787 void silc_net_close_connection(int sock)
789 SILC_LOG_DEBUG(("Closing sock %d", sock));
793 /* Set's the socket to non-blocking mode. */
795 int silc_net_set_socket_nonblock(SilcSocket sock)
797 return fcntl((int)sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
800 /* Converts the IP number string from numbers-and-dots notation to
803 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
807 if (silc_net_is_ip4(addr)) {
810 ret = inet_aton(addr, &tmp);
814 memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
817 struct addrinfo hints, *ai;
824 memset(&hints, 0, sizeof(hints));
825 hints.ai_family = AF_INET6;
826 if (getaddrinfo(addr, NULL, &hints, &ai))
830 s = (SilcSockaddr *)ai->ai_addr;
831 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
836 #endif /* HAVE_IPV6 */