5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2005, 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 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(("Operating System does not support IPv6"));
79 addr->sin.sin_family = AF_INET;
80 addr->sin.sin_addr.s_addr = INADDR_ANY;
82 addr->sin.sin_port = htons(port);
89 /****************************** TCP Listener ********************************/
91 /* Deliver new stream to upper layer */
93 static void silc_net_accept_stream(SilcSocketStreamStatus status,
94 SilcStream stream, void *context)
96 SilcNetListener listener = context;
98 if (status != SILC_SOCKET_OK)
101 listener->callback(SILC_NET_OK, stream, listener->context);
104 /* Accept incoming connection and notify upper layer */
106 SILC_TASK_CALLBACK(silc_net_accept)
108 SilcNetListener listener = context;
111 SILC_LOG_DEBUG(("Accepting new connection"));
113 sock = silc_net_accept_connection(fd);
114 if (sock == INVALID_SOCKET)
117 /* Set socket options */
118 silc_net_set_socket_nonblock(sock);
119 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
121 /* Create socket stream */
122 silc_socket_tcp_stream_create(sock, listener->lookup,
123 listener->require_fqdn, schedule,
124 silc_net_accept_stream, listener);
127 /* Create TCP network listener */
130 silc_net_tcp_create_listener(const char **local_ip_addr,
131 SilcUInt32 local_ip_count, int port,
132 SilcBool lookup, SilcBool require_fqdn,
133 SilcSchedule schedule,
134 SilcNetCallback callback, void *context)
136 SilcNetListener listener = NULL;
140 const char *ipany = "0.0.0.0";
142 SILC_LOG_DEBUG(("Creating TCP listener"));
144 if (port < 0 || !schedule || !callback)
147 listener = silc_calloc(1, sizeof(*listener));
150 listener->schedule = schedule;
151 listener->callback = callback;
152 listener->context = context;
153 listener->require_fqdn = require_fqdn;
154 listener->lookup = lookup;
156 if (local_ip_count > 0) {
157 listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
158 if (!listener->socks)
161 listener->socks = silc_calloc(1, sizeof(*listener->socks));
162 if (!listener->socks)
168 /* Bind to local addresses */
169 for (i = 0; i < local_ip_count; i++) {
170 SILC_LOG_DEBUG(("Binding to local address %s",
171 local_ip_addr ? local_ip_addr[i] : ipany));
173 /* Set sockaddr for server */
174 if (!silc_net_set_sockaddr(&server,
175 local_ip_addr ? local_ip_addr[i] : ipany,
179 /* Create the socket */
180 sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
181 if (sock == INVALID_SOCKET) {
182 SILC_LOG_ERROR(("Cannot create socket"));
186 /* Set the socket options */
187 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
188 if (rval == SOCKET_ERROR) {
189 SILC_LOG_ERROR(("Cannot set socket options"));
194 /* Bind the listener socket */
195 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
196 if (rval == SOCKET_ERROR) {
197 SILC_LOG_ERROR(("Cannot bind socket"));
202 /* Specify that we are listenning */
203 rval = listen(sock, SOMAXCONN);
204 if (rval == SOCKET_ERROR) {
205 SILC_LOG_ERROR(("Cannot set socket listenning"));
210 /* Set the server socket to non-blocking mode. Dunno if this works. */
211 silc_net_set_socket_nonblock(sock);
213 /* Schedule for incoming connections */
214 silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
216 SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
217 listener->socks[i] = sock;
218 listener->socks_count++;
225 silc_net_close_listener(listener);
229 /* Close network listener */
231 void silc_net_close_listener(SilcNetListener listener)
235 SILC_LOG_DEBUG(("Closing network listener"));
237 for (i = 0; i < listener->socks_count; i++) {
238 silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
239 shutdown(listener->socks[i], 2);
240 closesocket(listener->socks[i]);
243 silc_free(listener->socks);
247 /******************************* UDP Stream *********************************/
249 /* Create UDP stream */
252 silc_net_udp_connect(const char *local_ip_addr, int local_port,
253 const char *remote_ip_addr, int remote_port,
254 SilcSchedule schedule)
260 const char *ipany = "0.0.0.0";
262 SILC_LOG_DEBUG(("Creating UDP stream"));
267 /* Bind to local addresses */
268 SILC_LOG_DEBUG(("Binding to local address %s",
269 local_ip_addr ? local_ip_addr : ipany));
271 /* Set sockaddr for server */
272 if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
276 /* Create the socket */
277 sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
278 if (sock == INVALID_SOCKET) {
279 SILC_LOG_ERROR(("Cannot create socket"));
283 /* Set the socket options */
284 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
285 if (rval == SOCKET_ERROR) {
286 SILC_LOG_ERROR(("Cannot set socket options"));
290 rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
291 if (rval == SOCKET_ERROR) {
292 SILC_LOG_ERROR(("Cannot set socket options"));
295 #endif /* SO_REUSEPORT */
297 /* Bind the listener socket */
298 rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
299 if (rval == SOCKET_ERROR) {
300 SILC_LOG_DEBUG(("Cannot bind socket"));
304 /* Set socket to non-blocking mode */
305 silc_net_set_socket_nonblock(sock);
307 /* Set to connected state if remote address is provided. */
308 if (remote_ip_addr && remote_port) {
309 if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
312 rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
313 if (rval == SOCKET_ERROR) {
314 SILC_LOG_DEBUG(("Cannot connect UDP stream"));
319 /* Encapsulate into socket stream */
321 silc_socket_udp_stream_create(sock, local_ip_addr ?
322 silc_net_is_ip6(local_ip_addr) : FALSE,
323 remote_ip_addr ? TRUE : FALSE, schedule);
327 SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
336 /* Receive UDP packet */
338 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
339 SilcUInt32 remote_ip_addr_size, int *remote_port,
340 unsigned char *ret_data, SilcUInt32 data_size)
342 SilcSocketStream sock = stream;
344 struct sockaddr *from;
347 SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
349 if (remote_ip_addr && remote_port) {
351 from = (struct sockaddr *)&s.sin6;
352 flen = sizeof(s.sin6);
354 from = (struct sockaddr *)&s.sin;
355 flen = sizeof(s.sin);
357 len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
359 len = recv(sock->sock, ret_data, data_size, 0);
361 if (len == SOCKET_ERROR) {
362 err = WSAGetLastError();
363 if (err == WSAEWOULDBLOCK) {
364 SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
365 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
366 SILC_TASK_READ, FALSE);
369 SILC_LOG_DEBUG(("Cannot read from UDP socket: %d", sock->sock));
370 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
371 sock->sock_error = err;
375 SILC_LOG_DEBUG(("Read %d bytes", len));
378 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
380 /* Return remote address */
381 if (remote_ip_addr && remote_port) {
383 *remote_port = ntohs(s.sin6.sin6_port);
384 inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
385 remote_ip_addr_size);
387 *remote_port = ntohs(s.sin.sin_port);
388 inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
389 remote_ip_addr_size);
392 SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
398 /* Send UDP packet */
400 int silc_net_udp_send(SilcStream stream,
401 const char *remote_ip_addr, int remote_port,
402 const unsigned char *data, SilcUInt32 data_len)
404 SilcSocketStream sock = stream;
408 SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
411 if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
415 ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
416 SIZEOF_SOCKADDR(remote));
417 if (ret == SOCKET_ERROR) {
418 err = WSAGetLastError();
419 if (err == WSAEWOULDBLOCK) {
420 SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
421 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
422 SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
425 SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
426 silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
427 sock->sock_error = err;
431 SILC_LOG_DEBUG(("Sent data %d bytes", ret));
432 if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
434 silc_schedule_set_listen_fd(sock->schedule, sock->sock,
435 SILC_TASK_READ, FALSE);
441 /******************************* TCP Stream *********************************/
444 SilcNetStatus status;
445 SilcSocketStreamStatus stream_status;
448 SilcFSMThreadStruct thread;
449 SilcAsyncOperation op;
450 SilcAsyncOperation sop;
455 SilcNetCallback callback;
457 unsigned int port : 24;
458 unsigned int retry : 7;
459 unsigned int aborted : 1;
462 SILC_FSM_STATE(silc_net_connect_st_start);
463 SILC_FSM_STATE(silc_net_connect_st_stream);
464 SILC_FSM_STATE(silc_net_connect_st_finish);
466 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
467 SilcStream stream, void *context)
469 SilcNetConnect conn = context;
470 conn->stream_status = status;
471 conn->stream = stream;
472 SILC_FSM_CALL_CONTINUE(&conn->fsm);
475 /* Start connecting. Create a real thread where we connect. */
477 SILC_FSM_STATE(silc_net_connect_st_thread)
479 SilcNetConnect conn = context;
481 /* Connect in real thread as as to not block the application. */
482 silc_fsm_thread_init(&conn->thread, conn, NULL, NULL, TRUE);
483 silc_fsm_start(&conn->thread, silc_net_connect_st_start);
485 /* Wait for the thread to finish */
486 silc_fsm_next(fsm, silc_net_connect_st_finish);
487 SILC_FSM_THREAD_WAIT(&conn->thread);
490 /* Connecting thread */
492 SILC_FSM_STATE(silc_net_connect_st_start)
494 SilcNetConnect conn = fsm_context;
497 SilcSockaddr desthost;
498 SilcBool prefer_ipv6 = TRUE;
501 return SILC_FSM_FINISH;
505 if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
506 conn->ip_addr, sizeof(conn->ip_addr))) {
507 SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
508 "host", conn->remote));
510 /** Network unreachable */
511 conn->status = SILC_NET_HOST_UNREACHABLE;
512 return SILC_FSM_FINISH;
515 /* Set sockaddr for this connection */
516 if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port))
517 return SILC_FSM_FINISH;
519 /* Create the connection socket */
520 sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
521 if (sock == INVALID_SOCKET) {
522 /* If address is IPv6, then fallback to IPv4 and see whether we can do
523 better with that on socket creation. */
524 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
529 /** Cannot create socket */
530 SILC_LOG_ERROR(("Cannot create socket"));
531 return SILC_FSM_FINISH;
534 /* Bind to the local address if provided */
535 if (conn->local_ip) {
538 /* Set sockaddr for local listener, and try to bind it. */
539 if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
540 bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
543 /* Connect to the host */
544 rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
545 err = WSAGetLastError();
546 if (rval == SOCKET_ERROR) {
547 if (err != WSAEWOULDBLOCK) {
551 /* Retry using an IPv4 adress, if IPv6 didn't work */
552 if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
559 conn->status = SILC_NET_CONNECTION_TIMEOUT;
561 case WSAECONNREFUSED:
562 conn->status = SILC_NET_CONNECTION_REFUSED;
564 case WSAEHOSTUNREACH:
565 conn->status = SILC_NET_HOST_UNREACHABLE;
571 SILC_LOG_ERROR(("Cannot connect to remote host"));
572 return SILC_FSM_FINISH;
576 /* Set the socket to non-blocking mode */
577 silc_net_set_socket_nonblock(sock);
579 /* Set appropriate options */
580 #if defined(TCP_NODELAY)
581 silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
583 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
585 SILC_LOG_DEBUG(("TCP connection established"));
589 /** Connection created */
590 silc_fsm_next(fsm, silc_net_connect_st_stream);
591 SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
592 conn->sock, FALSE, FALSE,
594 silc_net_connect_wait_stream, conn)));
597 /* TCP socket stream created */
599 SILC_FSM_STATE(silc_net_connect_st_stream)
601 SilcNetConnect conn = fsm_context;
604 return SILC_FSM_FINISH;
606 if (conn->stream_status != SILC_SOCKET_OK) {
607 /** Stream creation failed */
608 if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
609 conn->status = SILC_NET_UNKNOWN_IP;
610 else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
611 conn->status = SILC_NET_UNKNOWN_HOST;
613 conn->status = SILC_NET_ERROR;
615 return SILC_FSM_FINISH;
618 /* Set stream information */
619 silc_socket_stream_set_info(conn->stream,
620 !silc_net_is_ip(conn->remote) ? conn->remote :
621 conn->ip_addr, conn->ip_addr, conn->port);
623 /** Stream created successfully */
624 SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
625 conn->status = SILC_NET_OK;
626 return SILC_FSM_FINISH;
629 SILC_FSM_STATE(silc_net_connect_st_finish)
631 SilcNetConnect conn = fsm_context;
633 /* Deliver error or new stream */
634 if (!conn->aborted) {
635 conn->callback(conn->status, conn->stream, conn->context);
637 silc_async_free(conn->op);
639 silc_async_free(conn->sop);
642 return SILC_FSM_FINISH;
645 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
647 SilcNetConnect conn = context;
648 conn->aborted = TRUE;
650 /* Abort underlaying stream creation too */
652 silc_async_abort(conn->sop, NULL, NULL);
655 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
656 void *destructor_context)
658 SilcNetConnect conn = fsm_context;
659 silc_free(conn->local_ip);
660 silc_free(conn->remote);
664 /* Create asynchronous TCP/IP connection. */
666 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
667 const char *remote_ip_addr,
669 SilcSchedule schedule,
670 SilcNetCallback callback,
675 if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
678 SILC_LOG_DEBUG(("Creating connection to host %s port %d",
679 remote_ip_addr, remote_port));
681 conn = silc_calloc(1, sizeof(*conn));
683 callback(SILC_NET_NO_MEMORY, NULL, context);
687 /* Start async operation */
688 conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
691 callback(SILC_NET_NO_MEMORY, NULL, context);
696 conn->local_ip = strdup(local_ip_addr);
697 conn->remote = strdup(remote_ip_addr);
699 silc_async_free(conn->op);
700 silc_free(conn->local_ip);
702 callback(SILC_NET_NO_MEMORY, NULL, context);
705 conn->port = remote_port;
706 conn->callback = callback;
707 conn->context = context;
709 conn->status = SILC_NET_ERROR;
711 silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
712 silc_fsm_start(&conn->fsm, silc_net_connect_st_thread);
717 /* Closes the connection by closing the socket connection. */
719 void silc_net_close_connection(int sock)
721 SILC_LOG_DEBUG(("Closing sock %d", sock));
725 /* Converts the IP number string from numbers-and-dots notation to
728 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
732 if (silc_net_is_ip4(addr)) {
734 ret = inet_addr(addr);
739 memcpy(bin, (unsigned char *)&ret, 4);
740 return ret != INADDR_NONE;
742 struct addrinfo hints, *ai;
749 memset(&hints, 0, sizeof(hints));
750 hints.ai_family = AF_INET6;
751 if (getaddrinfo(addr, NULL, &hints, &ai))
755 s = (SilcSockaddr *)ai->ai_addr;
756 memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
764 /* Set socket to non-blocking mode. */
766 int silc_net_set_socket_nonblock(int sock)
768 unsigned long on = 1;
769 return ioctlsocket(sock, FIONBIO, &on);
774 SilcBool silc_net_win32_init(void)
776 int ret, sopt = SO_SYNCHRONOUS_NONALERT;
778 WORD ver = MAKEWORD(1, 1);
780 ret = WSAStartup(ver, &wdata);
784 /* Allow using the SOCKET's as file descriptors so that we can poll
785 them with SILC Scheduler. */
786 ret = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&sopt,
794 /* Uninit Winsock2 */
796 void silc_net_win32_uninit(void)