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