summaryrefslogtreecommitdiff
path: root/lib/psocksxx/sockstreambuf.cpp
blob: af3f3080f3b1ba77c08425558aaa9505a57245f4 (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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/*
*  psocksxx - A C++ wrapper for POSIX sockets
*  Copyright (C) 2013 Uditha Atukorala
*
*  This software library is free software; you can redistribute it and/or modify
*  it under the terms of the GNU Lesser General Public License as published by
*  the Free Software Foundation; either version 3 of the License, or
*  (at your option) any later version.
*
*  This software library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public License
*  along with this software library. If not, see <http://www.gnu.org/licenses/>.
*
*/

#include "sockstreambuf.h"

#include <fcntl.h>
#include <cstring>

// Mac OSX does not define MSG_NOSIGNAL
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif


namespace psocksxx {

	sockstreambuf::sockstreambuf() throw() :
			_socket( -1 ), _bufsize( SOCKSTREAMBUF_SIZE ),
			_putbacksize( SOCKSTREAMBUF_PUTBACK_SIZE ) {

		// initialise defaults
		init_defaults();

		// initialise internal buffers
		init_buffers();

	}


	sockstreambuf::sockstreambuf( socket_t socket ) throw() :
			_bufsize( SOCKSTREAMBUF_SIZE ),
			_putbacksize( SOCKSTREAMBUF_PUTBACK_SIZE ) {

		// update local copy of the socket data
		_socket = socket;

		// initialise defaults
		init_defaults();

		// initialise internal buffers
		init_buffers();

	}


	sockstreambuf::~sockstreambuf() {

		// close any open sockets
		close();

		// cleanup buffers
		cleanup_buffers();

		// cleanup timeout
		if ( _timeout ) {
			delete _timeout;
		}

	}


	void sockstreambuf::init_defaults() throw() {

		// timeout structure reference
		_timeout = NULL;

		// timed-out status
		_timed_out = false;

	}


	void sockstreambuf::open( socket_domain_t domain, socket_type_t type, socket_protocol_t proto ) throw( sockexception ) {

		// create a communication endpoint
		_socket = ::socket( domain, type, proto );

		// sanity check
		if ( _socket == -1 ) {
			throw sockexception();
		}

#ifdef SO_NOSIGPIPE
		// suppress SIGPIPE (Mac OSX)
		int optval = 1;
		if ( setsockopt( _socket, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof( optval ) ) != 0 ) {
			throw sockexception();
		}
#endif

	}


	void sockstreambuf::close() throw() {

		// sanity check
		if ( _socket > -1 ) {

			// sync
			sync();

			// close the socket
			::close( _socket );

			// update socket data
			_socket = -1;

		}

	}


	void sockstreambuf::connect( const sockaddr * dest_addr, unsigned int timeout ) throw( sockexception, socktimeoutexception ) {

		timeval t_val;
		timeval * t_ptr;

		// check timeout value
		if ( timeout > 0 ) {

			// setup timeval structure
			t_val.tv_sec  = timeout;
			t_val.tv_usec = 0;

			// update pointer
			t_ptr = &t_val;

		} else {

			// fall-back to class value
			t_ptr = _timeout;

		}

		// call overloaded connect()
		connect( dest_addr, t_ptr );

	}


	void sockstreambuf::connect( const sockaddr * dest_addr, timeval * timeout ) throw( sockexception, socktimeoutexception ) {

		// copy current flags
		int s_flags = fcntl( _socket, F_GETFL );

		// sanity check - affectively we ignore the fcntl() error
		if ( s_flags == -1 ) {
			s_flags = 0;
		}

		// setup timeout if needed
		if ( timeout ) {

			// make the socket non-blocking
			if ( fcntl( _socket, F_SETFL, ( s_flags | O_NONBLOCK ) ) == -1 ) {
				throw sockexception();
			}

		}

		// connect
		if ( ::connect( _socket, dest_addr->psockaddr(), dest_addr->size() ) != 0 ) {
			throw sockexception();
		}

		// check for timeout if set
		if ( timeout ) {

			if (! ready( timeout ) ) {

				// shutdown
				::shutdown( _socket, 2 );

				// throw a timeout exception
				if ( _timed_out ) {
					throw socktimeoutexception( timeout, "sockstreambuf::connect()" );
				}

			}

			// reset flags back to what they were
			fcntl( _socket, F_SETFL, s_flags );

		}

	}


	void sockstreambuf::bind( const sockaddr * bind_addr, bool reuse_addr ) throw( sockexception ) {

		// set socket options - SO_REUSEADDR
		if ( reuse_addr ) {

			int optval = 1;
			if ( setsockopt( _socket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof( optval ) ) != 0 ) {
				throw sockexception();
			}

		}

		// bind
		if ( ::bind( _socket, bind_addr->psockaddr(), bind_addr->size() ) != 0 ) {
			throw sockexception();
		}

	}


	void sockstreambuf::listen( int backlog ) throw( sockexception ) {

		if ( ::listen( _socket, backlog ) != 0 ) {
			throw sockexception();
		}

	}


	sockstreambuf::socket_t sockstreambuf::accept() throw( sockexception ) {

		socket_t peer_sock;

		if ( ( peer_sock = ::accept( _socket, 0, 0 ) ) < 0 ) {
			throw sockexception();
		}

		return peer_sock;

	}


	const sockstreambuf::socket_t & sockstreambuf::socket() const throw() {
		return _socket;
	}


	const timeval * sockstreambuf::timeout( time_t sec, suseconds_t usec ) throw() {

		_timeout = new timeval;

		_timeout->tv_sec  = sec;
		_timeout->tv_usec = usec;

		return _timeout;

	}


	void * sockstreambuf::clear_timeout() throw() {

		// sanity check
		if ( _timeout ) {

			// delete structure
			delete _timeout;

			// set a null pointer
			_timeout = NULL;

		}

		return _timeout;

	}


	bool sockstreambuf::timedout() const throw() {
		return _timed_out;
	}


	void sockstreambuf::init_buffers() throw() {

		// allocate output buffer space
		char * pbuf = new char[_bufsize];

		// allocate input buffer space
		char * gbuf = new char[_bufsize];

		// setup output buffer
		setp( pbuf, pbuf + ( _bufsize - 1 ) );

		// setup input buffer
		setg( gbuf, gbuf, gbuf );

	}


	void sockstreambuf::cleanup_buffers() throw() {

		// cleanup output buffer
		delete [] pbase();

		// cleanup input buffer
		delete [] eback();

	}


	int sockstreambuf::flush() throw( socktimeoutexception ) {

		int flush_size = pptr() - pbase();
		bool b_ready   = false;

		// sanity check
		if ( flush_size > 0 ) {

			try {
				b_ready = ready( _timeout, false, true );
			} catch ( sockexception &e ) {
				// couldn't select the socket
				return eof;
			}

			if ( b_ready ) {
				if ( ::send( _socket, pbase(), flush_size, MSG_NOSIGNAL ) == flush_size ) {
					pbump( -flush_size );
					return flush_size;
				}
			} else {

				// timed out - throw a timeout exception
				if ( _timed_out ) {
					throw socktimeoutexception( _timeout, "sockstreambuf::flush()" );
				}

			}

		}

		return eof;

	}


	int sockstreambuf::sync() throw() {

		try {

			// flush buffer
			if ( flush() != eof ) {
				return 0;
			}

		} catch ( socktimeoutexception &e ) {
			// communication timeout - suppress the exception
		}

		// sync failed
		return -1;

	}


	int sockstreambuf::overflow( int c ) throw( socktimeoutexception ) {

		// sanity check
		if ( c != eof ) {

			// insert the overflowed char into the buffer
			*pptr() = c;
			pbump( 1 );

		}

		// flush the buffer - could throw a timeout exception
		if ( flush() == eof ) {
			return eof;
		}

		return c;

	}


	int sockstreambuf::underflow() throw( socktimeoutexception ) {

		// sanity check - read position before end-of-buffer?
		if ( gptr() < egptr() ) {
			return traits_type::to_int_type( *gptr() );
		}


		char * read_buffer;
		size_t putback_size  = gptr() - eback();
		size_t readable_size = 0;

		bool b_ready = false;
		ssize_t read_size = 0;

		// sanitise putback size
		if ( putback_size > _putbacksize ) {
			putback_size = _putbacksize;
		}

		// update read buffer position
		read_buffer = eback() + putback_size;

		// calculate read buffer size
		readable_size = _bufsize - putback_size;

		// check for availability
		try {
			b_ready = ready( _timeout, true, false );
		} catch ( sockexception &e ) {
			// couldn't select the socket
			return eof;
		}

		// read from socket
		if ( b_ready ) {
			read_size = ::read( _socket, read_buffer, readable_size );
		} else {

			// timed out - throw a timeout exception
			if ( _timed_out ) {
				throw socktimeoutexception( _timeout, "sockstreambuf::overflow()" );
			}

		}

		// sanity check
		if ( read_size <= 0 ) {
			return eof;
		}

		// update pointers
		setg( eback(), read_buffer, read_buffer + read_size );

		// return next character
		return traits_type::to_int_type( *gptr() );

	}


	bool sockstreambuf::ready( timeval * timeout, bool chk_read, bool chk_write ) throw( sockexception ) {

		// sanity check
		if ( _socket < 0 ) {
			throw sockexception( "sockstreambuf::ready(): invalid socket" );
		}


		fd_set  fds;
		fd_set * read_fds  = 0;
		fd_set * write_fds = 0;

		// timespec structure
		timespec * t_spec = 0;


		// set the fd_set so we only check our socket
		memset( &fds, 0, sizeof( fds ) );
		FD_SET( _socket, &fds );

		// set the actions we want to check
		if ( chk_read ) {
			read_fds = &fds;
		}

		if ( chk_write ) {
			write_fds = &fds;
		}

		// reset timed-out status
		_timed_out = false;

		// create timespec structure from timeval structure
		if ( timeout ) {
			t_spec = new timespec;
			t_spec->tv_sec  = timeout->tv_sec;
			t_spec->tv_nsec = ( timeout->tv_usec * 1000 );
		}

		// select the socket
		int s_status = ::pselect( ( _socket + 1 ), read_fds, write_fds, 0, t_spec, 0 );

		// cleanup
		if ( t_spec != 0  ) {
			delete t_spec;
		}

		// check status
		switch ( s_status ) {
			case 0:
				// timed-out
				_timed_out = true;
				break;

			case -1:
				throw sockexception();
				break;

			default:
				break;
		}

		// sanity check
		if ( FD_ISSET( _socket, &fds ) ) {
			return true;
		}

		return false;

	}

} /* end of namespace psocksxx */