Newer
Older
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
#define _GNU_SOURCE
#include "frontend_common.h"
#include "config.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <err.h>
struct backend_conn {
FILE * socket;
size_t len;
char * buf;
};
struct backend_conn * ucart_backendConnect()
{
int s;
struct sockaddr_un remote;
char str[100];
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
struct backend_conn * conn = NULL;
printf("Trying to connect...\n");
remote.sun_family = AF_UNIX;
char * sock_env = getenv(SOCKET_ENV);
strcpy(remote.sun_path, sock_env ? sock_env : DEFAULT_SOCKET);
if (connect(s, (struct sockaddr *)&remote, sizeof(remote)) == -1) {
perror("connect");
goto fail_final;
}
conn = malloc(sizeof(struct backend_conn));
if (conn == NULL) {
perror("malloc");
goto fail_sock;
}
conn->len = 0;
conn->buf = NULL;
if (conn->socket == NULL) {
perror("fdopen");
goto fail_malloc_conn;
}
/* success */
goto fail_final;
fail_malloc_conn:
free(conn);
conn = NULL;
fail_sock:
close(s);
fail_final:
return conn;
}
void ucart_backendDisconnect(struct backend_conn * conn)
{
fclose(conn->socket);
if (conn->buf) {
free(conn->buf);
}
free(conn);
}
char * ucart_backendGetline(struct backend_conn *conn)
{
getline(&conn->buf, &conn->len, conn->socket);
return conn->buf;
}
int ucart_backendWrite(struct backend_conn *conn, const char * line)