Fixed silc_net_tcp_connect crash.
[silc.git] / lib / silcutil / symbian / silcsymbiannet.cpp
1 /*
2
3   silcsymbiannet.cpp
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2006 - 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
20 #include "silc.h"
21 #include "silcsymbiansocketstream.h"
22
23 /****************************** TCP Listener ********************************/
24
25 class SilcSymbianTCPListener;
26
27 /* Deliver new stream to upper layer */
28
29 static void silc_net_accept_stream(SilcSocketStreamStatus status,
30                                    SilcStream stream, void *context)
31 {
32   SilcNetListener listener = (SilcNetListener)context;
33
34   /* In case of error, the socket has been destroyed already */
35   if (status != SILC_SOCKET_OK)
36     return;
37
38   listener->callback(SILC_NET_OK, stream, listener->context);
39 }
40
41 /* TCP Listener class */
42
43 class SilcSymbianTCPListener : public CActive {
44 public:
45   /* Constructor */
46   SilcSymbianTCPListener() : CActive(CActive::EPriorityStandard)
47   {
48     CActiveScheduler::Add(this);
49   }
50
51   /* Destructor */
52   ~SilcSymbianTCPListener()
53   {
54     Cancel();
55   }
56
57   /* Listen for connection */
58   void Listen()
59   {
60     new_conn = new RSocket;
61     if (!new_conn)
62       return;
63     if (new_conn->Open(ss) != KErrNone) {
64       Listen();
65       return;
66     }
67
68     /* Start listenning */
69     sock.Accept(*new_conn, iStatus);
70     SetActive();
71   }
72
73   /* Listener callback */
74   virtual void RunL()
75   {
76     if (iStatus != KErrNone) {
77       if (new_conn)
78         delete new_conn;
79       new_conn = NULL;
80       Listen();
81       return;
82     }
83
84     /* Set socket options */
85     new_conn->SetOpt(KSoReuseAddr, KSolInetIp, 1);
86
87     /* Create socket stream */
88     silc_socket_tcp_stream_create(
89                         (SilcSocket)silc_create_symbian_socket(new_conn, NULL),
90                         listener->lookup, listener->require_fqdn,
91                         listener->schedule, silc_net_accept_stream,
92                         (void *)listener);
93     new_conn = NULL;
94
95     /* Continue listenning */
96     Listen();
97   }
98
99   /* Cancel */
100   virtual void DoCancel()
101   {
102     sock.CancelAll();
103     ss.Close();
104     if (new_conn)
105       delete new_conn;
106   }
107
108   RSocket *new_conn;
109   RSocket sock;
110   RSocketServ ss;
111   SilcNetListener listener;
112 };
113
114 /* Create TCP listener */
115
116 SilcNetListener
117 silc_net_tcp_create_listener(const char **local_ip_addr,
118                              SilcUInt32 local_ip_count, int port,
119                              SilcBool lookup, SilcBool require_fqdn,
120                              SilcSchedule schedule,
121                              SilcNetCallback callback, void *context)
122 {
123   SilcNetListener listener = NULL;
124   SilcSymbianTCPListener *l = NULL;
125   TInetAddr server;
126   TInt ret;
127   TBuf<64> tmp;
128   int i;
129
130   SILC_LOG_DEBUG(("Creating TCP listener"));
131
132   if (port < 0 || !schedule || !callback)
133     goto err;
134
135   listener = (SilcNetListener)silc_calloc(1, sizeof(*listener));
136   if (!listener) {
137     callback(SILC_NET_NO_MEMORY, NULL, context);
138     return NULL;
139   }
140   listener->schedule = schedule;
141   listener->callback = callback;
142   listener->context = context;
143   listener->require_fqdn = require_fqdn;
144   listener->lookup = lookup;
145
146   if (local_ip_count > 0) {
147     listener->socks = (SilcSocket *)silc_calloc(local_ip_count,
148                                               sizeof(*listener->socks));
149     if (!listener->socks) {
150       callback(SILC_NET_NO_MEMORY, NULL, context);
151       return NULL;
152     }
153   } else {
154     listener->socks = (SilcSocket *)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] : "0.0.0.0"));
167
168     l = new SilcSymbianTCPListener;
169     if (!l)
170       goto err;
171
172     /* Connect to socket server */
173     ret = l->ss.Connect();
174     if (ret != KErrNone)
175       goto err;
176
177     /* Set listener address */
178     if (local_ip_addr) {
179       server = TInetAddr(port);
180       tmp = (TText *)local_ip_addr[i];
181       ret = server.Input(tmp);
182       if (ret != KErrNone)
183         goto err;
184     } else {
185       server = TInetAddr(KInetAddrAny, port);
186     }
187
188     /* Create the socket */
189     ret = l->sock.Open(l->ss, KAfInet, KSockStream, KProtocolInetTcp);
190     if (ret != KErrNone) {
191       SILC_LOG_ERROR(("Cannot create socket"));
192       goto err;
193     }
194
195     /* Set the socket options */
196     ret = l->sock.SetOpt(KSoReuseAddr, KSolInetIp, 1);
197     if (ret != KErrNone) {
198       SILC_LOG_ERROR(("Cannot set socket options"));
199       goto err;
200     }
201
202     /* Bind the listener socket */
203     ret = l->sock.Bind(server);
204     if (ret != KErrNone) {
205       SILC_LOG_DEBUG(("Cannot bind socket"));
206       goto err;
207     }
208
209     /* Specify that we are listenning */
210     ret = l->sock.Listen(5);
211     if (ret != KErrNone) {
212       SILC_LOG_ERROR(("Cannot set socket listenning"));
213       goto err;
214     }
215     l->Listen();
216
217     l->listener = listener;
218     listener->socks[i] = (SilcSocket)l;
219     listener->socks_count++;
220   }
221
222   SILC_LOG_DEBUG(("TCP listener created"));
223
224   return listener;
225
226  err:
227   if (l)
228     delete l;
229   if (callback)
230     callback(SILC_NET_ERROR, NULL, context);
231   if (listener)
232     silc_net_close_listener(listener);
233   return NULL;
234 }
235
236 /* Close network listener */
237
238 void silc_net_close_listener(SilcNetListener listener)
239 {
240   int i;
241
242   SILC_LOG_DEBUG(("Closing network listener"));
243
244   for (i = 0; i < listener->socks_count; i++) {
245     SilcSymbianTCPListener *l = (SilcSymbianTCPListener *)listener->socks[i];
246     l->sock.CancelAll();
247     l->sock.Close();
248     l->ss.Close();
249     if (l->new_conn)
250       delete l->new_conn;
251     delete l;
252   }
253
254   silc_free(listener->socks);
255   silc_free(listener);
256 }
257
258 /**************************** TCP/IP connecting *****************************/
259
260 static void silc_net_connect_stream(SilcSocketStreamStatus status,
261                                     SilcStream stream, void *context);
262
263 /* TCP connecting class */
264
265 class SilcSymbianTCPConnect : public CActive {
266 public:
267   /* Constructor */
268   SilcSymbianTCPConnect() : CActive(CActive::EPriorityStandard)
269   {
270     CActiveScheduler::Add(this);
271   }
272
273   /* Destructor */
274   ~SilcSymbianTCPConnect()
275   {
276     silc_free(remote);
277     if (op)
278       silc_async_free(op);
279     Cancel();
280   }
281
282   /* Connect to remote host */
283   void Connect(TSockAddr &addr)
284   {
285     sock->Connect(addr, iStatus);
286     SetActive();
287   }
288
289   /* Connection callback */
290   virtual void RunL()
291   {
292     if (iStatus != KErrNone) {
293       if (callback)
294         callback(SILC_NET_ERROR, NULL, context);
295       sock->CancelConnect();
296       delete sock;
297       ss->Close();
298       delete ss;
299       sock = NULL;
300       ss = NULL;
301       delete this;
302       return;
303     }
304
305     /* Create stream */
306     if (callback) {
307       silc_socket_tcp_stream_create(
308                              (SilcSocket)silc_create_symbian_socket(sock, ss),
309                              TRUE, FALSE, schedule, silc_net_connect_stream,
310                              (void *)this);
311     } else {
312       sock->Close();
313       delete sock;
314       ss->Close();
315       delete ss;
316       sock = NULL;
317       ss = NULL;
318     }
319
320     delete this;
321   }
322
323   /* Cancel */
324   virtual void DoCancel()
325   {
326     if (ss) {
327       ss->Close();
328       delete ss;
329     }
330     if (sock) {
331       sock->CancelConnect();
332       delete sock;
333     }
334   }
335
336   RSocket *sock;
337   RSocketServ *ss;
338   char *remote;
339   char remote_ip[64];
340   int port;
341   SilcAsyncOperation op;
342   SilcSchedule schedule;
343   SilcNetCallback callback;
344   void *context;
345 };
346
347 /* Stream creation callback */
348
349 static void silc_net_connect_stream(SilcSocketStreamStatus status,
350                                     SilcStream stream, void *context)
351 {
352   SilcSymbianTCPConnect *conn = (SilcSymbianTCPConnect *)context;
353   SilcNetStatus net_status = SILC_NET_OK;
354
355   if (status != SILC_SOCKET_OK) {
356     /* In case of error, the socket has been destroyed already */
357     if (status == SILC_SOCKET_UNKNOWN_IP)
358       net_status = SILC_NET_UNKNOWN_IP;
359     else if (status == SILC_SOCKET_UNKNOWN_HOST)
360       net_status = SILC_NET_UNKNOWN_HOST;
361     else
362       net_status = SILC_NET_ERROR;
363   }
364
365   /* Call connection callback */
366   if (conn->callback)
367     conn->callback(net_status, stream, conn->context);
368   else if (stream)
369     silc_stream_destroy(stream);
370
371   delete conn;
372 }
373
374 /* Connecting abort callback */
375
376 static void silc_net_connect_abort(SilcAsyncOperation op, void *context)
377 {
378   SilcSymbianTCPConnect *conn = (SilcSymbianTCPConnect *)context;
379
380   /* Abort */
381   conn->callback = NULL;
382   conn->op = NULL;
383   if (conn->sock)
384     sock->CancelConnect();
385 }
386
387 /* Create TCP/IP connection */
388
389 SilcAsyncOperation silc_net_tcp_connect(const char *local_ip_addr,
390                                         const char *remote_ip_addr,
391                                         int remote_port,
392                                         SilcSchedule schedule,
393                                         SilcNetCallback callback,
394                                         void *context)
395 {
396   SilcSymbianTCPConnect *conn;
397   TInetAddr local, remote;
398   SilcNetStatus status;
399   TBuf<64> tmp;
400   TInt ret;
401
402   if (!remote_ip_addr || remote_port < 1 || !schedule || !callback)
403     return NULL;
404
405   SILC_LOG_DEBUG(("Creating connection to host %s port %d",
406                   remote_ip_addr, remote_port));
407
408   conn = new SilcSymbianTCPConnect;
409   if (!conn) {
410     callback(SILC_NET_NO_MEMORY, NULL, context);
411     return NULL;
412   }
413   conn->schedule = schedule;
414   conn->callback = callback;
415   conn->context = context;
416   conn->port = remote_port;
417   conn->remote = strdup(remote_ip_addr);
418   if (!conn->remote) {
419     status = SILC_NET_NO_MEMORY;
420     goto err;
421   }
422
423   /* Allocate socket */
424   conn->sock = new RSocket;
425   if (!conn->sock) {
426     status = SILC_NET_NO_MEMORY;
427     goto err;
428   }
429
430   /* Allocate socket server */
431   conn->ss = new RSocketServ;
432   if (!conn->ss) {
433     status = SILC_NET_NO_MEMORY;
434     goto err;
435   }
436
437   /* Connect to socket server */
438   ret = conn->ss->Connect();
439   if (ret != KErrNone) {
440     status = SILC_NET_ERROR;
441     goto err;
442   }
443
444   /* Start async operation */
445   conn->op = silc_async_alloc(silc_net_connect_abort, NULL, (void *)conn);
446   if (!conn->op) {
447     status = SILC_NET_NO_MEMORY;
448     goto err;
449   }
450
451   /* Do host lookup */
452   if (!silc_net_is_ip(remote_ip_addr)) {
453     if (!silc_net_gethostbyname(remote_ip_addr, FALSE, conn->remote_ip,
454                                 sizeof(conn->remote_ip))) {
455       SILC_LOG_ERROR(("Network (%s) unreachable: could not resolve the "
456                       "host", conn->remote));
457       status = SILC_NET_HOST_UNREACHABLE;
458       goto err;
459     }
460   } else {
461     strcpy(conn->remote_ip, remote_ip_addr);
462   }
463
464   /* Create the connection socket */
465   ret = conn->sock->Open(*conn->ss, KAfInet, KSockStream, KProtocolInetTcp);
466   if (ret != KErrNone) {
467     SILC_LOG_ERROR(("Cannot create socket"));
468     status = SILC_NET_ERROR;
469     goto err;
470   }
471
472   /* Set appropriate options */
473   conn->sock->SetOpt(KSoTcpNoDelay, KSolInetTcp, 1);
474   conn->sock->SetOpt(KSoTcpKeepAlive, KSolInetTcp, 1);
475
476   /* Bind to the local address if provided */
477   if (local_ip_addr) {
478     local = TInetAddr(0);
479     tmp = (TText *)local_ip_addr;
480     ret = local.Input(tmp);
481     if (ret == KErrNone)
482       ret = conn->sock->Bind(local);
483   }
484
485   /* Connect to the host */
486   remote = TInetAddr(remote_port);
487   tmp = (TText *)conn->remote_ip;
488   ret = remote.Input(tmp);
489   if (ret != KErrNone) {
490     SILC_LOG_ERROR(("Cannot connect (cannot set address)"));
491     status = SILC_NET_ERROR;
492     goto err;
493   }
494   conn->Connect(remote);
495
496   SILC_LOG_DEBUG(("Connection operation in progress"));
497
498   return conn->op;
499
500  err:
501   if (conn->ss) {
502     conn->ss->Close();
503     delete conn->ss;
504   }
505   if (conn->sock)
506     delete conn->sock;
507   if (conn->remote)
508     silc_free(conn->remote);
509   if (conn->op)
510     silc_async_free(conn->op);
511   callback(status, NULL, context);
512   delete conn;
513   return NULL;
514 }
515
516 /****************************** UDP routines ********************************/
517
518 /* Create UDP/IP connection */
519
520 SilcStream silc_net_udp_connect(const char *local_ip_addr, int local_port,
521                                 const char *remote_ip_addr, int remote_port,
522                                 SilcSchedule schedule)
523 {
524   SilcSymbianSocket *s;
525   SilcStream stream;
526   TInetAddr local, remote;
527   TRequestStatus status;
528   RSocket *sock = NULL;
529   RSocketServ *ss = NULL;
530   TBuf<64> tmp;
531   TInt ret;
532
533   SILC_LOG_DEBUG(("Creating UDP stream"));
534
535   if (!schedule)
536     goto err;
537
538   SILC_LOG_DEBUG(("Binding to local address %s",
539                   local_ip_addr ? local_ip_addr : "0.0.0.0"));
540
541   sock = new RSocket;
542   if (!sock)
543     goto err;
544
545   ss = new RSocketServ;
546   if (!ss)
547     goto err;
548
549   /* Open socket server */
550   ret = ss->Connect();
551   if (ret != KErrNone)
552     goto err;
553
554   /* Get local bind address */
555   if (local_ip_addr) {
556     local = TInetAddr(local_port);
557     tmp = (TText *)local_ip_addr;
558     ret = local.Input(tmp);
559     if (ret != KErrNone)
560       goto err;
561   } else {
562     local = TInetAddr(KInetAddrAny, local_port);
563   }
564
565   /* Create the socket */
566   ret = sock->Open(*ss, KAfInet, KSockDatagram, KProtocolInetUdp);
567   if (ret != KErrNone) {
568     SILC_LOG_ERROR(("Cannot create socket"));
569     goto err;
570   }
571
572   /* Set the socket options */
573   sock->SetOpt(KSoReuseAddr, KSolInetIp, 1);
574
575   /* Bind the listener socket */
576   ret = sock->Bind(local);
577   if (ret != KErrNone) {
578     SILC_LOG_DEBUG(("Cannot bind socket"));
579     goto err;
580   }
581
582   /* Set to connected state if remote address is provided. */
583   if (remote_ip_addr && remote_port) {
584     remote = TInetAddr(remote_port);
585     tmp = (TText *)remote_ip_addr;
586     ret = remote.Input(tmp);
587     if (ret != KErrNone)
588       goto err;
589
590     sock->Connect(remote, status);
591     if (status != KErrNone) {
592       SILC_LOG_DEBUG(("Cannot connect UDP stream"));
593       goto err;
594     }
595   }
596
597   /* Encapsulate into socket stream */
598   s = silc_create_symbian_socket(sock, ss);
599   if (!s)
600     goto err;
601   stream =
602     silc_socket_udp_stream_create((SilcSocket)s, local_ip_addr ?
603                                   silc_net_is_ip6(local_ip_addr) : FALSE,
604                                   remote_ip_addr ? TRUE : FALSE, schedule);
605   if (!stream)
606     goto err;
607
608   SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
609   return stream;
610
611  err:
612   if (sock)
613     delete sock;
614   if (ss) {
615     ss->Close();
616     delete ss;
617   }
618   return NULL;
619 }
620
621 /* Sets socket to non-blocking mode */
622
623 int silc_net_set_socket_nonblock(SilcSocket sock)
624 {
625   /* Nothing to do in Symbian where blocking socket mode is asynchronous
626      already (ie. non-blocking). */
627   return 0;
628 }
629
630 /* Converts the IP number string from numbers-and-dots notation to
631    binary form. */
632
633 SilcBool silc_net_addr2bin(const char *addr, void *bin, SilcUInt32 bin_len)
634 {
635   int ret = 0;
636
637   struct in_addr tmp;
638   ret = inet_aton(addr, &tmp);
639   if (bin_len < 4)
640     return FALSE;
641
642   memcpy(bin, (unsigned char *)&tmp.s_addr, 4);
643
644   return ret != 0;
645 }
646
647 /* Get remote host and IP from socket */
648
649 SilcBool silc_net_check_host_by_sock(SilcSocket sock, char **hostname,
650                                      char **ip)
651 {
652   SilcSymbianSocket *s = (SilcSymbianSocket *)sock;
653   TInetAddr addr;
654   char host[256];
655   TBuf<64> tmp;
656
657   if (hostname)
658     *hostname = NULL;
659   *ip = NULL;
660
661   s->sock->RemoteName(addr);
662   addr.Output(tmp);
663
664   *ip = (char *)silc_memdup(tmp.Ptr(), tmp.Length());
665   if (*ip == NULL)
666     return FALSE;
667
668   /* Do reverse lookup if we want hostname too. */
669   if (hostname) {
670     /* Get host by address */
671     if (!silc_net_gethostbyaddr(*ip, host, sizeof(host)))
672       return FALSE;
673
674     *hostname = (char *)silc_memdup(host, strlen(host));
675     SILC_LOG_DEBUG(("Resolved hostname `%s'", *hostname));
676
677     /* Reverse */
678     if (!silc_net_gethostbyname(*hostname, TRUE, host, sizeof(host)))
679       return FALSE;
680
681     if (strcmp(*ip, host))
682       return FALSE;
683   }
684
685   SILC_LOG_DEBUG(("Resolved IP address `%s'", *ip));
686   return TRUE;
687 }
688
689 /* Get local host and IP from socket */
690
691 SilcBool silc_net_check_local_by_sock(SilcSocket sock, char **hostname,
692                                       char **ip)
693 {
694   SilcSymbianSocket *s = (SilcSymbianSocket *)sock;
695   TInetAddr addr;
696   char host[256];
697   TBuf<64> tmp;
698
699   if (hostname)
700     *hostname = NULL;
701   *ip = NULL;
702
703   s->sock->LocalName(addr);
704   addr.Output(tmp);
705
706   *ip = (char *)silc_memdup(tmp.Ptr(), tmp.Length());
707   if (*ip == NULL)
708     return FALSE;
709
710   /* Do reverse lookup if we want hostname too. */
711   if (hostname) {
712     /* Get host by address */
713     if (!silc_net_gethostbyaddr(*ip, host, sizeof(host)))
714       return FALSE;
715
716     *hostname = (char *)silc_memdup(host, strlen(host));
717     SILC_LOG_DEBUG(("Resolved hostname `%s'", *hostname));
718
719     /* Reverse */
720     if (!silc_net_gethostbyname(*hostname, TRUE, host, sizeof(host)))
721       return FALSE;
722
723     if (strcmp(*ip, host))
724       return FALSE;
725   }
726
727   SILC_LOG_DEBUG(("Resolved IP address `%s'", *ip));
728   return TRUE;
729 }
730
731 /* Get remote port from socket */
732
733 SilcUInt16 silc_net_get_remote_port(SilcSocket sock)
734 {
735   SilcSymbianSocket *s = (SilcSymbianSocket *)sock;
736   TInetAddr addr;
737
738   s->sock->RemoteName(addr);
739   return (SilcUInt16)addr.Port();
740 }
741
742 /* Get local port from socket */
743
744 SilcUInt16 silc_net_get_local_port(SilcSocket sock)
745 {
746   SilcSymbianSocket *s = (SilcSymbianSocket *)sock;
747   TInetAddr addr;
748
749   s->sock->LocalName(addr);
750   return (SilcUInt16)addr.Port();
751 }