summary refs log tree commit diff
path: root/child.c
blob: 58ee999a0d65f426d255e38dec3a4b740897baf1 (plain)
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
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>

#include "fdwatcher.h"
#include "logging.h"

struct ConnectionDataBuffer {
	size_t capacity;
	size_t length;
	char buf[];
};

struct ConnectionData {
	struct ConnectionDataBuffer *buffer;
};

static int
aura_addbufferdata(struct ConnectionDataBuffer *buffer, char *data, size_t length)
{
	if (buffer->length + length > buffer->capacity) {
		aura_printf("FUCK!\n");
		aura_printf("buffer->length: %ld\n", buffer->length);
		aura_printf("buffer->capacity: %ld\n", buffer->capacity);
		aura_printf("length: %ld\n", length);

		abort();
	}

	memcpy(buffer->buf, data, length);
	buffer->length = buffer->length + length;

	return 0;
}

static int
meowiero(struct FDWatchHandle *handle, enum FDWatch_EventType type, int fd, void *data)
{
	struct ConnectionData *connectiondata = (struct ConnectionData *)data;
	char c = 0;

	switch (type) {
	case FDWATCH_EVENT_INP:
		aura_printf("INPUT event in fd:%d\n", fd);

		read(fd, &c, 2);
		aura_addbufferdata(connectiondata->buffer, &c, 2);

		aura_printf("%c\n", c);
		break;
	case FDWATCH_EVENT_HUP:
		aura_printf("HANGUP event in fd:%d, exiting\n", fd);
		fdwatcher_remove(handle, fd);
		close(fd);
		return 0;
	}

	return 1;
}

/* init */
int childProcessMain(int argc, char **argv)
{
	struct ConnectionData *connectiondata = { 0 };
	struct FDWatchHandle fdhandle = { 0 };
	int sockie = 0;
	int ret = 0;

	connectiondata = (struct ConnectionData *)malloc(sizeof(struct ConnectionData));
	if (errno != 0) {
		perror("malloc(3)");
		return 1;
	}

	connectiondata->buffer = malloc(sizeof(struct ConnectionDataBuffer) + 65536);
	if (errno != 0) {
		perror("malloc(3)");
		return 1;
	}
	connectiondata->buffer->capacity = 65536;

	/* socket fd int in argv[2]! ^w^ */
	sscanf(argv[2], "%d", &sockie);
	aura_printf("received fd:%d\n", sockie);

	ret = fdwatcher_initialise(&fdhandle, 1);
	if (ret < 0) {
		aura_fprintf(stderr, "fdwatcher_initialise failed\n");
		return 1;
	}

	ret = fdwatcher_add(&fdhandle, sockie, (void *)connectiondata);
	if (ret < 0) {
		aura_fprintf(stderr, "fdwatcher_add failed\n");
		return 1;
	}

	fdwatcher_watch(&fdhandle, meowiero);
	aura_printf("finished\n");

	return 0;
}