-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol.c
133 lines (105 loc) · 2.37 KB
/
protocol.c
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include "protocol.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <message.h>
#include <common.h>
static long _fd_skt = -1;
static int sendAndReceive(message *sent)
{
if (message_send(_fd_skt, sent) == FALSE) {
return FALSE;
}
message *received = message_receive(_fd_skt);
if (received == NULL) {
return FALSE;
}
int result = FALSE;
if (received->op == message_ok) {
result = TRUE;
}
if (received->op == message_ko) {
fprintf(stderr,"%s\n", received->name);
result = FALSE;
}
if (sent->op == message_store) {
message_detach_data(sent); // avoid to release not owned data
}
message_destroy(sent);
message_destroy(received);
return result;
}
int os_connect(char *name)
{
if (_fd_skt < 0) {
struct sockaddr_un sa;
memset(&sa, 0, sizeof(sa));
strncpy(sa.sun_path, SOCKNAME, sizeof(sa.sun_path));
sa.sun_family = AF_UNIX;
if ((_fd_skt = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
return FALSE;
}
if (connect(_fd_skt, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
return FALSE;
}
}
message *sent = message_create(message_register, name, 0, NULL);
return sendAndReceive(sent);
}
int os_store(char *name, void *block, size_t len)
{
if (_fd_skt < 0) return FALSE;
message *sent = message_create(message_store, name, len, block);
return sendAndReceive(sent);
}
void *os_retrieve(char *name)
{
if (name == NULL) {
return NULL;
}
if (_fd_skt < 0) {
return NULL;
}
void *data = NULL;
message *sent = message_create(message_retrieve, name, 0, NULL);
if (message_send(_fd_skt, sent) == FALSE) {
message_destroy(sent);
return NULL;
}
message *received = message_receive(_fd_skt);
if (received == NULL) {
message_destroy(sent);
return NULL;
}
if (received->op == message_data) {
data = message_detach_data(received);
}
if (received->op == message_ko) {
fprintf(stderr,"%s\n", received->name);
}
message_destroy(sent);
message_destroy(received);
return data;
}
int os_delete(char *name)
{
if (_fd_skt < 0) {
return FALSE;
}
message *sent = message_create(message_delete, name, 0, NULL);
return sendAndReceive(sent);
}
int os_disconnect()
{
if (_fd_skt < 0) {
return FALSE;
}
message *sent = message_create(message_leave, NULL, 0, NULL);
int result = sendAndReceive(sent);
close(_fd_skt);
return result;
}