Added SILC Thread Queue API
[silc.git] / lib / silcutil / win32 / silcwin32net.c
1 /*
2
3   silcwin32net.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2007 Pekka Riikonen
8
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.
12
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.
17
18 */
19 /* $Id$ */
20
21 #include "silc.h"
22
23 /************************** Types and definitions ***************************/
24
25 #ifdef HAVE_IPV6
26 #define SIZEOF_SOCKADDR(so) ((so).sa.sa_family == AF_INET6 ?    \
27   sizeof(so.sin6) : sizeof(so.sin))
28 #else
29 #define SIZEOF_SOCKADDR(so) (sizeof(so.sin))
30 #endif
31
32 typedef union {
33   struct sockaddr sa;
34   struct sockaddr_in sin;
35 #ifdef HAVE_IPV6
36   struct sockaddr_in6 sin6;
37 #endif
38 } SilcSockaddr;
39
40
41 /************************ Static utility functions **************************/
42
43 static SilcBool silc_net_set_sockaddr(SilcSockaddr *addr, const char *ip_addr,
44                                       int port)
45 {
46   int len;
47
48   memset(addr, 0, sizeof(*addr));
49
50   /* Check for IPv4 and IPv6 addresses */
51   if (ip_addr) {
52     if (!silc_net_is_ip(ip_addr)) {
53       SILC_LOG_ERROR(("%s is not IP address", ip_addr));
54       silc_set_errno_reason(SILC_ERR_BAD_IP, "%s is not an IP address",
55                             ip_addr);
56       return FALSE;
57     }
58
59     if (silc_net_is_ip4(ip_addr)) {
60       /* IPv4 address */
61       len = sizeof(addr->sin.sin_addr);
62       if (!silc_net_addr2bin(ip_addr,
63                              (unsigned char *)&addr->sin.sin_addr.s_addr,
64                              len))
65         return FALSE;
66       addr->sin.sin_family = AF_INET;
67       addr->sin.sin_port = port ? htons(port) : 0;
68     } else {
69 #ifdef HAVE_IPV6
70       /* IPv6 address */
71       len = sizeof(addr->sin6.sin6_addr);
72       if (!silc_net_addr2bin(ip_addr,
73                              (unsigned char *)&addr->sin6.sin6_addr, len))
74         return FALSE;
75       addr->sin6.sin6_family = AF_INET6;
76       addr->sin6.sin6_port = port ? htons(port) : 0;
77 #else
78       SILC_LOG_ERROR(("Operating System does not support IPv6"));
79       return FALSE;
80 #endif
81     }
82   } else {
83     /* Any address */
84     addr->sin.sin_family = AF_INET;
85     addr->sin.sin_addr.s_addr = INADDR_ANY;
86     if (port)
87       addr->sin.sin_port = htons(port);
88   }
89
90   return TRUE;
91 }
92
93
94 /****************************** TCP Listener ********************************/
95
96 /* Deliver new stream to upper layer */
97
98 static void silc_net_accept_stream(SilcResult status,
99                                    SilcStream stream, void *context)
100 {
101   SilcNetListener listener = context;
102
103   if (status != SILC_OK)
104     return;
105
106   listener->callback(SILC_OK, stream, listener->context);
107 }
108
109 /* Accept incoming connection and notify upper layer */
110
111 SILC_TASK_CALLBACK(silc_net_accept)
112 {
113   SilcNetListener listener = context;
114   int sock;
115
116   SILC_LOG_DEBUG(("Accepting new connection"));
117
118   sock = silc_net_accept_connection(fd);
119   if (sock == INVALID_SOCKET)
120     return;
121
122   /* Set socket options */
123   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
124
125   /* Create socket stream */
126   silc_socket_tcp_stream_create(sock, listener->lookup,
127                                 listener->require_fqdn, schedule,
128                                 silc_net_accept_stream, listener);
129 }
130
131 /* Create TCP network listener */
132
133 SilcNetListener
134 silc_net_tcp_create_listener(const char **local_ip_addr,
135                              SilcUInt32 local_ip_count, int port,
136                              SilcBool lookup, SilcBool require_fqdn,
137                              SilcSchedule schedule,
138                              SilcNetCallback callback, void *context)
139 {
140   SilcNetListener listener = NULL;
141   SOCKET sock;
142   SilcSockaddr server;
143   int i, rval;
144   const char *ipany = "0.0.0.0";
145
146   SILC_LOG_DEBUG(("Creating TCP listener"));
147
148   if (!schedule) {
149     schedule = silc_schedule_get_global();
150     if (!schedule) {
151       silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
152       goto err;
153     }
154   }
155
156   if (port < 0 || !callback) {
157     silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
158     goto err;
159   }
160
161   listener = silc_calloc(1, sizeof(*listener));
162   if (!listener)
163     return NULL;
164   listener->schedule = schedule;
165   listener->callback = callback;
166   listener->context = context;
167   listener->require_fqdn = require_fqdn;
168   listener->lookup = lookup;
169
170   if (local_ip_count > 0) {
171     listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
172     if (!listener->socks)
173       return NULL;
174   } else {
175     listener->socks = silc_calloc(1, sizeof(*listener->socks));
176     if (!listener->socks)
177       return NULL;
178
179     local_ip_count = 1;
180   }
181
182   /* Bind to local addresses */
183   for (i = 0; i < local_ip_count; i++) {
184     SILC_LOG_DEBUG(("Binding to local address %s",
185                     local_ip_addr ? local_ip_addr[i] : ipany));
186
187     /* Set sockaddr for server */
188     if (!silc_net_set_sockaddr(&server,
189                                local_ip_addr ? local_ip_addr[i] : ipany,
190                                port))
191       goto err;
192
193     /* Create the socket */
194     sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
195     if (sock == INVALID_SOCKET) {
196       silc_set_errno_posix(WSAGetLastError());
197       SILC_LOG_ERROR(("Cannot create socket, error %s",
198                       silc_errno_string(silc_errno)));
199       goto err;
200     }
201
202     /* Set the socket options */
203     rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
204     if (rval == SOCKET_ERROR) {
205       SILC_LOG_ERROR(("Cannot set socket options, error %s",
206                       silc_errno_string(silc_errno)));
207       closesocket(sock);
208       goto err;
209     }
210
211     /* Bind the listener socket */
212     rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
213     if (rval == SOCKET_ERROR) {
214       silc_set_errno_posix(WSAGetLastError());
215       SILC_LOG_ERROR(("Cannot bind socket, error %s",
216                       silc_errno_string(silc_errno)));
217       closesocket(sock);
218       goto err;
219     }
220
221     /* Specify that we are listenning */
222     rval = listen(sock, SOMAXCONN);
223     if (rval == SOCKET_ERROR) {
224       silc_set_errno_posix(WSAGetLastError());
225       SILC_LOG_ERROR(("Cannot set socket listenning, error %s",
226                       silc_errno_string(silc_errno)));
227       closesocket(sock);
228       goto err;
229     }
230
231     /* Schedule for incoming connections */
232     silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
233
234     SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
235     listener->socks[i] = sock;
236     listener->socks_count++;
237   }
238
239   return listener;
240
241  err:
242   if (listener)
243     silc_net_close_listener(listener);
244   return NULL;
245 }
246
247 /* Create TCP network, multiple ports */
248
249 SilcNetListener
250 silc_net_tcp_create_listener2(const char *local_ip_addr, int *ports,
251                               SilcUInt32 port_count,
252                               SilcBool ignore_port_error,
253                               SilcBool lookup, SilcBool require_fqdn,
254                               SilcSchedule schedule,
255                               SilcNetCallback callback, void *context)
256 {
257   SilcNetListener listener = NULL;
258   SOCKET sock;
259   SilcSockaddr server;
260   int i, rval;
261   const char *ipany = "0.0.0.0";
262
263   SILC_LOG_DEBUG(("Creating TCP listener"));
264
265   if (!schedule) {
266     schedule = silc_schedule_get_global();
267     if (!schedule) {
268       silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
269       goto err;
270     }
271   }
272
273   if (!callback) {
274     silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
275     goto err;
276   }
277
278   listener = silc_calloc(1, sizeof(*listener));
279   if (!listener)
280     return NULL;
281   listener->schedule = schedule;
282   listener->callback = callback;
283   listener->context = context;
284   listener->require_fqdn = require_fqdn;
285   listener->lookup = lookup;
286
287   if (port_count > 0) {
288     listener->socks = silc_calloc(port_count, sizeof(*listener->socks));
289     if (!listener->socks)
290       return NULL;
291   } else {
292     listener->socks = silc_calloc(1, sizeof(*listener->socks));
293     if (!listener->socks)
294       return NULL;
295
296     port_count = 1;
297   }
298
299   /* Bind to local addresses */
300   for (i = 0; i < local_ip_count; i++) {
301     SILC_LOG_DEBUG(("Binding to local address %s:%d",
302                     local_ip_addr ? local_ip_addr : ipany,
303                     ports ? ports[i] : 0));
304
305     /* Set sockaddr for server */
306     if (!silc_net_set_sockaddr(&server,
307                                local_ip_addr ? local_ip_addr : ipany,
308                                ports ? ports[i] : 0)) {
309       if (ignore_port_error)
310         continue;
311       goto err;
312     }
313
314     /* Create the socket */
315     sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
316     if (sock == INVALID_SOCKET) {
317       if (ignore_port_error)
318         continue;
319       silc_set_errno_posix(WSAGetLastError());
320       SILC_LOG_ERROR(("Cannot create socket, error %s",
321                       silc_errno_string(silc_errno)));
322       goto err;
323     }
324
325     /* Set the socket options */
326     rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
327     if (rval == SOCKET_ERROR) {
328       closesocket(sock);
329       if (ignore_port_error)
330         continue;
331       SILC_LOG_ERROR(("Cannot set socket options, error %s",
332                       silc_errno_string(silc_errno)));
333       goto err;
334     }
335
336     /* Bind the listener socket */
337     rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
338     if (rval == SOCKET_ERROR) {
339       closesocket(sock);
340       if (ignore_port_error)
341         continue;
342       silc_set_errno_posix(WSAGetLastError());
343       SILC_LOG_ERROR(("Cannot bind socket, error %s",
344                       silc_errno_string(silc_errno)));
345       goto err;
346     }
347
348     /* Specify that we are listenning */
349     rval = listen(sock, SOMAXCONN);
350     if (rval == SOCKET_ERROR) {
351       closesocket(sock);
352       if (ignore_port_error)
353         continue;
354       silc_set_errno_posix(WSAGetLastError());
355       SILC_LOG_ERROR(("Cannot set socket listenning, error %s",
356                       silc_errno_string(silc_errno)));
357       goto err;
358     }
359
360     /* Schedule for incoming connections */
361     silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
362
363     SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
364     listener->socks[i] = sock;
365     listener->socks_count++;
366   }
367
368   if (ignore_port_error && !listener->socks_count)
369     goto err;
370
371   return listener;
372
373  err:
374   if (listener)
375     silc_net_close_listener(listener);
376   return NULL;
377 }
378
379 /* Close network listener */
380
381 void silc_net_close_listener(SilcNetListener listener)
382 {
383   int i;
384
385   SILC_LOG_DEBUG(("Closing network listener"));
386
387   if (!listener)
388     return;
389
390   for (i = 0; i < listener->socks_count; i++) {
391     silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
392     shutdown(listener->socks[i], 2);
393     closesocket(listener->socks[i]);
394   }
395
396   silc_free(listener->socks);
397   silc_free(listener);
398 }
399
400 /******************************* UDP Stream *********************************/
401
402 /* Create UDP stream */
403
404 SilcStream
405 silc_net_udp_connect(const char *local_ip_addr, int local_port,
406                      const char *remote_ip_addr, int remote_port,
407                      SilcSchedule schedule)
408 {
409   SilcStream stream;
410   SilcSockaddr server;
411   SOCKET sock;
412   int rval;
413   const char *ipany = "0.0.0.0";
414
415   SILC_LOG_DEBUG(("Creating UDP stream"));
416
417   if (!schedule) {
418     schedule = silc_schedule_get_global();
419     if (!schedule) {
420       silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
421       goto err;
422     }
423   }
424
425   /* Bind to local addresses */
426   SILC_LOG_DEBUG(("Binding to local address %s",
427                   local_ip_addr ? local_ip_addr : ipany));
428
429   /* Set sockaddr for server */
430   if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
431                              local_port))
432     goto err;
433
434   /* Create the socket */
435   sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
436   if (sock == INVALID_SOCKET) {
437     SILC_LOG_ERROR(("Cannot create socket"));
438     silc_set_errno_posix(WSAGetLastError());
439     goto err;
440   }
441
442   /* Set the socket options */
443   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
444   if (rval == SOCKET_ERROR) {
445     SILC_LOG_ERROR(("Cannot set socket options"));
446     goto err;
447   }
448 #ifdef SO_REUSEPORT
449   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
450   if (rval == SOCKET_ERROR) {
451     SILC_LOG_ERROR(("Cannot set socket options"));
452     goto err;
453   }
454 #endif /* SO_REUSEPORT */
455
456   /* Bind the listener socket */
457   rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
458   if (rval == SOCKET_ERROR) {
459     SILC_LOG_DEBUG(("Cannot bind socket"));
460     silc_set_errno_posix(WSAGetLastError());
461     goto err;
462   }
463
464   /* Set to connected state if remote address is provided. */
465   if (remote_ip_addr && remote_port) {
466     if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
467       goto err;
468
469     rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
470     if (rval == SOCKET_ERROR) {
471       SILC_LOG_DEBUG(("Cannot connect UDP stream"));
472       silc_set_errno_posix(WSAGetLastError());
473       goto err;
474     }
475   }
476
477   /* Encapsulate into socket stream */
478   stream =
479     silc_socket_udp_stream_create(sock, local_ip_addr ?
480                                   silc_net_is_ip6(local_ip_addr) : FALSE,
481                                   remote_ip_addr ? TRUE : FALSE, schedule);
482   if (!stream)
483     goto err;
484
485   SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
486   return stream;
487
488  err:
489   if (sock != -1)
490     close(sock);
491   return NULL;
492 }
493
494 /* Receive UDP packet */
495
496 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
497                          SilcUInt32 remote_ip_addr_size, int *remote_port,
498                          unsigned char *ret_data, SilcUInt32 data_size)
499 {
500   SilcSocketStream sock = stream;
501   SilcSockaddr s;
502   struct sockaddr *from;
503   int len, flen, err;
504
505   SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
506
507   if (remote_ip_addr && remote_port) {
508     if (sock->ipv6) {
509 #ifdef HAVE_IPV6
510       from = (struct sockaddr *)&s.sin6;
511       flen = sizeof(s.sin6);
512 #endif /* HAVE_IPV6 */
513     } else {
514       from = (struct sockaddr *)&s.sin;
515       flen = sizeof(s.sin);
516     }
517     len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
518   } else
519     len = recv(sock->sock, ret_data, data_size, 0);
520
521   if (len == SOCKET_ERROR) {
522     err = WSAGetLastError();
523     silc_set_errno_posix(err);
524     if (err == WSAEWOULDBLOCK) {
525       SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
526       silc_schedule_set_listen_fd(sock->schedule, sock->sock,
527                                   SILC_TASK_READ, FALSE);
528       return -1;
529     }
530     SILC_LOG_DEBUG(("Cannot read from UDP socket: %d: %s", sock->sock,
531                     silc_errno_string(silc_errno)));
532     silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
533     return -2;
534   }
535
536   SILC_LOG_DEBUG(("Read %d bytes", len));
537
538   if (!len)
539     silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
540
541   /* Return remote address */
542   if (remote_ip_addr && remote_port) {
543     if (sock->ipv6) {
544 #ifdef HAVE_IPV6
545       *remote_port = ntohs(s.sin6.sin6_port);
546       inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
547                 remote_ip_addr_size);
548 #endif /* HAVE_IPV6 */
549     } else {
550       const char *ip = inet_ntoa(s.sin.sin_addr);
551       if (ip)
552         silc_snprintf(remote_ip_addr, remote_ip_addr_size, ip);
553       *remote_port = ntohs(s.sin.sin_port);
554     }
555
556     SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
557   }
558
559   return len;
560 }
561
562 /* Send UDP packet */
563
564 int silc_net_udp_send(SilcStream stream,
565                       const char *remote_ip_addr, int remote_port,
566                       const unsigned char *data, SilcUInt32 data_len)
567 {
568   SilcSocketStream sock = stream;
569   SilcSockaddr remote;
570   int ret, err;
571
572   SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
573
574   /* Set sockaddr */
575   if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
576     return -2;
577
578   /* Send */
579   ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
580                SIZEOF_SOCKADDR(remote));
581   if (ret == SOCKET_ERROR) {
582     err = WSAGetLastError();
583     silc_set_errno_posix(err);
584     if (err == WSAEWOULDBLOCK) {
585       SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
586       silc_schedule_set_listen_fd(sock->schedule, sock->sock,
587                                   SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
588       return -1;
589     }
590     SILC_LOG_DEBUG(("Cannot send to UDP socket: %s",
591                     silc_errno_string(silc_errno)));
592     silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
593     return -2;
594   }
595
596   SILC_LOG_DEBUG(("Sent data %d bytes", ret));
597   if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
598       SILC_TASK_WRITE)
599     silc_schedule_set_listen_fd(sock->schedule, sock->sock,
600                                 SILC_TASK_READ, FALSE);
601
602   return ret;
603 }
604
605
606 /******************************* TCP Stream *********************************/
607
608 typedef struct {
609   SilcResult status;
610   SilcStream stream;
611   SilcFSMStruct fsm;
612   SilcFSMThreadStruct thread;
613   SilcAsyncOperation op;
614   SilcAsyncOperation sop;
615   char *local_ip;
616   char *remote;
617   char ip_addr[64];
618   int sock;
619   SilcNetCallback callback;
620   void *context;
621   unsigned int port     : 24;
622   unsigned int retry    : 7;
623   unsigned int aborted  : 1;
624 } *SilcNetConnect;
625
626 SILC_FSM_STATE(silc_net_connect_st_start);
627 SILC_FSM_STATE(silc_net_connect_st_stream);
628 SILC_FSM_STATE(silc_net_connect_st_finish);
629
630 static void silc_net_connect_wait_stream(SilcResult status,
631                                          SilcStream stream, void *context)
632 {
633   SilcNetConnect conn = context;
634   conn->sop = NULL;
635   conn->status = status;
636   conn->stream = stream;
637   SILC_FSM_CALL_CONTINUE(&conn->thread);
638 }
639
640 /* Start connecting.  Create a real thread where we connect. */
641
642 SILC_FSM_STATE(silc_net_connect_st_thread)
643 {
644   SilcNetConnect conn = fsm_context;
645
646   /* Connect in real thread so as to not block the application. */
647   silc_fsm_thread_init(&conn->thread, fsm, conn, NULL, NULL, TRUE);
648   silc_fsm_start(&conn->thread, silc_net_connect_st_start);
649
650   /* Wait for the thread to finish */
651   silc_fsm_next(fsm, silc_net_connect_st_finish);
652   SILC_FSM_THREAD_WAIT(&conn->thread);
653 }
654
655 /* Connecting thread */
656
657 SILC_FSM_STATE(silc_net_connect_st_start)
658 {
659   SilcNetConnect conn = fsm_context;
660   SOCKET sock;
661   int rval, err;
662   SilcSockaddr desthost;
663   SilcBool prefer_ipv6 = TRUE;
664
665   if (conn->aborted)
666     return SILC_FSM_FINISH;
667
668   /* Do host lookup */
669  retry:
670   if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
671                               conn->ip_addr, sizeof(conn->ip_addr))) {
672     SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
673                     "host, error %d", conn->remote, WSAGetLastError()));
674
675     /** Network unreachable */
676     conn->status = SILC_ERR_UNREACHABLE;
677     return SILC_FSM_FINISH;
678   }
679
680   /* Set sockaddr for this connection */
681   if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port))
682     return SILC_FSM_FINISH;
683
684   /* Create the connection socket */
685   sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
686   if (sock == INVALID_SOCKET) {
687     /* If address is IPv6, then fallback to IPv4 and see whether we can do
688        better with that on socket creation. */
689     if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
690       prefer_ipv6 = FALSE;
691       goto retry;
692     }
693
694     /** Cannot create socket */
695     silc_set_errno_posix(err);
696     SILC_LOG_ERROR(("Cannot create socket, error %d",
697                     silc_errno_string(silc_errno)));
698     return SILC_FSM_FINISH;
699   }
700
701   /* Bind to the local address if provided */
702   if (conn->local_ip) {
703     SilcSockaddr local;
704
705     /* Set sockaddr for local listener, and try to bind it. */
706     if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
707       bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
708   }
709
710   /* Connect to the host */
711   rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
712   err = WSAGetLastError();
713   if (rval == SOCKET_ERROR) {
714     if (err != WSAEWOULDBLOCK) {
715       shutdown(sock, 2);
716       closesocket(sock);
717
718       /* Retry using an IPv4 address, if IPv6 didn't work */
719       if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
720         prefer_ipv6 = FALSE;
721         goto retry;
722       }
723
724       /* Set error */
725       silc_set_errno_posix(err);
726       conn->status = silc_errno;
727
728       SILC_LOG_ERROR(("Cannot connect to remote host: %s",
729                       silc_errno_string(silc_errno)));
730       return SILC_FSM_FINISH;
731     }
732   }
733
734   /* Set the socket to non-blocking mode */
735   silc_net_set_socket_nonblock(sock);
736
737   /* Set appropriate options */
738 #if defined(TCP_NODELAY)
739   silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
740 #endif
741   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
742
743   SILC_LOG_DEBUG(("TCP connection established"));
744
745   conn->sock = sock;
746
747   /** Connection created */
748   silc_fsm_next(fsm, silc_net_connect_st_stream);
749   SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
750                                      conn->sock, TRUE, FALSE,
751                                      silc_fsm_get_schedule(&conn->fsm),
752                                      silc_net_connect_wait_stream, conn)));
753 }
754
755 /* TCP socket stream created */
756
757 SILC_FSM_STATE(silc_net_connect_st_stream)
758 {
759   SilcNetConnect conn = fsm_context;
760
761   if (conn->aborted)
762     return SILC_FSM_FINISH;
763
764   if (conn->status != SILC_OK) {
765     /** Stream creation failed */
766     return SILC_FSM_FINISH;
767   }
768
769   /** Stream created successfully */
770   SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
771   conn->status = SILC_OK;
772   return SILC_FSM_FINISH;
773 }
774
775 SILC_FSM_STATE(silc_net_connect_st_finish)
776 {
777   SilcNetConnect conn = fsm_context;
778
779   /* Deliver error or new stream */
780   if (!conn->aborted) {
781     conn->callback(conn->status, conn->stream, conn->context);
782     if (conn->op)
783       silc_async_free(conn->op);
784   }
785
786   return SILC_FSM_FINISH;
787 }
788
789 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
790 {
791   SilcNetConnect conn = context;
792   conn->aborted = TRUE;
793
794   /* Abort underlaying stream creation too */
795   if (conn->sop) {
796     silc_async_abort(conn->sop, NULL, NULL);
797     conn->sop = NULL;
798   }
799 }
800
801 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
802                                         void *destructor_context)
803 {
804   SilcNetConnect conn = fsm_context;
805   silc_free(conn->local_ip);
806   silc_free(conn->remote);
807   silc_free(conn);
808 }
809
810 /* Create asynchronous TCP/IP connection. */
811
812 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
813                                         const char *remote_ip_addr,
814                                         int remote_port,
815                                         SilcSchedule schedule,
816                                         SilcNetCallback callback,
817                                         void *context)
818 {
819   SilcNetConnect conn;
820
821   if (!schedule) {
822     schedule = silc_schedule_get_global();
823     if (!schedule) {
824       silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
825       return NULL;
826     }
827   }
828
829   if (!remote_ip_addr || remote_port < 1 || !callback) {
830     silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
831     return NULL;
832   }
833
834   SILC_LOG_DEBUG(("Creating connection to host %s port %d",
835                   remote_ip_addr, remote_port));
836
837   conn = silc_calloc(1, sizeof(*conn));
838   if (!conn) {
839     callback(SILC_ERR_OUT_OF_MEMORY, NULL, context);
840     return NULL;
841   }
842
843   /* Start async operation */
844   conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
845   if (!conn->op) {
846     silc_free(conn);
847     callback(SILC_ERR_OUT_OF_MEMORY, NULL, context);
848     return NULL;
849   }
850
851   if (local_ip_addr)
852     conn->local_ip = silc_strdup(local_ip_addr);
853   conn->remote = silc_strdup(remote_ip_addr);
854   if (!conn->remote) {
855     silc_async_free(conn->op);
856     silc_free(conn->local_ip);
857     silc_free(conn);
858     callback(SILC_ERR_OUT_OF_MEMORY, NULL, context);
859     return NULL;
860   }
861   conn->port = remote_port;
862   conn->callback = callback;
863   conn->context = context;
864   conn->retry = 1;
865   conn->status = SILC_ERR;
866
867   silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
868   silc_fsm_start(&conn->fsm, silc_net_connect_st_thread);
869
870   return conn->op;
871 }
872
873 /* Closes the connection by closing the socket connection. */
874
875 void silc_net_close_connection(int sock)
876 {
877   SILC_LOG_DEBUG(("Closing sock %d", sock));
878   closesocket(sock);
879 }
880
881 /* Converts the IP number string from numbers-and-dots notation to
882    binary form. */
883
884 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
885 {
886   if (silc_net_is_ip4(addr)) {
887     /* IPv4 address */
888     int i = 0, c = 0, d = 0, len = strlen(addr);
889     unsigned char ret[4];
890
891     memset(ret, 0, sizeof(ret));
892     while (len-- > 0) {
893       if (addr[i++] == '.') {
894         ret[c++] = d;
895         d = 0;
896         if (c > 3)
897           goto err;
898         continue;
899       }
900
901       if (!isdigit((int)addr[i - 1]))
902         goto err;
903
904       d = 10 * d + addr[i - 1] - '0';
905       if (d > 255)
906         goto err;
907     }
908     if (c != 3)
909       goto err;
910     ret[c] = d;
911
912     if (bin_len < sizeof(ret)) {
913       silc_set_errno(SILC_ERR_OVERFLOW);
914       return FALSE;
915     }
916
917     memcpy(bin, ret, sizeof(ret));
918     return TRUE;
919
920     err:
921     return FALSE;
922   } else {
923 #ifdef HAVE_IPV6
924     struct addrinfo hints, *ai;
925     SilcSockaddr *s;
926
927     /* IPv6 address */
928     if (bin_len < 16) {
929       silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
930       return FALSE;
931     }
932
933     memset(&hints, 0, sizeof(hints));
934     hints.ai_family = AF_INET6;
935     if (getaddrinfo(addr, NULL, &hints, &ai))
936       return FALSE;
937
938     if (ai) {
939       s = (SilcSockaddr *)ai->ai_addr;
940       memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
941       freeaddrinfo(ai);
942     }
943
944     return TRUE;
945 #else
946     return FALSE;
947 #endif /* HAVE_IPV6 */
948   }
949 }
950
951 /* Set socket to non-blocking mode. */
952
953 int silc_net_set_socket_nonblock(SilcSocket sock)
954 {
955   unsigned long on = 1;
956   return ioctlsocket(sock, FIONBIO, &on);
957 }