Added UDP network support.
[silc.git] / lib / silcutil / unix / silcunixnet.c
1 /*
2
3   silcunixnet.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2006 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 #include "silcnet.h"
23
24 #ifdef HAVE_IPV6
25 #define SIZEOF_SOCKADDR(so) ((so).sa.sa_family == AF_INET6 ?    \
26   sizeof(so.sin6) : sizeof(so.sin))
27 #else
28 #define SIZEOF_SOCKADDR(so) (sizeof(so.sin))
29 #endif
30
31 typedef union {
32   struct sockaddr sa;
33   struct sockaddr_in sin;
34 #ifdef HAVE_IPV6
35   struct sockaddr_in6 sin6;
36 #endif
37 } SilcSockaddr;
38
39 static SilcBool silc_net_set_sockaddr(SilcSockaddr *addr, const char *ip_addr,
40                                       int port)
41 {
42   int len;
43
44   memset(addr, 0, sizeof(*addr));
45
46   /* Check for IPv4 and IPv6 addresses */
47   if (ip_addr) {
48     if (!silc_net_is_ip(ip_addr)) {
49       SILC_LOG_ERROR(("%s is not IP address", ip_addr));
50       return FALSE;
51     }
52
53     if (silc_net_is_ip4(ip_addr)) {
54       /* IPv4 address */
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;
60     } else {
61 #ifdef HAVE_IPV6
62       /* IPv6 address */
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;
68 #else
69       SILC_LOG_ERROR(("IPv6 support is not compiled in"));
70       return FALSE;
71 #endif
72     }
73   } else {
74     /* Any address */
75     addr->sin.sin_family = AF_INET;
76     addr->sin.sin_addr.s_addr = INADDR_ANY;
77     if (port)
78       addr->sin.sin_port = htons(port);
79   }
80
81   return TRUE;
82 }
83
84 /* Deliver new stream to upper layer */
85
86 static void silc_net_accept_stream(SilcSocketStreamStatus status,
87                                    SilcStream stream, void *context)
88 {
89   SilcNetListener listener = context;
90
91   if (status != SILC_SOCKET_OK)
92     return;
93
94   listener->callback(SILC_NET_OK, stream, listener->context);
95 }
96
97 /* Accept incoming connection and notify upper layer */
98
99 SILC_TASK_CALLBACK(silc_net_accept)
100 {
101   SilcNetListener listener = context;
102   int sock;
103
104   SILC_LOG_DEBUG(("Accepting new connection"));
105
106   sock = silc_net_accept_connection(fd);
107   if (sock < 0)
108     return;
109
110   /* Set socket options */
111   silc_net_set_socket_nonblock(sock);
112   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
113
114   /* Create socket stream */
115   silc_socket_tcp_stream_create(sock, TRUE, listener->require_fqdn, schedule,
116                                 silc_net_accept_stream, listener);
117 }
118
119 /* Create TCP network listener */
120
121 SilcNetListener
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)
127 {
128   SilcNetListener listener = NULL;
129   SilcSockaddr server;
130   int i, sock, rval;
131   const char *ipany = "0.0.0.0";
132
133   SILC_LOG_DEBUG(("Creating TCP listener"));
134
135   if (port < 1 || !schedule || !callback)
136     goto err;
137
138   listener = silc_calloc(1, sizeof(*listener));
139   if (!listener) {
140     callback(SILC_NET_NO_MEMORY, NULL, context);
141     return NULL;
142   }
143   listener->schedule = schedule;
144   listener->callback = callback;
145   listener->context = context;
146
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);
151       return NULL;
152     }
153   } else {
154     listener->socks = silc_calloc(1, sizeof(*listener->socks));
155     if (!listener->socks) {
156       callback(SILC_NET_NO_MEMORY, NULL, context);
157       return NULL;
158     }
159
160     local_ip_count = 1;
161   }
162
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));
167
168     /* Set sockaddr for server */
169     if (!silc_net_set_sockaddr(&server,
170                                local_ip_addr ? local_ip_addr[i] : ipany,
171                                port))
172       goto err;
173
174     /* Create the socket */
175     sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
176     if (sock < 0) {
177       SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
178       goto err;
179     }
180
181     /* Set the socket options */
182     rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
183     if (rval < 0) {
184       SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
185       goto err;
186     }
187
188     /* Bind the listener socket */
189     rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
190     if (rval < 0) {
191       SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
192       goto err;
193     }
194
195     /* Specify that we are listenning */
196     rval = listen(sock, 5);
197     if (rval < 0) {
198       SILC_LOG_ERROR(("Cannot set socket listenning: %s", strerror(errno)));
199       goto err;
200     }
201
202     /* Set the server socket to non-blocking mode */
203     silc_net_set_socket_nonblock(sock);
204
205     /* Schedule for incoming connections */
206     silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
207
208     SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
209     listener->socks[i] = sock;
210     listener->socks_count++;
211   }
212
213   return listener;
214
215  err:
216   if (callback)
217     callback(SILC_NET_ERROR, NULL, context);
218   if (listener)
219     silc_net_close_listener(listener);
220   return NULL;
221 }
222
223 /* Close network listener */
224
225 void silc_net_close_listener(SilcNetListener listener)
226 {
227   int i;
228
229   SILC_LOG_DEBUG(("Closing network listener"));
230
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]);
235   }
236
237   silc_free(listener->socks);
238   silc_free(listener);
239 }
240
241 /* Create UDP stream */
242
243 SilcStream
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)
247 {
248   SilcStream stream;
249   SilcSockaddr server;
250   int sock = -1, rval;
251   const char *ipany = "0.0.0.0";
252
253   SILC_LOG_DEBUG(("Creating UDP stream"));
254
255   if (local_port < 1 || !schedule)
256     goto err;
257
258   /* Bind to local addresses */
259   SILC_LOG_DEBUG(("Binding to local address %s",
260                   local_ip_addr ? local_ip_addr : ipany));
261
262   /* Set sockaddr for server */
263   if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
264                              local_port))
265     goto err;
266
267   /* Create the socket */
268   sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
269   if (sock < 0) {
270     SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
271     goto err;
272   }
273
274   /* Set the socket options */
275   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
276   if (rval < 0) {
277     SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
278     goto err;
279   }
280 #ifdef SO_REUSEPORT
281   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
282   if (rval < 0) {
283     SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
284     goto err;
285   }
286 #endif /* SO_REUSEPORT */
287
288   /* Bind the listener socket */
289   rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
290   if (rval < 0) {
291     SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
292     goto err;
293   }
294
295   /* Set socket to non-blocking mode */
296   silc_net_set_socket_nonblock(sock);
297
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))
301       goto err;
302
303     rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
304     if (rval < 0) {
305       SILC_LOG_DEBUG(("Cannot connect UDP stream: %s", strerror(errno)));
306       goto err;
307     }
308   }
309
310   /* Set send and receive buffer size */
311 #ifdef SO_SNDBUF
312   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 65535);
313   if (rval < 0) {
314     SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
315     goto err;
316   }
317 #endif /* SO_SNDBUF */
318 #ifdef SO_RCVBUF
319   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 65535);
320   if (rval < 0) {
321     SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
322     goto err;
323   }
324 #endif /* SO_RCVBUF */
325
326   /* Encapsulate into socket stream */
327   stream =
328     silc_socket_udp_stream_create(sock, local_ip_addr ?
329                                   silc_net_is_ip6(local_ip_addr) : FALSE,
330                                   schedule);
331   if (!stream)
332     goto err;
333
334   SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
335   return stream;
336
337  err:
338   if (sock != -1)
339     close(sock);
340   return NULL;
341 }
342
343 /* Receive UDP packet */
344
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)
348 {
349   SilcSocketStream sock = stream;
350   SilcSockaddr s;
351   struct sockaddr *from;
352   int len, flen;
353
354   SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
355
356   if (remote_ip_addr && remote_port) {
357     if (sock->ipv6) {
358       from = (struct sockaddr *)&s.sin6;
359       flen = sizeof(s.sin6);
360     } else {
361       from = (struct sockaddr *)&s.sin;
362       flen = sizeof(s.sin);
363     }
364     len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
365   } else
366     len = recv(sock->sock, ret_data, data_size, 0);
367
368   if (len < 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);
373       return -1;
374     }
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;
379     return -2;
380   }
381
382   SILC_LOG_DEBUG(("Read %d bytes", len));
383
384   if (!len)
385     silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
386
387   /* Return remote address */
388   if (remote_ip_addr && remote_port) {
389     if (sock->ipv6) {
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);
393     } else {
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);
397     }
398   }
399
400   return len;
401 }
402
403 /* Send UDP packet */
404
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)
408 {
409   SilcSocketStream sock = stream;
410   SilcSockaddr remote;
411
412   SILC_LOG_DEBUG(("Writing data to UDP socket %d", sock->sock));
413
414   /* Set sockaddr for server */
415   if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
416     return;
417
418   /* Send */
419   sendto(sock->sock, data, data_len, 0, &remote.sa, SIZEOF_SOCKADDR(remote));
420 }
421
422 /* Asynchronous TCP/IP connecting */
423
424 typedef struct {
425   SilcNetStatus status;
426   SilcSocketStreamStatus stream_status;
427   SilcStream stream;
428   SilcFSMStruct fsm;
429   SilcFSMSemaStruct sema;
430   SilcAsyncOperation op;
431   SilcAsyncOperation sop;
432   char *local_ip;
433   char *remote;
434   char ip_addr[64];
435   int sock;
436   SilcNetCallback callback;
437   void *context;
438   unsigned int port     : 24;
439   unsigned int retry    : 7;
440   unsigned int aborted  : 1;
441 } *SilcNetConnect;
442
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);
447
448 SILC_TASK_CALLBACK(silc_net_connect_wait)
449 {
450   SilcNetConnect conn = context;
451   SILC_FSM_SEMA_POST(&conn->sema);
452 }
453
454 SILC_FSM_STATE(silc_net_connect_st_start)
455 {
456   SilcNetConnect conn = fsm_context;
457   int sock, rval;
458   SilcSockaddr desthost;
459   SilcBool prefer_ipv6 = TRUE;
460
461   if (conn->aborted) {
462     /** Aborted */
463     silc_fsm_next(fsm, silc_net_connect_st_finish);
464     return SILC_FSM_CONTINUE;
465   }
466
467   /* Do host lookup */
468  retry:
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));
473
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;
478   }
479
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;
485   }
486
487   /* Create the connection socket */
488   sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
489   if (sock < 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)) {
493       prefer_ipv6 = FALSE;
494       goto retry;
495     }
496
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;
501   }
502
503   /* Bind to the local address if provided */
504   if (conn->local_ip) {
505     SilcSockaddr local;
506
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));
510   }
511
512   /* Set the socket to non-blocking mode */
513   silc_net_set_socket_nonblock(sock);
514
515   /* Connect to the host */
516   rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
517   if (rval < 0) {
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)) {
521         shutdown(sock, 2);
522         close(sock);
523
524         prefer_ipv6 = FALSE;
525         goto retry;
526       }
527
528       shutdown(sock, 2);
529       close(sock);
530
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;
535     }
536   }
537
538   /* Set appropriate options */
539 #if defined(TCP_NODELAY)
540   silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
541 #endif
542   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
543
544   SILC_LOG_DEBUG(("Connection operation in progress"));
545
546   conn->sock = sock;
547
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;
557 }
558
559 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
560                                          SilcStream stream, void *context)
561 {
562   SilcNetConnect conn = context;
563   conn->stream_status = status;
564   conn->stream = stream;
565   SILC_FSM_CALL_CONTINUE(&conn->fsm);
566 }
567
568 SILC_FSM_STATE(silc_net_connect_st_connected)
569 {
570   SilcNetConnect conn = fsm_context;
571   SilcSchedule schedule = silc_fsm_get_schedule(fsm);
572   int opt = EINVAL, optlen = sizeof(opt), ret;
573
574   if (conn->aborted) {
575     /** Aborted */
576     silc_fsm_next(fsm, silc_net_connect_st_finish);
577     return SILC_FSM_CONTINUE;
578   }
579
580   ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
581                                 &opt, &optlen);
582
583   silc_schedule_task_del_by_fd(schedule, conn->sock);
584   silc_schedule_unset_listen_fd(schedule, conn->sock);
585
586   if (ret != 0 || opt != 0) {
587     if (conn->retry) {
588       /** Retry connecting */
589       SILC_LOG_DEBUG(("Retry connecting"));
590       conn->retry--;
591       silc_net_close_connection(conn->sock);
592       silc_fsm_next(fsm, silc_net_connect_st_start);
593       return SILC_FSM_CONTINUE;
594     }
595
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 */
608
609     /** Connecting failed */
610     SILC_LOG_DEBUG(("Connecting failed"));
611     silc_fsm_next(fsm, silc_net_connect_st_finish);
612     return SILC_FSM_CONTINUE;
613   }
614
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,
619                                      schedule,
620                                      silc_net_connect_wait_stream, conn)));
621 }
622
623 SILC_FSM_STATE(silc_net_connect_st_stream)
624 {
625   SilcNetConnect conn = fsm_context;
626
627   if (conn->aborted) {
628     /** Aborted */
629     silc_fsm_next(fsm, silc_net_connect_st_finish);
630     return SILC_FSM_CONTINUE;
631   }
632
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;
639     else
640       conn->status = SILC_NET_ERROR;
641     silc_fsm_next(fsm, silc_net_connect_st_finish);
642     return SILC_FSM_CONTINUE;
643   }
644
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);
649
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;
655 }
656
657 SILC_FSM_STATE(silc_net_connect_st_finish)
658 {
659   SilcNetConnect conn = fsm_context;
660
661   /* Deliver error or new stream */
662   if (!conn->aborted) {
663     conn->callback(conn->status, conn->stream, conn->context);
664     if (conn->op)
665       silc_async_free(conn->op);
666     if (conn->sop)
667       silc_async_free(conn->sop);
668   }
669
670   return SILC_FSM_FINISH;
671 }
672
673 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
674 {
675   SilcNetConnect conn = context;
676   conn->aborted = TRUE;
677
678   /* Abort underlaying stream creation too */
679   if (conn->sop)
680     silc_async_abort(conn->op, NULL, NULL);
681 }
682
683 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
684                                         void *destructor_context)
685 {
686   SilcNetConnect conn = fsm_context;
687   silc_free(conn->local_ip);
688   silc_free(conn->remote);
689   silc_free(conn);
690 }
691
692 /* Create asynchronous TCP/IP connection. */
693
694 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
695                                         const char *remote_ip_addr,
696                                         int remote_port,
697                                         SilcSchedule schedule,
698                                         SilcNetCallback callback,
699                                         void *context)
700 {
701   SilcNetConnect conn;
702
703   if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
704     return NULL;
705
706   SILC_LOG_DEBUG(("Creating connection to host %s port %d",
707                   remote_ip_addr, remote_port));
708
709   conn = silc_calloc(1, sizeof(*conn));
710   if (!conn) {
711     callback(SILC_NET_NO_MEMORY, NULL, context);
712     return NULL;
713   }
714
715   /* Start async operation */
716   conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
717   if (!conn->op) {
718     callback(SILC_NET_NO_MEMORY, NULL, context);
719     return NULL;
720   }
721
722   if (local_ip_addr)
723     conn->local_ip = strdup(local_ip_addr);
724   conn->remote = strdup(remote_ip_addr);
725   if (!conn->remote) {
726     callback(SILC_NET_NO_MEMORY, NULL, context);
727     return NULL;
728   }
729   conn->port = remote_port;
730   conn->callback = callback;
731   conn->context = context;
732   conn->retry = 1;
733   conn->status = SILC_NET_ERROR;
734
735   silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
736   silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
737
738   return conn->op;
739 }
740
741 /* Closes the connection by closing the socket connection. */
742
743 void silc_net_close_connection(int sock)
744 {
745   close(sock);
746 }
747
748 /* Set's the socket to non-blocking mode. */
749
750 int silc_net_set_socket_nonblock(int sock)
751 {
752   return fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
753 }
754
755 /* Converts the IP number string from numbers-and-dots notation to
756    binary form. */
757
758 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
759 {
760   int ret = 0;
761
762   if (silc_net_is_ip4(addr)) {
763     /* IPv4 address */
764     struct in_addr tmp;
765     ret = inet_aton(addr, &tmp);
766     if (bin_len < 4)
767       return FALSE;
768
769     memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
770 #ifdef HAVE_IPV6
771   } else {
772     struct addrinfo hints, *ai;
773     SilcSockaddr *s;
774
775     /* IPv6 address */
776     if (bin_len < 16)
777       return FALSE;
778
779     memset(&hints, 0, sizeof(hints));
780     hints.ai_family = AF_INET6;
781     if (getaddrinfo(addr, NULL, &hints, &ai))
782       return FALSE;
783
784     if (ai) {
785       s = (SilcSockaddr *)ai->ai_addr;
786       memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
787       freeaddrinfo(ai);
788     }
789
790     ret = TRUE;
791 #endif /* HAVE_IPV6 */
792   }
793
794   return ret != 0;
795 }