Revert "Merge plugin improvement commit"
[sdk/target/sdbd.git] / src / transport_local.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 <string.h>
20 #include <errno.h>
21 #include <arpa/inet.h>
22 #include <netdb.h>
23
24 #include "sysdeps.h"
25 #include <sys/types.h>
26
27 #ifndef HAVE_WIN32_IPC
28 #include <sys/ipc.h>
29 #include <sys/shm.h>
30 #include <unistd.h>
31 #endif
32
33 #define  TRACE_TAG  TRACE_TRANSPORT
34 #include "log.h"
35
36 #include "sdb.h"
37 #include "strutils.h"
38 #if !SDB_HOST
39 #include "commandline_sdbd.h"
40 #endif
41 #include "sdbd_plugin.h"
42 #include "plugin.h"
43
44 #ifdef HAVE_BIG_ENDIAN
45 #define H4(x)   (((x) & 0xFF000000) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | (((x) & 0x000000FF) << 24)
46 static inline void fix_endians(apacket *p)
47 {
48     p->msg.command     = H4(p->msg.command);
49     p->msg.arg0        = H4(p->msg.arg0);
50     p->msg.arg1        = H4(p->msg.arg1);
51     p->msg.data_length = H4(p->msg.data_length);
52     p->msg.data_check  = H4(p->msg.data_check);
53     p->msg.magic       = H4(p->msg.magic);
54 }
55 #else
56 #define fix_endians(p) do {} while (0)
57 #endif
58
59 #if SDB_HOST
60 /* we keep a list of opened transports. The atransport struct knows to which
61  * local transport it is connected. The list is used to detect when we're
62  * trying to connect twice to a given local transport.
63  */
64 #define  SDB_LOCAL_TRANSPORT_MAX  16
65
66 SDB_MUTEX_DEFINE( local_transports_lock );
67
68 static atransport*  local_transports[ SDB_LOCAL_TRANSPORT_MAX ];
69 #endif /* SDB_HOST */
70
71 SDB_MUTEX_DEFINE( register_noti_lock );
72 #ifndef _WIN32
73 static pthread_cond_t noti_cond = PTHREAD_COND_INITIALIZER;
74 #endif
75
76 static int remote_read(apacket *p, atransport *t)
77 {
78     if(readx(t->sfd, &p->msg, sizeof(amessage))){
79         D("remote local: read terminated (message)\n");
80         return -1;
81     }
82
83     fix_endians(p);
84
85 #if 0 && defined HAVE_BIG_ENDIAN
86     D("read remote packet: %04x arg0=%0x arg1=%0x data_length=%0x data_check=%0x magic=%0x\n",
87       p->msg.command, p->msg.arg0, p->msg.arg1, p->msg.data_length, p->msg.data_check, p->msg.magic);
88 #endif
89     if(check_header(p)) {
90         D("bad header: terminated (data)\n");
91         return -1;
92     }
93
94     if(readx(t->sfd, p->data, p->msg.data_length)){
95         D("remote local: terminated (data)\n");
96         return -1;
97     }
98
99     if(check_data(p)) {
100         D("bad data: terminated (data)\n");
101         return -1;
102     }
103
104     return 0;
105 }
106
107 static int remote_write(apacket *p, atransport *t)
108 {
109     int   length = p->msg.data_length;
110
111     fix_endians(p);
112
113 #if 0 && defined HAVE_BIG_ENDIAN
114     D("write remote packet: %04x arg0=%0x arg1=%0x data_length=%0x data_check=%0x magic=%0x\n",
115       p->msg.command, p->msg.arg0, p->msg.arg1, p->msg.data_length, p->msg.data_check, p->msg.magic);
116 #endif
117     if(writex(t->sfd, &p->msg, sizeof(amessage) + length)) {
118         D("remote local: write terminated\n");
119         return -1;
120     }
121
122     return 0;
123 }
124
125
126 int local_connect(int port, const char *device_name) {
127     return local_connect_arbitrary_ports(port-1, port, device_name);
128 }
129
130 int local_connect_arbitrary_ports(int console_port, int sdb_port, const char *device_name)
131 {
132     char buf[64];
133     int  fd = -1;
134
135 #if SDB_HOST
136     const char *host = getenv("SDBHOST");
137     if (host) {
138         fd = socket_network_client(host, sdb_port, SOCK_STREAM);
139     }
140 #endif
141     if (fd < 0) {
142         fd = socket_loopback_client(sdb_port, SOCK_STREAM);
143     }
144
145     if (fd >= 0) {
146         D("client: connected on remote on fd %d\n", fd);
147         if (close_on_exec(fd) < 0) {
148             D("failed to close fd exec\n");
149         }
150         disable_tcp_nagle(fd);
151         snprintf(buf, sizeof buf, "%s%d", LOCAL_CLIENT_PREFIX, console_port);
152         register_socket_transport(fd, buf, sdb_port, 1, device_name);
153         return 0;
154     }
155     return -1;
156 }
157
158 #if SDB_HOST /* tizen specific */
159 int get_devicename_from_shdmem(int port, char *device_name)
160 {
161     char *vms = NULL;
162 #ifndef HAVE_WIN32_IPC
163     int shm_id;
164     void *shared_memory = (void *)0;
165
166     shm_id = shmget( (key_t)port-1, 0, 0);
167     if (shm_id == -1)
168         return -1;
169
170     shared_memory = shmat(shm_id, (void *)0, SHM_RDONLY);
171
172     if (shared_memory == (void *)-1)
173     {
174         D("faild to get shdmem key (%d) : %s\n", port, strerror(errno));
175         return -1;
176     }
177
178     vms = strstr((char*)shared_memory, VMS_PATH);
179     if (vms != NULL)
180         s_strncpy(device_name, vms+strlen(VMS_PATH), DEVICENAME_MAX);
181     else
182         s_strncpy(device_name, DEFAULT_DEVICENAME, DEVICENAME_MAX);
183
184 #else /* _WIN32*/
185     HANDLE hMapFile;
186     char s_port[5];
187     char* pBuf;
188
189     sprintf(s_port, "%d", port-1);
190     hMapFile = OpenFileMapping(FILE_MAP_READ, TRUE, s_port);
191
192     if(hMapFile == NULL) {
193         D("faild to get shdmem key (%ld) : %s\n", port, GetLastError() );
194         return -1;
195     }
196     pBuf = (char*)MapViewOfFile(hMapFile,
197                             FILE_MAP_READ,
198                             0,
199                             0,
200                             50);
201     if (pBuf == NULL) {
202         D("Could not map view of file (%ld)\n", GetLastError());
203         CloseHandle(hMapFile);
204         return -1;
205     }
206
207     vms = strstr((char*)pBuf, VMS_PATH);
208     if (vms != NULL)
209         s_strncpy(device_name, vms+strlen(VMS_PATH), DEVICENAME_MAX);
210     else
211         s_strncpy(device_name, DEFAULT_DEVICENAME, DEVICENAME_MAX);
212     CloseHandle(hMapFile);
213 #endif
214     D("init device name %s on port %d\n", device_name, port);
215
216     return 0;
217 }
218
219 int read_line(const int fd, char* ptr, size_t maxlen)
220 {
221     unsigned int n = 0;
222     char c[2];
223     int rc;
224
225     while(n != maxlen) {
226         if((rc = sdb_read(fd, c, 1)) != 1)
227             return -1; // eof or read err
228
229         if(*c == '\n') {
230             ptr[n] = 0;
231             return n;
232         }
233         ptr[n++] = *c;
234     }
235     return -1; // no space
236 }
237 #endif
238
239 static void *client_socket_thread(void *x)
240 {
241 #if SDB_HOST
242     int  port  = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
243     int  count = SDB_LOCAL_TRANSPORT_MAX;
244
245     D("transport: client_socket_thread() starting\n");
246
247     /* try to connect to any number of running emulator instances     */
248     /* this is only done when SDB starts up. later, each new emulator */
249     /* will send a message to SDB to indicate that is is starting up  */
250     for ( ; count > 0; count--, port += 10 ) { /* tizen specific */
251         (void) local_connect(port, NULL);
252     }
253 #endif
254     return 0;
255 }
256
257 static void *server_socket_thread(void * arg)
258 {
259     int serverfd, fd;
260     struct sockaddr_in addr;
261     socklen_t alen;
262     int port = (int)arg;
263
264     D("transport: server_socket_thread() starting\n");
265     serverfd = -1;
266     for(;;) {
267         if(serverfd == -1) {
268             // socket_inaddr_any_server returns -1 if there is any error
269             serverfd = socket_inaddr_any_server(port, SOCK_STREAM);
270             if(serverfd < 0) {
271                 D("server: cannot bind socket yet\n");
272                 sdb_sleep_ms(1000);
273                 continue;
274             }
275             if (close_on_exec(serverfd) < 0) {
276                 D("failed to close serverfd exec\n");
277             }
278         }
279
280         alen = sizeof(addr);
281         D("server: trying to get new connection from %d\n", port);
282
283         if (is_emulator()) {
284             // im ready to accept new client!
285             pthread_cond_broadcast(&noti_cond);
286         }
287
288         fd = sdb_socket_accept(serverfd, (struct sockaddr *)&addr, &alen);
289         if(fd >= 0) {
290             D("server: new connection on fd %d\n", fd);
291             if (close_on_exec(fd) < 0) {
292                 D("failed to close fd exec\n");
293             }
294             disable_tcp_nagle(fd);
295
296             // Check the peer ip validation.
297             if (!is_emulator()
298                 && !request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_PEERIP, inet_ntoa(addr.sin_addr))) {
299                 sdb_close(fd);
300             } else {
301                 int ret = -1;
302                 ret = keep_alive(fd, 1, SDB_KEEPALIVE_CNT, SDB_KEEPALIVE_IDLE, SDB_KEEPALIVE_INTVL);
303                 if (ret < 0) {
304                     D("failed to set keep alive option. FD(%d), errno=%d\n", fd, errno);
305                 } else {
306                     D("Success to set keep alive option. FD(%d), cnt=%d, idle=%d(sec), interval=%d(sec)\n",
307                         fd, SDB_KEEPALIVE_CNT, SDB_KEEPALIVE_IDLE, SDB_KEEPALIVE_INTVL);
308                 }
309
310                 register_socket_transport(fd, "host", port, 1, NULL);
311             }
312         } else {
313             D("failed to accept() from sdb server\n");
314             //FIXME: implements error handle for EMFILE or ENFILE
315         }
316     }
317     D("transport: server_socket_thread() exiting\n");
318     return 0;
319 }
320
321 /* This is relevant only for SDB daemon running inside the emulator. */
322 #if !SDB_HOST
323 /*
324  * Redefine open and write for qemu_pipe.h that contains inlined references
325  * to those routines. We will redifine them back after qemu_pipe.h inclusion.
326  */
327 #undef open
328 #undef write
329 #define open    sdb_open
330 #define write   sdb_write
331 #include "qemu_pipe.h"
332 #undef open
333 #undef write
334 #define open    ___xxx_open
335 #define write   ___xxx_write
336
337 /* A worker thread that monitors host connections, and registers a transport for
338  * every new host connection. This thread replaces server_socket_thread on
339  * condition that sdbd daemon runs inside the emulator, and emulator uses QEMUD
340  * pipe to communicate with sdbd daemon inside the guest. This is done in order
341  * to provide more robust communication channel between SDB host and guest. The
342  * main issue with server_socket_thread approach is that it runs on top of TCP,
343  * and thus is sensitive to network disruptions. For instance, the
344  * ConnectionManager may decide to reset all network connections, in which case
345  * the connection between SDB host and guest will be lost. To make SDB traffic
346  * independent from the network, we use here 'sdb' QEMUD service to transfer data
347  * between the host, and the guest. See external/qemu/android/sdb-*.* that
348  * implements the emulator's side of the protocol. Another advantage of using
349  * QEMUD approach is that SDB will be up much sooner, since it doesn't depend
350  * anymore on network being set up.
351  * The guest side of the protocol contains the following phases:
352  * - Connect with sdb QEMUD service. In this phase a handle to 'sdb' QEMUD service
353  *   is opened, and it becomes clear whether or not emulator supports that
354  *   protocol.
355  * - Wait for the SDB host to create connection with the guest. This is done by
356  *   sending an 'accept' request to the sdb QEMUD service, and waiting on
357  *   response.
358  * - When new SDB host connection is accepted, the connection with sdb QEMUD
359  *   service is registered as the transport, and a 'start' request is sent to the
360  *   sdb QEMUD service, indicating that the guest is ready to receive messages.
361  *   Note that the guest will ignore messages sent down from the emulator before
362  *   the transport registration is completed. That's why we need to send the
363  *   'start' request after the transport is registered.
364  */
365 #if 0
366 static void *qemu_socket_thread(void * arg)
367 {
368 /* 'accept' request to the sdb QEMUD service. */
369 static const char _accept_req[] = "accept";
370 /* 'start' request to the sdb QEMUD service. */
371 static const char _start_req[]  = "start";
372 /* 'ok' reply from the sdb QEMUD service. */
373 static const char _ok_resp[]    = "ok";
374
375     const int port = (int)arg;
376     int res, fd;
377     char tmp[256];
378     char con_name[32];
379
380     D("transport: qemu_socket_thread() starting\n");
381
382     /* sdb QEMUD service connection request. */
383     snprintf(con_name, sizeof(con_name), "qemud:sdb:%d", port);
384
385     /* Connect to the sdb QEMUD service. */
386     fd = qemu_pipe_open(con_name);
387     if (fd < 0) {
388         /* This could be an older version of the emulator, that doesn't
389          * implement sdb QEMUD service. Fall back to the old TCP way. */
390         sdb_thread_t thr;
391         D("sdb service is not available. Falling back to TCP socket.\n");
392         sdb_thread_create(&thr, server_socket_thread, arg);
393         return 0;
394     }
395
396     for(;;) {
397         /*
398          * Wait till the host creates a new connection.
399          */
400
401         /* Send the 'accept' request. */
402         res = sdb_write(fd, _accept_req, strlen(_accept_req));
403         if (res == strlen(_accept_req)) {
404             /* Wait for the response. In the response we expect 'ok' on success,
405              * or 'ko' on failure. */
406             res = sdb_read(fd, tmp, sizeof(tmp));
407             if (res != 2 || memcmp(tmp, _ok_resp, 2)) {
408                 D("Accepting SDB host connection has failed.\n");
409                 sdb_close(fd);
410             } else {
411                 /* Host is connected. Register the transport, and start the
412                  * exchange. */
413                 register_socket_transport(fd, "host", port, 1, NULL);
414                 sdb_write(fd, _start_req, strlen(_start_req));
415             }
416
417             /* Prepare for accepting of the next SDB host connection. */
418             fd = qemu_pipe_open(con_name);
419             if (fd < 0) {
420                 D("sdb service become unavailable.\n");
421                 return 0;
422             }
423         } else {
424             D("Unable to send the '%s' request to SDB service.\n", _accept_req);
425             return 0;
426         }
427     }
428     D("transport: qemu_socket_thread() exiting\n");
429     return 0;
430 }
431 #endif  // !SDB_HOST
432 #endif
433
434 int connect_nonb(int sockfd, const struct sockaddr *saptr, socklen_t salen,
435         int nsec) {
436     int flags, n, error;
437     socklen_t len;
438     fd_set rset, wset;
439     struct timeval tval;
440
441     flags = fcntl(sockfd, F_GETFL, 0);
442     if(fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) == -1) {
443         D("failed to set file O_NONBLOCK status flag for socket %d: errno:%d\n",
444                      sockfd, errno);
445     }
446
447     error = 0;
448     if ((n = connect(sockfd, (struct sockaddr *) saptr, salen)) < 0)
449         if (errno != EINPROGRESS)
450             return (-1);
451
452     /* Do whatever we want while the connect is taking place. */
453
454     if (n == 0)
455         goto done;
456     /* connect completed immediately */
457
458     FD_ZERO(&rset);
459     FD_SET(sockfd, &rset);
460     wset = rset;
461     tval.tv_sec = nsec;
462     tval.tv_usec = 0;
463     if ((n = select(sockfd + 1, &rset, &wset, NULL, nsec ? &tval : NULL))
464             == 0) {
465         sdb_close(sockfd); /* timeout */
466         errno = ETIMEDOUT;
467         return (-1);
468     }
469     if (FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) {
470         len = sizeof(error);
471         if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
472             return (-1); /* Solaris pending error */
473     } else
474         D("select error: sockfd not set\n");
475
476     done:
477     if(fcntl(sockfd, F_SETFL, flags) == -1) { /* restore file status flags */
478         D("failed to restore file status flag for socket %d\n",
479                  sockfd);
480     }
481
482     if (error) {
483         sdb_close(sockfd); /* just in case */
484         errno = error;
485         return (-1);
486     }
487     return (0);
488 }
489
490 static int send_msg_to_localhost_from_guest(const char *host_ip, int local_port, char *request, int sock_type) {
491     int                  ret, s;
492     struct sockaddr_in   server;
493     int connect_timeout = 1;
494     memset( &server, 0, sizeof(server) );
495     server.sin_family      = AF_INET;
496     server.sin_port        = htons(local_port);
497     server.sin_addr.s_addr = inet_addr(host_ip);
498
499     D("try to send notification to host(%s:%d) using %s:[%s]\n", host_ip, local_port, (sock_type == 0) ? "tcp" : "udp", request);
500
501     if (sock_type == 0) {
502         s = socket(AF_INET, SOCK_STREAM, 0);
503     } else {
504         s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
505     }
506     if (s < 0) {
507         D("could not create socket\n");
508         return -1;
509     }
510     ret = connect_nonb(s, (struct sockaddr*) &server, sizeof(server), connect_timeout);
511     if (ret < 0) {
512         D("could not connect to server\n");
513         sdb_close(s);
514         return -1;
515     }
516     if (writex(s, request, strlen(request)) != 0) {
517         D("could not send notification request to host\n");
518         sdb_close(s);
519         return -1;
520     }
521     sdb_close(s);
522     D("sent notification request to host\n");
523
524     return 0;
525 }
526
527 // send the "emulator" request to sdbserver
528 static void* notify_sdbd_startup_thread(void* ptr) {
529     char                 buffer[512];
530     char                 request[512];
531
532     SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; // alias
533
534     // send the request to sdbserver
535     char vm_name[256]={0,};
536     char host_ip[256] = {0,};
537     char guest_ip[256] = {0,};
538     int sensors_port = sdbd_args->sensors.port;
539     int emulator_port = sdbd_args->emulator.port;
540
541     int r = get_emulator_name(vm_name, sizeof vm_name);
542     int time = 0;
543     //int try_limit_time = -1; // try_limit_time < 0 if unlimited
544     if (sensors_port < 0 || emulator_port < 0 || r < 0) {
545         return NULL;
546     }
547     if (get_emulator_hostip(host_ip, sizeof host_ip) == -1) {
548        D("failed to get emulator host ip\n");
549        return NULL;
550     }
551     // XXX: Known issue - log collision
552     while (1) {
553         // Trial limitation reached. terminate notify thread.
554         /*if (0 <= try_limit_time && try_limit_time <= time) {
555             break;
556         }*/
557         // If there is any connected (via TCP/IP) SDB server, sleep 10 secs
558         if (get_connected_count(kTransportLocal) > 0) {
559             if (time >= 0) {
560                 time = 0;
561                 D("notify_sdbd_startup() success after %d trial(s)\n", time);
562             }
563             sleep(10);
564             continue;
565         }
566
567         if (get_emulator_guestip(guest_ip, sizeof guest_ip) == -1) {
568                         D("failed to get emulator guest ip\n");
569                         goto sleep_and_continue;
570                 }
571
572         // tell qemu sdbd is just started with udp
573         if (send_msg_to_localhost_from_guest(host_ip, sensors_port, "2\n", 1) < 0) {
574             D("could not send sensord noti request, try again %dth\n", time+1);
575             goto sleep_and_continue;
576         }
577
578         // tell sdb server emulator's vms name
579         // TODO: should we use host:emulator request? let's talk about this!
580
581         if (!strncmp(host_ip, QEMU_FORWARD_IP, sizeof host_ip)) {
582             snprintf(request, sizeof request, "host:emulator:%d:%s", (emulator_port + 1), vm_name);
583         } else {
584             snprintf(request, sizeof request, "host:connect:%s:%d", guest_ip, DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
585         }
586         D("[%s:%d] request:%s \n", __FUNCTION__, __LINE__, request);
587         snprintf(buffer, sizeof buffer, "%04x%s", strlen(request), request );
588
589         if (send_msg_to_localhost_from_guest(host_ip, DEFAULT_SDB_PORT, buffer, 0) <0) {
590             D("could not send sdbd noti request. it might sdb server has not been started yet.\n");
591             goto sleep_and_continue;
592         }
593         //LOGI("sdbd noti request sent.\n");
594
595 sleep_and_continue:
596         time++;
597         sleep(1);
598     }
599 }
600
601 void local_init(int port)
602 {
603     sdb_thread_t thr;
604     void* (*func)(void *);
605
606     if(HOST) {
607         func = client_socket_thread;
608     } else {
609 #if SDB_HOST
610         func = server_socket_thread;
611 #else
612         /* For the sdbd daemon in the system image we need to distinguish
613          * between the device, and the emulator. */
614 #if 0 /* tizen specific */
615         char is_qemu[PROPERTY_VALUE_MAX];
616         property_get("ro.kernel.qemu", is_qemu, "");
617         if (!strcmp(is_qemu, "1")) {
618             /* Running inside the emulator: use QEMUD pipe as the transport. */
619             func = qemu_socket_thread;
620         } else
621 #endif
622         {
623             /* Running inside the device: use TCP socket as the transport. */
624             func = server_socket_thread;
625         }
626 #endif // !SDB_HOST
627     }
628
629     D("transport: local %s init\n", HOST ? "client" : "server");
630
631     if(sdb_thread_create(&thr, func, (void *)port)) {
632         fatal_errno("cannot create local socket %s thread",
633                     HOST ? "client" : "server");
634     }
635
636     /*
637      * wait until server socket thread made!
638      * get noti from server_socket_thread
639      */
640     if (is_emulator()) {
641         sdb_mutex_lock(&register_noti_lock);
642         pthread_cond_wait(&noti_cond, &register_noti_lock);
643
644         // thread start
645         if(sdb_thread_create(&thr, notify_sdbd_startup_thread, NULL)) {
646             fatal("cannot create notify_sdbd_startup_thread");
647             //notify_sdbd_startup(); // defensive code
648         }
649         sdb_mutex_unlock(&register_noti_lock);
650     }
651 }
652
653 static void remote_kick(atransport *t)
654 {
655     int fd = t->sfd;
656     t->sfd = -1;
657     sdb_shutdown(fd);
658     sdb_close(fd);
659
660 #if SDB_HOST
661     if(HOST) {
662         int  nn;
663         sdb_mutex_lock( &local_transports_lock );
664         for (nn = 0; nn < SDB_LOCAL_TRANSPORT_MAX; nn++) {
665             if (local_transports[nn] == t) {
666                 local_transports[nn] = NULL;
667                 break;
668             }
669         }
670         sdb_mutex_unlock( &local_transports_lock );
671     }
672 #endif
673 }
674
675 static void remote_close(atransport *t)
676 {
677     sdb_close(t->fd);
678 }
679
680
681 #if SDB_HOST
682 /* Only call this function if you already hold local_transports_lock. */
683 atransport* find_emulator_transport_by_sdb_port_locked(int sdb_port)
684 {
685     int i;
686     for (i = 0; i < SDB_LOCAL_TRANSPORT_MAX; i++) {
687         if (local_transports[i] && local_transports[i]->sdb_port == sdb_port) {
688             return local_transports[i];
689         }
690     }
691     return NULL;
692 }
693
694 atransport* find_emulator_transport_by_sdb_port(int sdb_port)
695 {
696     sdb_mutex_lock( &local_transports_lock );
697     atransport* result = find_emulator_transport_by_sdb_port_locked(sdb_port);
698     sdb_mutex_unlock( &local_transports_lock );
699     return result;
700 }
701
702 /* Only call this function if you already hold local_transports_lock. */
703 int get_available_local_transport_index_locked()
704 {
705     int i;
706     for (i = 0; i < SDB_LOCAL_TRANSPORT_MAX; i++) {
707         if (local_transports[i] == NULL) {
708             return i;
709         }
710     }
711     return -1;
712 }
713
714 int get_available_local_transport_index()
715 {
716     sdb_mutex_lock( &local_transports_lock );
717     int result = get_available_local_transport_index_locked();
718     sdb_mutex_unlock( &local_transports_lock );
719     return result;
720 }
721 #endif
722
723 int init_socket_transport(atransport *t, int s, int sdb_port, int local)
724 {
725     int  fail = 0;
726
727     t->kick = remote_kick;
728     t->close = remote_close;
729     t->read_from_remote = remote_read;
730     t->write_to_remote = remote_write;
731     t->sfd = s;
732     t->sync_token = 1;
733     t->connection_state = CS_OFFLINE;
734     t->type = kTransportLocal;
735     t->sdb_port = 0;
736
737 #if SDB_HOST
738     if (HOST && local) {
739         sdb_mutex_lock( &local_transports_lock );
740         {
741             t->sdb_port = sdb_port;
742             atransport* existing_transport =
743                     find_emulator_transport_by_sdb_port_locked(sdb_port);
744             int index = get_available_local_transport_index_locked();
745             if (existing_transport != NULL) {
746                 D("local transport for port %d already registered (%p)?\n",
747                 sdb_port, existing_transport);
748                 fail = -1;
749             } else if (index < 0) {
750                 // Too many emulators.
751                 D("cannot register more emulators. Maximum is %d\n",
752                         SDB_LOCAL_TRANSPORT_MAX);
753                 fail = -1;
754             } else {
755                 local_transports[index] = t;
756             }
757        }
758        sdb_mutex_unlock( &local_transports_lock );
759     }
760 #endif
761     return fail;
762 }