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