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