Moved regex routines to lib/silcutil/silcstrutil.[ch].
[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 - 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 #include "silcnet.h"
23
24 /************************** Types and definitions ***************************/
25
26 #ifdef HAVE_IPV6
27 #define SIZEOF_SOCKADDR(so) ((so).sa.sa_family == AF_INET6 ?    \
28   sizeof(so.sin6) : sizeof(so.sin))
29 #else
30 #define SIZEOF_SOCKADDR(so) (sizeof(so.sin))
31 #endif
32
33 typedef union {
34   struct sockaddr sa;
35   struct sockaddr_in sin;
36 #ifdef HAVE_IPV6
37   struct sockaddr_in6 sin6;
38 #endif
39 } SilcSockaddr;
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(("IPv6 support is not compiled in"));
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 /****************************** TCP Listener ********************************/
89
90 /* Deliver new stream to upper layer */
91
92 static void silc_net_accept_stream(SilcSocketStreamStatus status,
93                                    SilcStream stream, void *context)
94 {
95   SilcNetListener listener = context;
96
97   if (status != SILC_SOCKET_OK)
98     return;
99
100   listener->callback(SILC_NET_OK, stream, listener->context);
101 }
102
103 /* Accept incoming connection and notify upper layer */
104
105 SILC_TASK_CALLBACK(silc_net_accept)
106 {
107   SilcNetListener listener = context;
108   int sock;
109
110   SILC_LOG_DEBUG(("Accepting new connection"));
111
112   sock = silc_net_accept_connection(fd);
113   if (sock < 0)
114     return;
115
116   /* Set socket options */
117   silc_net_set_socket_nonblock(sock);
118   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
119
120   /* Create socket stream */
121   silc_socket_tcp_stream_create(sock, listener->lookup,
122                                 listener->require_fqdn, schedule,
123                                 silc_net_accept_stream, listener);
124 }
125
126 /* Create TCP network listener */
127
128 SilcNetListener
129 silc_net_tcp_create_listener(const char **local_ip_addr,
130                              SilcUInt32 local_ip_count, int port,
131                              SilcBool lookup, SilcBool require_fqdn,
132                              SilcSchedule schedule,
133                              SilcNetCallback callback, void *context)
134 {
135   SilcNetListener listener = NULL;
136   SilcSockaddr server;
137   int i, sock, rval;
138   const char *ipany = "0.0.0.0";
139
140   SILC_LOG_DEBUG(("Creating TCP listener"));
141
142   if (port < 0 || !schedule || !callback)
143     goto err;
144
145   listener = silc_calloc(1, sizeof(*listener));
146   if (!listener)
147     return NULL;
148   listener->schedule = schedule;
149   listener->callback = callback;
150   listener->context = context;
151   listener->require_fqdn = require_fqdn;
152   listener->lookup = lookup;
153
154   if (local_ip_count > 0) {
155     listener->socks = silc_calloc(local_ip_count, sizeof(*listener->socks));
156     if (!listener->socks)
157       return NULL;
158   } else {
159     listener->socks = silc_calloc(1, sizeof(*listener->socks));
160     if (!listener->socks)
161       return NULL;
162
163     local_ip_count = 1;
164   }
165
166   /* Bind to local addresses */
167   for (i = 0; i < local_ip_count; i++) {
168     SILC_LOG_DEBUG(("Binding to local address %s",
169                     local_ip_addr ? local_ip_addr[i] : ipany));
170
171     /* Set sockaddr for server */
172     if (!silc_net_set_sockaddr(&server,
173                                local_ip_addr ? local_ip_addr[i] : ipany,
174                                port))
175       goto err;
176
177     /* Create the socket */
178     sock = socket(server.sin.sin_family, SOCK_STREAM, 0);
179     if (sock < 0) {
180       SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
181       goto err;
182     }
183
184     /* Set the socket options */
185     rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
186     if (rval < 0) {
187       SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
188       close(sock);
189       goto err;
190     }
191
192     /* Bind the listener socket */
193     rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
194     if (rval < 0) {
195       SILC_LOG_ERROR(("Cannot bind socket: %s", strerror(errno)));
196       close(sock);
197       goto err;
198     }
199
200     /* Specify that we are listenning */
201     rval = listen(sock, 64);
202     if (rval < 0) {
203       SILC_LOG_ERROR(("Cannot set socket listenning: %s", strerror(errno)));
204       close(sock);
205       goto err;
206     }
207
208     /* Set the server socket to non-blocking mode */
209     silc_net_set_socket_nonblock(sock);
210
211     /* Schedule for incoming connections */
212     silc_schedule_task_add_fd(schedule, sock, silc_net_accept, listener);
213
214     SILC_LOG_DEBUG(("TCP listener created, fd=%d", sock));
215     listener->socks[i] = sock;
216     listener->socks_count++;
217   }
218
219   return listener;
220
221  err:
222   if (listener)
223     silc_net_close_listener(listener);
224   return NULL;
225 }
226
227 /* Close network listener */
228
229 void silc_net_close_listener(SilcNetListener listener)
230 {
231   int i;
232
233   SILC_LOG_DEBUG(("Closing network listener"));
234
235   for (i = 0; i < listener->socks_count; i++) {
236     silc_schedule_task_del_by_fd(listener->schedule, listener->socks[i]);
237     shutdown(listener->socks[i], 2);
238     close(listener->socks[i]);
239   }
240
241   silc_free(listener->socks);
242   silc_free(listener);
243 }
244
245 /******************************* UDP Stream *********************************/
246
247 /* Create UDP stream */
248
249 SilcStream
250 silc_net_udp_connect(const char *local_ip_addr, int local_port,
251                      const char *remote_ip_addr, int remote_port,
252                      SilcSchedule schedule)
253 {
254   SilcStream stream;
255   SilcSockaddr server;
256   int sock = -1, rval;
257   const char *ipany = "0.0.0.0";
258
259   SILC_LOG_DEBUG(("Creating UDP stream"));
260
261   if (!schedule)
262     goto err;
263
264   /* Bind to local addresses */
265   SILC_LOG_DEBUG(("Binding to local address %s",
266                   local_ip_addr ? local_ip_addr : ipany));
267
268   /* Set sockaddr for server */
269   if (!silc_net_set_sockaddr(&server, local_ip_addr ? local_ip_addr : ipany,
270                              local_port))
271     goto err;
272
273   /* Create the socket */
274   sock = socket(server.sin.sin_family, SOCK_DGRAM, 0);
275   if (sock < 0) {
276     SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
277     goto err;
278   }
279
280   /* Set the socket options */
281   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
282   if (rval < 0) {
283     SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
284     goto err;
285   }
286 #ifdef SO_REUSEPORT
287   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
288   if (rval < 0) {
289     SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
290     goto err;
291   }
292 #endif /* SO_REUSEPORT */
293
294   /* Bind the listener socket */
295   rval = bind(sock, &server.sa, SIZEOF_SOCKADDR(server));
296   if (rval < 0) {
297     SILC_LOG_DEBUG(("Cannot bind socket: %s", strerror(errno)));
298     goto err;
299   }
300
301   /* Set socket to non-blocking mode */
302   silc_net_set_socket_nonblock(sock);
303
304   /* Set to connected state if remote address is provided. */
305   if (remote_ip_addr && remote_port) {
306     if (!silc_net_set_sockaddr(&server, remote_ip_addr, remote_port))
307       goto err;
308
309     rval = connect(sock, &server.sa, SIZEOF_SOCKADDR(server));
310     if (rval < 0) {
311       SILC_LOG_DEBUG(("Cannot connect UDP stream: %s", strerror(errno)));
312       goto err;
313     }
314   }
315
316   /* Set send and receive buffer size */
317 #ifdef SO_SNDBUF
318   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 765535);
319   if (rval < 0) {
320     rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_SNDBUF, 65535);
321     if (rval < 0) {
322       SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
323       goto err;
324     }
325   }
326 #endif /* SO_SNDBUF */
327 #ifdef SO_RCVBUF
328   rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 765535);
329   if (rval < 0) {
330     rval = silc_net_set_socket_opt(sock, SOL_SOCKET, SO_RCVBUF, 65535);
331     if (rval < 0) {
332       SILC_LOG_ERROR(("Cannot set socket options: %s", strerror(errno)));
333       goto err;
334     }
335   }
336 #endif /* SO_RCVBUF */
337
338   /* Encapsulate into socket stream */
339   stream =
340     silc_socket_udp_stream_create(sock, local_ip_addr ?
341                                   silc_net_is_ip6(local_ip_addr) : FALSE,
342                                   remote_ip_addr ? TRUE : FALSE, schedule);
343   if (!stream)
344     goto err;
345
346   SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
347   return stream;
348
349  err:
350   if (sock != -1)
351     close(sock);
352   return NULL;
353 }
354
355 /* Receive UDP packet */
356
357 int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
358                          SilcUInt32 remote_ip_addr_size, int *remote_port,
359                          unsigned char *ret_data, SilcUInt32 data_size)
360 {
361   SilcSocketStream sock = stream;
362   SilcSockaddr s;
363   struct sockaddr *from;
364   int len, flen;
365
366   SILC_LOG_DEBUG(("Reading data from UDP socket %d", sock->sock));
367
368   if (remote_ip_addr && remote_port) {
369     if (sock->ipv6) {
370       from = (struct sockaddr *)&s.sin6;
371       flen = sizeof(s.sin6);
372     } else {
373       from = (struct sockaddr *)&s.sin;
374       flen = sizeof(s.sin);
375     }
376     len = recvfrom(sock->sock, ret_data, data_size, 0, from, &flen);
377   } else
378     len = recv(sock->sock, ret_data, data_size, 0);
379
380   if (len < 0) {
381     if (errno == EAGAIN || errno == EINTR) {
382       SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
383       silc_schedule_set_listen_fd(sock->schedule, sock->sock,
384                                   SILC_TASK_READ, FALSE);
385       return -1;
386     }
387     SILC_LOG_DEBUG(("Cannot read from UDP socket: %d:%s",
388                     sock->sock, strerror(errno)));
389     silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
390     sock->sock_error = errno;
391     return -2;
392   }
393
394   SILC_LOG_DEBUG(("Read %d bytes", len));
395
396   if (!len)
397     silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
398
399   /* Return remote address */
400   if (remote_ip_addr && remote_port) {
401     if (sock->ipv6) {
402       *remote_port = ntohs(s.sin6.sin6_port);
403       inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
404                 remote_ip_addr_size);
405     } else {
406       *remote_port = ntohs(s.sin.sin_port);
407       inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
408                 remote_ip_addr_size);
409     }
410
411     SILC_LOG_DEBUG(("UDP packet from %s:%d", remote_ip_addr, *remote_port));
412   }
413
414   return len;
415 }
416
417 /* Send UDP packet */
418
419 int silc_net_udp_send(SilcStream stream,
420                       const char *remote_ip_addr, int remote_port,
421                       const unsigned char *data, SilcUInt32 data_len)
422 {
423   SilcSocketStream sock = stream;
424   SilcSockaddr remote;
425   int ret;
426
427   SILC_LOG_DEBUG(("Sending data to UDP socket %d", sock->sock));
428
429   /* Set sockaddr */
430   if (!silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port))
431     return -2;
432
433   /* Send */
434   ret = sendto(sock->sock, data, data_len, 0, &remote.sa,
435                SIZEOF_SOCKADDR(remote));
436   if (ret < 0) {
437     if (errno == EAGAIN || errno == EINTR) {
438       SILC_LOG_DEBUG(("Could not send immediately, will do it later"));
439       silc_schedule_set_listen_fd(sock->schedule, sock->sock,
440                                   SILC_TASK_READ | SILC_TASK_WRITE, FALSE);
441       return -1;
442     }
443     SILC_LOG_DEBUG(("Cannot send to UDP socket: %s", strerror(errno)));
444     silc_schedule_unset_listen_fd(sock->schedule, sock->sock);
445     sock->sock_error = errno;
446     return -2;
447   }
448
449   SILC_LOG_DEBUG(("Sent data %d bytes", ret));
450   if (silc_schedule_get_fd_events(sock->schedule, sock->sock) &
451       SILC_TASK_WRITE)
452     silc_schedule_set_listen_fd(sock->schedule, sock->sock,
453                                 SILC_TASK_READ, FALSE);
454
455   return ret;
456 }
457
458 /******************************* TCP Stream *********************************/
459
460 /* Asynchronous TCP/IP connecting */
461
462 typedef struct {
463   SilcNetStatus status;
464   SilcSocketStreamStatus stream_status;
465   SilcStream stream;
466   SilcFSMStruct fsm;
467   SilcFSMEventStruct event;
468   SilcAsyncOperation op;
469   SilcAsyncOperation sop;
470   char *local_ip;
471   char *remote;
472   char ip_addr[64];
473   int sock;
474   SilcNetCallback callback;
475   void *context;
476   unsigned int port     : 24;
477   unsigned int retry    : 7;
478   unsigned int aborted  : 1;
479 } *SilcNetConnect;
480
481 SILC_FSM_STATE(silc_net_connect_st_start);
482 SILC_FSM_STATE(silc_net_connect_st_connected);
483 SILC_FSM_STATE(silc_net_connect_st_stream);
484 SILC_FSM_STATE(silc_net_connect_st_finish);
485
486 SILC_TASK_CALLBACK(silc_net_connect_wait)
487 {
488   SilcNetConnect conn = context;
489   SILC_FSM_EVENT_SIGNAL(&conn->event);
490 }
491
492 SILC_FSM_STATE(silc_net_connect_st_start)
493 {
494   SilcNetConnect conn = fsm_context;
495   int sock, rval;
496   SilcSockaddr desthost;
497   SilcBool prefer_ipv6 = TRUE;
498
499   if (conn->aborted) {
500     /** Aborted */
501     silc_fsm_next(fsm, silc_net_connect_st_finish);
502     return SILC_FSM_CONTINUE;
503   }
504
505   /* Do host lookup */
506  retry:
507   if (!silc_net_gethostbyname(conn->remote, prefer_ipv6,
508                               conn->ip_addr, sizeof(conn->ip_addr))) {
509     SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
510                     "host", conn->remote));
511
512     /** Network unreachable */
513     conn->status = SILC_NET_HOST_UNREACHABLE;
514     silc_fsm_next(fsm, silc_net_connect_st_finish);
515     return SILC_FSM_CONTINUE;
516   }
517
518   /* Set sockaddr for this connection */
519   if (!silc_net_set_sockaddr(&desthost, conn->ip_addr, conn->port)) {
520     /** Sockaddr failed */
521     silc_fsm_next(fsm, silc_net_connect_st_finish);
522     return SILC_FSM_CONTINUE;
523   }
524
525   /* Create the connection socket */
526   sock = socket(desthost.sin.sin_family, SOCK_STREAM, 0);
527   if (sock < 0) {
528     /* If address is IPv6, then fallback to IPv4 and see whether we can do
529        better with that on socket creation. */
530     if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
531       prefer_ipv6 = FALSE;
532       goto retry;
533     }
534
535     /** Cannot create socket */
536     SILC_LOG_ERROR(("Cannot create socket: %s", strerror(errno)));
537     silc_fsm_next(fsm, silc_net_connect_st_finish);
538     return SILC_FSM_CONTINUE;
539   }
540
541   /* Bind to the local address if provided */
542   if (conn->local_ip) {
543     SilcSockaddr local;
544
545     /* Set sockaddr for local listener, and try to bind it. */
546     if (silc_net_set_sockaddr(&local, conn->local_ip, 0))
547       bind(sock, &local.sa, SIZEOF_SOCKADDR(local));
548   }
549
550   /* Set the socket to non-blocking mode */
551   silc_net_set_socket_nonblock(sock);
552
553   /* Connect to the host */
554   rval = connect(sock, &desthost.sa, SIZEOF_SOCKADDR(desthost));
555   if (rval < 0) {
556     if (errno != EINPROGRESS) {
557       shutdown(sock, 2);
558       close(sock);
559
560       /* Retry using an IPv4 adress, if IPv6 didn't work */
561       if (prefer_ipv6 && silc_net_is_ip6(conn->ip_addr)) {
562         prefer_ipv6 = FALSE;
563         goto retry;
564       }
565
566       /** Cannot connect to remote host */
567       SILC_LOG_ERROR(("Cannot connect to remote host: %s", strerror(errno)));
568       silc_fsm_next(fsm, silc_net_connect_st_finish);
569       return SILC_FSM_CONTINUE;
570     }
571   }
572
573   /* Set appropriate options */
574 #if defined(TCP_NODELAY)
575   silc_net_set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
576 #endif
577   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
578
579   SILC_LOG_DEBUG(("Connection operation in progress"));
580
581   conn->sock = sock;
582
583   /** Wait for connection */
584   silc_fsm_next(fsm, silc_net_connect_st_connected);
585   silc_fsm_event_init(&conn->event, fsm);
586   silc_schedule_task_add_fd(silc_fsm_get_schedule(fsm), sock,
587                             silc_net_connect_wait, conn);
588   silc_schedule_set_listen_fd(silc_fsm_get_schedule(fsm), sock,
589                               SILC_TASK_WRITE, FALSE);
590   SILC_FSM_EVENT_WAIT(&conn->event);
591   return SILC_FSM_CONTINUE;
592 }
593
594 static void silc_net_connect_wait_stream(SilcSocketStreamStatus status,
595                                          SilcStream stream, void *context)
596 {
597   SilcNetConnect conn = context;
598   conn->stream_status = status;
599   conn->stream = stream;
600   SILC_FSM_CALL_CONTINUE(&conn->fsm);
601 }
602
603 SILC_FSM_STATE(silc_net_connect_st_connected)
604 {
605   SilcNetConnect conn = fsm_context;
606   SilcSchedule schedule = silc_fsm_get_schedule(fsm);
607   int opt = EINVAL, optlen = sizeof(opt), ret;
608
609   if (conn->aborted) {
610     /** Aborted */
611     silc_schedule_unset_listen_fd(schedule, conn->sock);
612     silc_schedule_task_del_by_fd(schedule, conn->sock);
613     silc_fsm_next(fsm, silc_net_connect_st_finish);
614     return SILC_FSM_CONTINUE;
615   }
616
617   ret = silc_net_get_socket_opt(conn->sock, SOL_SOCKET, SO_ERROR,
618                                 &opt, &optlen);
619
620   silc_schedule_unset_listen_fd(schedule, conn->sock);
621   silc_schedule_task_del_by_fd(schedule, conn->sock);
622
623   if (ret != 0 || opt != 0) {
624     if (conn->retry) {
625       /** Retry connecting */
626       SILC_LOG_DEBUG(("Retry connecting"));
627       conn->retry--;
628       silc_net_close_connection(conn->sock);
629       silc_fsm_next(fsm, silc_net_connect_st_start);
630       return SILC_FSM_CONTINUE;
631     }
632
633 #if defined(ECONNREFUSED)
634     if (errno == ECONNREFUSED)
635       conn->status = SILC_NET_CONNECTION_REFUSED;
636 #endif /* ECONNREFUSED */
637 #if defined(ETIMEDOUT)
638     if (errno == ETIMEDOUT)
639       conn->status = SILC_NET_CONNECTION_TIMEOUT;
640 #endif /* ETIMEDOUT */
641 #if defined(ENETUNREACH)
642     if (errno == ENETUNREACH)
643       conn->status = SILC_NET_HOST_UNREACHABLE;
644 #endif /* ENETUNREACH */
645
646     /** Connecting failed */
647     SILC_LOG_DEBUG(("Connecting failed"));
648     silc_fsm_next(fsm, silc_net_connect_st_finish);
649     return SILC_FSM_CONTINUE;
650   }
651
652   SILC_LOG_DEBUG(("TCP connection established"));
653
654   /** Connection created */
655   silc_fsm_next(fsm, silc_net_connect_st_stream);
656   SILC_FSM_CALL((conn->sop = silc_socket_tcp_stream_create(
657                                      conn->sock, FALSE, FALSE,
658                                      schedule,
659                                      silc_net_connect_wait_stream, conn)));
660 }
661
662 SILC_FSM_STATE(silc_net_connect_st_stream)
663 {
664   SilcNetConnect conn = fsm_context;
665
666   if (conn->aborted) {
667     /** Aborted */
668     silc_fsm_next(fsm, silc_net_connect_st_finish);
669     return SILC_FSM_CONTINUE;
670   }
671
672   if (conn->stream_status != SILC_SOCKET_OK) {
673     /** Stream creation failed */
674     if (conn->stream_status == SILC_SOCKET_UNKNOWN_IP)
675       conn->status = SILC_NET_UNKNOWN_IP;
676     else if (conn->stream_status == SILC_SOCKET_UNKNOWN_HOST)
677       conn->status = SILC_NET_UNKNOWN_HOST;
678     else
679       conn->status = SILC_NET_ERROR;
680     silc_fsm_next(fsm, silc_net_connect_st_finish);
681     return SILC_FSM_CONTINUE;
682   }
683
684   /* Set stream information */
685   silc_socket_stream_set_info(conn->stream,
686                               !silc_net_is_ip(conn->remote) ? conn->remote :
687                               conn->ip_addr, conn->ip_addr, conn->port);
688
689   /** Stream created successfully */
690   SILC_LOG_DEBUG(("Connected successfully, sock %d", conn->sock));
691   conn->status = SILC_NET_OK;
692   silc_fsm_next(fsm, silc_net_connect_st_finish);
693   return SILC_FSM_CONTINUE;
694 }
695
696 SILC_FSM_STATE(silc_net_connect_st_finish)
697 {
698   SilcNetConnect conn = fsm_context;
699
700   /* Deliver error or new stream */
701   if (!conn->aborted) {
702     conn->callback(conn->status, conn->stream, conn->context);
703     if (conn->op)
704       silc_async_free(conn->op);
705     if (conn->sop)
706       silc_async_free(conn->sop);
707   }
708
709   return SILC_FSM_FINISH;
710 }
711
712 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
713 {
714   SilcNetConnect conn = context;
715   conn->aborted = TRUE;
716
717   /* Abort underlaying stream creation too */
718   if (conn->sop)
719     silc_async_abort(conn->sop, NULL, NULL);
720 }
721
722 static void silc_net_connect_destructor(SilcFSM fsm, void *fsm_context,
723                                         void *destructor_context)
724 {
725   SilcNetConnect conn = fsm_context;
726   silc_free(conn->local_ip);
727   silc_free(conn->remote);
728   silc_free(conn);
729 }
730
731 /* Create asynchronous TCP/IP connection. */
732
733 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
734                                         const char *remote_ip_addr,
735                                         int remote_port,
736                                         SilcSchedule schedule,
737                                         SilcNetCallback callback,
738                                         void *context)
739 {
740   SilcNetConnect conn;
741
742   if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
743     return NULL;
744
745   SILC_LOG_DEBUG(("Creating connection to host %s port %d",
746                   remote_ip_addr, remote_port));
747
748   conn = silc_calloc(1, sizeof(*conn));
749   if (!conn) {
750     callback(SILC_NET_NO_MEMORY, NULL, context);
751     return NULL;
752   }
753
754   /* Start async operation */
755   conn->op = silc_async_alloc(silc_net_connect_abort, NULL, conn);
756   if (!conn->op) {
757     silc_free(conn);
758     callback(SILC_NET_NO_MEMORY, NULL, context);
759     return NULL;
760   }
761
762   if (local_ip_addr)
763     conn->local_ip = strdup(local_ip_addr);
764   conn->remote = strdup(remote_ip_addr);
765   if (!conn->remote) {
766     silc_async_free(conn->op);
767     silc_free(conn->local_ip);
768     silc_free(conn);
769     callback(SILC_NET_NO_MEMORY, NULL, context);
770     return NULL;
771   }
772   conn->port = remote_port;
773   conn->callback = callback;
774   conn->context = context;
775   conn->retry = 1;
776   conn->status = SILC_NET_ERROR;
777
778   silc_fsm_init(&conn->fsm, conn, silc_net_connect_destructor, NULL, schedule);
779   silc_fsm_start(&conn->fsm, silc_net_connect_st_start);
780
781   return conn->op;
782 }
783
784 /* Closes the connection by closing the socket connection. */
785
786 void silc_net_close_connection(int sock)
787 {
788   SILC_LOG_DEBUG(("Closing sock %d", sock));
789   close(sock);
790 }
791
792 /* Set's the socket to non-blocking mode. */
793
794 int silc_net_set_socket_nonblock(SilcSocket sock)
795 {
796   return fcntl((int)sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
797 }
798
799 /* Converts the IP number string from numbers-and-dots notation to
800    binary form. */
801
802 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
803 {
804   int ret = 0;
805
806   if (silc_net_is_ip4(addr)) {
807     /* IPv4 address */
808     struct in_addr tmp;
809     ret = inet_aton(addr, &tmp);
810     if (bin_len < 4)
811       return FALSE;
812
813     memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
814 #ifdef HAVE_IPV6
815   } else {
816     struct addrinfo hints, *ai;
817     SilcSockaddr *s;
818
819     /* IPv6 address */
820     if (bin_len < 16)
821       return FALSE;
822
823     memset(&hints, 0, sizeof(hints));
824     hints.ai_family = AF_INET6;
825     if (getaddrinfo(addr, NULL, &hints, &ai))
826       return FALSE;
827
828     if (ai) {
829       s = (SilcSockaddr *)ai->ai_addr;
830       memcpy(bin, &s->sin6.sin6_addr, sizeof(s->sin6.sin6_addr));
831       freeaddrinfo(ai);
832     }
833
834     ret = TRUE;
835 #endif /* HAVE_IPV6 */
836   }
837
838   return ret != 0;
839 }