File: main.c

package info (click to toggle)
oolite 1.77.1-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 41,264 kB
  • ctags: 5,362
  • sloc: objc: 132,090; ansic: 10,457; python: 2,225; sh: 1,325; makefile: 332; perl: 259; xml: 125; php: 5
file content (405 lines) | stat: -rw-r--r-- 9,114 bytes parent folder | download
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#include <CoreFoundation/CoreFoundation.h>
#include "JAPrint.h"
#include "JAAutoreleasePool.h"
#include "OOConsoleConnection.h"
#include "OODebugTCPConsoleProtocol.h"

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>


static int						sClientSocket = -1;
static OOConsoleConnectionRef	sConnection = NULL;
static Boolean					sQuit = FALSE;


static int SetUpServerSocket(in_port_t port);
static void RunServerLoop(int serverSocket);

static void RejectConnection(int connectionFD);

static void HandleInput(void);
static void HandleIncomingData(void);

static CFStringRef ErrnoDesc(void);


static void ConnectionSendData(void *cbInfo, const void *bytes, size_t length);
static void ConnectionConsoleOutput(void *cbInfo, CFStringRef text, CFStringRef colorKey, CFRange *emphasisRanges, uint32_t emphasisRangeCount);
static void ConnectionConnectionEstablished(void *cbInfo, CFStringRef ooliteVersion);
static void ConnectionClose(void *cbInfo, Boolean closedRemotely, CFStringRef message);
static void ConnectionError(void *cbInfo, CFStringRef message);


int main (int argc, char *argv[])
{
	int						serverSocket = -1;
	JAAutoreleasePoolRef	pool = NULL;
	in_port_t				serverPort = kOOTCPConsolePort;
	OOConsoleConnectionCallbacks callbacks =
	{
		ConnectionSendData,
		ConnectionConsoleOutput,
		NULL,
		NULL,
		NULL,
		ConnectionConnectionEstablished,
		ConnectionClose,
		ConnectionError,
		NULL
	};
	
	pool = JACreateAutoreleasePool();
	
	// Create protocol decoder
	sConnection = OOConsoleConnectionCreate(CFSTR("simpleDebugConsole"), &callbacks, NULL);
	if (sConnection == NULL)
	{
		JAPrintErrC("* Could not create connection object.\n");
		return EXIT_FAILURE;
	}
	
	if (argc > 1)
	{
		serverPort = atoi(argv[1]);
		if (serverPort < 1)
		{
			JAPrintErrC("* Invalid port (%i).\n", (int)serverPort);
			return EXIT_FAILURE;
		}
	}
	
	serverSocket = SetUpServerSocket(serverPort);
	if (serverSocket == -1)  return EXIT_FAILURE;
	
	JADestroyAutoreleasePool(pool);
	pool = JACreateAutoreleasePool();
	
	JAPrintC("- Waiting for connection.\n");
	RunServerLoop(serverSocket);
	
	OOConsoleConnectionDestroy(sConnection);
	
	return 0;
}


static int SetUpServerSocket(in_port_t port)
{
	int						sock = -1;
	
	// Create socket.
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == -1)
	{
		JAPrintErrC("* Could not create server socket (%@).\n", ErrnoDesc());
		return -1;
	}
	
	// Allow local address reuse.
	int yes = 1;
	if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
	{
		JAPrintErrC("* Could not configure server socket (%@).\n", ErrnoDesc());
		return -1;
	}
	
	// Bind to listen on specified port.
	struct sockaddr_in serverAddress =
	{
		sin_len: 0,
		sin_family: AF_INET,
		sin_addr: { s_addr: INADDR_ANY },
		sin_port: htons(port),
		sin_zero: { 0,0,0,0,0,0,0,0 }
	};
	if (bind(sock, (struct sockaddr *)&serverAddress, sizeof serverAddress) == -1)
	{
		JAPrintErrC("* Could not bind server socket (%@).\n", ErrnoDesc());
		return -1;
	}
	
	// Listen, allowing one connection at a time.
	if (listen(sock, 1) == -1)
	{
		JAPrintErrC("* Could not listen on server socket (%@).\n", ErrnoDesc());
		return -1;
	}
	
	return sock;
}


static void RunServerLoop(int serverSocket)
{
	JAAutoreleasePoolRef	pool = NULL;
	fd_set					masterSet, tempSet;
	struct sockaddr_in		clientAddress;
	socklen_t				addressLength;
	int						newFD;
	int						maxFD;
	
	// Set up file descriptor set for select()
	FD_ZERO(&masterSet);
	FD_SET(serverSocket, &masterSet);
	FD_SET(0 /* stdin */, &masterSet);
	maxFD = 0;
	if (serverSocket > maxFD)  maxFD = serverSocket;
	
	// Run select() loop
	do
	{
		JADestroyAutoreleasePool(pool);
		pool = JACreateAutoreleasePool();
		
		FD_COPY(&masterSet, &tempSet);
		if (select(maxFD + 1, &tempSet, NULL, NULL, NULL) == -1)
		{
			if (errno != EINTR)  JAPrintErrC("* select() failed (%@)!", ErrnoDesc());
			continue;
		}
		
		// If we got a message on the server socket:
		if(FD_ISSET(serverSocket, &tempSet))
		{
			addressLength = sizeof clientAddress;			
			newFD = accept(serverSocket, (struct sockaddr *)&clientAddress, &addressLength);
			if (newFD == -1)
			{
				JAPrintErrC("* Client connection failed, error in accept() (%@).\n", ErrnoDesc());
			}
			else
			{
				if (sClientSocket == -1)
				{
					// No client connected yet.
					sClientSocket = newFD;
					fcntl(sClientSocket, F_SETFL, O_NONBLOCK);
					FD_SET(sClientSocket, &masterSet);
					
					// Specify the host, if not localhost.
					if (clientAddress.sin_family == AF_INET)
					{
						if (clientAddress.sin_addr.s_addr != INADDR_LOOPBACK)
						{
							JAPrintC("- Client connected from %s.\n", inet_ntoa(clientAddress.sin_addr));
						}
						else  JAPrintC("- Client connected locally.\n");
					}
					else  JAPrintC("- Client connected.\n");
					
					JAPrintFlush();
					if (sClientSocket > maxFD)  maxFD = sClientSocket;
				}
				else
				{
					// We already have one client, and don't deal with more.
					RejectConnection(newFD);
					JAPrintC("* Rejected attempted connection by second client.\n");
				}
			}
		}
		if (FD_ISSET(0, &tempSet))
		{
			HandleInput();
		}
		if (sClientSocket != -1 && FD_ISSET(sClientSocket, &tempSet))
		{
			HandleIncomingData();
		}
	} while (!sQuit);
	
	JADestroyAutoreleasePool(pool);
}


static void RejectConnection(int connectionFD)
{
	// TODO: send reject packet
	close(connectionFD);
}


static void HandleInput(void)
{
	CFMutableDataRef		data = NULL;
	int						input;
	UInt8					byte;
	CFStringRef				string = NULL;
	
	data = CFDataCreateMutable(kCFAllocatorDefault, 0);
	if (data == NULL)  return;
	
	for (;;)
	{
		input = getchar();
		if (input == '\n' || input == EOF)  break;
		byte = input;
		CFDataAppendBytes(data, &byte, 1);
	}
	
	string = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, data, kCFStringEncodingUTF8);
	CFRelease(data);
	if (string != NULL)
	{
		OOConsoleConnectionPerformCommand(sConnection, string);
	}
	else
	{
		JAPrintErrC("* Could not interpret input as UTF-8.\n");
	}
}


static void HandleIncomingData(void)
{
	enum { kBufferSize = 16 << 10 };
	
	ssize_t					length;
	unsigned char			buffer[kBufferSize];
	
	while (length = recv(sClientSocket, buffer, kBufferSize, 0), length > 0)
	{
		if (sQuit)  return;
		OOConsoleConnectionReceiveBytes(sConnection, buffer, length);
	}
	if (length == -1 && errno != EAGAIN)
	{
		JAPrintC("*** Connection broken (%@).\n\n", ErrnoDesc());
		sQuit = TRUE;
	}
	if (length == 0)
	{
		JAPrintC("*** Connection closed by remote.\n\n");
		sQuit = TRUE;
	}
}


static void ConnectionSendData(void *cbInfo, const void *bytes, size_t length)
{
	ssize_t					sent;
	
	
	fcntl(sClientSocket, F_SETFL, 0);
	
	while (length > 0)
	{
		if (sQuit)  break;
		sent = send(sClientSocket, bytes, length, 0);
		if (sent == -1)
		{
			JAPrintErrC("*** Connection broken (%@).\n", ErrnoDesc());
			sQuit = TRUE;
		}
		bytes += sent;
		length -= sent;
	}
	
	fcntl(sClientSocket, F_SETFL, O_NONBLOCK);
}


static void ConnectionConsoleOutput(void *cbInfo, CFStringRef text, CFStringRef colorKey, CFRange *emphasisRanges, uint32_t emphasisRangeCount)
{
	JAPrintC("  %@\n", text);
	JAPrintFlush();
}


static void ConnectionConnectionEstablished(void *cbInfo, CFStringRef ooliteVersion)
{
	JAPrintC("- Connection established to Oolite %@.\n\n", ooliteVersion);
}


static void ConnectionClose(void *cbInfo, Boolean closedRemotely, CFStringRef message)
{
	JAPrintC("- Connection closed: %@\n\n", message ? message : CFSTR("no reason given."));
	sQuit = TRUE;
}


static void ConnectionError(void *cbInfo, CFStringRef message)
{
	JAPrintErrC("* %@\n", message);
}


static CFStringRef ErrnoDesc(void)
{
	int						error;
	
	error = errno;
	
	switch (error)
	{
		case 0:
			return CFSTR("no error");
			
		case EPROTONOSUPPORT:
			return CFSTR("protocol is not supported in this domain");
			
		case EMFILE:
			return CFSTR("file descriptor table is full");
			
		case ENFILE:
			return CFSTR("system file table is full");
			
		case EACCES:
			return CFSTR("permission denied");
			
		case ENOBUFS:
			return CFSTR("insufficient buffer space available");
			
		case ENOMEM:
			return CFSTR("out of memory");
			
		case EBADF:
			return CFSTR("bad file descriptor");
			
		case ENOTSOCK:
			return CFSTR("not a socket");
			
		case ENOPROTOOPT:
			return CFSTR("unknown option for protocol level");
			
		case EFAULT:
			return CFSTR("out-of-bounds pointer");
			
		case EDOM:
			return CFSTR("out-of-bounds value");
			
		case EADDRNOTAVAIL:
			return CFSTR("address is not available");
			
		case EADDRINUSE:
			return CFSTR("address is in use");
			
		case EINVAL:
			return CFSTR("invalid argument");
			
		case EOPNOTSUPP:
			return CFSTR("operation not supported");
			
		case EINTR:
			return CFSTR("interrupted");
			
		case EHOSTUNREACH:
			return CFSTR("host unreachable");
			
		case EPIPE:
			return CFSTR("broken pipe");
			
		case ECONNRESET:
			return CFSTR("connection reset by peer");
	}
	
	return CFFMTSTR("unknown errno %i", error);
}