summaryrefslogtreecommitdiffstats
path: root/kopete/protocols/jabber/libiris/cutestuff/network/ndns.cpp
blob: d36b1fd09b3e952c8181ea6fdd2bbada9e3ce880 (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
/*
 * ndns.cpp - native DNS resolution
 * Copyright (C) 2001, 2002  Justin Karneges
 *
 * This 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 2.1 of the License, or (at your option) any later version.
 *
 * 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

//! \class NDns ndns.h
//! \brief Simple DNS resolution using native system calls
//!
//! This class is to be used when TQt's TQDns is not good enough.  Because TQDns
//! does not use threads, it cannot make a system call asyncronously.  Thus,
//! TQDns tries to imitate the behavior of each platform's native behavior, and
//! generally falls short.
//!
//! NDns uses a thread to make the system call happen in the background.  This
//! gives your program native DNS behavior, at the cost of requiring threads
//! to build.
//!
//! \code
//! #include "ndns.h"
//!
//! ...
//!
//! NDns dns;
//! dns.resolve("psi.affinix.com");
//!
//! // The class will emit the resultsReady() signal when the resolution
//! // is finished. You may then retrieve the results:
//!
//! uint ip_address = dns.result();
//!
//! // or if you want to get the IP address as a string:
//!
//! TQString ip_address = dns.resultString();
//! \endcode

#include "ndns.h"

#include <tqapplication.h>
#include <tqsocketdevice.h>
#include <tqptrlist.h>
#include <tqeventloop.h>

#ifdef Q_OS_UNIX
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#ifdef Q_OS_WIN32
#include <windows.h>
#endif

// CS_NAMESPACE_BEGIN

//! \if _hide_doc_
class NDnsWorkerEvent : public TQCustomEvent
{
public:
	enum Type { WorkerEvent = TQEvent::User + 100 };
	NDnsWorkerEvent(NDnsWorker *);

	NDnsWorker *worker;
};

class NDnsWorker : public TQThread
{
public:
	NDnsWorker(TQObject *, const TQCString &);

	bool success;
	bool cancelled;
	TQHostAddress addr;

protected:
	void run();

private:
	TQCString host;
	TQObject *par;
};
//! \endif

//----------------------------------------------------------------------------
// NDnsManager
//----------------------------------------------------------------------------
#ifndef HAVE_GETHOSTBYNAME_R
static TQMutex *workerMutex = 0;
static TQMutex *workerCancelled = 0;
#endif
static NDnsManager *man = 0;
bool winsock_init = false;

class NDnsManager::Item
{
public:
	NDns *ndns;
	NDnsWorker *worker;
};

class NDnsManager::Private
{
public:
	Item *find(const NDns *n)
	{
		TQPtrListIterator<Item> it(list);
		for(Item *i; (i = it.current()); ++it) {
			if(i->ndns == n)
				return i;
		}
		return 0;
	}

	Item *find(const NDnsWorker *w)
	{
		TQPtrListIterator<Item> it(list);
		for(Item *i; (i = it.current()); ++it) {
			if(i->worker == w)
				return i;
		}
		return 0;
	}

	TQPtrList<Item> list;
};

NDnsManager::NDnsManager()
{
#ifndef HAVE_GETHOSTBYNAME_R
	workerMutex = new TQMutex;
	workerCancelled = new TQMutex;
#endif

#ifdef Q_OS_WIN32
	if(!winsock_init) {
		winsock_init = true;
		TQSocketDevice *sd = new TQSocketDevice;
		delete sd;
	}
#endif

	d = new Private;
	d->list.setAutoDelete(true);

	connect(tqApp, TQT_SIGNAL(aboutToQuit()), TQT_SLOT(app_aboutToQuit()));
}

NDnsManager::~NDnsManager()
{
	delete d;

#ifndef HAVE_GETHOSTBYNAME_R
	delete workerMutex;
	workerMutex = 0;
	delete workerCancelled;
	workerCancelled = 0;
#endif
}

void NDnsManager::resolve(NDns *self, const TQString &name)
{
	Item *i = new Item;
	i->ndns = self;
	i->worker = new NDnsWorker(this, name.utf8());
	d->list.append(i);

	i->worker->start();
}

void NDnsManager::stop(NDns *self)
{
	Item *i = d->find(self);
	if(!i)
		return;
	// disassociate
	i->ndns = 0;

#ifndef HAVE_GETHOSTBYNAME_R
	// cancel
	workerCancelled->lock();
	i->worker->cancelled = true;
	workerCancelled->unlock();
#endif
}

bool NDnsManager::isBusy(const NDns *self) const
{
	Item *i = d->find(self);
	return (i ? true: false);
}

bool NDnsManager::event(TQEvent *e)
{
	if((int)e->type() == (int)NDnsWorkerEvent::WorkerEvent) {
		NDnsWorkerEvent *we = static_cast<NDnsWorkerEvent*>(e);
		we->worker->wait(); // ensure that the thread is terminated

		Item *i = d->find(we->worker);
		if(!i) {
			// should NOT happen
			return true;
		}
		TQHostAddress addr = i->worker->addr;
		NDns *ndns = i->ndns;
		delete i->worker;
		d->list.removeRef(i);

		// nuke manager if no longer needed (code that follows MUST BE SAFE!)
		tryDestroy();

		// requestor still around?
		if(ndns)
			ndns->finished(addr);
		return true;
	}
	return false;
}

void NDnsManager::tryDestroy()
{
	if(d->list.isEmpty()) {
		man = 0;
		delete this;
	}
}

void NDnsManager::app_aboutToQuit()
{
	while(man) {
		TQEventLoop *e = tqApp->eventLoop();
		e->processEvents(TQEventLoop::WaitForMore);
	}
}


//----------------------------------------------------------------------------
// NDns
//----------------------------------------------------------------------------

//! \fn void NDns::resultsReady()
//! This signal is emitted when the DNS resolution succeeds or fails.

//!
//! Constructs an NDns object with parent \a parent.
NDns::NDns(TQObject *parent)
:TQObject(parent)
{
}

//!
//! Destroys the object and frees allocated resources.
NDns::~NDns()
{
	stop();
}

//!
//! Resolves hostname \a host (eg. psi.affinix.com)
void NDns::resolve(const TQString &host)
{
	stop();
	if(!man)
		man = new NDnsManager;
	man->resolve(this, host);
}

//!
//! Cancels the lookup action.
//! \note This will not stop the underlying system call, which must finish before the next lookup will proceed.
void NDns::stop()
{
	if(man)
		man->stop(this);
}

//!
//! Returns the IP address as a 32-bit integer in host-byte-order.  This will be 0 if the lookup failed.
//! \sa resultsReady()
uint NDns::result() const
{
	return addr.ip4Addr();
}

//!
//! Returns the IP address as a string.  This will be an empty string if the lookup failed.
//! \sa resultsReady()
TQString NDns::resultString() const
{
	return addr.toString();
}

//!
//! Returns TRUE if busy resolving a hostname.
bool NDns::isBusy() const
{
	if(!man)
		return false;
	return man->isBusy(this);
}

void NDns::finished(const TQHostAddress &a)
{
	addr = a;
	resultsReady();
}

//----------------------------------------------------------------------------
// NDnsWorkerEvent
//----------------------------------------------------------------------------
NDnsWorkerEvent::NDnsWorkerEvent(NDnsWorker *p)
:TQCustomEvent(WorkerEvent)
{
	worker = p;
}

//----------------------------------------------------------------------------
// NDnsWorker
//----------------------------------------------------------------------------
NDnsWorker::NDnsWorker(TQObject *_par, const TQCString &_host)
{
	success = cancelled = false;
	par = _par;
	host = _host.copy(); // do we need this to avoid sharing across threads?
}

void NDnsWorker::run()
{
	hostent *h = 0;

#ifdef HAVE_GETHOSTBYNAME_R
	hostent buf;
	char char_buf[1024];
	int err;
	gethostbyname_r(host.data(), &buf, char_buf, sizeof(char_buf), &h, &err);
#else
	// lock for gethostbyname
	TQMutexLocker locker(workerMutex);

	// check for cancel
	workerCancelled->lock();
	bool cancel = cancelled;
	workerCancelled->unlock();

	if(!cancel)
		h = gethostbyname(host.data());
#endif

	if(!h) {
		success = false;
		TQApplication::postEvent(par, new NDnsWorkerEvent(this));
		return;
	}

	in_addr a = *((struct in_addr *)h->h_addr_list[0]);
	addr.setAddress(ntohl(a.s_addr));
	success = true;

	TQApplication::postEvent(par, new NDnsWorkerEvent(this));
}

// CS_NAMESPACE_END

#include "ndns.moc"