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.
23 /************************** Types and definitions ***************************/
26 #define SIZEOF_SOCKADDR(so) ((so).sa.sa_family == AF_INET6 ? \
27 sizeof(so.sin6) : sizeof(so.sin))
29 #define SIZEOF_SOCKADDR(so) (sizeof(so.sin))
34 struct sockaddr_in sin;
36 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 if (!silc_net_addr2bin(ip_addr,
61 (unsigned char *)&addr->sin.sin_addr.s_addr,
64 addr->sin.sin_family = AF_INET;
65 addr->sin.sin_port = port ? htons(port) : 0;
69 len = sizeof(addr->sin6.sin6_addr);
70 if (!silc_net_addr2bin(ip_addr,
71 (unsigned char *)&addr->sin6.sin6_addr, len))
73 addr->sin6.sin6_family = AF_INET6;
74 addr->sin6.sin6_port = port ? htons(port) : 0;
76 SILC_LOG_ERROR(("Operating System does not support IPv6"));
82 addr->sin.sin_family = AF_INET;
83 addr->sin.sin_addr.s_addr = INADDR_ANY;
85 addr->sin.sin_port = htons(port);
92 /****************************** TCP Listener ********************************/
94 /* Deliver new stream to upper layer */
96 static void silc_net_accept_stream(SilcSocketStreamStatus status,
97 SilcStream stream, void *context)
99 SilcNetListener listener = context;
101 if (status != SILC_SOCKET_OK)
104 listener->callback(SILC_NET_OK, stream, listener->context);
107 /* Accept incoming connection and notify upper layer */
109 SILC_TASK_CALLBACK(silc_net_accept)
111 SilcNetListener listener = context;
114 SILC_LOG_DEBUG(("Accepting new connection"));
116 sock = silc_net_accept_connection(fd);
117 if (sock == INVALID_SOCKET)
120 /* Set socket options */
121 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
123 /* Create socket stream */
124 silc_socket_tcp_stream_create(sock, listener->lookup,
125 listener->require_fqdn, schedule,
126 silc_net_accept_stream, listener);
129 /* Create TCP network listener */
132 silc_net_tcp_create_listener(const char **local_ip_addr,
133 SilcUInt32 local_ip_count, int port,
134 SilcBool lookup, SilcBool require_fqdn,
135 SilcSchedule schedule,
136 SilcNetCallback callback, void *context)
138 SilcNetListener listener = NULL;
142 const char *ipany = "0.0.0.0";
144 SILC_LOG_DEBUG(("Creating TCP listener"));
146 if (port < 0 || !schedule || !callback)
149 listener = silc_calloc(1, sizeof(*listener));
152 listener->schedule = schedule;
153 listener->callback = callback;
154 listener->context = context;
155 listener->require_fqdn = require_fqdn;
156 listener->lookup = lookup;
158 if (local_ip_count > 0) {
159 listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
160 if (!listener->socks)
163 listener->socks = silc_calloc(1, sizeof(*listener->socks));
164 if (!listener->socks)
170 /* Bind to local addresses */
171 for (i = 0; i < local_ip_count; i++) {
172 SILC_LOG_DEBUG(("Binding to local address %s",
173 local_ip_addr ? local_ip_addr[i] : ipany));
175 /* Set sockaddr for server */
176 if (!silc_net_set_sockaddr(&server,
177 local_ip_addr ? local_ip_addr[i] : ipany,
181 /* Create the socket */
182 sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
183 if (sock == INVALID_SOCKET) {
184 SILC_LOG_ERROR(("Cannot create socket, error %d", WSAGetLastError()));
188 /* Set the socket options */
189 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
190 if (rval == SOCKET_ERROR) {
191 SILC_LOG_ERROR(("Cannot set socket options, error %d",
197 /* Bind the listener socket */
198 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
199 if (rval == SOCKET_ERROR) {
200 SILC_LOG_ERROR(("Cannot bind socket, error %d", WSAGetLastError()));
205 /* Specify that we are listenning */
206 rval = listen(sock, SOMAXCONN);
207 if (rval == SOCKET_ERROR) {
208 SILC_LOG_ERROR(("Cannot set socket listenning, error %d",
214 /* Schedule for incoming connections */
215 silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
217 SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
218 listener->socks[i] = sock;
219 listener->socks_count++;
226 silc_net_close_listener(listener);
230 /* Create TCP network, multiple ports */
233 silc_net_tcp_create_listener2(const char *local_ip_addr, int *ports,
234 SilcUInt32 port_count,
235 SilcBool ignore_port_error,
236 SilcBool lookup, SilcBool require_fqdn,
237 SilcSchedule schedule,
238 SilcNetCallback callback, void *context)
240 SilcNetListener listener = NULL;
244 const char *ipany = "0.0.0.0";
246 SILC_LOG_DEBUG(("Creating TCP listener"));
248 if (!schedule || !callback)
251 listener = silc_calloc(1, sizeof(*listener));
254 listener->schedule = schedule;
255 listener->callback = callback;
256 listener->context = context;
257 listener->require_fqdn = require_fqdn;
258 listener->lookup = lookup;
260 if (port_count > 0) {
261 listener->socks = silc_calloc(port_count, sizeof(*listener->socks));
262 if (!listener->socks)
265 listener->socks = silc_calloc(1, sizeof(*listener->socks));
266 if (!listener->socks)
272 /* Bind to local addresses */
273 for (i = 0; i < local_ip_count; i++) {
274 SILC_LOG_DEBUG(("Binding to local address %s:%d",
275 local_ip_addr ? local_ip_addr : ipany,
276 ports ? ports[i] : 0));
278 /* Set sockaddr for server */
279 if (!silc_net_set_sockaddr(&server,
280 local_ip_addr ? local_ip_addr : ipany,
281 ports ? ports[i] : 0)) {
282 if (ignore_port_error)
287 /* Create the socket */
288 sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
289 if (sock == INVALID_SOCKET) {
290 if (ignore_port_error)
292 SILC_LOG_ERROR(("Cannot create socket, error %d", WSAGetLastError()));
296 /* Set the socket options */
297 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
298 if (rval == SOCKET_ERROR) {
300 if (ignore_port_error)
302 SILC_LOG_ERROR(("Cannot set socket options, error %d",
307 /* Bind the listener socket */
308 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
309 if (rval == SOCKET_ERROR) {
311 if (ignore_port_error)
313 SILC_LOG_ERROR(("Cannot bind socket, error %d", WSAGetLastError()));
317 /* Specify that we are listenning */
318 rval = listen(sock, SOMAXCONN);
319 if (rval == SOCKET_ERROR) {
321 if (ignore_port_error)
323 SILC_LOG_ERROR(("Cannot set socket listenning, error %d",
328 /* Schedule for incoming connections */
329 silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
331 SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
332 listener->socks[i] = sock;
333 listener->socks_count++;
336 if (ignore_port_error && !listener->socks_count)
343 silc_net_close_listener(listener);
347 /* Close network listener */
349 void silc_net_close_listener(SilcNetListener listener)
353 SILC_LOG_DEBUG(("Closing network listener"));
358 for (i = 0; i < listener->socks_count; i++) {
359 silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
360 shutdown(listener->socks[i], 2);
361 closesocket(listener->socks[i]);
364 silc_free(listener->socks);
368 /******************************* UDP Stream *********************************/
370 /* Create UDP stream */
373 silc_net_udp_connect(const char *local_ip_addr, int local_port,
374 const char *remote_ip_addr, int remote_port,
375 SilcSchedule schedule)
381 const char *ipany = "0.0.0.0";
383 SILC_LOG_DEBUG(("Creating UDP stream"));
388 /* Bind to local addresses */
389 SILC_LOG_DEBUG(("Binding to local address %s",
390 local_ip_addr ? local_ip_addr : ipany));
392 /* Set sockaddr for server */
393 if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
397 /* Create the socket */
398 sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
399 if (sock == INVALID_SOCKET) {
400 SILC_LOG_ERROR(("Cannot create socket"));
404 /* Set the socket options */
405 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
406 if (rval == SOCKET_ERROR) {
407 SILC_LOG_ERROR(("Cannot set socket options"));
411 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
412 if (rval == SOCKET_ERROR) {
413 SILC_LOG_ERROR(("Cannot set socket options"));
416 #endif /* SO_REUSEPORT */
418 /* Bind the listener socket */
419 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
420 if (rval == SOCKET_ERROR) {
421 SILC_LOG_DEBUG(("Cannot bind socket"));
425 /* Set to connected state if remote address is provided. */
426 if (remote_ip_addr && remote_port) {
427 if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
430 rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
431 if (rval == SOCKET_ERROR) {
432 SILC_LOG_DEBUG(("Cannot connect UDP stream"));
437 /* Encapsulate into socket stream */
439 silc_socket_udp_stream_create(sock, local_ip_addr ?
440 silc_net_is_ip6(local_ip_addr) : FALSE,
441 remote_ip_addr ? TRUE : FALSE, schedule);
445 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
454 /* Receive UDP packet */
456 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
457 SilcUInt32 remote_ip_addr_size, int *remote_port,
458 unsigned char *ret_data, SilcUInt32 data_size)
460 SilcSocketStream sock = stream;
462 struct sockaddr *from;
465 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
467 if (remote_ip_addr && remote_port) {
470 from = (struct sockaddr *)&s.sin6;
471 flen = sizeof(s.sin6);
472 #endif /* HAVE_IPV6 */
474 from = (struct sockaddr *)&s.sin;
475 flen = sizeof(s.sin);
477 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
479 len = recv(sock->sock, ret_data, data_size, 0);
481 if (len == SOCKET_ERROR) {
482 err = WSAGetLastError();
483 if (err == WSAEWOULDBLOCK) {
484 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
485 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
486 SILC_TASK_READ, FALSE);
489 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d", sock->sock));
490 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
491 sock->sock_error = err;
495 SILC_LOG_DEBUG(("Read %d bytes", len));
498 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
500 /* Return remote address */
501 if (remote_ip_addr && remote_port) {
504 *remote_port = ntohs(s.sin6.sin6_port);
505 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
506 remote_ip_addr_size);
507 #endif /* HAVE_IPV6 */
509 const char *ip = inet_ntoa(s.sin.sin_addr);
511 silc_snprintf(remote_ip_addr, remote_ip_addr_size, ip);
512 *remote_port = ntohs(s.sin.sin_port);
515 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
521 /* Send UDP packet */
523 int silc_net_udp_send(SilcStream stream,
524 const char *remote_ip_addr, int remote_port,
525 const unsigned char *data, SilcUInt32 data_len)
527 SilcSocketStream sock = stream;
531 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
534 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
538 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
539 SIZEOF_SOCKADDR(remote));
540 if (ret == SOCKET_ERROR) {
541 err = WSAGetLastError();
542 if (err == WSAEWOULDBLOCK) {
543 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
544 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
545 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
548 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
549 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
550 sock->sock_error = err;
554 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
555 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
557 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
558 SILC_TASK_READ, FALSE);
564 /******************************* TCP Stream *********************************/
567 SilcNetStatus status;
568 SilcSocketStreamStatus stream_status;
571 SilcFSMThreadStruct thread;
572 SilcAsyncOperation op;
573 SilcAsyncOperation sop;
578 SilcNetCallback callback;
580 unsigned int port : 24;
581 unsigned int retry : 7;
582 unsigned int aborted : 1;
585 SILC_FSM_STATE(silc_net_connect_st_start);
586 SILC_FSM_STATE(silc_net_connect_st_stream);
587 SILC_FSM_STATE(silc_net_connect_st_finish);
589 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
590 SilcStream stream, void *context)
592 SilcNetConnect conn = context;
594 conn->stream_status = status;
595 conn->stream = stream;
596 SILC_FSM_CALL_CONTINUE(&conn->thread);
599 /* Start connecting. Create a real thread where we connect. */
601 SILC_FSM_STATE(silc_net_connect_st_thread)
603 SilcNetConnect conn = fsm_context;
605 /* Connect in real thread so as to not block the application. */
606 silc_fsm_thread_init(&conn->thread, fsm, conn, NULL, NULL, TRUE);
607 silc_fsm_start(&conn->thread, silc_net_connect_st_start);
609 /* Wait for the thread to finish */
610 silc_fsm_next(fsm, silc_net_connect_st_finish);
611 SILC_FSM_THREAD_WAIT(&conn->thread);
614 /* Connecting thread */
616 SILC_FSM_STATE(silc_net_connect_st_start)
618 SilcNetConnect conn = fsm_context;
621 SilcSockaddr desthost;
622 SilcBool prefer_ipv6 = TRUE;
625 return SILC_FSM_FINISH;
629 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
630 conn->ip_addr, sizeof(conn->ip_addr))) {
631 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
632 "host, error %d", conn->remote, WSAGetLastError()));
634 /** Network unreachable */
635 conn->status = SILC_NET_HOST_UNREACHABLE;
636 return SILC_FSM_FINISH;
639 /* Set sockaddr for this connection */
640 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port))
641 return SILC_FSM_FINISH;
643 /* Create the connection socket */
644 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
645 if (sock == INVALID_SOCKET) {
646 /* If address is IPv6, then fallback to IPv4 and see whether we can do
647 better with that on socket creation. */
648 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
653 /** Cannot create socket */
654 SILC_LOG_ERROR(("Cannot create socket, error %d", WSAGetLastError()));
655 return SILC_FSM_FINISH;
658 /* Bind to the local address if provided */
659 if (conn->local_ip) {
662 /* Set sockaddr for local listener, and try to bind it. */
663 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
664 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
667 /* Connect to the host */
668 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
669 err = WSAGetLastError();
670 if (rval == SOCKET_ERROR) {
671 if (err != WSAEWOULDBLOCK) {
675 /* Retry using an IPv4 address, if IPv6 didn't work */
676 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
683 conn->status = SILC_NET_CONNECTION_TIMEOUT;
685 case WSAECONNREFUSED:
686 conn->status = SILC_NET_CONNECTION_REFUSED;
688 case WSAEHOSTUNREACH:
689 conn->status = SILC_NET_HOST_UNREACHABLE;
695 SILC_LOG_ERROR(("Cannot connect to remote host, error %d",
697 return SILC_FSM_FINISH;
701 /* Set the socket to non-blocking mode */
702 silc_net_set_socket_nonblock(sock);
704 /* Set appropriate options */
705 #if defined(TCP_NODELAY)
706 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
708 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
710 SILC_LOG_DEBUG(("TCP connection established"));
714 /** Connection created */
715 silc_fsm_next(fsm, silc_net_connect_st_stream);
716 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
717 conn->sock, TRUE, FALSE,
718 silc_fsm_get_schedule(&conn->fsm),
719 silc_net_connect_wait_stream, conn)));
722 /* TCP socket stream created */
724 SILC_FSM_STATE(silc_net_connect_st_stream)
726 SilcNetConnect conn = fsm_context;
729 return SILC_FSM_FINISH;
731 if (conn->stream_status != SILC_SOCKET_OK) {
732 /** Stream creation failed */
733 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
734 conn->status = SILC_NET_UNKNOWN_IP;
735 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
736 conn->status = SILC_NET_UNKNOWN_HOST;
738 conn->status = SILC_NET_ERROR;
740 return SILC_FSM_FINISH;
743 /** Stream created successfully */
744 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
745 conn->status = SILC_NET_OK;
746 return SILC_FSM_FINISH;
749 SILC_FSM_STATE(silc_net_connect_st_finish)
751 SilcNetConnect conn = fsm_context;
753 /* Deliver error or new stream */
754 if (!conn->aborted) {
755 conn->callback(conn->status, conn->stream, conn->context);
757 silc_async_free(conn->op);
760 return SILC_FSM_FINISH;
763 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
765 SilcNetConnect conn = context;
766 conn->aborted = TRUE;
768 /* Abort underlaying stream creation too */
770 silc_async_abort(conn->sop, NULL, NULL);
775 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
776 void *destructor_context)
778 SilcNetConnect conn = fsm_context;
779 silc_free(conn->local_ip);
780 silc_free(conn->remote);
784 /* Create asynchronous TCP/IP connection. */
786 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
787 const char *remote_ip_addr,
789 SilcSchedule schedule,
790 SilcNetCallback callback,
795 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
798 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
799 remote_ip_addr, remote_port));
801 conn = silc_calloc(1, sizeof(*conn));
803 callback(SILC_NET_NO_MEMORY, NULL, context);
807 /* Start async operation */
808 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
811 callback(SILC_NET_NO_MEMORY, NULL, context);
816 conn->local_ip = strdup(local_ip_addr);
817 conn->remote = strdup(remote_ip_addr);
819 silc_async_free(conn->op);
820 silc_free(conn->local_ip);
822 callback(SILC_NET_NO_MEMORY, NULL, context);
825 conn->port = remote_port;
826 conn->callback = callback;
827 conn->context = context;
829 conn->status = SILC_NET_ERROR;
831 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
832 silc_fsm_start(&conn->fsm, silc_net_connect_st_thread);
837 /* Closes the connection by closing the socket connection. */
839 void silc_net_close_connection(int sock)
841 SILC_LOG_DEBUG(("Closing sock %d", sock));
845 /* Converts the IP number string from numbers-and-dots notation to
848 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
850 if (silc_net_is_ip4(addr)) {
852 int i = 0, c = 0, d = 0, len = strlen(addr);
853 unsigned char ret[4];
855 memset(ret, 0, sizeof(ret));
857 if (addr[i++] == '.') {
865 if (!isdigit((int)addr[i - 1]))
868 d = 10 * d + addr[i - 1] - '0';
876 if (bin_len < sizeof(ret))
879 memcpy(bin, ret, sizeof(ret));
883 struct addrinfo hints, *ai;
890 memset(&hints, 0, sizeof(hints));
891 hints.ai_family = AF_INET6;
892 if (getaddrinfo(addr, NULL, &hints, &ai))
896 s = (SilcSockaddr *)ai->ai_addr;
897 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
904 #endif /* HAVE_IPV6 */
908 /* Set socket to non-blocking mode. */
910 int silc_net_set_socket_nonblock(SilcSocket sock)
912 unsigned long on = 1;
913 return ioctlsocket(sock, FIONBIO, &on);