summaryrefslogtreecommitdiffstats
path: root/tdecore/network/kserversocket.cpp
blob: 0cfba8fa504b22b91499a993de316df0ca4e242d (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
/*
 *  Copyright (C) 2003 Thiago Macieira <thiago.macieira@kdemail.net>
 *
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included 
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <config.h>

#include <tqsocketnotifier.h>
#include <tqmutex.h>

#include "tdesocketaddress.h"
#include "kresolver.h"
#include "tdesocketbase.h"
#include "tdesocketdevice.h"
#include "kstreamsocket.h"
#include "kbufferedsocket.h"
#include "kserversocket.h"

using namespace KNetwork;

class KNetwork::TDEServerSocketPrivate
{
public:
  KResolver resolver;
  KResolverResults resolverResults;

  enum { None, LookupDone, Bound, Listening } state;
  int backlog;
  int timeout;

  bool bindWhenFound : 1, listenWhenBound : 1, useTDEBufferedSocket : 1;

  TDEServerSocketPrivate()
    : state(None), timeout(0), bindWhenFound(false), listenWhenBound(false),
      useTDEBufferedSocket(true)
  { 
    resolver.setFlags(KResolver::Passive);
    resolver.setFamily(KResolver::KnownFamily);
  }
};

TDEServerSocket::TDEServerSocket(TQObject* parent, const char *name)
  : TQObject(parent, name), d(new TDEServerSocketPrivate)
{
  TQObject::connect(&d->resolver, TQ_SIGNAL(finished(KResolverResults)), 
		   this, TQ_SLOT(lookupFinishedSlot()));
}

TDEServerSocket::TDEServerSocket(const TQString& service, TQObject* parent, const char *name)
  : TQObject(parent, name), d(new TDEServerSocketPrivate)
{
  TQObject::connect(&d->resolver, TQ_SIGNAL(finished(KResolverResults)), 
		   this, TQ_SLOT(lookupFinishedSlot()));
  d->resolver.setServiceName(service);
}

TDEServerSocket::TDEServerSocket(const TQString& node, const TQString& service,
			     TQObject* parent, const char* name)
  : TQObject(parent, name), d(new TDEServerSocketPrivate)
{
  TQObject::connect(&d->resolver, TQ_SIGNAL(finished(KResolverResults)), 
		   this, TQ_SLOT(lookupFinishedSlot()));
  setAddress(node, service);
}

TDEServerSocket::~TDEServerSocket()
{
  close();
  delete d;
}

bool TDEServerSocket::setSocketOptions(int opts)
{
  TQMutexLocker locker(mutex());
  TDESocketBase::setSocketOptions(opts); // call parent
  bool result = socketDevice()->setSocketOptions(opts); // and set the implementation
  copyError();
  return result;
}

KResolver& TDEServerSocket::resolver() const
{
  return d->resolver;
}

const KResolverResults& TDEServerSocket::resolverResults() const
{
  return d->resolverResults;
}

void TDEServerSocket::setResolutionEnabled(bool enable)
{
  if (enable)
    d->resolver.setFlags(d->resolver.flags() & ~KResolver::NoResolve);
  else
    d->resolver.setFlags(d->resolver.flags() | KResolver::NoResolve);
}

void TDEServerSocket::setFamily(int families)
{
  d->resolver.setFamily(families);
}

void TDEServerSocket::setAddress(const TQString& service)
{
  d->resolver.setNodeName(TQString::null);
  d->resolver.setServiceName(service);
  d->resolverResults.empty();
  if (d->state <= TDEServerSocketPrivate::LookupDone)
    d->state = TDEServerSocketPrivate::None;
}

void TDEServerSocket::setAddress(const TQString& node, const TQString& service)
{
  d->resolver.setNodeName(node);
  d->resolver.setServiceName(service);
  d->resolverResults.empty();
  if (d->state <= TDEServerSocketPrivate::LookupDone)
    d->state = TDEServerSocketPrivate::None;
}

void TDEServerSocket::setTimeout(int msec)
{
  d->timeout = msec;
}

bool TDEServerSocket::lookup()
{
  setError(NoError);
  if (d->resolver.isRunning() && !blocking())
    return true;		// already doing lookup

  if (d->state >= TDEServerSocketPrivate::LookupDone)
    return true;		// results are already available

  // make sure we have at least one parameter for lookup
  if (d->resolver.serviceName().isNull() &&
      !d->resolver.nodeName().isNull())
    d->resolver.setServiceName(TQString::fromLatin1(""));

  // don't restart the lookups if they had succeeded and
  // the input values weren't changed

  // reset results
  d->resolverResults = KResolverResults();

  if (d->resolver.status() <= 0)
    // if it's already running, there's no harm in calling again
    d->resolver.start();	// signal may emit

  if (blocking())
    {
      // we're in blocking mode operation
      // wait for the results

      d->resolver.wait();	// signal may be emitted again
      // lookupFinishedSlot has been called
    }

  return true;
}

bool TDEServerSocket::bind(const KResolverEntry& address)
{
  if (socketDevice()->bind(address))
    {
      setError(NoError);

      d->state = TDEServerSocketPrivate::Bound;
      emit bound(address);
      return true;
    }
  copyError();
  return false;
}

bool TDEServerSocket::bind(const TQString& node, const TQString& service)
{
  setAddress(node, service);
  return bind();
}

bool TDEServerSocket::bind(const TQString& service)
{
  setAddress(service);
  return bind();
}

bool TDEServerSocket::bind()
{
  if (d->state >= TDEServerSocketPrivate::Bound)
    return true;

  if (d->state < TDEServerSocketPrivate::LookupDone)
    {
      if (!blocking())
	{
	  d->bindWhenFound = true;
	  bool ok = lookup();	// will call doBind
	  if (d->state >= TDEServerSocketPrivate::Bound)
	    d->bindWhenFound = false;
	  return ok;
	}

      // not blocking
      if (!lookup())
	return false;
    }

  return doBind();
}

bool TDEServerSocket::listen(int backlog)
{
  // WARNING
  // this function has to be reentrant
  // due to the mechanisms used for binding, this function might
  // end up calling itself

  if (d->state == TDEServerSocketPrivate::Listening)
    return true;		// already listening

  d->backlog = backlog;

  if (d->state < TDEServerSocketPrivate::Bound)
    {
      // we must bind
      // note that we can end up calling ourselves here
      d->listenWhenBound = true;
      if (!bind())
	{
	  d->listenWhenBound = false;
	  return false;
	}

      if (d->state < TDEServerSocketPrivate::Bound)
	// asynchronous lookup in progress...
	// we can't be blocking here anyways
	return true;

      d->listenWhenBound = false;
    }

  if (d->state < TDEServerSocketPrivate::Listening)
    return doListen();

  return true;
}

void TDEServerSocket::close()
{
  socketDevice()->close();
  if (d->resolver.isRunning())
    d->resolver.cancel(false);
  d->state = TDEServerSocketPrivate::None;
  emit closed();
}

void TDEServerSocket::setAcceptBuffered(bool enable)
{
  d->useTDEBufferedSocket = enable;
}

KActiveSocketBase* TDEServerSocket::accept()
{
  if (d->state < TDEServerSocketPrivate::Listening)
    {
      if (!blocking())
	{
	  listen();
	  setError(WouldBlock);
	  return NULL;
	}
      else if (!listen())
	// error happened during listen
	return 0L;
    }

  // check to see if we're doing a timeout
  if (blocking() && d->timeout > 0)
    {
      bool timedout;
      if (!socketDevice()->poll(d->timeout, &timedout))
	{
	  copyError();
	  return NULL;
	}

      if (timedout)
	return 0L;
    }

  // we're listening here
  TDESocketDevice* accepted = socketDevice()->accept();
  if (!accepted)
    {
      // error happened during accept
      copyError();
      return NULL;
    }

  KStreamSocket* streamsocket;
  if (d->useTDEBufferedSocket)
    streamsocket = new TDEBufferedSocket();
  else
    streamsocket = new KStreamSocket();
  streamsocket->setSocketDevice(accepted);

  // FIXME!
  // when KStreamSocket can find out the state of the socket passed through
  // setSocketDevice, this will probably be unnecessary:
  streamsocket->setState(KStreamSocket::Connected);
  streamsocket->setFlags(IO_Sequential | IO_Raw | IO_ReadWrite | IO_Open | IO_Async);

  return streamsocket;
}

TDESocketAddress TDEServerSocket::localAddress() const
{
  return socketDevice()->localAddress();
}

TDESocketAddress TDEServerSocket::externalAddress() const
{
  return socketDevice()->externalAddress();
}

void TDEServerSocket::lookupFinishedSlot()
{
  if (d->resolver.isRunning() || d->state > TDEServerSocketPrivate::LookupDone)
    return;

  if (d->resolver.status() < 0)
    {
      setError(LookupFailure);
      emit gotError(LookupFailure);
      d->bindWhenFound = d->listenWhenBound = false;
      d->state = TDEServerSocketPrivate::None;
      return;
    }

  // lookup succeeded
  d->resolverResults = d->resolver.results();
  d->state = TDEServerSocketPrivate::LookupDone;
  emit hostFound();

  if (d->bindWhenFound)
    doBind();
}

void TDEServerSocket::copyError()
{
  setError(socketDevice()->error());
}

bool TDEServerSocket::doBind()
{
  d->bindWhenFound = false;
  // loop through the results and bind to the first that works

  KResolverResults::ConstIterator it = d->resolverResults.begin();
  for ( ; it != d->resolverResults.end(); ++it)
    if (bind(*it))
      {
	if (d->listenWhenBound)
	  return doListen();
	return true;
      }
    else
      socketDevice()->close();	// didn't work, try again

  // failed to bind
  emit gotError(error());
  return false;
}

bool TDEServerSocket::doListen()
{
  if (!socketDevice()->listen(d->backlog))
    {
      copyError();
      emit gotError(error());
      return false;		// failed to listen
    }
  
  // set up ready accept signal
  TQObject::connect(socketDevice()->readNotifier(), TQ_SIGNAL(activated(int)),
		   this, TQ_SIGNAL(readyAccept()));
  d->state = TDEServerSocketPrivate::Listening;
  return true;
}


#include "kserversocket.moc"