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);
119 /* Create socket stream */
120 silc_socket_tcp_stream_create(sock, listener->lookup,
121 listener->require_fqdn, schedule,
122 silc_net_accept_stream, listener);
125 /* Create TCP network listener */
128 silc_net_tcp_create_listener(const char **local_ip_addr,
129 SilcUInt32 local_ip_count, int port,
130 SilcBool lookup, SilcBool require_fqdn,
131 SilcSchedule schedule,
132 SilcNetCallback callback, void *context)
134 SilcNetListener listener = NULL;
137 const char *ipany = "0.0.0.0";
139 SILC_LOG_DEBUG(("Creating TCP listener"));
141 if (port < 0 || !schedule || !callback)
144 listener = silc_calloc(1, sizeof(*listener));
147 listener->schedule = schedule;
148 listener->callback = callback;
149 listener->context = context;
150 listener->require_fqdn = require_fqdn;
151 listener->lookup = lookup;
153 if (local_ip_count > 0) {
154 listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
155 if (!listener->socks)
158 listener->socks = silc_calloc(1, sizeof(*listener->socks));
159 if (!listener->socks)
165 /* Bind to local addresses */
166 for (i = 0; i < local_ip_count; i++) {
167 SILC_LOG_DEBUG(("Binding to local address %s",
168 local_ip_addr ? local_ip_addr[i] : ipany));
170 /* Set sockaddr for server */
171 if (!silc_net_set_sockaddr(&server,
172 local_ip_addr ? local_ip_addr[i] : ipany,
176 /* Create the socket */
177 sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
179 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
183 /* Set the socket options */
184 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
186 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_ERROR(("Cannot bind socket: %s", strerror(errno)));
199 /* Specify that we are listenning */
200 rval = listen(sock, 64);
202 SILC_LOG_ERROR(("Cannot set socket listenning: %s", strerror(errno)));
207 /* Set the server socket to non-blocking mode */
208 silc_net_set_socket_nonblock(sock);
210 /* Schedule for incoming connections */
211 silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
213 SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
214 listener->socks[i] = sock;
215 listener->socks_count++;
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 /******************************* UDP Stream *********************************/
246 /* Create UDP stream */
249 silc_net_udp_connect(const char *local_ip_addr, int local_port,
250 const char *remote_ip_addr, int remote_port,
251 SilcSchedule schedule)
256 const char *ipany = "0.0.0.0";
258 SILC_LOG_DEBUG(("Creating UDP stream"));
263 /* Bind to local addresses */
264 SILC_LOG_DEBUG(("Binding to local address %s",
265 local_ip_addr ? local_ip_addr : ipany));
267 /* Set sockaddr for server */
268 if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
272 /* Create the socket */
273 sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
275 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
279 /* Set the socket options */
280 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
282 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
286 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
288 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
291 #endif /* SO_REUSEPORT */
293 /* Bind the listener socket */
294 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
296 SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
300 /* Set to connected state if remote address is provided. */
301 if (remote_ip_addr && remote_port) {
302 if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
305 rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
307 SILC_LOG_DEBUG(("Cannot connect UDP stream: %s", strerror(errno)));
312 /* Set send and receive buffer size */
314 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 765535);
316 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 65535);
318 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
322 #endif /* SO_SNDBUF */
324 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 765535);
326 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 65535);
328 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
332 #endif /* SO_RCVBUF */
334 /* Encapsulate into socket stream */
336 silc_socket_udp_stream_create(sock, local_ip_addr ?
337 silc_net_is_ip6(local_ip_addr) : FALSE,
338 remote_ip_addr ? TRUE : FALSE, schedule);
342 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
351 /* Receive UDP packet */
353 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
354 SilcUInt32 remote_ip_addr_size, int *remote_port,
355 unsigned char *ret_data, SilcUInt32 data_size)
357 SilcSocketStream sock = stream;
359 struct sockaddr *from;
362 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
364 if (remote_ip_addr && remote_port) {
366 from = (struct sockaddr *)&s.sin6;
367 flen = sizeof(s.sin6);
369 from = (struct sockaddr *)&s.sin;
370 flen = sizeof(s.sin);
372 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
374 len = recv(sock->sock, ret_data, data_size, 0);
377 if (errno == EAGAIN || errno == EINTR) {
378 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
379 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
380 SILC_TASK_READ, FALSE);
383 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d:%s",
384 sock->sock, strerror(errno)));
385 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
386 sock->sock_error = errno;
390 SILC_LOG_DEBUG(("Read %d bytes", len));
393 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
395 /* Return remote address */
396 if (remote_ip_addr && remote_port) {
398 *remote_port = ntohs(s.sin6.sin6_port);
399 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
400 remote_ip_addr_size);
402 *remote_port = ntohs(s.sin.sin_port);
403 inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
404 remote_ip_addr_size);
407 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
413 /* Send UDP packet */
415 int silc_net_udp_send(SilcStream stream,
416 const char *remote_ip_addr, int remote_port,
417 const unsigned char *data, SilcUInt32 data_len)
419 SilcSocketStream sock = stream;
423 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
426 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
430 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
431 SIZEOF_SOCKADDR(remote));
433 if (errno == EAGAIN || errno == EINTR) {
434 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
435 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
436 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
439 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
440 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
441 sock->sock_error = errno;
445 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
446 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
448 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
449 SILC_TASK_READ, FALSE);
454 /******************************* TCP Stream *********************************/
456 /* Asynchronous TCP/IP connecting */
459 SilcNetStatus status;
460 SilcSocketStreamStatus stream_status;
463 SilcFSMEventStruct event;
464 SilcAsyncOperation op;
465 SilcAsyncOperation sop;
470 SilcNetCallback callback;
472 unsigned int port : 24;
473 unsigned int retry : 7;
474 unsigned int aborted : 1;
477 SILC_FSM_STATE(silc_net_connect_st_start);
478 SILC_FSM_STATE(silc_net_connect_st_connected);
479 SILC_FSM_STATE(silc_net_connect_st_stream);
480 SILC_FSM_STATE(silc_net_connect_st_finish);
482 SILC_TASK_CALLBACK(silc_net_connect_wait)
484 SilcNetConnect conn = context;
485 SILC_FSM_EVENT_SIGNAL(&conn->event);
488 SILC_FSM_STATE(silc_net_connect_st_start)
490 SilcNetConnect conn = fsm_context;
492 SilcSockaddr desthost;
493 SilcBool prefer_ipv6 = TRUE;
497 silc_fsm_next(fsm, silc_net_connect_st_finish);
498 return SILC_FSM_CONTINUE;
503 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
504 conn->ip_addr, sizeof(conn->ip_addr))) {
505 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
506 "host", conn->remote));
508 /** Network unreachable */
509 conn->status = SILC_NET_HOST_UNREACHABLE;
510 silc_fsm_next(fsm, silc_net_connect_st_finish);
511 return SILC_FSM_CONTINUE;
514 /* Set sockaddr for this connection */
515 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port)) {
516 /** Sockaddr failed */
517 silc_fsm_next(fsm, silc_net_connect_st_finish);
518 return SILC_FSM_CONTINUE;
521 /* Create the connection socket */
522 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
524 /* If address is IPv6, then fallback to IPv4 and see whether we can do
525 better with that on socket creation. */
526 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
531 /** Cannot create socket */
532 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
533 silc_fsm_next(fsm, silc_net_connect_st_finish);
534 return SILC_FSM_CONTINUE;
537 /* Bind to the local address if provided */
538 if (conn->local_ip) {
541 /* Set sockaddr for local listener, and try to bind it. */
542 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
543 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
546 /* Set the socket to non-blocking mode */
547 silc_net_set_socket_nonblock(sock);
549 /* Connect to the host */
550 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
552 if (errno != EINPROGRESS) {
556 /* Retry using an IPv4 adress, if IPv6 didn't work */
557 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
562 /** Cannot connect to remote host */
563 SILC_LOG_ERROR(("Cannot connect to remote host: %s", strerror(errno)));
564 silc_fsm_next(fsm, silc_net_connect_st_finish);
565 return SILC_FSM_CONTINUE;
569 /* Set appropriate options */
570 #if defined(TCP_NODELAY)
571 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
573 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
575 SILC_LOG_DEBUG(("Connection operation in progress"));
579 /** Wait for connection */
580 silc_fsm_next(fsm, silc_net_connect_st_connected);
581 silc_fsm_event_init(&conn->event, fsm);
582 silc_schedule_task_add_fd(silc_fsm_get_schedule(fsm), sock,
583 silc_net_connect_wait, conn);
584 silc_schedule_set_listen_fd(silc_fsm_get_schedule(fsm), sock,
585 SILC_TASK_WRITE, FALSE);
586 SILC_FSM_EVENT_WAIT(&conn->event);
587 return SILC_FSM_CONTINUE;
590 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
591 SilcStream stream, void *context)
593 SilcNetConnect conn = context;
594 conn->stream_status = status;
595 conn->stream = stream;
596 SILC_FSM_CALL_CONTINUE(&conn->fsm);
599 SILC_FSM_STATE(silc_net_connect_st_connected)
601 SilcNetConnect conn = fsm_context;
602 SilcSchedule schedule = silc_fsm_get_schedule(fsm);
603 int opt = EINVAL, optlen = sizeof(opt), ret;
607 silc_schedule_unset_listen_fd(schedule, conn->sock);
608 silc_schedule_task_del_by_fd(schedule, conn->sock);
609 silc_fsm_next(fsm, silc_net_connect_st_finish);
610 return SILC_FSM_CONTINUE;
613 ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
616 silc_schedule_unset_listen_fd(schedule, conn->sock);
617 silc_schedule_task_del_by_fd(schedule, conn->sock);
619 if (ret != 0 || opt != 0) {
621 /** Retry connecting */
622 SILC_LOG_DEBUG(("Retry connecting"));
624 silc_net_close_connection(conn->sock);
625 silc_fsm_next(fsm, silc_net_connect_st_start);
626 return SILC_FSM_CONTINUE;
629 #if defined(ECONNREFUSED)
630 if (errno == ECONNREFUSED)
631 conn->status = SILC_NET_CONNECTION_REFUSED;
632 #endif /* ECONNREFUSED */
633 #if defined(ETIMEDOUT)
634 if (errno == ETIMEDOUT)
635 conn->status = SILC_NET_CONNECTION_TIMEOUT;
636 #endif /* ETIMEDOUT */
637 #if defined(ENETUNREACH)
638 if (errno == ENETUNREACH)
639 conn->status = SILC_NET_HOST_UNREACHABLE;
640 #endif /* ENETUNREACH */
642 /** Connecting failed */
643 SILC_LOG_DEBUG(("Connecting failed"));
644 silc_fsm_next(fsm, silc_net_connect_st_finish);
645 return SILC_FSM_CONTINUE;
648 SILC_LOG_DEBUG(("TCP connection established"));
650 /** Connection created */
651 silc_fsm_next(fsm, silc_net_connect_st_stream);
652 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
653 conn->sock, FALSE, FALSE,
655 silc_net_connect_wait_stream, conn)));
658 SILC_FSM_STATE(silc_net_connect_st_stream)
660 SilcNetConnect conn = fsm_context;
664 silc_fsm_next(fsm, silc_net_connect_st_finish);
665 return SILC_FSM_CONTINUE;
668 if (conn->stream_status != SILC_SOCKET_OK) {
669 /** Stream creation failed */
670 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
671 conn->status = SILC_NET_UNKNOWN_IP;
672 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
673 conn->status = SILC_NET_UNKNOWN_HOST;
675 conn->status = SILC_NET_ERROR;
676 silc_fsm_next(fsm, silc_net_connect_st_finish);
677 return SILC_FSM_CONTINUE;
680 /* Set stream information */
681 silc_socket_stream_set_info(conn->stream,
682 !silc_net_is_ip(conn->remote) ? conn->remote :
683 conn->ip_addr, conn->ip_addr, conn->port);
685 /** Stream created successfully */
686 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
687 conn->status = SILC_NET_OK;
688 silc_fsm_next(fsm, silc_net_connect_st_finish);
689 return SILC_FSM_CONTINUE;
692 SILC_FSM_STATE(silc_net_connect_st_finish)
694 SilcNetConnect conn = fsm_context;
696 /* Deliver error or new stream */
697 if (!conn->aborted) {
698 conn->callback(conn->status, conn->stream, conn->context);
700 silc_async_free(conn->op);
702 silc_async_free(conn->sop);
705 return SILC_FSM_FINISH;
708 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
710 SilcNetConnect conn = context;
711 conn->aborted = TRUE;
713 /* Abort underlaying stream creation too */
715 silc_async_abort(conn->sop, NULL, NULL);
718 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
719 void *destructor_context)
721 SilcNetConnect conn = fsm_context;
722 silc_free(conn->local_ip);
723 silc_free(conn->remote);
727 /* Create asynchronous TCP/IP connection. */
729 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
730 const char *remote_ip_addr,
732 SilcSchedule schedule,
733 SilcNetCallback callback,
738 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
741 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
742 remote_ip_addr, remote_port));
744 conn = silc_calloc(1, sizeof(*conn));
746 callback(SILC_NET_NO_MEMORY, NULL, context);
750 /* Start async operation */
751 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
754 callback(SILC_NET_NO_MEMORY, NULL, context);
759 conn->local_ip = strdup(local_ip_addr);
760 conn->remote = strdup(remote_ip_addr);
762 silc_async_free(conn->op);
763 silc_free(conn->local_ip);
765 callback(SILC_NET_NO_MEMORY, NULL, context);
768 conn->port = remote_port;
769 conn->callback = callback;
770 conn->context = context;
772 conn->status = SILC_NET_ERROR;
774 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
775 silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
780 /* Closes the connection by closing the socket connection. */
782 void silc_net_close_connection(int sock)
784 SILC_LOG_DEBUG(("Closing sock %d", sock));
788 /* Set's the socket to non-blocking mode. */
790 int silc_net_set_socket_nonblock(SilcSocket sock)
792 return fcntl((int)sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
795 /* Converts the IP number string from numbers-and-dots notation to
798 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
802 if (silc_net_is_ip4(addr)) {
805 ret = inet_aton(addr, &tmp);
809 memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
812 struct addrinfo hints, *ai;
819 memset(&hints, 0, sizeof(hints));
820 hints.ai_family = AF_INET6;
821 if (getaddrinfo(addr, NULL, &hints, &ai))
825 s = (SilcSockaddr *)ai->ai_addr;
826 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
831 #endif /* HAVE_IPV6 */