e8bb48cba12142e7fa2669d4014c69d9bd475cde
[sdk/target/sdbd.git] / src / sdb.h
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 #ifndef __SDB_H
18 #define __SDB_H
19
20 #include <limits.h>
21 #include <stdlib.h>
22
23 #include "transport.h"  /* readx(), writex() */
24 #include "fdevent.h"
25 #if !SDB_HOST
26 #include "commandline_sdbd.h"
27 #endif
28
29 #define MAX_PAYLOAD 4096
30
31 #define A_SYNC 0x434e5953
32 #define A_CNXN 0x4e584e43
33 #define A_OPEN 0x4e45504f
34 #define A_OKAY 0x59414b4f
35 #define A_CLSE 0x45534c43
36 #define A_WRTE 0x45545257
37
38 #define A_VERSION 0x01000000        // SDB protocol version
39
40 #define SDB_VERSION_MAJOR 2         // Used for help/version information
41 #define SDB_VERSION_MINOR 1         // Used for help/version information
42
43 #define SDB_SERVER_VERSION 0        // Increment this when we want to force users to start a new sdb server
44
45 typedef struct amessage amessage;
46 typedef struct apacket apacket;
47 typedef struct asocket asocket;
48 typedef struct alistener alistener;
49 typedef struct aservice aservice;
50 typedef struct atransport atransport;
51 typedef struct adisconnect  adisconnect;
52 typedef struct usb_handle usb_handle;
53
54 struct amessage {
55     unsigned command;       /* command identifier constant      */
56     unsigned arg0;          /* first argument                   */
57     unsigned arg1;          /* second argument                  */
58     unsigned data_length;   /* length of payload (0 is allowed) */
59     unsigned data_check;    /* checksum of data payload         */
60     unsigned magic;         /* command ^ 0xffffffff             */
61 };
62
63 struct apacket
64 {
65     apacket *next;
66
67     unsigned len;
68     unsigned char *ptr;
69
70     amessage msg;
71     unsigned char data[MAX_PAYLOAD];
72 };
73
74 /* An asocket represents one half of a connection between a local and
75 ** remote entity.  A local asocket is bound to a file descriptor.  A
76 ** remote asocket is bound to the protocol engine.
77 */
78 struct asocket {
79         /* chain pointers for the local/remote list of
80         ** asockets that this asocket lives in
81         */
82     asocket *next;
83     asocket *prev;
84
85         /* the unique identifier for this asocket
86         */
87     unsigned id;
88
89         /* flag: set when the socket's peer has closed
90         ** but packets are still queued for delivery
91         */
92     int    closing;
93
94         /* flag: quit adbd when both ends close the
95         ** local service socket
96         */
97     int    exit_on_close;
98
99         /* the asocket we are connected to
100         */
101
102     asocket *peer;
103
104         /* For local asockets, the fde is used to bind
105         ** us to our fd event system.  For remote asockets
106         ** these fields are not used.
107         */
108     fdevent fde;
109     int fd;
110
111         /* queue of apackets waiting to be written
112         */
113     apacket *pkt_first;
114     apacket *pkt_last;
115
116         /* enqueue is called by our peer when it has data
117         ** for us.  It should return 0 if we can accept more
118         ** data or 1 if not.  If we return 1, we must call
119         ** peer->ready() when we once again are ready to
120         ** receive data.
121         */
122     int (*enqueue)(asocket *s, apacket *pkt);
123
124         /* ready is called by the peer when it is ready for
125         ** us to send data via enqueue again
126         */
127     void (*ready)(asocket *s);
128
129         /* close is called by the peer when it has gone away.
130         ** we are not allowed to make any further calls on the
131         ** peer once our close method is called.
132         */
133     void (*close)(asocket *s);
134
135         /* socket-type-specific extradata */
136     void *extra;
137
138         /* A socket is bound to atransport */
139     atransport *transport;
140 };
141
142
143 /* the adisconnect structure is used to record a callback that
144 ** will be called whenever a transport is disconnected (e.g. by the user)
145 ** this should be used to cleanup objects that depend on the
146 ** transport (e.g. remote sockets, listeners, etc...)
147 */
148 struct  adisconnect
149 {
150     void        (*func)(void*  opaque, atransport*  t);
151     void*         opaque;
152     adisconnect*  next;
153     adisconnect*  prev;
154 };
155
156
157 /* a transport object models the connection to a remote device or emulator
158 ** there is one transport per connected device/emulator. a "local transport"
159 ** connects through TCP (for the emulator), while a "usb transport" through
160 ** USB (for real devices)
161 **
162 ** note that kTransportHost doesn't really correspond to a real transport
163 ** object, it's a special value used to indicate that a client wants to
164 ** connect to a service implemented within the SDB server itself.
165 */
166 typedef enum transport_type {
167         kTransportUsb,
168         kTransportLocal,
169         kTransportAny,
170         kTransportHost,
171 } transport_type;
172
173 struct atransport
174 {
175     atransport *next;
176     atransport *prev;
177
178     int (*read_from_remote)(apacket *p, atransport *t);
179     int (*write_to_remote)(apacket *p, atransport *t);
180     void (*close)(atransport *t);
181     void (*kick)(atransport *t);
182
183     int fd;
184     int transport_socket;
185     fdevent transport_fde;
186     int ref_count;
187     unsigned sync_token;
188     int connection_state;
189     transport_type type;
190
191         /* usb handle or socket fd as needed */
192     usb_handle *usb;
193     int sfd;
194
195         /* used to identify transports for clients */
196     char *serial;
197     char *product;
198     int sdb_port; // Use for emulators (local transport)
199     char *device_name; // for connection explorer
200
201         /* a list of adisconnect callbacks called when the transport is kicked */
202     int          kicked;
203     adisconnect  disconnects;
204 };
205
206
207 /* A listener is an entity which binds to a local port
208 ** and, upon receiving a connection on that port, creates
209 ** an asocket to connect the new local connection to a
210 ** specific remote service.
211 **
212 ** TODO: some listeners read from the new connection to
213 ** determine what exact service to connect to on the far
214 ** side.
215 */
216 struct alistener
217 {
218     alistener *next;
219     alistener *prev;
220
221     fdevent fde;
222     int fd;
223
224     const char *local_name;
225     const char *connect_to;
226     atransport *transport;
227     adisconnect  disconnect;
228 };
229
230
231 void print_packet(const char *label, apacket *p);
232
233 asocket *find_local_socket(unsigned id);
234 void install_local_socket(asocket *s);
235 void remove_socket(asocket *s);
236 void close_all_sockets(atransport *t);
237
238 #define  LOCAL_CLIENT_PREFIX  "emulator-"
239
240 asocket *create_local_socket(int fd);
241 asocket *create_local_service_socket(const char *destination);
242
243 asocket *create_remote_socket(unsigned id, atransport *t);
244 void connect_to_remote(asocket *s, const char *destination);
245 void connect_to_smartsocket(asocket *s);
246
247 void fatal(const char *fmt, ...);
248 void fatal_errno(const char *fmt, ...);
249
250 void handle_packet(apacket *p, atransport *t);
251 void send_packet(apacket *p, atransport *t);
252
253 void get_my_path(char *s, size_t maxLen);
254 int launch_server(int server_port);
255 int sdb_main(int is_daemon, int server_port);
256
257
258 /* transports are ref-counted
259 ** get_device_transport does an acquire on your behalf before returning
260 */
261 void init_transport_registration(void);
262 int  list_transports(char *buf, size_t  bufsize);
263 void update_transports(void);
264
265 asocket*  create_device_tracker(void);
266
267 /* Obtain a transport from the available transports.
268 ** If state is != CS_ANY, only transports in that state are considered.
269 ** If serial is non-NULL then only the device with that serial will be chosen.
270 ** If no suitable transport is found, error is set.
271 */
272 atransport *acquire_one_transport(int state, transport_type ttype, const char* serial, char **error_out);
273 void   add_transport_disconnect( atransport*  t, adisconnect*  dis );
274 void   remove_transport_disconnect( atransport*  t, adisconnect*  dis );
275 void   run_transport_disconnects( atransport*  t );
276 void   kick_transport( atransport*  t );
277
278 /* initialize a transport object's func pointers and state */
279 #if SDB_HOST
280 int get_available_local_transport_index();
281 #endif
282 int  init_socket_transport(atransport *t, int s, int port, int local);
283 void init_usb_transport(atransport *t, usb_handle *usb, int state);
284
285 /* for MacOS X cleanup */
286 void close_usb_devices();
287
288 /* cause new transports to be init'd and added to the list */
289 void register_socket_transport(int s, const char *serial, int port, int local, const char *device_name);
290
291 /* these should only be used for the "sdb disconnect" command */
292 void unregister_transport(atransport *t);
293 void unregister_all_tcp_transports();
294
295 void register_usb_transport(usb_handle *h, const char *serial, unsigned writeable);
296
297 /* this should only be used for transports with connection_state == CS_NOPERM */
298 void unregister_usb_transport(usb_handle *usb);
299
300 atransport *find_transport(const char *serial);
301 #if SDB_HOST
302 atransport* find_emulator_transport_by_sdb_port(int sdb_port);
303 #endif
304
305 int service_to_fd(const char *name);
306 #if SDB_HOST
307 asocket *host_service_to_socket(const char*  name, const char *serial);
308 #endif
309
310 #if !SDB_HOST
311 int       init_jdwp(void);
312 asocket*  create_jdwp_service_socket();
313 asocket*  create_jdwp_tracker_service_socket();
314 int       create_jdwp_connection_fd(int  jdwp_pid);
315 #endif
316
317 #if !SDB_HOST
318 typedef enum {
319     BACKUP,
320     RESTORE
321 } BackupOperation;
322 int backup_service(BackupOperation operation, char* args);
323 void framebuffer_service(int fd, void *cookie);
324 void log_service(int fd, void *cookie);
325 void remount_service(int fd, void *cookie);
326 char * get_log_file_path(const char * log_name);
327
328 int rootshell_mode;// 0: developer, 1: root
329
330 // This is the users and groups config for the platform
331
332 #define SID_ROOT        0    /* traditional unix root user */
333 #define SID_TTY         5    /* group for /dev/ptmx */
334 #define SID_APP         5000 /* application */
335 #define SID_DEVELOPER   5100 /* developer with SDK */
336 #define SID_APP_LOGGING 6509
337 #define SID_SYS_LOGGING 6527
338 #define SID_INPUT       1004
339
340 #endif
341
342 int should_drop_privileges(void);
343 int set_developer_privileges();
344 void set_root_privileges();
345
346 int get_emulator_forward_port(void);
347 int get_emulator_name(char str[], int str_size);
348 int get_device_name(char str[], int str_size);
349 /* packet allocator */
350 apacket *get_apacket(void);
351 void put_apacket(apacket *p);
352
353 int check_header(apacket *p);
354 int check_data(apacket *p);
355
356 /* define SDB_TRACE to 1 to enable tracing support, or 0 to disable it */
357
358 #define  SDB_TRACE    1
359
360 /* IMPORTANT: if you change the following list, don't
361  * forget to update the corresponding 'tags' table in
362  * the sdb_trace_init() function implemented in sdb.c
363  */
364 typedef enum {
365     TRACE_SDB = 0,
366     TRACE_SOCKETS,
367     TRACE_PACKETS,
368     TRACE_TRANSPORT,
369     TRACE_RWX,
370     TRACE_USB,
371     TRACE_SYNC,
372     TRACE_SYSDEPS,
373     TRACE_JDWP,
374     TRACE_SERVICES,
375     TRACE_PROPERTIES,
376     TRACE_SDKTOOLS
377 } SdbTrace;
378
379 #if SDB_TRACE
380
381 #if !SDB_HOST
382 /*
383  * When running inside the emulator, guest's sdbd can connect to 'sdb-debug'
384  * qemud service that can display sdb trace messages (on condition that emulator
385  * has been started with '-debug sdb' option).
386  */
387
388 /* Delivers a trace message to the emulator via QEMU pipe. */
389 void sdb_qemu_trace(const char* fmt, ...);
390 /* Macro to use to send SDB trace messages to the emulator. */
391 #define DQ(...)    sdb_qemu_trace(__VA_ARGS__)
392 #else
393 #define DQ(...) ((void)0)
394 #endif  /* !SDB_HOST */
395
396   extern int     sdb_trace_mask;
397   extern unsigned char    sdb_trace_output_count;
398   void    sdb_trace_init(void);
399
400 #  define SDB_TRACING  ((sdb_trace_mask & (1 << TRACE_TAG)) != 0)
401
402   /* you must define TRACE_TAG before using this macro */
403 #  define  D(...)                                      \
404         do {                                           \
405             if (SDB_TRACING) {                         \
406                 int save_errno = errno;                \
407                 sdb_mutex_lock(&D_lock);               \
408                 fprintf(stderr, "%s::%s():",           \
409                         __FILE__, __FUNCTION__);       \
410                 errno = save_errno;                    \
411                 fprintf(stderr, __VA_ARGS__ );         \
412                 fflush(stderr);                        \
413                 sdb_mutex_unlock(&D_lock);             \
414                 errno = save_errno;                    \
415            }                                           \
416         } while (0)
417 #  define  DR(...)                                     \
418         do {                                           \
419             if (SDB_TRACING) {                         \
420                 int save_errno = errno;                \
421                 sdb_mutex_lock(&D_lock);               \
422                 errno = save_errno;                    \
423                 fprintf(stderr, __VA_ARGS__ );         \
424                 fflush(stderr);                        \
425                 sdb_mutex_unlock(&D_lock);             \
426                 errno = save_errno;                    \
427            }                                           \
428         } while (0)
429 #else
430 #  define  D(...)          ((void)0)
431 #  define  DR(...)         ((void)0)
432 #  define  SDB_TRACING     0
433 #endif
434
435
436 #if !TRACE_PACKETS
437 #define print_packet(tag,p) do {} while (0)
438 #endif
439
440 #if SDB_HOST_ON_TARGET
441 /* sdb and sdbd are coexisting on the target, so use 26099 for sdb
442  * to avoid conflicting with sdbd's usage of 26098
443  */
444 #  define DEFAULT_SDB_PORT 26099 /* tizen specific */
445 #else
446 #  define DEFAULT_SDB_PORT 26099 /* tizen specific */
447 #endif
448
449 #  define QEMU_FORWARD_IP "10.0.2.2"
450
451 #define DEFAULT_SDB_LOCAL_TRANSPORT_PORT 26101 /* tizen specific */
452 #define DEFAULT_SENSORS_LOCAL_TRANSPORT_PORT 26103 /* tizen specific */
453
454 #define SDB_CLASS              0xff
455 #define SDB_SUBCLASS           0x20 //0x42 /* tizen specific */
456 #define SDB_PROTOCOL           0x02 //0x01 /* tizen specific */
457
458
459 void local_init(int port);
460 int  local_connect(int  port, const char *device_name);
461 int  local_connect_arbitrary_ports(int console_port, int sdb_port, const char *device_name);
462
463 /* usb host/client interface */
464 void usb_init();
465 void usb_cleanup();
466 int usb_write(usb_handle *h, const void *data, int len);
467 int usb_read(usb_handle *h, void *data, int len);
468 int usb_close(usb_handle *h);
469 void usb_kick(usb_handle *h);
470
471 /* used for USB device detection */
472 #if SDB_HOST
473 int is_sdb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol);
474 #endif
475
476 unsigned host_to_le32(unsigned n);
477 int sdb_commandline(int argc, char **argv);
478
479 int connection_state(atransport *t);
480
481 #define CS_ANY       -1
482 #define CS_OFFLINE    0
483 #define CS_BOOTLOADER 1
484 #define CS_DEVICE     2
485 #define CS_HOST       3
486 #define CS_RECOVERY   4
487 #define CS_NOPERM     5 /* Insufficient permissions to communicate with the device */
488 #define CS_SIDELOAD   6
489
490 extern int HOST;
491 extern int SHELL_EXIT_NOTIFY_FD;
492 #if !SDB_HOST
493 extern SdbdCommandlineArgs sdbd_commandline_args;
494 #endif
495
496 #define CHUNK_SIZE (64*1024)
497
498 int sendfailmsg(int fd, const char *reason);
499 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s);
500
501 int is_emulator(void);
502 #define DEFAULT_DEVICENAME "unknown"
503
504 #if SDB_HOST /* tizen-specific */
505 #define DEVICEMAP_SEPARATOR ":"
506 #define DEVICENAME_MAX 256
507 #define VMS_PATH OS_PATH_SEPARATOR_STR "vms" OS_PATH_SEPARATOR_STR // should include sysdeps.h above
508
509 void register_device_name(const char *device_type, const char *device_name, int port);
510 int get_devicename_from_shdmem(int port, char *device_name);
511 int read_line(const int fd, char* ptr, const size_t maxlen);
512 #endif
513 #endif
514
515 #define USB_NODE_FILE "/dev/samsung_sdb"