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