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_nonblock(sock);
118 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 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",
169 local_ip_addr ? local_ip_addr[i] : ipany));
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 socket to non-blocking mode */
302 silc_net_set_socket_nonblock(sock);
304 /* Set to connected state if remote address is provided. */
305 if (remote_ip_addr && remote_port) {
306 if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
309 rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
311 SILC_LOG_DEBUG(("Cannot connect UDP stream: %s", strerror(errno)));
316 /* Set send and receive buffer size */
318 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 765535);
320 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 65535);
322 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
326 #endif /* SO_SNDBUF */
328 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 765535);
330 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 65535);
332 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
336 #endif /* SO_RCVBUF */
338 /* Encapsulate into socket stream */
340 silc_socket_udp_stream_create(sock, local_ip_addr ?
341 silc_net_is_ip6(local_ip_addr) : FALSE,
342 remote_ip_addr ? TRUE : FALSE, schedule);
346 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
355 /* Receive UDP packet */
357 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
358 SilcUInt32 remote_ip_addr_size, int *remote_port,
359 unsigned char *ret_data, SilcUInt32 data_size)
361 SilcSocketStream sock = stream;
363 struct sockaddr *from;
366 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
368 if (remote_ip_addr && remote_port) {
370 from = (struct sockaddr *)&s.sin6;
371 flen = sizeof(s.sin6);
373 from = (struct sockaddr *)&s.sin;
374 flen = sizeof(s.sin);
376 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
378 len = recv(sock->sock, ret_data, data_size, 0);
381 if (errno == EAGAIN || errno == EINTR) {
382 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
383 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
384 SILC_TASK_READ, FALSE);
387 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d:%s",
388 sock->sock, strerror(errno)));
389 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
390 sock->sock_error = errno;
394 SILC_LOG_DEBUG(("Read %d bytes", len));
397 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
399 /* Return remote address */
400 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);
406 *remote_port = ntohs(s.sin.sin_port);
407 inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
408 remote_ip_addr_size);
411 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
417 /* Send UDP packet */
419 int silc_net_udp_send(SilcStream stream,
420 const char *remote_ip_addr, int remote_port,
421 const unsigned char *data, SilcUInt32 data_len)
423 SilcSocketStream sock = stream;
427 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
430 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
434 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
435 SIZEOF_SOCKADDR(remote));
437 if (errno == EAGAIN || errno == EINTR) {
438 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
439 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
440 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
443 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
444 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
445 sock->sock_error = errno;
449 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
450 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
452 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
453 SILC_TASK_READ, FALSE);
458 /******************************* TCP Stream *********************************/
460 /* Asynchronous TCP/IP connecting */
463 SilcNetStatus status;
464 SilcSocketStreamStatus stream_status;
467 SilcFSMEventStruct event;
468 SilcAsyncOperation op;
469 SilcAsyncOperation sop;
474 SilcNetCallback callback;
476 unsigned int port : 24;
477 unsigned int retry : 7;
478 unsigned int aborted : 1;
481 SILC_FSM_STATE(silc_net_connect_st_start);
482 SILC_FSM_STATE(silc_net_connect_st_connected);
483 SILC_FSM_STATE(silc_net_connect_st_stream);
484 SILC_FSM_STATE(silc_net_connect_st_finish);
486 SILC_TASK_CALLBACK(silc_net_connect_wait)
488 SilcNetConnect conn = context;
489 SILC_FSM_EVENT_SIGNAL(&conn->event);
492 SILC_FSM_STATE(silc_net_connect_st_start)
494 SilcNetConnect conn = fsm_context;
496 SilcSockaddr desthost;
497 SilcBool prefer_ipv6 = TRUE;
501 silc_fsm_next(fsm, silc_net_connect_st_finish);
502 return SILC_FSM_CONTINUE;
507 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
508 conn->ip_addr, sizeof(conn->ip_addr))) {
509 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
510 "host", conn->remote));
512 /** Network unreachable */
513 conn->status = SILC_NET_HOST_UNREACHABLE;
514 silc_fsm_next(fsm, silc_net_connect_st_finish);
515 return SILC_FSM_CONTINUE;
518 /* Set sockaddr for this connection */
519 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port)) {
520 /** Sockaddr failed */
521 silc_fsm_next(fsm, silc_net_connect_st_finish);
522 return SILC_FSM_CONTINUE;
525 /* Create the connection socket */
526 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
528 /* If address is IPv6, then fallback to IPv4 and see whether we can do
529 better with that on socket creation. */
530 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
535 /** Cannot create socket */
536 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
537 silc_fsm_next(fsm, silc_net_connect_st_finish);
538 return SILC_FSM_CONTINUE;
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 /* Set the socket to non-blocking mode */
551 silc_net_set_socket_nonblock(sock);
553 /* Connect to the host */
554 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
556 if (errno != EINPROGRESS) {
560 /* Retry using an IPv4 adress, if IPv6 didn't work */
561 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
566 /** Cannot connect to remote host */
567 SILC_LOG_ERROR(("Cannot connect to remote host: %s", strerror(errno)));
568 silc_fsm_next(fsm, silc_net_connect_st_finish);
569 return SILC_FSM_CONTINUE;
573 /* Set appropriate options */
574 #if defined(TCP_NODELAY)
575 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
577 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
579 SILC_LOG_DEBUG(("Connection operation in progress"));
583 /** Wait for connection */
584 silc_fsm_next(fsm, silc_net_connect_st_connected);
585 silc_fsm_event_init(&conn->event, fsm);
586 silc_schedule_task_add_fd(silc_fsm_get_schedule(fsm), sock,
587 silc_net_connect_wait, conn);
588 silc_schedule_set_listen_fd(silc_fsm_get_schedule(fsm), sock,
589 SILC_TASK_WRITE, FALSE);
590 SILC_FSM_EVENT_WAIT(&conn->event);
591 return SILC_FSM_CONTINUE;
594 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
595 SilcStream stream, void *context)
597 SilcNetConnect conn = context;
598 conn->stream_status = status;
599 conn->stream = stream;
600 SILC_FSM_CALL_CONTINUE(&conn->fsm);
603 SILC_FSM_STATE(silc_net_connect_st_connected)
605 SilcNetConnect conn = fsm_context;
606 SilcSchedule schedule = silc_fsm_get_schedule(fsm);
607 int opt = EINVAL, optlen = sizeof(opt), ret;
611 silc_schedule_unset_listen_fd(schedule, conn->sock);
612 silc_schedule_task_del_by_fd(schedule, conn->sock);
613 silc_fsm_next(fsm, silc_net_connect_st_finish);
614 return SILC_FSM_CONTINUE;
617 ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
620 silc_schedule_unset_listen_fd(schedule, conn->sock);
621 silc_schedule_task_del_by_fd(schedule, conn->sock);
623 if (ret != 0 || opt != 0) {
625 /** Retry connecting */
626 SILC_LOG_DEBUG(("Retry connecting"));
628 silc_net_close_connection(conn->sock);
629 silc_fsm_next(fsm, silc_net_connect_st_start);
630 return SILC_FSM_CONTINUE;
633 #if defined(ECONNREFUSED)
634 if (errno == ECONNREFUSED)
635 conn->status = SILC_NET_CONNECTION_REFUSED;
636 #endif /* ECONNREFUSED */
637 #if defined(ETIMEDOUT)
638 if (errno == ETIMEDOUT)
639 conn->status = SILC_NET_CONNECTION_TIMEOUT;
640 #endif /* ETIMEDOUT */
641 #if defined(ENETUNREACH)
642 if (errno == ENETUNREACH)
643 conn->status = SILC_NET_HOST_UNREACHABLE;
644 #endif /* ENETUNREACH */
646 /** Connecting failed */
647 SILC_LOG_DEBUG(("Connecting failed"));
648 silc_fsm_next(fsm, silc_net_connect_st_finish);
649 return SILC_FSM_CONTINUE;
652 SILC_LOG_DEBUG(("TCP connection established"));
654 /** Connection created */
655 silc_fsm_next(fsm, silc_net_connect_st_stream);
656 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
657 conn->sock, FALSE, FALSE,
659 silc_net_connect_wait_stream, conn)));
662 SILC_FSM_STATE(silc_net_connect_st_stream)
664 SilcNetConnect conn = fsm_context;
668 silc_fsm_next(fsm, silc_net_connect_st_finish);
669 return SILC_FSM_CONTINUE;
672 if (conn->stream_status != SILC_SOCKET_OK) {
673 /** Stream creation failed */
674 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
675 conn->status = SILC_NET_UNKNOWN_IP;
676 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
677 conn->status = SILC_NET_UNKNOWN_HOST;
679 conn->status = SILC_NET_ERROR;
680 silc_fsm_next(fsm, silc_net_connect_st_finish);
681 return SILC_FSM_CONTINUE;
684 /* Set stream information */
685 silc_socket_stream_set_info(conn->stream,
686 !silc_net_is_ip(conn->remote) ? conn->remote :
687 conn->ip_addr, conn->ip_addr, conn->port);
689 /** Stream created successfully */
690 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
691 conn->status = SILC_NET_OK;
692 silc_fsm_next(fsm, silc_net_connect_st_finish);
693 return SILC_FSM_CONTINUE;
696 SILC_FSM_STATE(silc_net_connect_st_finish)
698 SilcNetConnect conn = fsm_context;
700 /* Deliver error or new stream */
701 if (!conn->aborted) {
702 conn->callback(conn->status, conn->stream, conn->context);
704 silc_async_free(conn->op);
706 silc_async_free(conn->sop);
709 return SILC_FSM_FINISH;
712 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
714 SilcNetConnect conn = context;
715 conn->aborted = TRUE;
717 /* Abort underlaying stream creation too */
719 silc_async_abort(conn->sop, NULL, NULL);
722 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
723 void *destructor_context)
725 SilcNetConnect conn = fsm_context;
726 silc_free(conn->local_ip);
727 silc_free(conn->remote);
731 /* Create asynchronous TCP/IP connection. */
733 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
734 const char *remote_ip_addr,
736 SilcSchedule schedule,
737 SilcNetCallback callback,
742 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
745 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
746 remote_ip_addr, remote_port));
748 conn = silc_calloc(1, sizeof(*conn));
750 callback(SILC_NET_NO_MEMORY, NULL, context);
754 /* Start async operation */
755 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
758 callback(SILC_NET_NO_MEMORY, NULL, context);
763 conn->local_ip = strdup(local_ip_addr);
764 conn->remote = strdup(remote_ip_addr);
766 silc_async_free(conn->op);
767 silc_free(conn->local_ip);
769 callback(SILC_NET_NO_MEMORY, NULL, context);
772 conn->port = remote_port;
773 conn->callback = callback;
774 conn->context = context;
776 conn->status = SILC_NET_ERROR;
778 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
779 silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
784 /* Closes the connection by closing the socket connection. */
786 void silc_net_close_connection(int sock)
788 SILC_LOG_DEBUG(("Closing sock %d", sock));
792 /* Set's the socket to non-blocking mode. */
794 int silc_net_set_socket_nonblock(SilcSocket sock)
796 return fcntl((int)sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
799 /* Converts the IP number string from numbers-and-dots notation to
802 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
806 if (silc_net_is_ip4(addr)) {
809 ret = inet_aton(addr, &tmp);
813 memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
816 struct addrinfo hints, *ai;
823 memset(&hints, 0, sizeof(hints));
824 hints.ai_family = AF_INET6;
825 if (getaddrinfo(addr, NULL, &hints, &ai))
829 s = (SilcSockaddr *)ai->ai_addr;
830 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
835 #endif /* HAVE_IPV6 */