summaryrefslogtreecommitdiff
path: root/src/connection.cpp
blob: aa130dbb378da0c5b7217a1a837d159548064103 (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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#include "connection.h"
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <errno.h>
#include "exceptions.h"

Connection::Connection()
{
	nSocket = -1;
	bActive = false;
	bDisconnectMe = false;
	pProtocol = NULL;
}

Connection::~Connection()
{
	if( pProtocol != NULL ) delete pProtocol;
}

bool Connection::appendOutput( const char *lpOutput, int nSize )
{
	return xOutputBuf.appendData( lpOutput, nSize );
}

bool Connection::appendOutput( const char lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const short lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const int lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const long lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const float lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const double lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const unsigned char lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const unsigned short lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const unsigned long lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendOutput( const unsigned int lOutput )
{
	return xOutputBuf.appendData( lOutput );
}

bool Connection::appendInput( const char *lpInput, int nSize )
{
	return xInputBuf.appendData( lpInput, nSize );
}

int Connection::scanInputFor( char cTarget )
{
	const char *lpTmp = xInputBuf.getData();
	int jMax = xInputBuf.getLength();

	for( int j = 0; j < jMax; j++ )
	{
		if( lpTmp[j] == cTarget )
		{
			return j;
		}
	}

	return -1;
}

const char *Connection::getOutput()
{
	return xOutputBuf.getData();
}

const char *Connection::getInput()
{
	return xInputBuf.getData();
}

void Connection::setSocket( int nNewSocket )
{
	nSocket = nNewSocket;
}

int Connection::getSocket()
{
	return nSocket;
}

bool Connection::isActive()
{
	return bActive;
}

void Connection::close()
{
	if( bActive )
	{
		fsync( nSocket );
		::close( nSocket );
	}
	bActive = false;
	//nSocket = -1;
	xInputBuf.clearData();
	xOutputBuf.clearData();
	if( pProtocol != NULL )
	{
		delete pProtocol;
		pProtocol = NULL;
	}
}

bool Connection::open( int nNewSocket )
{
	bActive = true;
	setSocket( nNewSocket );
	bDisconnectMe = false;

	return true;
}

bool Connection::open( const char *sAddr, int nPort )
{
	struct sockaddr_in xServerName;
	bActive = false;
     
	/* Create the socket. */
	nSocket = socket( PF_INET, SOCK_STREAM, 0 );
	if( nSocket < 0 )
	{
		bActive = false;
		return false;
	}
     
	/* Connect to the server. */
	{
		struct hostent *hostinfo;
     
		xServerName.sin_family = AF_INET;
		xServerName.sin_port = htons( nPort );
		hostinfo = gethostbyname( sAddr );
		if (hostinfo == NULL)
		{
			return false;
		}
		xServerName.sin_addr = *(struct in_addr *) hostinfo->h_addr;
	}

	int ret = connect(
		nSocket,
		(struct sockaddr *)&xServerName,
		sizeof(xServerName)
		);

	if( ret < 0 )
	{
		return false;
	}

	bActive = true;
	bDisconnectMe = false;

	return true;
}

int Connection::readInput()
{
	char buffer[2048];
	int nbytes;
	int nTotalRead=0;

	for(;;)
	{
		//memset( buffer, 0, 2048 );

		nbytes = read( nSocket, buffer, 2048 );
		if( nbytes < 0 && errno != 0 && errno != EAGAIN )
		{
			printf("errno: %d, %s\n", errno, strerror( errno ) );
			/* Read error. */
			//perror("readInput");
			throw ConnectionException( excodeReadError, "Read error: %s", strerror( errno ) );
		}
		else
		{
			if( nbytes <= 0 )
				break;
			nTotalRead += nbytes;
			appendInput( buffer, nbytes );
			/* Data read. */
			if( nbytes < 2048 )
			{
				break;
			}
		}
	}

	if( pProtocol != NULL && nTotalRead > 0 )
	{
		pProtocol->onNewData();
	}

	return nTotalRead;
}

bool Connection::readInput( int nSec, int nUSec, int *pnSecBack, int *pnUSecBack )
{
	fd_set rfds;
	struct timeval tv, start, end;
	struct timezone tz;
	int retval;
	
	gettimeofday( &start, &tz );

	FD_ZERO(&rfds);
	FD_SET(nSocket, &rfds);

	tv.tv_sec = nSec;
	tv.tv_usec = nUSec;

	//printf("Starting at %d %d\n", nSec, nUSec );
	retval = select( nSocket+1, &rfds, NULL, NULL, &tv );

	if( retval == -1 )
	{
		// Oh my god!!! some kind of horrible problem!!!!
		throw ConnectionException( excodeBadReadError, "Bad Read error");
		return false;
	}
	else if( retval )
	{
		//printf("retval=%d, nSocket=%d,%d, sec=%d, usec=%d\n", retval, nSocket, FD_ISSET( nSocket, &rfds ), tv.tv_sec, tv.tv_usec );
		// None of them have data, but the connection is still active.
		if( readInput() == 0 )
		{
			this->close();
			throw ConnectionException( excodeConnectionClosed, "Connection closed");
		}
	}

	gettimeofday( &end, &tz );

	int st, ust;
	st = nSec - ( end.tv_sec - start.tv_sec );
	if( ( end.tv_usec - start.tv_usec ) > nUSec )
	{
		(st)--;
		ust = 1000000 - (end.tv_usec - start.tv_usec);
	}
	else
	{
		ust = nUSec - (end.tv_usec - start.tv_usec);
	}

	if( st < 0 )
	{
		st = ust = 0;
	}

	if( pnSecBack )
	{
		*pnSecBack = st;
		*pnUSecBack = ust;
	}

	//printf("New time:  %d %d\n", *pnSecBack, *pnUSecBack );

	return true;
}

void Connection::waitForInput( int nBytesIn, int nSec, int nUSec )
{
	int rlen = getInputAmnt();

	if( rlen >= nBytesIn )
		return;

	while( rlen < nBytesIn )
	{
		if( nSec == 0 && nUSec == 0 )
		{
			throw ConnectionException( excodeSocketTimeout, "Timed out while waiting for %d bytes.", nBytesIn );
		}
		readInput( nSec, nUSec, &nSec, &nUSec );
		rlen = getInputAmnt();
	}
}

bool Connection::clearOutput()
{
	return xOutputBuf.clearData();
}

bool Connection::clearInput()
{
	return xInputBuf.clearData();
}

#define min( a, b )   ((a<b)?(a):(b))

bool Connection::writeOutput()
{
	//int nBytes = TEMP_FAILURE_RETRY( write( nSocket, xOutputBuf.getData(), min( 2048, xOutputBuf.getLength() ) ) );
	int nBytes = TEMP_FAILURE_RETRY( write( nSocket, xOutputBuf.getData(), xOutputBuf.getLength() ) );
	if( nBytes < 0 )
	{
		perror("writeOutput");
		return true;
	}
	/*	
	if( nBytes < xOutputBuf.getLength() )
	{
		printf("Havn't written all the data (%d/%d/%d%%)\n", nBytes, xOutputBuf.getLength(), nBytes/(xOutputBuf.getLength()*100) );
	}
	else
	{
		printf("Wrote all pending data.\n");
	}
	*/
	xOutputBuf.usedData( nBytes );
	//clearOutput();

	return true;
}

bool Connection::hasOutput()
{
	if( xOutputBuf.getLength() == 0 )
	{
		return false;
	}
	else
	{
		return true;
	}
}

bool Connection::hasInput()
{
	if( xInputBuf.getLength() == 0 )
	{
		return false;
	}
	else
	{
		return true;
	}
}

bool Connection::usedInput( int nAmount )
{
	return xInputBuf.usedData( nAmount );
}

bool Connection::needDisconnect()
{
	return bDisconnectMe;
}

void Connection::disconnect()
{
	bDisconnectMe = true;
}

void Connection::setProtocol( class Protocol *pNewProtocol )
{
	pProtocol = pNewProtocol;
	pProtocol->setConnection( this );
}

int Connection::getInputAmnt()
{
	return xInputBuf.getLength();
}

int Connection::getOutputAmnt()
{
	return xOutputBuf.getLength();
}

class Protocol *Connection::getProtocol()
{
	return pProtocol;
}

void Connection::printInputDebug( const char *lpPrefix, FILE *fh, int nBytesMax )
{
	printDataDebug(
		(const unsigned char *)xInputBuf.getData(),
		xInputBuf.getLength(),
		"input",
		lpPrefix,
		fh,
		nBytesMax
		);
}

void Connection::printOutputDebug( const char *lpPrefix, FILE *fh, int nBytesMax )
{
	printDataDebug(
		(const unsigned char *)xOutputBuf.getData(),
		xOutputBuf.getLength(),
		"output",
		lpPrefix,
		fh,
		nBytesMax
		);
}

void Connection::printDataDebug( const unsigned char *pData, long nDataLen, const char *lpName, const char *lpPrefix, FILE *fh, int nBytesMax )
{
	if( nBytesMax > 0 )
	{
		nDataLen = (nBytesMax<nDataLen)?(nBytesMax):(nDataLen);
	}

	fprintf( fh, "%sDisplaying %ld bytes of %s.\n", lpPrefix, nDataLen, lpName );
	int j = 0;
	fprintf( fh, lpPrefix );
	for( int l = 0; l < 8*3+2*8+2; l++ ) fprintf( fh, (l!=8*3)?("-"):("+") ); fprintf( fh, "\n");
	for(;;)
	{
		fprintf( fh, lpPrefix );
		int kmax = 8;
		if( nDataLen-j < 8 ) kmax = nDataLen-j;
		for(int k = 0; k < 8; k++ )
		{
			if( k < kmax )
			{
				fprintf( fh, "%02X ", (int)((unsigned char)pData[j+k]) );
			}
			else
			{
				fprintf( fh, "-- ");
			}
		}
		printf("| ");
		for(int k = 0; k < kmax; k++ )
		{
			fprintf( fh, "%c ", (pData[j+k]>32 && pData[j+k]<=128)?(pData[j+k]):('.') );
		}
		fprintf( fh, "\n");
		j += kmax;
		if( j >= nDataLen ) break;
	}
	fprintf( fh, lpPrefix );
	for( int l = 0; l < 8*3+2*8+2; l++ ) fprintf( fh, (l!=8*3)?("-"):("+") ); fprintf( fh, "\n");
}