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