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:%d",
168 local_ip_addr ? local_ip_addr[i] : ipany, port));
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) {
367 from = (struct sockaddr *)&s.sin6;
368 flen = sizeof(s.sin6);
369 #endif /* HAVE_IPV6 */
371 from = (struct sockaddr *)&s.sin;
372 flen = sizeof(s.sin);
374 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
376 len = recv(sock->sock, ret_data, data_size, 0);
379 if (errno == EAGAIN || errno == EINTR) {
380 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
381 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
382 SILC_TASK_READ, FALSE);
385 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d:%s",
386 sock->sock, strerror(errno)));
387 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
388 sock->sock_error = errno;
392 SILC_LOG_DEBUG(("Read %d bytes", len));
395 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
397 /* Return remote address */
398 if (remote_ip_addr && remote_port) {
401 *remote_port = ntohs(s.sin6.sin6_port);
402 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
403 remote_ip_addr_size);
406 #endif /* HAVE_IPV6 */
408 *remote_port = ntohs(s.sin.sin_port);
409 inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
410 remote_ip_addr_size);
413 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
419 /* Send UDP packet */
421 int silc_net_udp_send(SilcStream stream,
422 const char *remote_ip_addr, int remote_port,
423 const unsigned char *data, SilcUInt32 data_len)
425 SilcSocketStream sock = stream;
429 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
432 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
436 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
437 SIZEOF_SOCKADDR(remote));
439 if (errno == EAGAIN || errno == EINTR) {
440 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
441 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
442 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
445 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
446 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
447 sock->sock_error = errno;
451 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
452 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
454 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
455 SILC_TASK_READ, FALSE);
460 /******************************* TCP Stream *********************************/
462 /* Asynchronous TCP/IP connecting */
465 SilcNetStatus status;
466 SilcSocketStreamStatus stream_status;
469 SilcFSMEventStruct event;
470 SilcAsyncOperation op;
471 SilcAsyncOperation sop;
476 SilcNetCallback callback;
478 unsigned int port : 24;
479 unsigned int retry : 7;
480 unsigned int aborted : 1;
483 SILC_FSM_STATE(silc_net_connect_st_start);
484 SILC_FSM_STATE(silc_net_connect_st_connected);
485 SILC_FSM_STATE(silc_net_connect_st_stream);
486 SILC_FSM_STATE(silc_net_connect_st_finish);
488 SILC_TASK_CALLBACK(silc_net_connect_wait)
490 SilcNetConnect conn = context;
491 SILC_FSM_EVENT_SIGNAL(&conn->event);
494 SILC_FSM_STATE(silc_net_connect_st_start)
496 SilcNetConnect conn = fsm_context;
498 SilcSockaddr desthost;
499 SilcBool prefer_ipv6 = TRUE;
503 silc_fsm_next(fsm, silc_net_connect_st_finish);
504 return SILC_FSM_CONTINUE;
509 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
510 conn->ip_addr, sizeof(conn->ip_addr))) {
511 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
512 "host", conn->remote));
514 /** Network unreachable */
515 conn->status = SILC_NET_HOST_UNREACHABLE;
516 silc_fsm_next(fsm, silc_net_connect_st_finish);
517 return SILC_FSM_CONTINUE;
520 /* Set sockaddr for this connection */
521 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port)) {
522 /** Sockaddr failed */
523 silc_fsm_next(fsm, silc_net_connect_st_finish);
524 return SILC_FSM_CONTINUE;
527 /* Create the connection socket */
528 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
530 /* If address is IPv6, then fallback to IPv4 and see whether we can do
531 better with that on socket creation. */
532 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
537 /** Cannot create socket */
538 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
539 silc_fsm_next(fsm, silc_net_connect_st_finish);
540 return SILC_FSM_CONTINUE;
543 /* Bind to the local address if provided */
544 if (conn->local_ip) {
547 /* Set sockaddr for local listener, and try to bind it. */
548 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
549 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
552 /* Set the socket to non-blocking mode */
553 silc_net_set_socket_nonblock(sock);
555 /* Connect to the host */
556 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
558 if (errno != EINPROGRESS) {
562 /* Retry using an IPv4 adress, if IPv6 didn't work */
563 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
568 /** Cannot connect to remote host */
569 SILC_LOG_ERROR(("Cannot connect to remote host: %s", strerror(errno)));
570 silc_fsm_next(fsm, silc_net_connect_st_finish);
571 return SILC_FSM_CONTINUE;
575 /* Set appropriate options */
576 #if defined(TCP_NODELAY)
577 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
579 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
581 SILC_LOG_DEBUG(("Connection operation in progress"));
585 /** Wait for connection */
586 silc_fsm_next(fsm, silc_net_connect_st_connected);
587 silc_fsm_event_init(&conn->event, fsm);
588 silc_schedule_task_add_fd(silc_fsm_get_schedule(fsm), sock,
589 silc_net_connect_wait, conn);
590 silc_schedule_set_listen_fd(silc_fsm_get_schedule(fsm), sock,
591 SILC_TASK_WRITE, FALSE);
592 SILC_FSM_EVENT_WAIT(&conn->event);
593 return SILC_FSM_CONTINUE;
596 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
597 SilcStream stream, void *context)
599 SilcNetConnect conn = context;
601 conn->stream_status = status;
602 conn->stream = stream;
603 SILC_FSM_CALL_CONTINUE(&conn->fsm);
606 SILC_FSM_STATE(silc_net_connect_st_connected)
608 SilcNetConnect conn = fsm_context;
609 SilcSchedule schedule = silc_fsm_get_schedule(fsm);
610 int opt = EINVAL, optlen = sizeof(opt), ret;
614 silc_schedule_unset_listen_fd(schedule, conn->sock);
615 silc_schedule_task_del_by_fd(schedule, conn->sock);
616 silc_fsm_next(fsm, silc_net_connect_st_finish);
617 return SILC_FSM_CONTINUE;
620 ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
623 silc_schedule_unset_listen_fd(schedule, conn->sock);
624 silc_schedule_task_del_by_fd(schedule, conn->sock);
626 if (ret != 0 || opt != 0) {
628 /** Retry connecting */
629 SILC_LOG_DEBUG(("Retry connecting"));
631 silc_net_close_connection(conn->sock);
632 silc_fsm_next(fsm, silc_net_connect_st_start);
633 return SILC_FSM_CONTINUE;
636 #if defined(ECONNREFUSED)
637 if (opt == ECONNREFUSED)
638 conn->status = SILC_NET_CONNECTION_REFUSED;
639 #endif /* ECONNREFUSED */
640 #if defined(ETIMEDOUT)
641 if (opt == ETIMEDOUT)
642 conn->status = SILC_NET_CONNECTION_TIMEOUT;
643 #endif /* ETIMEDOUT */
644 #if defined(ENETUNREACH)
645 if (opt == ENETUNREACH)
646 conn->status = SILC_NET_HOST_UNREACHABLE;
647 #endif /* ENETUNREACH */
649 /** Connecting failed */
650 SILC_LOG_DEBUG(("Connecting failed, error %s", strerror(opt)));
651 silc_fsm_next(fsm, silc_net_connect_st_finish);
652 return SILC_FSM_CONTINUE;
655 SILC_LOG_DEBUG(("TCP connection established"));
657 /** Connection created */
658 silc_fsm_next(fsm, silc_net_connect_st_stream);
659 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
660 conn->sock, TRUE, FALSE, schedule,
661 silc_net_connect_wait_stream, conn)));
664 SILC_FSM_STATE(silc_net_connect_st_stream)
666 SilcNetConnect conn = fsm_context;
670 silc_fsm_next(fsm, silc_net_connect_st_finish);
671 return SILC_FSM_CONTINUE;
674 if (conn->stream_status != SILC_SOCKET_OK) {
675 /** Stream creation failed */
676 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
677 conn->status = SILC_NET_UNKNOWN_IP;
678 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
679 conn->status = SILC_NET_UNKNOWN_HOST;
681 conn->status = SILC_NET_ERROR;
682 silc_fsm_next(fsm, silc_net_connect_st_finish);
683 return SILC_FSM_CONTINUE;
686 /** Stream created successfully */
687 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
688 conn->status = SILC_NET_OK;
689 silc_fsm_next(fsm, silc_net_connect_st_finish);
690 return SILC_FSM_CONTINUE;
693 SILC_FSM_STATE(silc_net_connect_st_finish)
695 SilcNetConnect conn = fsm_context;
697 /* Deliver error or new stream */
698 if (!conn->aborted) {
699 conn->callback(conn->status, conn->stream, conn->context);
701 silc_async_free(conn->op);
704 return SILC_FSM_FINISH;
707 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
709 SilcNetConnect conn = context;
710 conn->aborted = TRUE;
712 /* Abort underlaying stream creation too */
714 silc_async_abort(conn->sop, NULL, NULL);
719 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
720 void *destructor_context)
722 SilcNetConnect conn = fsm_context;
723 silc_free(conn->local_ip);
724 silc_free(conn->remote);
728 /* Create asynchronous TCP/IP connection. */
730 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
731 const char *remote_ip_addr,
733 SilcSchedule schedule,
734 SilcNetCallback callback,
739 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
742 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
743 remote_ip_addr, remote_port));
745 conn = silc_calloc(1, sizeof(*conn));
747 callback(SILC_NET_NO_MEMORY, NULL, context);
751 /* Start async operation */
752 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
755 callback(SILC_NET_NO_MEMORY, NULL, context);
760 conn->local_ip = strdup(local_ip_addr);
761 conn->remote = strdup(remote_ip_addr);
763 silc_async_free(conn->op);
764 silc_free(conn->local_ip);
766 callback(SILC_NET_NO_MEMORY, NULL, context);
769 conn->port = remote_port;
770 conn->callback = callback;
771 conn->context = context;
773 conn->status = SILC_NET_ERROR;
775 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
776 silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
781 /* Closes the connection by closing the socket connection. */
783 void silc_net_close_connection(int sock)
785 SILC_LOG_DEBUG(("Closing sock %d", sock));
789 /* Set's the socket to non-blocking mode. */
791 int silc_net_set_socket_nonblock(SilcSocket sock)
793 return fcntl((int)sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
796 /* Converts the IP number string from numbers-and-dots notation to
799 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
803 if (silc_net_is_ip4(addr)) {
806 ret = inet_aton(addr, &tmp);
810 memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
813 struct addrinfo hints, *ai;
820 memset(&hints, 0, sizeof(hints));
821 hints.ai_family = AF_INET6;
822 if (getaddrinfo(addr, NULL, &hints, &ai))
826 s = (SilcSockaddr *)ai->ai_addr;
827 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
832 #endif /* HAVE_IPV6 */