summaryrefslogtreecommitdiffstats
path: root/win/qeventloopex.cpp
blob: 57c53a229ddadda2748626034a85a22311265833 (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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/*
   This file is part of the KDE libraries
   Copyright (C) 2005 Andreas Roth <[email protected]>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include <windows.h>
#include <string.h>
#include <stdlib.h>
#include <io.h>
#include <stdio.h>
#include <tqeventloop.h>
#include <tqapplication.h>
#include "qeventloopex.h"


// Local defined structures and classes (needed only for QEventLoopEx implementation)
struct QSockNotEx
{
	TQSocketNotifier *obj;
	int fd;
	fd_set *queue;
};

class QSockNotTypeEx
{
public:
	QSockNotTypeEx();
	~QSockNotTypeEx();

	TQPtrList<QSockNotEx> *list;
	fd_set select_fds;
	fd_set enabled_fds;
	fd_set pending_fds;

};

class QEventLoopExPrivate
{
public:
	QEventLoopExPrivate()
	{
		reset();
	}

	void reset() {
		m_bStopped = false;
		m_hThread = NULL;
		m_sockUpdate = 0;
		m_evPendingListEmpty = NULL;
		sn_highest = 0;
	}
	bool m_bStopped;

	HANDLE m_hThread;
	SOCKET m_sockUpdate;

	// pending socket notifiers list
	TQPtrList<QSockNotEx> sn_pending_list;
	HANDLE m_evPendingListEmpty;
	CRITICAL_SECTION m_csPendingList;

	// highest fd for all socket notifiers
	int sn_highest;
	// 3 socket notifier types - read, write and exception
	QSockNotTypeEx sn_vec[3];
	CRITICAL_SECTION m_csVec;
};


/*****************************************************************************
 Socket notifier type
 *****************************************************************************/
QSockNotTypeEx::QSockNotTypeEx()
	: list( 0 )
{
	FD_ZERO( &select_fds );
	FD_ZERO( &enabled_fds );
	FD_ZERO( &pending_fds );
}

QSockNotTypeEx::~QSockNotTypeEx()
{
	delete list;
	list = 0;
}

QEventLoopEx::QEventLoopEx( TQObject *parent, const char *name) : 
	TQEventLoop(parent,name)
{
	DWORD dwThreadId;

#ifdef _DEBUG_EVENTLOOPEX
	tqDebug( "QEventLoopEx::QEventLoopEx enter");
#endif
	d = new QEventLoopExPrivate;

	InitializeCriticalSection(&d->m_csVec);
	InitializeCriticalSection(&d->m_csPendingList);

	d->m_evPendingListEmpty = CreateEvent(NULL,TRUE,FALSE,NULL);

	d->m_sockUpdate = socket(AF_INET,SOCK_DGRAM,0);
	d->m_hThread = CreateThread(NULL,0,ThreadProc,this,0,&dwThreadId);
#ifdef _DEBUG_EVENTLOOPEX
	tqDebug( "QEventLoopEx::QEventLoopEx leave");
#endif	
}

QEventLoopEx::~QEventLoopEx()
{
#ifdef _DEBUG_EVENTLOOPEX	
	tqDebug( "QEventLoopEx::~QEventLoopEx enter");
#endif
	d->m_bStopped = true;
	// Ensure that you thread gets unblocked and can terminate gracefully
	SetEvent(d->m_evPendingListEmpty);
	
	closesocket(d->m_sockUpdate);

	WaitForSingleObject(d->m_hThread,INFINITE);
	CloseHandle(d->m_hThread);

	CloseHandle(d->m_evPendingListEmpty);
	DeleteCriticalSection(&d->m_csVec);
	DeleteCriticalSection(&d->m_csPendingList);
	
	delete d;
	
#ifdef _DEBUG_EVENTLOOPEX
	tqDebug( "QEventLoopEx::~QEventLoopEx leave");
#endif
}



/*****************************************************************************
 QEventLoopEx implementations for Windows (for synchronous socket calls)
 *****************************************************************************/
void QEventLoopEx::registerSocketNotifier( TQSocketNotifier *notifier )
{
	int sockfd = notifier->socket();
	int type = notifier->type();
	u_long	n;
	DWORD dw;
#ifdef _DEBUG_EVENTLOOPEX
	tqDebug( "TQSocketNotifier::registerSocketNotifier %p", notifier );
#endif
	if(ioctlsocket(sockfd,FIONREAD,&n) == SOCKET_ERROR)
	{
#ifdef _DEBUG_EVENTLOOPEX
		tqDebug( "TQSocketNotifier::registerSocketNotifier %p not a socket", notifier );
#endif
		dw = WSAGetLastError();
		TQEventLoop::registerSocketNotifier(notifier);
		return;
	}

	if ( sockfd < 0 || type < 0 || type > 2 || notifier == 0 ) 
	{
#if defined(QT_CHECK_RANGE)
		tqWarning( "TQSocketNotifier: Internal error" );
#endif
		return;
	}

	EnterCriticalSection(&d->m_csVec);

	TQPtrList<QSockNotEx>  *list = d->sn_vec[type].list;
	fd_set *fds  = &d->sn_vec[type].enabled_fds;
	QSockNotEx *sn;

	if ( ! list ) {
		// create new list, the QSockNotType destructor will delete it for us
		list = new TQPtrList<QSockNotEx>;
		TQ_CHECK_PTR( list );
		list->setAutoDelete( TRUE );
		d->sn_vec[type].list = list;
	}

	sn = new QSockNotEx;
	TQ_CHECK_PTR( sn );
	sn->obj = notifier;
	sn->fd = sockfd;
	sn->queue = &d->sn_vec[type].pending_fds;

	if ( list->isEmpty() ) {
		list->insert( 0, sn );
	} else { // sort list by fd, decreasing
		QSockNotEx *p = list->first();
		while ( p && p->fd > sockfd )
			p = list->next();
		if ( p )
			list->insert( list->at(), sn );
		else
			list->append( sn );
	}

	FD_SET( sockfd, fds );

	d->sn_highest = QMAX( d->sn_highest, sockfd );
	LeaveCriticalSection(&d->m_csVec);
	
#ifdef _DEBUG_EVENTLOOPEX
	tqDebug( "TQSocketNotifier::signal update socket");
#endif	
	closesocket(d->m_sockUpdate);
}

void QEventLoopEx::unregisterSocketNotifier( TQSocketNotifier *notifier )
{
	int sockfd = notifier->socket();
	int type = notifier->type();
	if ( sockfd < 0 || type < 0 || type > 2 || notifier == 0 ) {
#if defined(QT_CHECK_RANGE)
		tqWarning( "TQSocketNotifier: Internal error" );
#endif
		return;
	}
#ifdef _DEBUG_EVENTLOOPEX	
	tqDebug( "TQSocketNotifier::unregisterSocketNotifier %p", notifier );
#endif

	EnterCriticalSection(&d->m_csVec);
	TQPtrList<QSockNotEx> *list = d->sn_vec[type].list;
	fd_set *fds  =  &d->sn_vec[type].enabled_fds;
	QSockNotEx *sn;
	if ( ! list ) {
		LeaveCriticalSection(&d->m_csVec);
		TQEventLoop::unregisterSocketNotifier(notifier);
		return;
	}
	sn = list->first();
	while ( sn && !(sn->obj == notifier && sn->fd == sockfd) )
	sn = list->next();
	if ( !sn ) {// not found
		LeaveCriticalSection(&d->m_csVec);
		TQEventLoop::unregisterSocketNotifier(notifier);
		return;
	}

	FD_CLR( sockfd, fds ); // clear fd bit
	FD_CLR( sockfd, sn->queue );

	EnterCriticalSection(&d->m_csPendingList);
	d->sn_pending_list.removeRef( sn );		// remove from activation list
	bool bNowEmpty = (d->sn_pending_list.count() == 0);
	LeaveCriticalSection(&d->m_csPendingList);
	if(bNowEmpty)
		SetEvent(d->m_evPendingListEmpty);
	list->remove(); // remove notifier found above

	if ( d->sn_highest == sockfd ) {// find highest fd
		d->sn_highest = -1;
		for ( int i=0; i<3; i++ ) {
			if ( d->sn_vec[i].list && ! d->sn_vec[i].list->isEmpty() )
			d->sn_highest = QMAX( d->sn_highest,  // list is fd-sorted
				d->sn_vec[i].list->getFirst()->fd );
		}
	}
	LeaveCriticalSection(&d->m_csVec);
#ifdef _DEBUG_EVENTLOOPEX	
	tqDebug( "TQSocketNotifier::signal update socket");
#endif
	closesocket(d->m_sockUpdate);
}

bool QEventLoopEx::processEvents( ProcessEventsFlags flags )
{
	if(!TQEventLoop::processEvents(flags))
		return false;

	activateSocketNotifiers();
	return true;
}

void QEventLoopEx::setSocketNotifierPending( TQSocketNotifier *notifier )
{
	int sockfd = notifier->socket();
	int type = notifier->type();
	if ( sockfd < 0 || type < 0 || type > 2 || notifier == 0 ) 
	{
#if defined(QT_CHECK_RANGE)
		tqWarning( "TQSocketNotifier: Internal error" );
#endif
		return;
	}
#ifdef _DEBUG_EVENTLOOPEX	
	tqDebug( "TQSocketNotifier::setSocketNotifierPending %p",notifier );
#endif
	EnterCriticalSection(&d->m_csVec);

	TQPtrList<QSockNotEx> *list = d->sn_vec[type].list;
	QSockNotEx *sn;
	if ( ! list )
	{
#ifdef _DEBUG_EVENTLOOPEX	
		tqDebug( "TQSocketNotifier::setSocketNotifierPending %p: no list",notifier );
#endif
		LeaveCriticalSection(&d->m_csVec);
		return;
	}
	sn = list->first();
	while ( sn && !(sn->obj == notifier && sn->fd == sockfd) )
	sn = list->next();
	if ( ! sn ) { // not found
#ifdef _DEBUG_EVENTLOOPEX	
		tqDebug( "TQSocketNotifier::setSocketNotifierPending %p: not found",notifier );
#endif
		LeaveCriticalSection(&d->m_csVec);
		return;
	}

	// We choose a random activation order to be more fair under high load.
	// If a constant order is used and a peer early in the list can
	// saturate the IO, it might grab our attention completely.
	// Also, if we're using a straight list, the callback routines may
	// delete other entries from the list before those other entries are
	// processed.
	EnterCriticalSection(&d->m_csPendingList);
	if ( ! FD_ISSET( sn->fd, sn->queue ) ) {
		d->sn_pending_list.insert( (rand() & 0xff) %
				   (d->sn_pending_list.count()+1), sn );
		FD_SET( sn->fd, sn->queue );
	}
	LeaveCriticalSection(&d->m_csPendingList);
	LeaveCriticalSection(&d->m_csVec);
}

int QEventLoopEx::activateSocketNotifiers()
{
	if ( d->sn_pending_list.isEmpty() )
		return 0; // nothing to do

	int n_act = 0;
	TQEvent event( TQEvent::SockAct );

	EnterCriticalSection(&d->m_csVec);			// Avoid deaklock
	EnterCriticalSection(&d->m_csPendingList);
	TQPtrListIterator<QSockNotEx> it( d->sn_pending_list );
	QSockNotEx *sn;
	while ( (sn=it.current()) ) {
		++it;
		d->sn_pending_list.removeRef( sn );
		if ( FD_ISSET(sn->fd, sn->queue) ) {
			FD_CLR( sn->fd, sn->queue );
#ifdef _DEBUG_EVENTLOOPEX	
			tqDebug("QEventLoopEx:activateSocketNotifiers %p to object %p",sn, sn->obj);
#endif
			TQApplication::sendEvent( sn->obj, &event );
			n_act++;
		}
	}

	LeaveCriticalSection(&d->m_csPendingList);
	LeaveCriticalSection(&d->m_csVec);			// Avoid deaklock

#ifdef _DEBUG_EVENTLOOPEX	
	tqDebug( "TQSocketNotifier::activateSocketNotifiers set m_evPendingListEmpty");
#endif
	SetEvent(d->m_evPendingListEmpty);

	return n_act;
}

DWORD QEventLoopEx::ThreadProc(void * p)
{
	QEventLoopEx * pEventLoopEx = static_cast<QEventLoopEx *>(p);
	pEventLoopEx->run();
	return 0;
}

void QEventLoopEx::run()
{
	do 
	{
		EnterCriticalSection(&d->m_csVec);
		// return the highest fd we can wait for input on
		if ( d->sn_highest >= 0 ) { // has socket notifier(s)
			if ( d->sn_vec[0].list && ! d->sn_vec[0].list->isEmpty() )
				d->sn_vec[0].select_fds = d->sn_vec[0].enabled_fds;
			else
				FD_ZERO( &d->sn_vec[0].select_fds );

			if ( d->sn_vec[1].list && ! d->sn_vec[1].list->isEmpty() )
				d->sn_vec[1].select_fds = d->sn_vec[1].enabled_fds;
			else
				FD_ZERO( &d->sn_vec[1].select_fds );

			if ( d->sn_vec[2].list && ! d->sn_vec[2].list->isEmpty() )
				d->sn_vec[2].select_fds = d->sn_vec[2].enabled_fds;
			else
				FD_ZERO( &d->sn_vec[2].select_fds );
		} 
		else {
			FD_ZERO( &d->sn_vec[0].select_fds );
			FD_ZERO( &d->sn_vec[1].select_fds );
			FD_ZERO( &d->sn_vec[2].select_fds );
		}

		FD_SET(d->m_sockUpdate,&d->sn_vec[0].select_fds);
		d->sn_highest = QMAX(d->sn_highest,(int)d->m_sockUpdate);
//		FD_SET(m_sockUpdate,&sn_vec[1].select_fds);
//		FD_SET(m_sockUpdate,&sn_vec[2].select_fds);

		LeaveCriticalSection(&d->m_csVec);

#ifdef _DEBUG_EVENTLOOPEX	
		tqDebug("QEventLoopEx: select(%d,%d, %d, %d)",sn_highest,sn_vec[0].select_fds.fd_count,sn_vec[1].select_fds.fd_count,sn_vec[2].select_fds.fd_count);
#endif
		int nsel = select( d->sn_highest,
				&d->sn_vec[0].select_fds,
				&d->sn_vec[1].select_fds,
				&d->sn_vec[2].select_fds,
				NULL );
#ifdef _DEBUG_EVENTLOOPEX	
		tqDebug("QEventLoopEx: select returned %d",nsel);
#endif
		if (nsel == SOCKET_ERROR) {
			if (WSAGetLastError() == WSAENOTSOCK) {

				
				// it seems a socket notifier has a bad fd... find out
				// which one it is and disable it
				fd_set fdset;
				struct timeval zerotm;
				int ret;
				zerotm.tv_sec = zerotm.tv_usec = 0l;

				FD_ZERO(&fdset);
				FD_SET(d->m_sockUpdate, &fdset);

				ret = select(d->m_sockUpdate + 1, &fdset, 0, 0, &zerotm);
				if(ret == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK)
				{
					// Update the waiting sockets
					d->m_sockUpdate = socket(AF_INET,SOCK_DGRAM,0);
				}
				else
				{
					EnterCriticalSection(&d->m_csVec);
					
					for (int type = 0; type < 3; ++type)
					{
						TQPtrList<QSockNotEx> *list = d->sn_vec[type].list;
						if (!list) 
							continue;

						QSockNotEx *sn = list->first();
						while (sn) {
							FD_ZERO(&fdset);
							FD_SET(sn->fd, &fdset);

							
							do {
								switch (type) {
								case 0: // read
									ret = select(sn->fd + 1, &fdset, 0, 0, &zerotm);
									break;
								case 1: // write
									ret = select(sn->fd + 1, 0, &fdset, 0, &zerotm);
									break;
								case 2: // except
									ret = select(sn->fd + 1, 0, 0, &fdset, &zerotm);
									break;
								}
							} while (ret == SOCKET_ERROR && WSAGetLastError() != WSAENOTSOCK);

							if (ret == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK)
							{
								// disable the invalid socket notifier
								static const char *t[] = { "Read", "Write", "Exception" };
								tqWarning("TQSocketNotifier: invalid socket %d and type '%s', disabling...",
									sn->fd, t[type]);
								sn->obj->setEnabled(FALSE);
							}

							sn = list->next();
						}
					}
					LeaveCriticalSection(&d->m_csVec);
				}
			} else {
				// EINVAL... shouldn't happen, so let's complain to stderr
				// and hope someone sends us a bug report
				DWORD dw = WSAGetLastError();
				tqWarning("QEventLoopEx: select failed with error %i\n",dw);
			}
		}
		else
		{
			EnterCriticalSection(&d->m_csVec);

			if(FD_ISSET( d->m_sockUpdate, &d->sn_vec[0].select_fds))
			{
				d->m_sockUpdate = socket(AF_INET,SOCK_DGRAM,0);
#ifdef _DEBUG_EVENTLOOPEX	
				tqDebug("QEventLoopEx: update socket signaled -> recreate it %i",d->m_sockUpdate);
#endif
			}

			// if select says data is ready on any socket, then set the socket notifier
			// to pending
			int i;
			for ( i=0; i<3; i++ ) 
			{
				if ( ! d->sn_vec[i].list )
					continue;

				TQPtrList<QSockNotEx> *list = d->sn_vec[i].list;
				QSockNotEx *sn = list->first();
				while ( sn ) {
					if ( FD_ISSET( sn->fd, &d->sn_vec[i].select_fds ) )
					{
						TQEvent event( TQEvent::SockAct );
						setSocketNotifierPending( sn->obj );
					}
					sn = list->next();
				}
			}
			LeaveCriticalSection(&d->m_csVec);
		}
		if(!d->sn_pending_list.isEmpty() )
		{
			TQApplication::eventLoop()->wakeUp();
#ifdef _DEBUG_EVENTLOOPEX	
			tqDebug("QEventLoopEx: wake up main event loop and wait for pending list empty");
#endif
			WaitForSingleObject(d->m_evPendingListEmpty,INFINITE);
#ifdef _DEBUG_EVENTLOOPEX	
			tqDebug("QEventLoopEx: pending list now empty again");
#endif
			ResetEvent(d->m_evPendingListEmpty);
		}
	}
	while(!d->m_bStopped);
}

#include "qeventloopex.moc"