Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: cd2fbbf8f847fbc9176a563d2bda2ee7bbda314c (plain) (blame)
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*******************************************************************************
 * Copyright (c) 2013 protos software gmbh (http://www.protos.de).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * CONTRIBUTORS:
 * 		Henrik Rentz-Reichert (initial contribution)
 *
 *******************************************************************************/

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "osal/etTcpSockets.h"
#include "osal/etThread.h"

#define STACK_SIZE		(1024*256)
#define PRIO			0
#define LOCAL_HOST		"127.0.0.1"
#define INVALID_SOCKET	-1

#define PRINT_DEBUG(x)	{ printf(x); fflush(stdout); }

typedef int SOCKET;

/* implementation versions of data */

typedef struct etSocketConnectionDataImpl {
	/* public part */
	etSocketConnectionData data;

	/* implementation specific */
	SOCKET socket;
	int channel;
	struct sockaddr_in address;
	etThread readThread;
}
etSocketConnectionDataImpl;

typedef struct etSocketServerDataImpl {
	/* public part */
	etSocketServerData data;

	/* implementation specific */
	SOCKET socket;
	etThread listenerThread;
	int nConnections;
	etSocketConnectionDataImpl connections[MAX_CONNECTIONS];
}
etSocketServerDataImpl;

/* thread function reading from the socket */
static void readThreadFunc(void* threadData) {
	etSocketConnectionDataImpl* self = (etSocketConnectionDataImpl*) threadData;
	int len, retval;
	int8* buffer = (self->data.bufferProvider)(self->data.userData, &len);

	while (TRUE) {
		retval = recv(self->socket, buffer, len, 0);
		if (retval<=0) {
			/* TODO: call  WSAGetLastError and do error handling */
			PRINT_DEBUG("connection thread: socket lost, exiting\n")
			self->socket = INVALID_SOCKET;
			return;
		}

		(self->data.receiver)(self->data.userData, self->channel, retval, buffer);
	}
}

/* thread function listening to the socket and creating new listener threads for accepted connections */
static void listenerThreadFunc(void* threadData) {
	etSocketServerDataImpl* self = (etSocketServerDataImpl*) threadData;

	PRINT_DEBUG("server: listening\n")
	if (listen(self->socket, self->data.maxConnections) == INVALID_SOCKET) {
		PRINT_DEBUG("server: error\n")
		return;
	}

	while (self->data.maxConnections > self->nConnections) {
		int slot;
		int len;

		/* find next free slot */
		for (slot=0; slot<MAX_CONNECTIONS; ++slot)
			if (self->connections[slot].socket==INVALID_SOCKET)
				break;

		PRINT_DEBUG("server: accepting\n")
		len = sizeof(self->connections[slot].address);
		self->connections[slot].socket = accept(
				self->socket,
				(struct sockaddr*) &self->connections[slot].address,
				&len);

		if (self->connections[slot].socket == INVALID_SOCKET) {
			/* TODO: error handling */
			PRINT_DEBUG("server: accept interrupted, exiting\n")
			return;
		}

		PRINT_DEBUG("server: accepted new client, starting read thread\n")
		self->connections[slot].channel = self->nConnections++;

		etThread_construct(
				&self->connections[slot].readThread,
				STACK_SIZE,
				PRIO,
				"etSocketServer",
				readThreadFunc,
				&self->connections[slot]);
	}

	/* TODO: if maxConnections is reached this thread terminates.
	 * Should we wait until a connection is closed and accept again?
	 */

	PRINT_DEBUG("server: exiting listener thread\n")
}

etSocketError etInitSockets() {
	PRINT_DEBUG("sockets: init\n")
	return ETSOCKET_OK;
}

etSocketError etCleanupSockets() {
	PRINT_DEBUG("sockets: clean-up\n")
	return ETSOCKET_OK;
}

etSocketServerData* etCreateSocketServerData() {
	etSocketServerDataImpl* data = malloc(sizeof(etSocketServerDataImpl));
	memset(data, 0, sizeof(etSocketServerDataImpl));
	return &data->data;
}

void etFreeSocketServerData(etSocketServerData* data) {
	etSocketServerDataImpl* self = (etSocketServerDataImpl*) data;
	free(self);
}

etSocketError etStartListening(etSocketServerData* data, short port) {
	etSocketServerDataImpl* self = (etSocketServerDataImpl*) data;
	struct sockaddr_in local;
	int i;

	if (self==NULL)
		return ETSOCKET_ERROR;

	if (self->data.maxConnections>MAX_CONNECTIONS)
		return ETSOCKET_ERROR;

	/* mark all connections unused and set receiver and buffer provider */
	for (i=0; i<MAX_CONNECTIONS; ++i) {
		self->connections[i].socket = INVALID_SOCKET;
		self->connections[i].data.receiver = self->data.receiver;
		self->connections[i].data.bufferProvider = self->data.bufferProvider;
		self->connections[i].data.userData = self->data.userData;
	}
	self->nConnections = 0;

	local.sin_family = AF_INET;
	local.sin_addr.s_addr = INADDR_ANY;

	local.sin_port = htons(port);

	self->socket = socket(AF_INET, SOCK_STREAM, 0);
	if (self->socket == INVALID_SOCKET)
		return ETSOCKET_ERROR;

	if (bind(self->socket, (struct sockaddr*) &local, sizeof(local)) < 0)
		return ETSOCKET_ERROR;

	PRINT_DEBUG("server: starting listener thread\n")
	etThread_construct(
			&self->listenerThread,
			STACK_SIZE,
			PRIO,
			"etSocketServer",
			listenerThreadFunc,
			self);

	return ETSOCKET_OK;
}

etSocketError etStopSocketServer(etSocketServerData* data) {
	etSocketServerDataImpl* self = (etSocketServerDataImpl*) data;
	PRINT_DEBUG("server: stop\n")
	close(self->socket);
	return ETSOCKET_OK;
}

etSocketError etWriteServerSocket(etSocketServerData* dat, int connection, int size, const int8* data) {
	etSocketServerDataImpl* self = (etSocketServerDataImpl*) dat;
	int offset = 0;

	if (connection<0 || connection>MAX_CONNECTIONS || self->connections[connection].socket==INVALID_SOCKET)
		return ETSOCKET_ERROR;

	/* Note: loop required because:
	 * If no error occurs, send returns the total number of bytes sent, which can be less than the number
	 * requested to be sent in the len parameter.
	 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740149%28v=vs.85%29.aspx
	 */

	while (size>0) {
		int sent = send(self->connections[connection].socket, ((int8*)data)+offset, size, 0);
		if (sent<=0)
			return ETSOCKET_ERROR;

		offset += sent;
		size -= sent;
	}

	return ETSOCKET_OK;
}

etSocketError etCloseServerSocket(etSocketServerData* data, int connection) {
	etSocketServerDataImpl* self = (etSocketServerDataImpl*) data;

	if (self->connections[connection].socket!=INVALID_SOCKET) {
		PRINT_DEBUG("server: close connection\n")
		close(self->connections[connection].socket);
		self->connections[connection].socket = INVALID_SOCKET;
	}

	return ETSOCKET_OK;
}

etSocketError etCloseAllServerSockets(etSocketServerData* data) {
	etSocketServerDataImpl* self = (etSocketServerDataImpl*) data;
	int i;

	PRINT_DEBUG("server: close all connections\n")
	for (i=0; i<MAX_CONNECTIONS; ++i) {
		if (self->connections[i].socket!=INVALID_SOCKET) {
			close(self->connections[i].socket);
			self->connections[i].socket = INVALID_SOCKET;
		}
	}

	return ETSOCKET_OK;
}

etSocketConnectionData* etCreateSocketConnectionData() {
	etSocketConnectionDataImpl* data = malloc(sizeof(etSocketConnectionDataImpl));
	memset(data, 0, sizeof(etSocketConnectionDataImpl));
	return &data->data;
}

void etFreeSocketConnectionData(etSocketConnectionData* data) {
	etSocketConnectionDataImpl* self = (etSocketConnectionDataImpl*) data;
	free(self);
}

etSocketError etConnectServer(etSocketConnectionData* data, const char* addr, short port) {
	etSocketConnectionDataImpl* self = (etSocketConnectionDataImpl*) data;
	struct hostent *host;

	if (addr==NULL)
		addr = LOCAL_HOST;

	if (isalpha((int)addr[0])) {
		host = gethostbyname(addr);
	}
	else {
		unsigned long a = inet_addr(addr);
		host = gethostbyaddr((char *)&a, 4, AF_INET);
	}

	if (host == NULL )
		return ETSOCKET_ERROR;

	memset(&self->address, 0, sizeof(self->address));
	memcpy(&(self->address.sin_addr), host->h_addr, host->h_length);
	self->address.sin_family = host->h_addrtype;
	self->address.sin_port = htons(port);

	self->socket = socket(AF_INET, SOCK_STREAM, 0);
	if (self->socket==INVALID_SOCKET)
		return ETSOCKET_ERROR;

	PRINT_DEBUG("client: connecting\n")
	if (connect(self->socket, (struct sockaddr*)&(self->address), sizeof(self->address)) == INVALID_SOCKET)
		return ETSOCKET_ERROR;

	PRINT_DEBUG("client: connected\n")
	PRINT_DEBUG("client: starting read thread\n")
	etThread_construct(
			&self->readThread,
			STACK_SIZE,
			PRIO,
			"etSocketConnection",
			readThreadFunc,
			self);

	return ETSOCKET_OK;
}

etSocketError etWriteSocket(etSocketConnectionData* dat, int size, const int8* data) {
	etSocketConnectionDataImpl* self = (etSocketConnectionDataImpl*) dat;
	int offset = 0;

	while (size>0) {
		int sent = send(self->socket, ((int8*)data)+offset, size, 0);
		if (sent<=0)
			return ETSOCKET_ERROR;

		offset += sent;
		size -= sent;
	}

	return ETSOCKET_OK;
}

etSocketError etCloseSocket(etSocketConnectionData* data) {
	etSocketConnectionDataImpl* self = (etSocketConnectionDataImpl*) data;

	close(self->socket);

	return ETSOCKET_OK;
}

Back to the top