add data encryption feature
[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 #include <stddef.h>
23
24 #include "transport.h"  /* readx(), writex() */
25 #include "fdevent.h"
26 #include "sdbd_plugin.h"
27 #if !SDB_HOST
28 #include "commandline_sdbd.h"
29 #endif
30 #include <tzplatform_config.h>
31
32 #define MAX_PAYLOAD 4096
33
34 #define A_SYNC 0x434e5953
35 #define A_CNXN 0x4e584e43
36 #define A_OPEN 0x4e45504f
37 #define A_OKAY 0x59414b4f
38 #define A_CLSE 0x45534c43
39 #define A_WRTE 0x45545257
40 #define A_STAT 0x54415453
41 #define A_ENCR 0x40682018 // encryption 메시지
42
43 #ifdef SUPPORT_ENCRYPT
44  #define ENCR_SET_ON_REQ 0 // encryption hello 메시지
45  #define ENCR_SET_ON_OK 1 // encryption ack 메시지
46  #define ENCR_SET_OFF 2 // encryption mode off 메시지
47  #define ENCR_GET 3 // encryption status get 메시지
48  #define ENCR_ON_FAIL 4 // encryption on 실패 메시지
49  #define ENCR_OFF_FAIL 5 // encryption off 실패 메시지
50  #define ENCR_ON 1 // encryption on 상태
51  #define ENCR_OFF 0 // encryption off 상태
52 #endif
53
54 #define A_VERSION 0x02000000        // SDB protocol version
55
56 #define SDB_VERSION_MAJOR 2         // Used for help/version information
57 #define SDB_VERSION_MINOR 2         // Used for help/version information
58 #define SDB_VERSION_PATCH 31        // Used for help/version information
59
60 #define SDB_SERVER_VERSION 0        // Increment this when we want to force users to start a new sdb server
61
62 typedef struct amessage amessage;
63 typedef struct apacket apacket;
64 typedef struct asocket asocket;
65 typedef struct alistener alistener;
66 typedef struct aservice aservice;
67 typedef struct atransport atransport;
68 typedef struct adisconnect  adisconnect;
69 typedef struct usb_handle usb_handle;
70
71 struct amessage {
72     unsigned command;       /* command identifier constant      */
73     unsigned arg0;          /* first argument                   */
74     unsigned arg1;          /* second argument                  */
75     unsigned data_length;   /* length of payload (0 is allowed) */
76     unsigned data_check;    /* checksum of data payload         */
77     unsigned magic;         /* command ^ 0xffffffff             */
78 };
79
80 struct apacket
81 {
82     apacket *next;
83
84     unsigned len;
85     unsigned char *ptr;
86
87     amessage msg;
88     unsigned char data[MAX_PAYLOAD];
89 };
90
91 /* An asocket represents one half of a connection between a local and
92 ** remote entity.  A local asocket is bound to a file descriptor.  A
93 ** remote asocket is bound to the protocol engine.
94 */
95 struct asocket {
96         /* chain pointers for the local/remote list of
97         ** asockets that this asocket lives in
98         */
99     asocket *next;
100     asocket *prev;
101
102         /* the unique identifier for this asocket
103         */
104     unsigned id;
105
106         /* flag: set when the socket's peer has closed
107         ** but packets are still queued for delivery
108         */
109     int    closing;
110
111         /* the asocket we are connected to
112         */
113
114     asocket *peer;
115
116         /* For local asockets, the fde is used to bind
117         ** us to our fd event system.  For remote asockets
118         ** these fields are not used.
119         */
120     fdevent fde;
121     int fd;
122
123         /* queue of apackets waiting to be written
124         */
125     apacket *pkt_first;
126     apacket *pkt_last;
127
128         /* enqueue is called by our peer when it has data
129         ** for us.  It should return 0 if we can accept more
130         ** data or 1 if not.  If we return 1, we must call
131         ** peer->ready() when we once again are ready to
132         ** receive data.
133         */
134     int (*enqueue)(asocket *s, apacket *pkt);
135
136         /* ready is called by the peer when it is ready for
137         ** us to send data via enqueue again
138         */
139     void (*ready)(asocket *s);
140
141         /* close is called by the peer when it has gone away.
142         ** we are not allowed to make any further calls on the
143         ** peer once our close method is called.
144         */
145     void (*close)(asocket *s);
146
147         /* socket-type-specific extradata */
148     void *extra;
149
150         /* A socket is bound to atransport */
151     atransport *transport;
152 };
153
154
155 /* the adisconnect structure is used to record a callback that
156 ** will be called whenever a transport is disconnected (e.g. by the user)
157 ** this should be used to cleanup objects that depend on the
158 ** transport (e.g. remote sockets, listeners, etc...)
159 */
160 struct  adisconnect
161 {
162     void        (*func)(void*  opaque, atransport*  t);
163     void*         opaque;
164     adisconnect*  next;
165     adisconnect*  prev;
166 };
167
168
169 /* a transport object models the connection to a remote device or emulator
170 ** there is one transport per connected device/emulator. a "local transport"
171 ** connects through TCP (for the emulator), while a "usb transport" through
172 ** USB (for real devices)
173 **
174 ** note that kTransportHost doesn't really correspond to a real transport
175 ** object, it's a special value used to indicate that a client wants to
176 ** connect to a service implemented within the SDB server itself.
177 */
178 typedef enum transport_type {
179         kTransportUsb,
180         kTransportLocal,
181         kTransportAny,
182         kTransportHost,
183 } transport_type;
184
185 struct atransport
186 {
187     atransport *next;
188     atransport *prev;
189
190     int (*read_from_remote)(apacket *p, atransport *t);
191     int (*write_to_remote)(apacket *p, atransport *t);
192     void (*close)(atransport *t);
193     void (*kick)(atransport *t);
194
195     int fd;
196     int transport_socket;
197     fdevent transport_fde;
198     int ref_count;
199     unsigned sync_token;
200     int connection_state;
201     transport_type type;
202
203         /* usb handle or socket fd as needed */
204     usb_handle *usb;
205     int sfd;
206
207         /* used to identify transports for clients */
208     char *serial;
209     char *product;
210     int sdb_port; // Use for emulators (local transport)
211     char *device_name; // for connection explorer
212
213         /* a list of adisconnect callbacks called when the transport is kicked */
214     int          kicked;
215     adisconnect  disconnects;
216
217 #ifdef SUPPORT_ENCRYPT
218         unsigned encryption; // 해당 연결이 암호화 모드인지 확인하는 flag , 0 = no-encryption / 1 = encryption
219         int sessionID; // 암호화 세션 ID, 암호화 map에 대한 key
220 #endif
221 };
222
223
224 /* A listener is an entity which binds to a local port
225 ** and, upon receiving a connection on that port, creates
226 ** an asocket to connect the new local connection to a
227 ** specific remote service.
228 **
229 ** TODO: some listeners read from the new connection to
230 ** determine what exact service to connect to on the far
231 ** side.
232 */
233 struct alistener
234 {
235     alistener *next;
236     alistener *prev;
237
238     fdevent fde;
239     int fd;
240
241     const char *local_name;
242     const char *connect_to;
243     atransport *transport;
244     adisconnect  disconnect;
245 };
246
247 #define UNKNOWN "unknown"
248 #define INFOBUF_MAXLEN 64
249 #define INFO_VERSION "2.2.0"
250 typedef struct platform_info {
251     char platform_info_version[INFOBUF_MAXLEN];
252     char model_name[INFOBUF_MAXLEN]; // Emulator
253     char platform_name[INFOBUF_MAXLEN]; // Tizen
254     char platform_version[INFOBUF_MAXLEN]; // 2.2.1
255     char profile_name[INFOBUF_MAXLEN]; // 2.2.1
256 } pinfo;
257
258 #define ENABLED "enabled"
259 #define DISABLED "disabled"
260 #define CPUARCH_ARMV6 "armv6"
261 #define CPUARCH_ARMV7 "armv7"
262 #define CPUARCH_X86 "x86"
263 #define CAPBUF_SIZE 4096
264 #define CAPBUF_ITEMSIZE 32
265 #define CAPBUF_L_ITEMSIZE 256
266 #define CAPBUF_LL_ITEMSIZE PATH_MAX
267 #define SDBD_CAP_VERSION_MAJOR 1
268 #define SDBD_CAP_VERSION_MINOR 0
269 typedef struct platform_capabilities
270 {
271     char secure_protocol[CAPBUF_ITEMSIZE];      // enabled or disabled
272     char intershell_support[CAPBUF_ITEMSIZE];   // enabled or disabled
273     char filesync_support[CAPBUF_ITEMSIZE];     // push or pull or pushpull or disabled
274     char rootonoff_support[CAPBUF_ITEMSIZE];    // enabled or disabled
275     char zone_support[CAPBUF_ITEMSIZE];         // enabled or disabled
276     char multiuser_support[CAPBUF_ITEMSIZE];    // enabled or disabled
277     char syncwinsz_support[CAPBUF_ITEMSIZE];    // enabled or disabled
278     char usbproto_support[CAPBUF_ITEMSIZE];     // enabled or disabled
279     char sockproto_support[CAPBUF_ITEMSIZE];    // enabled or disabled
280     char encryption_support[CAPBUF_ITEMSIZE];   // enabled or disabled
281
282     char log_enable[CAPBUF_ITEMSIZE];    // enabled or disabled
283     char log_path[CAPBUF_LL_ITEMSIZE];    // path of sdbd log
284
285     char cpu_arch[CAPBUF_ITEMSIZE];             // cpu architecture (ex. x86)
286     char profile_name[CAPBUF_ITEMSIZE];         // profile name (ex. mobile)
287     char vendor_name[CAPBUF_ITEMSIZE];          // vendor name (ex. Tizen)
288     char sdk_toolpath[CAPBUF_L_ITEMSIZE];       // sdk tool path
289     char can_launch[CAPBUF_L_ITEMSIZE];         // target name
290
291     char platform_version[CAPBUF_ITEMSIZE];     // platform version (ex. 2.3.0)
292     char product_version[CAPBUF_ITEMSIZE];      // product version (ex. 1.0)
293     char sdbd_version[CAPBUF_ITEMSIZE];         // sdbd version
294     char sdbd_plugin_version[CAPBUF_ITEMSIZE];  // sdbd plugin version
295     char sdbd_cap_version[CAPBUF_ITEMSIZE];     // capability version
296 } pcap;
297 extern pcap g_capabilities;
298
299 #define SDBD_PLUGIN_PATH    "/usr/lib/libsdbd_plugin.so"
300 #define SDBD_PLUGIN_INTF    "sdbd_plugin_cmd_proc"
301 typedef int (*SDBD_PLUGIN_CMD_PROC_PTR)(const char*, const char*, sdbd_plugin_param);
302 extern SDBD_PLUGIN_CMD_PROC_PTR sdbd_plugin_cmd_proc;
303 int request_plugin_cmd(const char* cmd, const char* in_buf, char *out_buf, unsigned int out_len);
304 int request_plugin_verification(const char* cmd, const char* in_buf);
305
306 void print_packet(const char *label, apacket *p);
307
308 asocket *find_local_socket(unsigned id);
309 void install_local_socket(asocket *s);
310 void remove_socket(asocket *s);
311 void close_all_sockets(atransport *t);
312
313 #define  LOCAL_CLIENT_PREFIX  "emulator-"
314
315 asocket *create_local_socket(int fd);
316 asocket *create_local_service_socket(const char *destination);
317
318 asocket *create_remote_socket(unsigned id, atransport *t);
319 void connect_to_remote(asocket *s, const char *destination);
320 void connect_to_smartsocket(asocket *s);
321
322 void fatal(const char *fmt, ...);
323 void fatal_errno(const char *fmt, ...);
324
325 void handle_packet(apacket *p, atransport *t);
326 void send_packet(apacket *p, atransport *t);
327
328 void get_my_path(char *s, size_t maxLen);
329 int launch_server(int server_port);
330 int sdb_main(int is_daemon, int server_port);
331
332
333 /* transports are ref-counted
334 ** get_device_transport does an acquire on your behalf before returning
335 */
336 void init_transport_registration(void);
337 int  list_transports(char *buf, size_t  bufsize);
338 void update_transports(void);
339 void broadcast_transport(apacket *p);
340 int get_connected_count(transport_type type);
341
342 asocket*  create_device_tracker(void);
343
344 /* Obtain a transport from the available transports.
345 ** If state is != CS_ANY, only transports in that state are considered.
346 ** If serial is non-NULL then only the device with that serial will be chosen.
347 ** If no suitable transport is found, error is set.
348 */
349 atransport *acquire_one_transport(int state, transport_type ttype, const char* serial, char **error_out);
350 void   add_transport_disconnect( atransport*  t, adisconnect*  dis );
351 void   remove_transport_disconnect( atransport*  t, adisconnect*  dis );
352 void   run_transport_disconnects( atransport*  t );
353 void   kick_transport( atransport*  t );
354
355 /* initialize a transport object's func pointers and state */
356 #if SDB_HOST
357 int get_available_local_transport_index();
358 #endif
359 int  init_socket_transport(atransport *t, int s, int port, int local);
360 void init_usb_transport(atransport *t, usb_handle *usb, int state);
361
362 /* for MacOS X cleanup */
363 void close_usb_devices();
364
365 /* cause new transports to be init'd and added to the list */
366 void register_socket_transport(int s, const char *serial, int port, int local, const char *device_name);
367
368 /* these should only be used for the "sdb disconnect" command */
369 void unregister_transport(atransport *t);
370 void unregister_all_tcp_transports();
371
372 void register_usb_transport(usb_handle *h, const char *serial, unsigned writeable);
373
374 /* this should only be used for transports with connection_state == CS_NOPERM */
375 void unregister_usb_transport(usb_handle *usb);
376
377 atransport *find_transport(const char *serial);
378 #if SDB_HOST
379 atransport* find_emulator_transport_by_sdb_port(int sdb_port);
380 #endif
381
382 int service_to_fd(const char *name);
383 #if SDB_HOST
384 asocket *host_service_to_socket(const char*  name, const char *serial);
385 #endif
386
387 #if !SDB_HOST
388 int       init_jdwp(void);
389 asocket*  create_jdwp_service_socket();
390 asocket*  create_jdwp_tracker_service_socket();
391 int       create_jdwp_connection_fd(int  jdwp_pid);
392 #endif
393
394 #if !SDB_HOST
395 typedef enum {
396     BACKUP,
397     RESTORE
398 } BackupOperation;
399 int backup_service(BackupOperation operation, char* args);
400 void framebuffer_service(int fd, void *cookie);
401 void log_service(int fd, void *cookie);
402 void remount_service(int fd, void *cookie);
403 char * get_log_file_path(const char * log_name);
404
405 extern int rootshell_mode; // 0: sdk user, 1: root
406 extern int booting_done; // 0: platform booting is in progess 1: platform booting is done
407
408 // This is the users and groups config for the platform
409
410 #define SID_ROOT        0    /* traditional unix root user */
411
412 #define SDK_USER_NAME   tzplatform_getenv(TZ_SDK_USER_NAME)
413 #define SDK_TOOL_PATH   tzplatform_getenv(TZ_SDK_TOOLS)
414 #define STATIC_SDK_USER_ID      5001
415 #define STATIC_SDK_GROUP_ID     100
416 #define STATIC_SDK_HOME_DIR     "/home/owner"
417 extern uid_t g_sdk_user_id;
418 extern gid_t g_sdk_group_id;
419 extern char* g_sdk_home_dir;
420 extern char* g_sdk_home_dir_env;
421 #endif
422
423 int is_pwlocked(void);
424 int should_drop_privileges(void);
425 int set_sdk_user_privileges();
426 void set_root_privileges();
427
428 int get_emulator_forward_port(void);
429 int get_emulator_name(char str[], int str_size);
430 int get_device_name(char str[], int str_size);
431 int get_emulator_hostip(char str[], int str_size);
432 int get_emulator_guestip(char str[], int str_size);
433
434 /* packet allocator */
435 apacket *get_apacket(void);
436 void put_apacket(apacket *p);
437
438 int check_header(apacket *p);
439 int check_data(apacket *p);
440
441 /* define SDB_TRACE to 1 to enable tracing support, or 0 to disable it */
442
443 #define  SDB_TRACE    1
444
445 /* IMPORTANT: if you change the following list, don't
446  * forget to update the corresponding 'tags' table in
447  * the sdb_trace_init() function implemented in sdb.c
448  */
449 typedef enum {
450     TRACE_SDB = 0,
451     TRACE_SOCKETS,
452     TRACE_PACKETS,
453     TRACE_TRANSPORT,
454     TRACE_RWX,
455     TRACE_USB,
456     TRACE_SYNC,
457     TRACE_SYSDEPS,
458     TRACE_JDWP,
459     TRACE_SERVICES,
460     TRACE_PROPERTIES,
461     TRACE_SDKTOOLS
462 } SdbTrace;
463
464 #if SDB_TRACE
465
466 #if !SDB_HOST
467 /*
468  * When running inside the emulator, guest's sdbd can connect to 'sdb-debug'
469  * qemud service that can display sdb trace messages (on condition that emulator
470  * has been started with '-debug sdb' option).
471  */
472
473 /* Delivers a trace message to the emulator via QEMU pipe. */
474 void sdb_qemu_trace(const char* fmt, ...);
475 /* Macro to use to send SDB trace messages to the emulator. */
476 #define DQ(...)    sdb_qemu_trace(__VA_ARGS__)
477 #else
478 #define DQ(...) ((void)0)
479 #endif  /* !SDB_HOST */
480
481   extern int     sdb_trace_mask;
482   extern unsigned char    sdb_trace_output_count;
483   void    sdb_trace_init(void);
484
485 #  define SDB_TRACING  ((sdb_trace_mask & (1 << TRACE_TAG)) != 0)
486
487   /* you must define TRACE_TAG before using this macro */
488 #  define  D(...)                                      \
489         do {                                           \
490             if (SDB_TRACING) {                         \
491                 int save_errno = errno;                \
492                 sdb_mutex_lock(&D_lock);               \
493                 fprintf(stderr, "%s::%s():",           \
494                         __FILE__, __FUNCTION__);       \
495                 errno = save_errno;                    \
496                 fprintf(stderr, __VA_ARGS__ );         \
497                 fflush(stderr);                        \
498                 sdb_mutex_unlock(&D_lock);             \
499                 errno = save_errno;                    \
500            }                                           \
501         } while (0)
502 #  define  DR(...)                                     \
503         do {                                           \
504             if (SDB_TRACING) {                         \
505                 int save_errno = errno;                \
506                 sdb_mutex_lock(&D_lock);               \
507                 errno = save_errno;                    \
508                 fprintf(stderr, __VA_ARGS__ );         \
509                 fflush(stderr);                        \
510                 sdb_mutex_unlock(&D_lock);             \
511                 errno = save_errno;                    \
512            }                                           \
513         } while (0)
514 #else
515 #  define  D(...)          ((void)0)
516 #  define  DR(...)         ((void)0)
517 #  define  SDB_TRACING     0
518 #endif
519
520
521 #if !TRACE_PACKETS
522 #define print_packet(tag,p) do {} while (0)
523 #endif
524
525 #if SDB_HOST_ON_TARGET
526 /* sdb and sdbd are coexisting on the target, so use 26099 for sdb
527  * to avoid conflicting with sdbd's usage of 26098
528  */
529 #  define DEFAULT_SDB_PORT 26099 /* tizen specific */
530 #else
531 #  define DEFAULT_SDB_PORT 26099 /* tizen specific */
532 #endif
533
534 #  define QEMU_FORWARD_IP "10.0.2.2"
535
536 #define DEFAULT_SDB_LOCAL_TRANSPORT_PORT 26101 /* tizen specific */
537 #define DEFAULT_SENSORS_LOCAL_TRANSPORT_PORT 26103 /* tizen specific */
538
539 #define SDB_CLASS              0xff
540 #define SDB_SUBCLASS           0x20 //0x42 /* tizen specific */
541 #define SDB_PROTOCOL           0x02 //0x01 /* tizen specific */
542
543
544 void local_init(int port);
545 int  local_connect(int  port, const char *device_name);
546 int  local_connect_arbitrary_ports(int console_port, int sdb_port, const char *device_name);
547
548 /* usb host/client interface */
549 #if SDB_HOST
550 void usb_init();
551 void usb_cleanup();
552 int usb_write(usb_handle *h, const void *data, int len);
553 int usb_read(usb_handle *h, void *data, size_t len);
554 int usb_close(usb_handle *h);
555 void usb_kick(usb_handle *h);
556 #else
557
558 extern void (*usb_init)();
559 extern void (*usb_cleanup)();
560 extern int (*usb_write)(usb_handle *h, const void *data, int len);
561 extern int (*usb_read)(usb_handle *h, void *data, size_t len);
562 extern int (*usb_close)(usb_handle *h);
563 extern void (*usb_kick)(usb_handle *h);
564
565 /* functionfs backend */
566 void ffs_usb_init();
567 void ffs_usb_cleanup();
568 int ffs_usb_write(usb_handle *h, const void *data, int len);
569 int ffs_usb_read(usb_handle *h, void *data, size_t len);
570 int ffs_usb_close(usb_handle *h);
571 void ffs_usb_kick(usb_handle *h);
572
573 /* kernel sdb gadget backend */
574 void linux_usb_init();
575 void linux_usb_cleanup();
576 int linux_usb_write(usb_handle *h, const void *data, int len);
577 int linux_usb_read(usb_handle *h, void *data, size_t len);
578 int linux_usb_close(usb_handle *h);
579 void linux_usb_kick(usb_handle *h);
580
581 #endif
582
583 /* used for USB device detection */
584 #if SDB_HOST
585 int is_sdb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol);
586 #endif
587
588 unsigned host_to_le32(unsigned n);
589 int sdb_commandline(int argc, char **argv);
590
591 int connection_state(atransport *t);
592
593 #define CS_ANY       -1
594 #define CS_OFFLINE    0
595 #define CS_BOOTLOADER 1
596 #define CS_DEVICE     2
597 #define CS_HOST       3
598 #define CS_RECOVERY   4
599 #define CS_NOPERM     5 /* Insufficient permissions to communicate with the device */
600 #define CS_SIDELOAD   6
601 #define CS_PWLOCK     10
602
603 extern int HOST;
604 extern int SHELL_EXIT_NOTIFY_FD;
605 #if !SDB_HOST
606 extern SdbdCommandlineArgs sdbd_commandline_args;
607 #endif
608
609 #define CHUNK_SIZE (64*1024)
610
611 int sendfailmsg(int fd, const char *reason);
612 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s);
613 int copy_packet(apacket* dest, apacket* src);
614
615 int is_emulator(void);
616 #define DEFAULT_DEVICENAME "unknown"
617
618 #if SDB_HOST /* tizen-specific */
619 #define DEVICEMAP_SEPARATOR ":"
620 #define DEVICENAME_MAX 256
621 #define VMS_PATH OS_PATH_SEPARATOR_STR "vms" OS_PATH_SEPARATOR_STR // should include sysdeps.h above
622
623 void register_device_name(const char *device_type, const char *device_name, int port);
624 int get_devicename_from_shdmem(int port, char *device_name);
625 int read_line(const int fd, char* ptr, const size_t maxlen);
626 #endif
627 #endif
628
629 #define USB_FUNCFS_SDB_PATH "/dev/usbgadget/sdb"
630 #define USB_NODE_FILE "/dev/samsung_sdb"