forked from IngCr3at1on/android_bootable_recovery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
messagesocket.cpp
116 lines (106 loc) · 2.34 KB
/
messagesocket.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include "messagesocket.h"
static const char * const SOCKET_PATH = "/tmp/.dialog_sock";
bool MessageSocket::ServerInit()
{
int fd, rc;
unlink(SOCKET_PATH);
fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
return false;
}
struct sockaddr_un sa;
socklen_t salen;
memset(&sa, 0, sizeof(sa));
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, SOCKET_PATH);
rc = ::bind(fd, (struct sockaddr *)&sa, sizeof(sa));
if (rc != 0) {
::close(fd);
return false;
}
rc = ::listen(fd, 5);
if (rc != 0) {
::close(fd);
return false;
}
_sock = fd;
return true;
}
MessageSocket* MessageSocket::Accept()
{
int clientfd;
struct sockaddr_un sa;
socklen_t salen;
memset(&sa, 0, sizeof(sa));
salen = sizeof(sa);
clientfd = ::accept(_sock, (struct sockaddr*)&sa, &salen);
if (clientfd < 0) {
return NULL;
}
return new MessageSocket(clientfd);
}
ssize_t MessageSocket::Read(void* buf, size_t len)
{
//XXX: use fdopen/getline
ssize_t nread = ::read(_sock, buf, len);
if (nread > 0) {
char* p = (char*)memchr(buf, '\n', nread);
if (p) {
*p = '\0';
}
}
return nread;
}
bool MessageSocket::ClientInit()
{
int fd, rc;
fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
return false;
}
struct sockaddr_un sa;
socklen_t salen;
memset(&sa, 0, sizeof(sa));
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, SOCKET_PATH);
rc = ::connect(fd, (struct sockaddr*)&sa, sizeof(sa));
if (rc != 0) {
::close(fd);
return false;
}
_sock = fd;
return true;
}
bool MessageSocket::Show(const char* message)
{
char buf[256];
sprintf(buf, "show %s", message);
return send_command(buf);
}
bool MessageSocket::Dismiss()
{
return send_command("dismiss");
}
void MessageSocket::Close()
{
if (_sock != -1) {
::close(_sock);
_sock = -1;
}
}
bool MessageSocket::send_command(const char* command)
{
char buf[256];
int len;
ssize_t written;
len = sprintf(buf, "dialog %s\n", command);
written = ::write(_sock, buf, len);
return (written == len);
}