5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2006 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.
25 #define SIZEOF_SOCKADDR(so) ((so).sa.sa_family == AF_INET6 ? \
26 sizeof(so.sin6) : sizeof(so.sin))
28 #define SIZEOF_SOCKADDR(so) (sizeof(so.sin))
33 struct sockaddr_in sin;
35 struct sockaddr_in6 sin6;
39 static SilcBool silc_net_set_sockaddr(SilcSockaddr *addr, const char *ip_addr,
44 memset(addr, 0, sizeof(*addr));
46 /* Check for IPv4 and IPv6 addresses */
48 if (!silc_net_is_ip(ip_addr)) {
49 SILC_LOG_ERROR(("%s is not IP address", ip_addr));
53 if (silc_net_is_ip4(ip_addr)) {
55 len = sizeof(addr->sin.sin_addr);
56 silc_net_addr2bin(ip_addr,
57 (unsigned char *)&addr->sin.sin_addr.s_addr, len);
58 addr->sin.sin_family = AF_INET;
59 addr->sin.sin_port = port ? htons(port) : 0;
63 len = sizeof(addr->sin6.sin6_addr);
64 silc_net_addr2bin(ip_addr,
65 (unsigned char *)&addr->sin6.sin6_addr, len);
66 addr->sin6.sin6_family = AF_INET6;
67 addr->sin6.sin6_port = port ? htons(port) : 0;
69 SILC_LOG_ERROR(("IPv6 support is not compiled in"));
75 addr->sin.sin_family = AF_INET;
76 addr->sin.sin_addr.s_addr = INADDR_ANY;
78 addr->sin.sin_port = htons(port);
84 /* Deliver new stream to upper layer */
86 static void silc_net_accept_stream(SilcSocketStreamStatus status,
87 SilcStream stream, void *context)
89 SilcNetListener listener = context;
91 if (status != SILC_SOCKET_OK)
94 listener->callback(SILC_NET_OK, stream, listener->context);
97 /* Accept incoming connection and notify upper layer */
99 SILC_TASK_CALLBACK(silc_net_accept)
101 SilcNetListener listener = context;
104 SILC_LOG_DEBUG(("Accepting new connection"));
106 sock = silc_net_accept_connection(fd);
110 /* Set socket options */
111 silc_net_set_socket_nonblock(sock);
112 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
114 /* Create socket stream */
115 silc_socket_tcp_stream_create(sock, TRUE, listener->require_fqdn, schedule,
116 silc_net_accept_stream, listener);
119 /* Create TCP network listener */
122 silc_net_tcp_create_listener(const char **local_ip_addr,
123 SilcUInt32 local_ip_count,
124 int port, SilcBool require_fqdn,
125 SilcSchedule schedule,
126 SilcNetCallback callback, void *context)
128 SilcNetListener listener = NULL;
131 const char *ipany = "0.0.0.0";
133 SILC_LOG_DEBUG(("Creating TCP listener"));
135 if (port < 1 || !schedule || !callback)
138 listener = silc_calloc(1, sizeof(*listener));
140 callback(SILC_NET_NO_MEMORY, NULL, context);
143 listener->schedule = schedule;
144 listener->callback = callback;
145 listener->context = context;
147 if (local_ip_count > 0) {
148 listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
149 if (!listener->socks) {
150 callback(SILC_NET_NO_MEMORY, NULL, context);
154 listener->socks = silc_calloc(1, sizeof(*listener->socks));
155 if (!listener->socks) {
156 callback(SILC_NET_NO_MEMORY, NULL, context);
163 /* Bind to local addresses */
164 for (i = 0; i < local_ip_count; i++) {
165 SILC_LOG_DEBUG(("Binding to local address %s",
166 local_ip_addr ? local_ip_addr[i] : ipany));
168 /* Set sockaddr for server */
169 if (!silc_net_set_sockaddr(&server,
170 local_ip_addr ? local_ip_addr[i] : ipany,
174 /* Create the socket */
175 sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
177 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
181 /* Set the socket options */
182 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
184 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
188 /* Bind the listener socket */
189 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
191 SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
195 /* Specify that we are listenning */
196 rval = listen(sock, 5);
198 SILC_LOG_ERROR(("Cannot set socket listenning: %s", strerror(errno)));
202 /* Set the server socket to non-blocking mode */
203 silc_net_set_socket_nonblock(sock);
205 /* Schedule for incoming connections */
206 silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
208 SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
209 listener->socks[i] = sock;
210 listener->socks_count++;
217 callback(SILC_NET_ERROR, NULL, context);
219 silc_net_close_listener(listener);
223 /* Close network listener */
225 void silc_net_close_listener(SilcNetListener listener)
229 SILC_LOG_DEBUG(("Closing network listener"));
231 for (i = 0; i < listener->socks_count; i++) {
232 silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
233 shutdown(listener->socks[i], 2);
234 close(listener->socks[i]);
237 silc_free(listener->socks);
241 /* Create UDP stream */
244 silc_net_udp_connect(const char *local_ip_addr, int local_port,
245 const char *remote_ip_addr, int remote_port,
246 SilcSchedule schedule)
251 const char *ipany = "0.0.0.0";
253 SILC_LOG_DEBUG(("Creating UDP stream"));
258 /* Bind to local addresses */
259 SILC_LOG_DEBUG(("Binding to local address %s",
260 local_ip_addr ? local_ip_addr : ipany));
262 /* Set sockaddr for server */
263 if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
267 /* Create the socket */
268 sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
270 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
274 /* Set the socket options */
275 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
277 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
281 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
283 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
286 #endif /* SO_REUSEPORT */
288 /* Bind the listener socket */
289 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
291 SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
295 /* Set socket to non-blocking mode */
296 silc_net_set_socket_nonblock(sock);
298 /* Set to connected state if remote address is provided. */
299 if (remote_ip_addr && remote_port) {
300 if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
303 rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
305 SILC_LOG_DEBUG(("Cannot connect UDP stream: %s", strerror(errno)));
310 /* Set send and receive buffer size */
312 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 65535);
314 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
317 #endif /* SO_SNDBUF */
319 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 65535);
321 SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
324 #endif /* SO_RCVBUF */
326 /* Encapsulate into socket stream */
328 silc_socket_udp_stream_create(sock, local_ip_addr ?
329 silc_net_is_ip6(local_ip_addr) : FALSE,
334 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
343 /* Receive UDP packet */
345 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
346 SilcUInt32 remote_ip_addr_size, int *remote_port,
347 unsigned char *ret_data, SilcUInt32 data_size)
349 SilcSocketStream sock = stream;
351 struct sockaddr *from;
354 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
356 if (remote_ip_addr && remote_port) {
358 from = (struct sockaddr *)&s.sin6;
359 flen = sizeof(s.sin6);
361 from = (struct sockaddr *)&s.sin;
362 flen = sizeof(s.sin);
364 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
366 len = recv(sock->sock, ret_data, data_size, 0);
369 if (errno == EAGAIN || errno == EINTR) {
370 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
371 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
372 SILC_TASK_READ, FALSE);
375 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d:%s",
376 sock->sock, strerror(errno)));
377 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
378 sock->sock_error = errno;
382 SILC_LOG_DEBUG(("Read %d bytes", len));
385 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
387 /* Return remote address */
388 if (remote_ip_addr && remote_port) {
390 *remote_port = ntohs(s.sin6.sin6_port);
391 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
392 remote_ip_addr_size);
394 *remote_port = ntohs(s.sin.sin_port);
395 inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
396 remote_ip_addr_size);
403 /* Send UDP packet */
405 void silc_net_udp_send(SilcStream stream,
406 const char *remote_ip_addr, int remote_port,
407 const unsigned char *data, SilcUInt32 data_len)
409 SilcSocketStream sock = stream;
412 SILC_LOG_DEBUG(("Writing data to UDP socket %d", sock->sock));
414 /* Set sockaddr for server */
415 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
419 sendto(sock->sock, data, data_len, 0, &remote.sa, SIZEOF_SOCKADDR(remote));
422 /* Asynchronous TCP/IP connecting */
425 SilcNetStatus status;
426 SilcSocketStreamStatus stream_status;
429 SilcFSMSemaStruct sema;
430 SilcAsyncOperation op;
431 SilcAsyncOperation sop;
436 SilcNetCallback callback;
438 unsigned int port : 24;
439 unsigned int retry : 7;
440 unsigned int aborted : 1;
443 SILC_FSM_STATE(silc_net_connect_st_start);
444 SILC_FSM_STATE(silc_net_connect_st_connected);
445 SILC_FSM_STATE(silc_net_connect_st_stream);
446 SILC_FSM_STATE(silc_net_connect_st_finish);
448 SILC_TASK_CALLBACK(silc_net_connect_wait)
450 SilcNetConnect conn = context;
451 SILC_FSM_SEMA_POST(&conn->sema);
454 SILC_FSM_STATE(silc_net_connect_st_start)
456 SilcNetConnect conn = fsm_context;
458 SilcSockaddr desthost;
459 SilcBool prefer_ipv6 = TRUE;
463 silc_fsm_next(fsm, silc_net_connect_st_finish);
464 return SILC_FSM_CONTINUE;
469 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
470 conn->ip_addr, sizeof(conn->ip_addr))) {
471 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
472 "host", conn->remote));
474 /** Network unreachable */
475 conn->status = SILC_NET_HOST_UNREACHABLE;
476 silc_fsm_next(fsm, silc_net_connect_st_finish);
477 return SILC_FSM_CONTINUE;
480 /* Set sockaddr for this connection */
481 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port)) {
482 /** Sockaddr failed */
483 silc_fsm_next(fsm, silc_net_connect_st_finish);
484 return SILC_FSM_CONTINUE;
487 /* Create the connection socket */
488 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
490 /* If address is IPv6, then fallback to IPv4 and see whether we can do
491 better with that on socket creation. */
492 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
497 /** Cannot create socket */
498 SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
499 silc_fsm_next(fsm, silc_net_connect_st_finish);
500 return SILC_FSM_CONTINUE;
503 /* Bind to the local address if provided */
504 if (conn->local_ip) {
507 /* Set sockaddr for local listener, and try to bind it. */
508 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
509 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
512 /* Set the socket to non-blocking mode */
513 silc_net_set_socket_nonblock(sock);
515 /* Connect to the host */
516 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
518 if (errno != EINPROGRESS) {
519 /* retry using an IPv4 adress, if IPv6 didn't work */
520 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
531 /** Cannot connect to remote host */
532 SILC_LOG_ERROR(("Cannot connect to remote host: %s", strerror(errno)));
533 silc_fsm_next(fsm, silc_net_connect_st_finish);
534 return SILC_FSM_CONTINUE;
538 /* Set appropriate options */
539 #if defined(TCP_NODELAY)
540 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
542 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
544 SILC_LOG_DEBUG(("Connection operation in progress"));
548 /** Wait for connection */
549 silc_fsm_next(fsm, silc_net_connect_st_connected);
550 silc_fsm_sema_init(&conn->sema, fsm, 0);
551 silc_schedule_task_add_fd(silc_fsm_get_schedule(fsm), sock,
552 silc_net_connect_wait, conn);
553 silc_schedule_set_listen_fd(silc_fsm_get_schedule(fsm), sock,
554 SILC_TASK_WRITE, FALSE);
555 SILC_FSM_SEMA_WAIT(&conn->sema);
556 return SILC_FSM_CONTINUE;
559 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
560 SilcStream stream, void *context)
562 SilcNetConnect conn = context;
563 conn->stream_status = status;
564 conn->stream = stream;
565 SILC_FSM_CALL_CONTINUE(&conn->fsm);
568 SILC_FSM_STATE(silc_net_connect_st_connected)
570 SilcNetConnect conn = fsm_context;
571 SilcSchedule schedule = silc_fsm_get_schedule(fsm);
572 int opt = EINVAL, optlen = sizeof(opt), ret;
576 silc_fsm_next(fsm, silc_net_connect_st_finish);
577 return SILC_FSM_CONTINUE;
580 ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
583 silc_schedule_task_del_by_fd(schedule, conn->sock);
584 silc_schedule_unset_listen_fd(schedule, conn->sock);
586 if (ret != 0 || opt != 0) {
588 /** Retry connecting */
589 SILC_LOG_DEBUG(("Retry connecting"));
591 silc_net_close_connection(conn->sock);
592 silc_fsm_next(fsm, silc_net_connect_st_start);
593 return SILC_FSM_CONTINUE;
596 #if defined(ECONNREFUSED)
597 if (errno == ECONNREFUSED)
598 conn->status = SILC_NET_CONNECTION_REFUSED;
599 #endif /* ECONNREFUSED */
600 #if defined(ETIMEDOUT)
601 if (errno == ETIMEDOUT)
602 conn->status = SILC_NET_CONNECTION_TIMEOUT;
603 #endif /* ETIMEDOUT */
604 #if defined(ENETUNREACH)
605 if (errno == ENETUNREACH)
606 conn->status = SILC_NET_HOST_UNREACHABLE;
607 #endif /* ENETUNREACH */
609 /** Connecting failed */
610 SILC_LOG_DEBUG(("Connecting failed"));
611 silc_fsm_next(fsm, silc_net_connect_st_finish);
612 return SILC_FSM_CONTINUE;
615 /** Connection created */
616 silc_fsm_next(fsm, silc_net_connect_st_stream);
617 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
618 conn->sock, FALSE, FALSE,
620 silc_net_connect_wait_stream, conn)));
623 SILC_FSM_STATE(silc_net_connect_st_stream)
625 SilcNetConnect conn = fsm_context;
629 silc_fsm_next(fsm, silc_net_connect_st_finish);
630 return SILC_FSM_CONTINUE;
633 if (conn->stream_status != SILC_SOCKET_OK) {
634 /** Stream creation failed */
635 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
636 conn->status = SILC_NET_UNKNOWN_IP;
637 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
638 conn->status = SILC_NET_UNKNOWN_HOST;
640 conn->status = SILC_NET_ERROR;
641 silc_fsm_next(fsm, silc_net_connect_st_finish);
642 return SILC_FSM_CONTINUE;
645 /* Set stream information */
646 silc_socket_stream_set_info(conn->stream,
647 !silc_net_is_ip(conn->remote) ? conn->remote :
648 conn->ip_addr, conn->ip_addr, conn->port);
650 /** Stream created successfully */
651 SILC_LOG_DEBUG(("Connected successfully"));
652 conn->status = SILC_NET_OK;
653 silc_fsm_next(fsm, silc_net_connect_st_finish);
654 return SILC_FSM_CONTINUE;
657 SILC_FSM_STATE(silc_net_connect_st_finish)
659 SilcNetConnect conn = fsm_context;
661 /* Deliver error or new stream */
662 if (!conn->aborted) {
663 conn->callback(conn->status, conn->stream, conn->context);
665 silc_async_free(conn->op);
667 silc_async_free(conn->sop);
670 return SILC_FSM_FINISH;
673 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
675 SilcNetConnect conn = context;
676 conn->aborted = TRUE;
678 /* Abort underlaying stream creation too */
680 silc_async_abort(conn->op, NULL, NULL);
683 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
684 void *destructor_context)
686 SilcNetConnect conn = fsm_context;
687 silc_free(conn->local_ip);
688 silc_free(conn->remote);
692 /* Create asynchronous TCP/IP connection. */
694 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
695 const char *remote_ip_addr,
697 SilcSchedule schedule,
698 SilcNetCallback callback,
703 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
706 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
707 remote_ip_addr, remote_port));
709 conn = silc_calloc(1, sizeof(*conn));
711 callback(SILC_NET_NO_MEMORY, NULL, context);
715 /* Start async operation */
716 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
718 callback(SILC_NET_NO_MEMORY, NULL, context);
723 conn->local_ip = strdup(local_ip_addr);
724 conn->remote = strdup(remote_ip_addr);
726 callback(SILC_NET_NO_MEMORY, NULL, context);
729 conn->port = remote_port;
730 conn->callback = callback;
731 conn->context = context;
733 conn->status = SILC_NET_ERROR;
735 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
736 silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
741 /* Closes the connection by closing the socket connection. */
743 void silc_net_close_connection(int sock)
748 /* Set's the socket to non-blocking mode. */
750 int silc_net_set_socket_nonblock(int sock)
752 return fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
755 /* Converts the IP number string from numbers-and-dots notation to
758 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
762 if (silc_net_is_ip4(addr)) {
765 ret = inet_aton(addr, &tmp);
769 memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
772 struct addrinfo hints, *ai;
779 memset(&hints, 0, sizeof(hints));
780 hints.ai_family = AF_INET6;
781 if (getaddrinfo(addr, NULL, &hints, &ai))
785 s = (SilcSockaddr *)ai->ai_addr;
786 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
791 #endif /* HAVE_IPV6 */