Ported SILC Net API (TCP & UDP), SILC Socket Stream 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 - 2005, 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       return FALSE;
55     }
56
57     if (silc_net_is_ip4(ip_addr)) {
58       /* IPv4 address */
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;
64     } else {
65 #ifdef HAVE_IPV6
66       /* IPv6 address */
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;
72 #else
73       SILC_LOG_ERROR(("Operating System does not support IPv6"));
74       return FALSE;
75 #endif
76     }
77   } else {
78     /* Any address */
79     addr->sin.sin_family = AF_INET;
80     addr->sin.sin_addr.s_addr = INADDR_ANY;
81     if (port)
82       addr->sin.sin_port = htons(port);
83   }
84
85   return TRUE;
86 }
87
88
89 /****************************** TCP Listener ********************************/
90
91 /* Deliver new stream to upper layer */
92
93 static void silc_net_accept_stream(SilcSocketStreamStatus status,
94                                    SilcStream stream, void *context)
95 {
96   SilcNetListener listener = context;
97
98   if (status != SILC_SOCKET_OK)
99     return;
100
101   listener->callback(SILC_NET_OK, stream, listener->context);
102 }
103
104 /* Accept incoming connection and notify upper layer */
105
106 SILC_TASK_CALLBACK(silc_net_accept)
107 {
108   SilcNetListener listener = context;
109   int sock;
110
111   SILC_LOG_DEBUG(("Accepting new connection"));
112
113   sock = silc_net_accept_connection(fd);
114   if (sock == INVALID_SOCKET)
115     return;
116
117   /* Set socket options */
118   silc_net_set_socket_nonblock(sock);
119   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
120
121   /* Create socket stream */
122   silc_socket_tcp_stream_create(sock, listener->lookup,
123                                 listener->require_fqdn, schedule,
124                                 silc_net_accept_stream, listener);
125 }
126
127 /* Create TCP network listener */
128
129 SilcNetListener
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)
135 {
136   SilcNetListener listener = NULL;
137   SOCKET sock;
138   SilcSockaddr server;
139   int i, sock, rval;
140   const char *ipany = "0.0.0.0";
141
142   SILC_LOG_DEBUG(("Creating TCP listener"));
143
144   if (port < 0 || !schedule || !callback)
145     goto err;
146
147   listener = silc_calloc(1, sizeof(*listener));
148   if (!listener)
149     return NULL;
150   listener->schedule = schedule;
151   listener->callback = callback;
152   listener->context = context;
153   listener->require_fqdn = require_fqdn;
154   listener->lookup = lookup;
155
156   if (local_ip_count > 0) {
157     listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
158     if (!listener->socks)
159       return NULL;
160   } else {
161     listener->socks = silc_calloc(1, sizeof(*listener->socks));
162     if (!listener->socks)
163       return NULL;
164
165     local_ip_count = 1;
166   }
167
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));
172
173     /* Set sockaddr for server */
174     if (!silc_net_set_sockaddr(&server,
175                                local_ip_addr ? local_ip_addr[i] : ipany,
176                                port))
177       goto err;
178
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"));
183       goto err;
184     }
185
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"));
190       closesocket(sock);
191       goto err;
192     }
193
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"));
198       closesocket(sock);
199       goto err;
200     }
201
202     /* Specify that we are listenning */
203     rval = listen(sock, SOMAXCONN);
204     if (rval == SOCKET_ERROR) {
205       SILC_LOG_ERROR(("Cannot set socket listenning"));
206       closesocket(sock);
207       goto err;
208     }
209
210     /* Set the server socket to non-blocking mode.  Dunno if this works. */
211     silc_net_set_socket_nonblock(sock);
212
213     /* Schedule for incoming connections */
214     silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
215
216     SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
217     listener->socks[i] = sock;
218     listener->socks_count++;
219   }
220
221   return listener;
222
223  err:
224   if (listener)
225     silc_net_close_listener(listener);
226   return NULL;
227 }
228
229 /* Close network listener */
230
231 void silc_net_close_listener(SilcNetListener listener)
232 {
233   int i;
234
235   SILC_LOG_DEBUG(("Closing network listener"));
236
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]);
241   }
242
243   silc_free(listener->socks);
244   silc_free(listener);
245 }
246
247 /******************************* UDP Stream *********************************/
248
249 /* Create UDP stream */
250
251 SilcStream
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)
255 {
256   SilcStream stream;
257   SilcSockaddr server;
258   SOCKET sock;
259   int rval;
260   const char *ipany = "0.0.0.0";
261
262   SILC_LOG_DEBUG(("Creating UDP stream"));
263
264   if (!schedule)
265     goto err;
266
267   /* Bind to local addresses */
268   SILC_LOG_DEBUG(("Binding to local address %s",
269                   local_ip_addr ? local_ip_addr : ipany));
270
271   /* Set sockaddr for server */
272   if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
273                              local_port))
274     goto err;
275
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"));
280     goto err;
281   }
282
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"));
287     goto err;
288   }
289 #ifdef SO_REUSEPORT
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"));
293     goto err;
294   }
295 #endif /* SO_REUSEPORT */
296
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"));
301     goto err;
302   }
303
304   /* Set socket to non-blocking mode */
305   silc_net_set_socket_nonblock(sock);
306
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))
310       goto err;
311
312     rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
313     if (rval == SOCKET_ERROR) {
314       SILC_LOG_DEBUG(("Cannot connect UDP stream"));
315       goto err;
316     }
317   }
318
319   /* Encapsulate into socket stream */
320   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);
324   if (!stream)
325     goto err;
326
327   SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
328   return stream;
329
330  err:
331   if (sock != -1)
332     close(sock);
333   return NULL;
334 }
335
336 /* Receive UDP packet */
337
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)
341 {
342   SilcSocketStream sock = stream;
343   SilcSockaddr s;
344   struct sockaddr *from;
345   int len, flen, err;
346
347   SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
348
349   if (remote_ip_addr && remote_port) {
350     if (sock->ipv6) {
351       from = (struct sockaddr *)&s.sin6;
352       flen = sizeof(s.sin6);
353     } else {
354       from = (struct sockaddr *)&s.sin;
355       flen = sizeof(s.sin);
356     }
357     len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
358   } else
359     len = recv(sock->sock, ret_data, data_size, 0);
360
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);
367       return -1;
368     }
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;
372     return -2;
373   }
374
375   SILC_LOG_DEBUG(("Read %d bytes", len));
376
377   if (!len)
378     silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
379
380   /* Return remote address */
381   if (remote_ip_addr && remote_port) {
382     if (sock->ipv6) {
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);
386     } else {
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);
390     }
391
392     SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
393   }
394
395   return len;
396 }
397
398 /* Send UDP packet */
399
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)
403 {
404   SilcSocketStream sock = stream;
405   SilcSockaddr remote;
406   int ret, err;
407
408   SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
409
410   /* Set sockaddr */
411   if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
412     return -2;
413
414   /* Send */
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);
423       return -1;
424     }
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;
428     return -2;
429   }
430
431   SILC_LOG_DEBUG(("Sent data %d bytes", ret));
432   if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
433       SILC_TASK_WRITE)
434     silc_schedule_set_listen_fd(sock->schedule, sock->sock,
435                                 SILC_TASK_READ, FALSE);
436
437   return ret;
438 }
439
440
441 /******************************* TCP Stream *********************************/
442
443 typedef struct {
444   SilcNetStatus status;
445   SilcSocketStreamStatus stream_status;
446   SilcStream stream;
447   SilcFSMStruct fsm;
448   SilcFSMThreadStruct thread;
449   SilcAsyncOperation op;
450   SilcAsyncOperation sop;
451   char *local_ip;
452   char *remote;
453   char ip_addr[64];
454   int sock;
455   SilcNetCallback callback;
456   void *context;
457   unsigned int port     : 24;
458   unsigned int retry    : 7;
459   unsigned int aborted  : 1;
460 } *SilcNetConnect;
461
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);
465
466 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
467                                          SilcStream stream, void *context)
468 {
469   SilcNetConnect conn = context;
470   conn->stream_status = status;
471   conn->stream = stream;
472   SILC_FSM_CALL_CONTINUE(&conn->fsm);
473 }
474
475 /* Start connecting.  Create a real thread where we connect. */
476
477 SILC_FSM_STATE(silc_net_connect_st_thread)
478 {
479   SilcNetConnect conn = context;
480
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);
484
485   /* Wait for the thread to finish */
486   silc_fsm_next(fsm, silc_net_connect_st_finish);
487   SILC_FSM_THREAD_WAIT(&conn->thread);
488 }
489
490 /* Connecting thread */
491
492 SILC_FSM_STATE(silc_net_connect_st_start)
493 {
494   SilcNetConnect conn = fsm_context;
495   SOCKET sock;
496   int rval, err;
497   SilcSockaddr desthost;
498   SilcBool prefer_ipv6 = TRUE;
499
500   if (conn->aborted)
501     return SILC_FSM_FINISH;
502
503   /* Do host lookup */
504  retry:
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));
509
510     /** Network unreachable */
511     conn->status = SILC_NET_HOST_UNREACHABLE;
512     return SILC_FSM_FINISH;
513   }
514
515   /* Set sockaddr for this connection */
516   if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port))
517     return SILC_FSM_FINISH;
518
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)) {
525       prefer_ipv6 = FALSE;
526       goto retry;
527     }
528
529     /** Cannot create socket */
530     SILC_LOG_ERROR(("Cannot create socket"));
531     return SILC_FSM_FINISH;
532   }
533
534   /* Bind to the local address if provided */
535   if (conn->local_ip) {
536     SilcSockaddr local;
537
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));
541   }
542
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) {
548       shutdown(sock, 2);
549       closesocket(sock);
550
551       /* Retry using an IPv4 adress, if IPv6 didn't work */
552       if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
553         prefer_ipv6 = FALSE;
554         goto retry;
555       }
556
557       switch (err) {
558       case WSAETIMEDOUT:
559         conn->status = SILC_NET_CONNECTION_TIMEOUT;
560         break;
561       case WSAECONNREFUSED:
562         conn->status = SILC_NET_CONNECTION_REFUSED;
563         break;
564       case WSAEHOSTUNREACH:
565         conn->status = SILC_NET_HOST_UNREACHABLE;
566         break;
567       default:
568         break;
569       }
570
571       SILC_LOG_ERROR(("Cannot connect to remote host"));
572       return SILC_FSM_FINISH;
573     }
574   }
575
576   /* Set the socket to non-blocking mode */
577   silc_net_set_socket_nonblock(sock);
578
579   /* Set appropriate options */
580 #if defined(TCP_NODELAY)
581   silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
582 #endif
583   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
584
585   SILC_LOG_DEBUG(("TCP connection established"));
586
587   conn->sock = sock;
588
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,
593                                      schedule,
594                                      silc_net_connect_wait_stream, conn)));
595 }
596
597 /* TCP socket stream created */
598
599 SILC_FSM_STATE(silc_net_connect_st_stream)
600 {
601   SilcNetConnect conn = fsm_context;
602
603   if (conn->aborted)
604     return SILC_FSM_FINISH;
605
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;
612     else
613       conn->status = SILC_NET_ERROR;
614
615     return SILC_FSM_FINISH;
616   }
617
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);
622
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;
627 }
628
629 SILC_FSM_STATE(silc_net_connect_st_finish)
630 {
631   SilcNetConnect conn = fsm_context;
632
633   /* Deliver error or new stream */
634   if (!conn->aborted) {
635     conn->callback(conn->status, conn->stream, conn->context);
636     if (conn->op)
637       silc_async_free(conn->op);
638     if (conn->sop)
639       silc_async_free(conn->sop);
640   }
641
642   return SILC_FSM_FINISH;
643 }
644
645 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
646 {
647   SilcNetConnect conn = context;
648   conn->aborted = TRUE;
649
650   /* Abort underlaying stream creation too */
651   if (conn->sop)
652     silc_async_abort(conn->sop, NULL, NULL);
653 }
654
655 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
656                                         void *destructor_context)
657 {
658   SilcNetConnect conn = fsm_context;
659   silc_free(conn->local_ip);
660   silc_free(conn->remote);
661   silc_free(conn);
662 }
663
664 /* Create asynchronous TCP/IP connection. */
665
666 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
667                                         const char *remote_ip_addr,
668                                         int remote_port,
669                                         SilcSchedule schedule,
670                                         SilcNetCallback callback,
671                                         void *context)
672 {
673   SilcNetConnect conn;
674
675   if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
676     return NULL;
677
678   SILC_LOG_DEBUG(("Creating connection to host %s port %d",
679                   remote_ip_addr, remote_port));
680
681   conn = silc_calloc(1, sizeof(*conn));
682   if (!conn) {
683     callback(SILC_NET_NO_MEMORY, NULL, context);
684     return NULL;
685   }
686
687   /* Start async operation */
688   conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
689   if (!conn->op) {
690     silc_free(conn);
691     callback(SILC_NET_NO_MEMORY, NULL, context);
692     return NULL;
693   }
694
695   if (local_ip_addr)
696     conn->local_ip = strdup(local_ip_addr);
697   conn->remote = strdup(remote_ip_addr);
698   if (!conn->remote) {
699     silc_async_free(conn->op);
700     silc_free(conn->local_ip);
701     silc_free(conn);
702     callback(SILC_NET_NO_MEMORY, NULL, context);
703     return NULL;
704   }
705   conn->port = remote_port;
706   conn->callback = callback;
707   conn->context = context;
708   conn->retry = 1;
709   conn->status = SILC_NET_ERROR;
710
711   silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
712   silc_fsm_start(&conn->fsm, silc_net_connect_st_thread);
713
714   return conn->op;
715 }
716
717 /* Closes the connection by closing the socket connection. */
718
719 void silc_net_close_connection(int sock)
720 {
721   SILC_LOG_DEBUG(("Closing sock %d", sock));
722   closesocket(sock);
723 }
724
725 /* Converts the IP number string from numbers-and-dots notation to
726    binary form. */
727
728 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
729 {
730   unsigned long ret;
731
732   if (silc_net_is_ip4(addr)) {
733     /* IPv4 address */
734     ret = inet_addr(addr);
735
736     if (bin_len < 4)
737       return FALSE;
738
739     memcpy(bin, (unsigned char *)&ret, 4);
740     return ret != INADDR_NONE;
741   } else {
742     struct addrinfo hints, *ai;
743     SilcSockaddr *s;
744
745     /* IPv6 address */
746     if (bin_len < 16)
747       return FALSE;
748
749     memset(&hints, 0, sizeof(hints));
750     hints.ai_family = AF_INET6;
751     if (getaddrinfo(addr, NULL, &hints, &ai))
752       return FALSE;
753
754     if (ai) {
755       s = (SilcSockaddr *)ai->ai_addr;
756       memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
757       freeaddrinfo(ai);
758     }
759
760     return TRUE;
761   }
762 }
763
764 /* Set socket to non-blocking mode. */
765
766 int silc_net_set_socket_nonblock(int sock)
767 {
768   unsigned long on = 1;
769   return ioctlsocket(sock, FIONBIO, &on);
770 }
771
772 /* Init Winsock2. */
773
774 SilcBool silc_net_win32_init(void)
775 {
776   int ret, sopt = SO_SYNCHRONOUS_NONALERT;
777   WSADATA wdata;
778   WORD ver = MAKEWORD(1, 1);
779
780   ret = WSAStartup(ver, &wdata);
781   if (ret)
782     return FALSE;
783
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,
787                    sizeof(sopt));
788   if (ret)
789     return FALSE;
790
791   return TRUE;
792 }
793
794 /* Uninit Winsock2 */
795
796 void silc_net_win32_uninit(void)
797 {
798   WSACleanup();
799 }