12baadee80ed0594b38dc3b153b69dd8c936a9d0
[sdk/target/sdbd.git] / src / sockets.c
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <errno.h>
21 #include <string.h>
22 #include <ctype.h>
23
24 #include "sysdeps.h"
25
26 #define  TRACE_TAG  TRACE_SOCKETS
27 #include "log.h"
28
29 #include "sdb.h"
30 #include "strutils.h"
31 #include "utils.h"
32
33 SDB_MUTEX_DEFINE( socket_list_lock );
34
35 static void local_socket_close_locked(asocket *s);
36
37 int sendfailmsg(int fd, const char *reason)
38 {
39     char buf[9];
40     int len;
41     len = strlen(reason);
42     if(len > 0xffff) len = 0xffff;
43     snprintf(buf, sizeof buf, "FAIL%04x", len);
44     if(writex(fd, buf, 8)) return -1;
45     return writex(fd, reason, len);
46 }
47
48 //extern int online;
49
50 static unsigned local_socket_next_id = 1;
51
52 static asocket local_socket_list = {
53     .next = &local_socket_list,
54     .prev = &local_socket_list,
55 };
56
57 /* the the list of currently closing local sockets.
58 ** these have no peer anymore, but still packets to
59 ** write to their fd.
60 */
61 static asocket local_socket_closing_list = {
62     .next = &local_socket_closing_list,
63     .prev = &local_socket_closing_list,
64 };
65
66 asocket *find_local_socket(unsigned id)
67 {
68     asocket *s;
69     asocket *result = NULL;
70
71     sdb_mutex_lock(&socket_list_lock);
72     for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
73         if (s->id == id) {
74             result = s;
75             break;
76         }
77     }
78     sdb_mutex_unlock(&socket_list_lock);
79
80     return result;
81 }
82
83 static void
84 insert_local_socket(asocket*  s, asocket*  list)
85 {
86     s->next       = list;
87     s->prev       = s->next->prev;
88     s->prev->next = s;
89     s->next->prev = s;
90 }
91
92
93 void install_local_socket(asocket *s)
94 {
95     sdb_mutex_lock(&socket_list_lock);
96
97     s->id = local_socket_next_id++;
98     insert_local_socket(s, &local_socket_list);
99
100     sdb_mutex_unlock(&socket_list_lock);
101 }
102
103 void remove_socket(asocket *s)
104 {
105     // socket_list_lock should already be held
106     if (s->prev && s->next)
107     {
108         s->prev->next = s->next;
109         s->next->prev = s->prev;
110         s->next = 0;
111         s->prev = 0;
112         s->id = 0;
113     }
114 }
115
116 void close_all_sockets(atransport *t)
117 {
118     asocket *s;
119
120         /* this is a little gross, but since s->close() *will* modify
121         ** the list out from under you, your options are limited.
122         */
123     sdb_mutex_lock(&socket_list_lock);
124 restart:
125     for(s = local_socket_list.next; s != &local_socket_list; s = s->next){
126         if(s->transport == t || (s->peer && s->peer->transport == t)) {
127             local_socket_close_locked(s);
128             goto restart;
129         }
130     }
131     sdb_mutex_unlock(&socket_list_lock);
132 }
133
134 static int local_socket_enqueue(asocket *s, apacket *p)
135 {
136     D("LS(%d): enqueue %d\n", s->id, p->len);
137
138     p->ptr = p->data;
139
140         /* if there is already data queue'd, we will receive
141         ** events when it's time to write.  just add this to
142         ** the tail
143         */
144     if(s->pkt_first) {
145         goto enqueue;
146     }
147
148         /* write as much as we can, until we
149         ** would block or there is an error/eof
150         */
151     while(p->len > 0) {
152         int r = sdb_write(s->fd, p->ptr, p->len);
153         if(r > 0) {
154             p->len -= r;
155             p->ptr += r;
156             continue;
157         }
158         if((r == 0) || (errno != EAGAIN)) {
159             D( "LS(%d): not ready, errno=%d\n", s->id, errno);
160             s->close(s);
161             return 1; /* not ready (error) */
162         } else {
163             break;
164         }
165     }
166
167     if(p->len == 0) {
168         put_apacket(p);
169         return 0; /* ready for more data */
170     }
171
172 enqueue:
173     p->next = 0;
174     if(s->pkt_first) {
175         s->pkt_last->next = p;
176     } else {
177         s->pkt_first = p;
178     }
179     s->pkt_last = p;
180
181         /* make sure we are notified when we can drain the queue */
182     fdevent_add(&s->fde, FDE_WRITE);
183
184     return 1; /* not ready (backlog) */
185 }
186
187 static void local_socket_ready(asocket *s)
188 {
189         /* far side is ready for data, pay attention to
190            readable events */
191     fdevent_add(&s->fde, FDE_READ);
192 //    D("LS(%d): ready()\n", s->id);
193 }
194
195 static void local_socket_close(asocket *s)
196 {
197     sdb_mutex_lock(&socket_list_lock);
198     local_socket_close_locked(s);
199     sdb_mutex_unlock(&socket_list_lock);
200 }
201
202 // be sure to hold the socket list lock when calling this
203 static void local_socket_destroy(asocket  *s)
204 {
205     apacket *p, *n;
206
207     D("LS(%d): destroying fde.fd=%d\n", s->id, s->fde.fd);
208
209         /* IMPORTANT: the remove closes the fd
210         ** that belongs to this socket
211         */
212     fdevent_remove(&s->fde);
213
214         /* dispose of any unwritten data */
215     for(p = s->pkt_first; p; p = n) {
216         D("LS(%d): discarding %d bytes\n", s->id, p->len);
217         n = p->next;
218         put_apacket(p);
219     }
220     remove_socket(s);
221     free(s);
222 }
223
224
225 static void local_socket_close_locked(asocket *s)
226 {
227     D("entered. LS(%d) fd=%d\n", s->id, s->fd);
228     if(s->peer) {
229         D("LS(%d): closing peer. peer->id=%d peer->fd=%d\n",
230           s->id, s->peer->id, s->peer->fd);
231         s->peer->peer = 0;
232         // tweak to avoid deadlock
233         if (s->peer->close == local_socket_close) {
234             local_socket_close_locked(s->peer);
235         } else {
236             s->peer->close(s->peer);
237         }
238         s->peer = 0;
239     }
240
241         /* If we are already closing, or if there are no
242         ** pending packets, destroy immediately
243         */
244     if (s->closing || s->pkt_first == NULL) {
245         int   id = s->id;
246         local_socket_destroy(s);
247         D("LS(%d): closed\n", id);
248         return;
249     }
250
251         /* otherwise, put on the closing list
252         */
253     D("LS(%d): closing\n", s->id);
254     s->closing = 1;
255     fdevent_del(&s->fde, FDE_READ);
256     remove_socket(s);
257     D("LS(%d): put on socket_closing_list fd=%d\n", s->id, s->fd);
258     insert_local_socket(s, &local_socket_closing_list);
259 }
260
261 static void local_socket_event_func(int fd, unsigned ev, void *_s)
262 {
263     asocket *s = _s;
264
265     D("LS(%d): event_func(fd=%d(==%d), ev=%04x)\n", s->id, s->fd, fd, ev);
266
267     /* put the FDE_WRITE processing before the FDE_READ
268     ** in order to simplify the code.
269     */
270     if(ev & FDE_WRITE){
271         apacket *p;
272
273         while((p = s->pkt_first) != 0) {
274             while(p->len > 0) {
275                 int r = sdb_write(fd, p->ptr, p->len);
276                 if(r > 0) {
277                     p->ptr += r;
278                     p->len -= r;
279                     continue;
280                 }
281                 if(r < 0) {
282                     /* returning here is ok because FDE_READ will
283                     ** be processed in the next iteration loop
284                     */
285                     if(errno == EAGAIN) return;
286                     if(errno == EINTR) continue;
287                 }
288                 D(" closing after write because r=%d and errno is %d\n", r, errno);
289                 s->close(s);
290                 return;
291             }
292
293             if(p->len == 0) {
294                 s->pkt_first = p->next;
295                 if(s->pkt_first == 0) s->pkt_last = 0;
296                 put_apacket(p);
297             }
298         }
299
300             /* if we sent the last packet of a closing socket,
301             ** we can now destroy it.
302             */
303         if (s->closing) {
304             D(" closing because 'closing' is set after write\n");
305             s->close(s);
306             return;
307         }
308
309             /* no more packets queued, so we can ignore
310             ** writable events again and tell our peer
311             ** to resume writing
312             */
313         fdevent_del(&s->fde, FDE_WRITE);
314         s->peer->ready(s->peer);
315     }
316
317
318     if(ev & FDE_READ){
319         apacket *p = get_apacket();
320         unsigned char *x = p->data;
321 #ifdef SUPPORT_ENCRYPT
322         // sdb.c:536에서 sdb server의 패킷은 MAX_PAYLOAD-100으로 정하여서,
323         // sdb server에서 패킷 데이터의 크기를 MAX_PAYLOAD-100보다 작은 지를 체크함.
324         // sdbd에서 패킷 데이터를 MAX_PAYLOAD - 200로 잡아서 암호화 하게되면
325         // 최대 MAX_PAYLOAD - 100 크기의 패킷을 생성하게 됨.
326         const size_t max_payload = asock_get_max_payload(s) - 200;
327 #else
328         const size_t max_payload = asock_get_max_payload(s);
329 #endif
330         int avail = max_payload;
331         int r = 0;
332         int is_eof = 0;
333
334         while (avail > 0) {
335             r = sdb_read(fd, x, avail);
336             D("LS(%d): post sdb_read(fd=%d,...) r=%d (errno=%d) avail=%d\n",
337               s->id, s->fd, r, r < 0 ? errno : 0, avail);
338             if (r > 0 && r <= avail) {
339                 avail -= r;
340                 x += r;
341                 continue;
342             }
343             if (r < 0) {
344                 if (errno == EAGAIN) break;
345                 if (errno == EINTR) continue;
346             }
347
348             /* r = 0 or unhandled error */
349             is_eof = 1;
350             break;
351         }
352         D("LS(%d): fd=%d post avail loop. r=%d is_eof=%d forced_eof=%d\n",
353           s->id, s->fd, r, is_eof, s->fde.force_eof);
354
355         //변경된 최대 패킷 크기로 코드 수정
356         if ((avail == max_payload) || (s->peer == 0)) {
357             put_apacket(p);
358         } else {
359             p->len = max_payload >= avail ? max_payload - avail : 0;
360             r = s->peer->enqueue(s->peer, p);
361             D("LS(%d): fd=%d post peer->enqueue(). r=%d\n", s->id, s->fd, r);
362
363             if(r < 0) {
364                     /* error return means they closed us as a side-effect
365                     ** and we must return immediately.
366                     **
367                     ** note that if we still have buffered packets, the
368                     ** socket will be placed on the closing socket list.
369                     ** this handler function will be called again
370                     ** to process FDE_WRITE events.
371                     */
372                 return;
373             }
374
375             if(r > 0) {
376                     /* if the remote cannot accept further events,
377                     ** we disable notification of READs.  They'll
378                     ** be enabled again when we get a call to ready()
379                     */
380                 fdevent_del(&s->fde, FDE_READ);
381             }
382         }
383         /* Don't allow a forced eof if data is still there */
384         if((s->fde.force_eof && !r) || is_eof) {
385             D(" closing because is_eof=%d r=%d s->fde.force_eof=%d\n", is_eof, r, s->fde.force_eof);
386             s->close(s);
387         }
388     }
389
390     if(ev & FDE_ERROR){
391             /* this should be caught be the next read or write
392             ** catching it here means we may skip the last few
393             ** bytes of readable data.
394             */
395 //        s->close(s);
396         D("LS(%d): FDE_ERROR (fd=%d)\n", s->id, s->fd);
397
398         return;
399     }
400 }
401
402 asocket *create_local_socket(int fd)
403 {
404     asocket *s = calloc(1, sizeof(asocket));
405     if (s == NULL) fatal("cannot allocate socket");
406     s->fd = fd;
407     s->enqueue = local_socket_enqueue;
408     s->ready = local_socket_ready;
409     s->close = local_socket_close;
410     install_local_socket(s);
411
412     fdevent_install(&s->fde, fd, local_socket_event_func, s);
413 /*    fdevent_add(&s->fde, FDE_ERROR); */
414     //fprintf(stderr, "Created local socket in create_local_socket \n");
415     D("LS(%d): created (fd=%d)\n", s->id, s->fd);
416     return s;
417 }
418
419 asocket *create_local_service_socket(const char *name)
420 {
421     asocket *s;
422     int fd;
423
424 #if 0 /* not support in tizen */
425     if (!strcmp(name,"jdwp")) {
426         return create_jdwp_service_socket();
427     }
428     if (!strcmp(name,"track-jdwp")) {
429         return create_jdwp_tracker_service_socket();
430     }
431 #endif
432     fd = service_to_fd(name);
433     if(fd < 0) return 0;
434
435     s = create_local_socket(fd);
436     D("LS(%d): bound to '%s' via %d\n", s->id, name, fd);
437
438     return s;
439 }
440
441 /* a Remote socket is used to send/receive data to/from a given transport object
442 ** it needs to be closed when the transport is forcibly destroyed by the user
443 */
444 typedef struct aremotesocket {
445     asocket      socket;
446     adisconnect  disconnect;
447 } aremotesocket;
448
449 static int remote_socket_enqueue(asocket *s, apacket *p)
450 {
451     D("entered remote_socket_enqueue RS(%d) WRITE fd=%d peer.fd=%d\n",
452       s->id, s->fd, s->peer->fd);
453     p->msg.command = A_WRTE;
454     p->msg.arg0 = s->peer->id;
455     p->msg.arg1 = s->id;
456     p->msg.data_length = p->len;
457     send_packet(p, s->transport);
458     return 1;
459 }
460
461 static void remote_socket_ready(asocket *s)
462 {
463     D("entered remote_socket_ready RS(%d) OKAY fd=%d peer.fd=%d\n",
464       s->id, s->fd, s->peer->fd);
465     apacket *p = get_apacket();
466     p->msg.command = A_OKAY;
467     p->msg.arg0 = s->peer->id;
468     p->msg.arg1 = s->id;
469     send_packet(p, s->transport);
470 }
471
472 static void remote_socket_close(asocket *s)
473 {
474     D("entered remote_socket_close RS(%d) CLOSE fd=%d peer->fd=%d\n",
475       s->id, s->fd, s->peer?s->peer->fd:-1);
476     apacket *p = get_apacket();
477     p->msg.command = A_CLSE;
478     if(s->peer) {
479         p->msg.arg0 = s->peer->id;
480         s->peer->peer = 0;
481         D("RS(%d) peer->close()ing peer->id=%d peer->fd=%d\n",
482           s->id, s->peer->id, s->peer->fd);
483         s->peer->close(s->peer);
484     }
485     p->msg.arg1 = s->id;
486     send_packet(p, s->transport);
487     D("RS(%d): closed\n", s->id);
488     remove_transport_disconnect( s->transport, &((aremotesocket*)s)->disconnect );
489     free(s);
490 }
491
492 static void remote_socket_disconnect(void*  _s, atransport*  t)
493 {
494     asocket*  s    = _s;
495     asocket*  peer = s->peer;
496
497     D("remote_socket_disconnect RS(%d)\n", s->id);
498     if (peer) {
499         peer->peer = NULL;
500         peer->close(peer);
501     }
502     remove_transport_disconnect( s->transport, &((aremotesocket*)s)->disconnect );
503     free(s);
504 }
505
506 asocket *create_remote_socket(unsigned id, atransport *t)
507 {
508     asocket *s = calloc(1, sizeof(aremotesocket));
509     adisconnect*  dis = &((aremotesocket*)s)->disconnect;
510
511     if (s == NULL) fatal("cannot allocate socket");
512     s->id = id;
513     s->enqueue = remote_socket_enqueue;
514     s->ready = remote_socket_ready;
515     s->close = remote_socket_close;
516     s->transport = t;
517
518     dis->func   = remote_socket_disconnect;
519     dis->opaque = s;
520     add_transport_disconnect( t, dis );
521     D("RS(%d): created\n", s->id);
522     return s;
523 }
524
525 void connect_to_remote(asocket *s, const char *destination)
526 {
527     D("Connect_to_remote call RS(%d) fd=%d\n", s->id, s->fd);
528     apacket *p = get_apacket();
529     size_t len = strlen(destination) + 1;
530
531     if(len > (asock_get_max_payload(s)-1)) {
532         fatal("destination oversized");
533     }
534
535     D("LS(%d): connect('%s')\n", s->id, destination);
536     p->msg.command = A_OPEN;
537     p->msg.arg0 = s->id;
538     p->msg.data_length = len;
539     s_strncpy((char*) p->data, destination, len);
540     send_packet(p, s->transport);
541 }
542
543
544 /* this is used by magic sockets to rig local sockets to
545    send the go-ahead message when they connect */
546 static void local_socket_ready_notify(asocket *s)
547 {
548     s->ready = local_socket_ready;
549     s->close = local_socket_close;
550     sdb_write(s->fd, "OKAY", 4);
551     s->ready(s);
552 }
553
554 /* this is used by magic sockets to rig local sockets to
555    send the failure message if they are closed before
556    connected (to avoid closing them without a status message) */
557 static void local_socket_close_notify(asocket *s)
558 {
559     s->ready = local_socket_ready;
560     s->close = local_socket_close;
561     sendfailmsg(s->fd, "closed");
562     s->close(s);
563 }
564
565 unsigned unhex(unsigned char *s, int len)
566 {
567     unsigned n = 0, c;
568
569     while(len-- > 0) {
570         switch((c = *s++)) {
571         case '0': case '1': case '2':
572         case '3': case '4': case '5':
573         case '6': case '7': case '8':
574         case '9':
575             c -= '0';
576             break;
577         case 'a': case 'b': case 'c':
578         case 'd': case 'e': case 'f':
579             c = c - 'a' + 10;
580             break;
581         case 'A': case 'B': case 'C':
582         case 'D': case 'E': case 'F':
583             c = c - 'A' + 10;
584             break;
585         default:
586             return 0xffffffff;
587         }
588
589         n = (n << 4) | c;
590     }
591
592     return n;
593 }
594
595 /* skip_host_serial return the position in a string
596    skipping over the 'serial' parameter in the SDB protocol,
597    where parameter string may be a host:port string containing
598    the protocol delimiter (colon). */
599 char *skip_host_serial(char *service) {
600     char *first_colon, *serial_end;
601
602     first_colon = strchr(service, ':');
603     if (!first_colon) {
604         /* No colon in service string. */
605         return NULL;
606     }
607     serial_end = first_colon;
608     if (isdigit(serial_end[1])) {
609         serial_end++;
610         while ((*serial_end) && isdigit(*serial_end)) {
611             serial_end++;
612         }
613         if ((*serial_end) != ':') {
614             // Something other than numbers was found, reset the end.
615             serial_end = first_colon;
616         }
617     }
618     return serial_end;
619 }
620
621 static int smart_socket_enqueue(asocket *s, apacket *p)
622 {
623     unsigned len;
624
625     D("SS(%d): enqueue %d\n", s->id, p->len);
626
627     if(s->pkt_first == 0) {
628         s->pkt_first = p;
629         s->pkt_last = p;
630     } else {
631         if((s->pkt_first->len + p->len) > asock_get_max_payload(s)) {
632             D("SS(%d): overflow\n", s->id);
633             put_apacket(p);
634             goto fail;
635         }
636
637         memcpy(s->pkt_first->data + s->pkt_first->len,
638                p->data, p->len);
639         s->pkt_first->len += p->len;
640         put_apacket(p);
641
642         p = s->pkt_first;
643     }
644
645         /* don't bother if we can't decode the length */
646     if(p->len < 4) return 0;
647
648     len = unhex(p->data, 4);
649     if((len < 1) ||  (len > 1024)) {
650         D("SS(%d): bad size (%d)\n", s->id, len);
651         goto fail;
652     }
653
654     D("SS(%d): len is %d\n", s->id, len );
655         /* can't do anything until we have the full header */
656     if((len + 4) > p->len) {
657         D("SS(%d): waiting for %d more bytes\n", s->id, len+4 - p->len);
658         return 0;
659     }
660
661     p->data[len + 4] = 0;
662
663     D("SS(%d): '%s'\n", s->id, (char*) (p->data + 4));
664
665     if (s->transport == NULL) {
666         char* error_string = "unknown failure";
667         s->transport = acquire_one_transport (CS_ANY,
668                 kTransportAny, NULL, &error_string);
669
670         if (s->transport == NULL) {
671             sendfailmsg(s->peer->fd, error_string);
672             goto fail;
673         }
674     }
675
676     if(!(s->transport) || (s->transport->connection_state == CS_OFFLINE)) {
677            /* if there's no remote we fail the connection
678             ** right here and terminate it
679             */
680         sendfailmsg(s->peer->fd, "device offline (x)");
681         goto fail;
682     }
683
684
685         /* instrument our peer to pass the success or fail
686         ** message back once it connects or closes, then
687         ** detach from it, request the connection, and
688         ** tear down
689         */
690     s->peer->ready = local_socket_ready_notify;
691     s->peer->close = local_socket_close_notify;
692     s->peer->peer = 0;
693         /* give him our transport and upref it */
694     s->peer->transport = s->transport;
695
696     connect_to_remote(s->peer, (char*) (p->data + 4));
697     s->peer = 0;
698     s->close(s);
699     return 1;
700
701 fail:
702         /* we're going to close our peer as a side-effect, so
703         ** return -1 to signal that state to the local socket
704         ** who is enqueueing against us
705         */
706     s->close(s);
707     return -1;
708 }
709
710 static void smart_socket_ready(asocket *s)
711 {
712     D("SS(%d): ready\n", s->id);
713 }
714
715 static void smart_socket_close(asocket *s)
716 {
717     D("SS(%d): closed\n", s->id);
718     if(s->pkt_first){
719         put_apacket(s->pkt_first);
720     }
721     if(s->peer) {
722         s->peer->peer = 0;
723         s->peer->close(s->peer);
724         s->peer = 0;
725     }
726     free(s);
727 }
728
729 asocket *create_smart_socket(void (*action_cb)(asocket *s, const char *act))
730 {
731     D("Creating smart socket \n");
732     asocket *s = calloc(1, sizeof(asocket));
733     if (s == NULL) fatal("cannot allocate socket");
734     s->enqueue = smart_socket_enqueue;
735     s->ready = smart_socket_ready;
736     s->close = smart_socket_close;
737     s->extra = action_cb;
738
739     D("SS(%d): created %p\n", s->id, action_cb);
740     return s;
741 }
742
743 void smart_socket_action(asocket *s, const char *act)
744 {
745
746 }
747
748 void connect_to_smartsocket(asocket *s)
749 {
750     D("Connecting to smart socket \n");
751     asocket *ss = create_smart_socket(smart_socket_action);
752     s->peer = ss;
753     ss->peer = s;
754     s->ready(s);
755 }
756
757 size_t asock_get_max_payload(asocket *s)
758 {
759     size_t max_payload = MAX_PAYLOAD;
760     if (s->transport) {
761         max_payload = min(max_payload, s->transport->max_payload);
762     }
763     if (s->peer && s->peer->transport) {
764         max_payload = min(max_payload, s->peer->transport->max_payload);
765     }
766     return max_payload;
767 }