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