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 /* Close network listener */
232 void silc_net_close_listener(SilcNetListener listener)
236 SILC_LOG_DEBUG(("Closing network listener"));
241 for (i = 0; i < listener->socks_count; i++) {
242 silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
243 shutdown(listener->socks[i], 2);
244 closesocket(listener->socks[i]);
247 silc_free(listener->socks);
251 /******************************* UDP Stream *********************************/
253 /* Create UDP stream */
256 silc_net_udp_connect(const char *local_ip_addr, int local_port,
257 const char *remote_ip_addr, int remote_port,
258 SilcSchedule schedule)
264 const char *ipany = "0.0.0.0";
266 SILC_LOG_DEBUG(("Creating UDP stream"));
271 /* Bind to local addresses */
272 SILC_LOG_DEBUG(("Binding to local address %s",
273 local_ip_addr ? local_ip_addr : ipany));
275 /* Set sockaddr for server */
276 if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
280 /* Create the socket */
281 sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
282 if (sock == INVALID_SOCKET) {
283 SILC_LOG_ERROR(("Cannot create socket"));
287 /* Set the socket options */
288 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
289 if (rval == SOCKET_ERROR) {
290 SILC_LOG_ERROR(("Cannot set socket options"));
294 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
295 if (rval == SOCKET_ERROR) {
296 SILC_LOG_ERROR(("Cannot set socket options"));
299 #endif /* SO_REUSEPORT */
301 /* Bind the listener socket */
302 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
303 if (rval == SOCKET_ERROR) {
304 SILC_LOG_DEBUG(("Cannot bind socket"));
308 /* Set to connected state if remote address is provided. */
309 if (remote_ip_addr && remote_port) {
310 if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
313 rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
314 if (rval == SOCKET_ERROR) {
315 SILC_LOG_DEBUG(("Cannot connect UDP stream"));
320 /* Encapsulate into socket stream */
322 silc_socket_udp_stream_create(sock, local_ip_addr ?
323 silc_net_is_ip6(local_ip_addr) : FALSE,
324 remote_ip_addr ? TRUE : FALSE, schedule);
328 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
337 /* Receive UDP packet */
339 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
340 SilcUInt32 remote_ip_addr_size, int *remote_port,
341 unsigned char *ret_data, SilcUInt32 data_size)
343 SilcSocketStream sock = stream;
345 struct sockaddr *from;
348 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
350 if (remote_ip_addr && remote_port) {
353 from = (struct sockaddr *)&s.sin6;
354 flen = sizeof(s.sin6);
355 #endif /* HAVE_IPV6 */
357 from = (struct sockaddr *)&s.sin;
358 flen = sizeof(s.sin);
360 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
362 len = recv(sock->sock, ret_data, data_size, 0);
364 if (len == SOCKET_ERROR) {
365 err = WSAGetLastError();
366 if (err == WSAEWOULDBLOCK) {
367 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
368 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
369 SILC_TASK_READ, FALSE);
372 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d", sock->sock));
373 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
374 sock->sock_error = err;
378 SILC_LOG_DEBUG(("Read %d bytes", len));
381 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
383 /* Return remote address */
384 if (remote_ip_addr && remote_port) {
387 *remote_port = ntohs(s.sin6.sin6_port);
388 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
389 remote_ip_addr_size);
390 #endif /* HAVE_IPV6 */
392 const char *ip = inet_ntoa(s.sin.sin_addr);
394 silc_snprintf(remote_ip_addr, remote_ip_addr_size, ip);
395 *remote_port = ntohs(s.sin.sin_port);
398 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
404 /* Send UDP packet */
406 int silc_net_udp_send(SilcStream stream,
407 const char *remote_ip_addr, int remote_port,
408 const unsigned char *data, SilcUInt32 data_len)
410 SilcSocketStream sock = stream;
414 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
417 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
421 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
422 SIZEOF_SOCKADDR(remote));
423 if (ret == SOCKET_ERROR) {
424 err = WSAGetLastError();
425 if (err == WSAEWOULDBLOCK) {
426 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
427 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
428 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
431 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
432 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
433 sock->sock_error = err;
437 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
438 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
440 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
441 SILC_TASK_READ, FALSE);
447 /******************************* TCP Stream *********************************/
450 SilcNetStatus status;
451 SilcSocketStreamStatus stream_status;
454 SilcFSMThreadStruct thread;
455 SilcAsyncOperation op;
456 SilcAsyncOperation sop;
461 SilcNetCallback callback;
463 unsigned int port : 24;
464 unsigned int retry : 7;
465 unsigned int aborted : 1;
468 SILC_FSM_STATE(silc_net_connect_st_start);
469 SILC_FSM_STATE(silc_net_connect_st_stream);
470 SILC_FSM_STATE(silc_net_connect_st_finish);
472 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
473 SilcStream stream, void *context)
475 SilcNetConnect conn = context;
477 conn->stream_status = status;
478 conn->stream = stream;
479 SILC_FSM_CALL_CONTINUE(&conn->thread);
482 /* Start connecting. Create a real thread where we connect. */
484 SILC_FSM_STATE(silc_net_connect_st_thread)
486 SilcNetConnect conn = fsm_context;
488 /* Connect in real thread so as to not block the application. */
489 silc_fsm_thread_init(&conn->thread, fsm, conn, NULL, NULL, TRUE);
490 silc_fsm_start(&conn->thread, silc_net_connect_st_start);
492 /* Wait for the thread to finish */
493 silc_fsm_next(fsm, silc_net_connect_st_finish);
494 SILC_FSM_THREAD_WAIT(&conn->thread);
497 /* Connecting thread */
499 SILC_FSM_STATE(silc_net_connect_st_start)
501 SilcNetConnect conn = fsm_context;
504 SilcSockaddr desthost;
505 SilcBool prefer_ipv6 = TRUE;
508 return SILC_FSM_FINISH;
512 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
513 conn->ip_addr, sizeof(conn->ip_addr))) {
514 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
515 "host, error %d", conn->remote, WSAGetLastError()));
517 /** Network unreachable */
518 conn->status = SILC_NET_HOST_UNREACHABLE;
519 return SILC_FSM_FINISH;
522 /* Set sockaddr for this connection */
523 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port))
524 return SILC_FSM_FINISH;
526 /* Create the connection socket */
527 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
528 if (sock == INVALID_SOCKET) {
529 /* If address is IPv6, then fallback to IPv4 and see whether we can do
530 better with that on socket creation. */
531 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
536 /** Cannot create socket */
537 SILC_LOG_ERROR(("Cannot create socket, error %d", WSAGetLastError()));
538 return SILC_FSM_FINISH;
541 /* Bind to the local address if provided */
542 if (conn->local_ip) {
545 /* Set sockaddr for local listener, and try to bind it. */
546 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
547 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
550 /* Connect to the host */
551 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
552 err = WSAGetLastError();
553 if (rval == SOCKET_ERROR) {
554 if (err != WSAEWOULDBLOCK) {
558 /* Retry using an IPv4 address, if IPv6 didn't work */
559 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
566 conn->status = SILC_NET_CONNECTION_TIMEOUT;
568 case WSAECONNREFUSED:
569 conn->status = SILC_NET_CONNECTION_REFUSED;
571 case WSAEHOSTUNREACH:
572 conn->status = SILC_NET_HOST_UNREACHABLE;
578 SILC_LOG_ERROR(("Cannot connect to remote host, error %d",
580 return SILC_FSM_FINISH;
584 /* Set the socket to non-blocking mode */
585 silc_net_set_socket_nonblock(sock);
587 /* Set appropriate options */
588 #if defined(TCP_NODELAY)
589 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
591 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
593 SILC_LOG_DEBUG(("TCP connection established"));
597 /** Connection created */
598 silc_fsm_next(fsm, silc_net_connect_st_stream);
599 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
600 conn->sock, TRUE, FALSE,
601 silc_fsm_get_schedule(&conn->fsm),
602 silc_net_connect_wait_stream, conn)));
605 /* TCP socket stream created */
607 SILC_FSM_STATE(silc_net_connect_st_stream)
609 SilcNetConnect conn = fsm_context;
612 return SILC_FSM_FINISH;
614 if (conn->stream_status != SILC_SOCKET_OK) {
615 /** Stream creation failed */
616 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
617 conn->status = SILC_NET_UNKNOWN_IP;
618 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
619 conn->status = SILC_NET_UNKNOWN_HOST;
621 conn->status = SILC_NET_ERROR;
623 return SILC_FSM_FINISH;
626 /** Stream created successfully */
627 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
628 conn->status = SILC_NET_OK;
629 return SILC_FSM_FINISH;
632 SILC_FSM_STATE(silc_net_connect_st_finish)
634 SilcNetConnect conn = fsm_context;
636 /* Deliver error or new stream */
637 if (!conn->aborted) {
638 conn->callback(conn->status, conn->stream, conn->context);
640 silc_async_free(conn->op);
643 return SILC_FSM_FINISH;
646 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
648 SilcNetConnect conn = context;
649 conn->aborted = TRUE;
651 /* Abort underlaying stream creation too */
653 silc_async_abort(conn->sop, NULL, NULL);
658 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
659 void *destructor_context)
661 SilcNetConnect conn = fsm_context;
662 silc_free(conn->local_ip);
663 silc_free(conn->remote);
667 /* Create asynchronous TCP/IP connection. */
669 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
670 const char *remote_ip_addr,
672 SilcSchedule schedule,
673 SilcNetCallback callback,
678 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
681 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
682 remote_ip_addr, remote_port));
684 conn = silc_calloc(1, sizeof(*conn));
686 callback(SILC_NET_NO_MEMORY, NULL, context);
690 /* Start async operation */
691 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
694 callback(SILC_NET_NO_MEMORY, NULL, context);
699 conn->local_ip = strdup(local_ip_addr);
700 conn->remote = strdup(remote_ip_addr);
702 silc_async_free(conn->op);
703 silc_free(conn->local_ip);
705 callback(SILC_NET_NO_MEMORY, NULL, context);
708 conn->port = remote_port;
709 conn->callback = callback;
710 conn->context = context;
712 conn->status = SILC_NET_ERROR;
714 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
715 silc_fsm_start(&conn->fsm, silc_net_connect_st_thread);
720 /* Closes the connection by closing the socket connection. */
722 void silc_net_close_connection(int sock)
724 SILC_LOG_DEBUG(("Closing sock %d", sock));
728 /* Converts the IP number string from numbers-and-dots notation to
731 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
733 if (silc_net_is_ip4(addr)) {
735 int i = 0, c = 0, d = 0, len = strlen(addr);
736 unsigned char ret[4];
738 memset(ret, 0, sizeof(ret));
740 if (addr[i++] == '.') {
748 if (!isdigit((int)addr[i - 1]))
751 d = 10 * d + addr[i - 1] - '0';
759 if (bin_len < sizeof(ret))
762 memcpy(bin, ret, sizeof(ret));
766 struct addrinfo hints, *ai;
773 memset(&hints, 0, sizeof(hints));
774 hints.ai_family = AF_INET6;
775 if (getaddrinfo(addr, NULL, &hints, &ai))
779 s = (SilcSockaddr *)ai->ai_addr;
780 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
787 #endif /* HAVE_IPV6 */
791 /* Set socket to non-blocking mode. */
793 int silc_net_set_socket_nonblock(SilcSocket sock)
795 unsigned long on = 1;
796 return ioctlsocket(sock, FIONBIO, &on);