#include "srvctrlsocket.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
SrvConnection* srvctrl_connet(
char *socketfile) {
if(!socketfile) {
fprintf(stderr,
"srvctrl_connect: no socketfile\n");
return NULL;
}
size_t len = strlen(socketfile);
if(len ==
0) {
fprintf(stderr,
"srvctrl_connect: invalid socket path\n");
return NULL;
}
if(len >
100) {
fprintf(stderr,
"srvctrl_connect: socket path too long\n");
return NULL;
}
int fd = socket(
AF_UNIX,
SOCK_STREAM,
0);
if(fd == -
1) {
perror(
"srvctrl_connect: cannot create socket");
return NULL;
}
struct sockaddr_un addr;
memset(&addr,
0,
sizeof(addr));
addr.sun_family =
AF_UNIX;
memcpy(addr.sun_path, socketfile, len);
if(connect(fd, (
struct sockaddr*)&addr,
sizeof(addr))) {
perror(
"srvctrl_connect");
close(fd);
return NULL;
}
FILE *stream = fdopen(fd,
"r+");
if(!stream) {
close(fd);
return NULL;
}
SrvConnection *conn = calloc(
1,
sizeof(SrvConnection));
conn->socket = fd;
conn->stream = stream;
return conn;
}
void srvctrl_close(SrvConnection *conn) {
fclose(conn->stream);
free(conn);
}
int srvctrl_readmsg(SrvConnection *conn, SrvMsg *msg) {
int type =
0;
uint16_t length;
type = fgetc(conn->stream);
if(type ==
EOF) {
return 1;
}
if(fread(&length,
1,
2, conn->stream) !=
2) {
return -
1;
}
msg->type = type;
msg->length = length;
msg->message = malloc(length);
size_t r = fread(msg->message,
1, length, conn->stream);
if(r != length) {
free(msg->message);
return -
1;
}
return 0;
}