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 #include "srvctrlsocket.h"
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <string.h>
35 #include <sys/socket.h>
36 #include <sys/un.h>
37
38 SrvConnection* srvctrl_connet(
char *socketfile) {
39 if(!socketfile) {
40 fprintf(stderr,
"srvctrl_connect: no socketfile\n");
41 return NULL;
42 }
43 size_t len = strlen(socketfile);
44 if(len ==
0) {
45 fprintf(stderr,
"srvctrl_connect: invalid socket path\n");
46 return NULL;
47 }
48 if(len >
100) {
49 fprintf(stderr,
"srvctrl_connect: socket path too long\n");
50 return NULL;
51 }
52
53 int fd = socket(
AF_UNIX,
SOCK_STREAM,
0);
54 if(fd == -
1) {
55 perror(
"srvctrl_connect: cannot create socket");
56 return NULL;
57 }
58
59 struct sockaddr_un addr;
60 memset(&addr,
0,
sizeof(addr));
61 addr.sun_family =
AF_UNIX;
62 memcpy(addr.sun_path, socketfile, len);
63
64 if(connect(fd, (
struct sockaddr*)&addr,
sizeof(addr))) {
65 perror(
"srvctrl_connect");
66 close(fd);
67 return NULL;
68 }
69
70 FILE *stream = fdopen(fd,
"r+");
71 if(!stream) {
72 close(fd);
73 return NULL;
74 }
75
76 SrvConnection *conn = calloc(
1,
sizeof(SrvConnection));
77 conn->socket = fd;
78 conn->stream = stream;
79
80 return conn;
81 }
82
83 void srvctrl_close(SrvConnection *conn) {
84 fclose(conn->stream);
85 free(conn);
86 }
87
88 int srvctrl_readmsg(SrvConnection *conn, SrvMsg *msg) {
89 int type =
0;
90 uint16_t length;
91
92 type = fgetc(conn->stream);
93 if(type ==
EOF) {
94 return 1;
95 }
96
97 if(fread(&length,
1,
2, conn->stream) !=
2) {
98 return -
1;
99 }
100
101 msg->type = type;
102 msg->length = length;
103 msg->message = malloc(length);
104
105 size_t r = fread(msg->message,
1, length, conn->stream);
106 if(r != length) {
107 free(msg->message);
108 return -
1;
109 }
110
111 return 0;
112 }
113