summaryrefslogtreecommitdiffstats
path: root/krfb/kinetd/kinetd.cpp
blob: 5e12ca08c363b451b3ab479dca8fd9f3fd0ce7be (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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658

/***************************************************************************
                                kinetd.cpp
                              --------------
    begin                : Mon Feb 11 2002
    copyright            : (C) 2002 by Tim Jansen
    email                : [email protected]
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kinetd.h"
#include "kinetd.moc"
#include "kinetinterface.h"
#include "kuser.h"
#include "uuid.h"
#include <tqregexp.h>
#include <kservicetype.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kconfig.h>
#include <knotifyclient.h>
#include <ksockaddr.h>
#include <kextsock.h>
#include <klocale.h>
#include <kglobal.h>

#include <unistd.h>
#include <fcntl.h>

PortListener::PortListener(KService::Ptr s,
			   KConfig *config,
			   KServiceRegistry *srvreg) :
	m_port(-1),
	m_serviceRegistered(false),
	m_socket(0),
	m_config(config),
	m_srvreg(srvreg),
	m_dnssdreg(0)
{
	m_dnssdRegistered = false;

	m_uuid = createUUID();
	loadConfig(s);

	if (m_valid && m_enabled)
		acquirePort();
}

bool PortListener::acquirePort() {
	if (m_socket) {
		if ((m_port >= m_portBase) &&
		    (m_port < (m_portBase + m_autoPortRange)))
			return true;
		else
			delete m_socket;
	}
	m_port = m_portBase;
	m_socket = new KServerSocket(m_port, false);
	while (!m_socket->bindAndListen()) {
		m_port++;
		if (m_port >= (m_portBase+m_autoPortRange)) {
			kdDebug() << "Kinetd cannot load service "<<m_serviceName
				  <<": unable to get port" << endl;
			m_port = -1;
			delete m_socket;
			m_socket = 0;
			return false;
		}
		delete m_socket;
		m_socket = new KServerSocket(m_port, false);
	}
	connect(m_socket, TQT_SIGNAL(accepted(KSocket*)),
		TQT_SLOT(accepted(KSocket*)));

	bool s = m_registerService;
	bool sd =m_dnssdRegister;
	setServiceRegistrationEnabledInternal(false);
	dnssdRegister(false);
	setServiceRegistrationEnabledInternal(s);
	dnssdRegister(sd);
	return true;
}

void PortListener::freePort() {
	m_port = -1;
	if (m_socket)
		delete m_socket;
	m_socket = 0;
	setServiceRegistrationEnabledInternal(m_registerService);
	dnssdRegister(false);
}

void PortListener::loadConfig(KService::Ptr s) {
	m_valid = true;
	m_autoPortRange = 0;
	m_enabled = true;
	m_argument = TQString();
	m_multiInstance = false;

	TQVariant vid, vport, vautoport, venabled, vargument, vmultiInstance, vurl,
	  vsattributes, vslifetime, vdname, vdtype, vddata;

	m_execPath = s->exec().utf8();
	vid = s->property("X-KDE-KINETD-id");
	vport = s->property("X-KDE-KINETD-port");
	vautoport = s->property("X-KDE-KINETD-autoPortRange");
	venabled = s->property("X-KDE-KINETD-enabled");
	vargument = s->property("X-KDE-KINETD-argument");
	vmultiInstance = s->property("X-KDE-KINETD-multiInstance");
	vurl = s->property("X-KDE-KINETD-serviceURL");
	vsattributes = s->property("X-KDE-KINETD-serviceAttributes");
	vslifetime = s->property("X-KDE-KINETD-serviceLifetime");
	vdname = s->property("X-KDE-KINETD-DNSSD-Name");
	vdtype = s->property("X-KDE-KINETD-DNSSD-Type");
	vddata = s->property("X-KDE-KINETD-DNSSD-Properties");

	if (!vid.isValid()) {
		kdDebug() << "Kinetd cannot load service "<<m_serviceName
			  <<": no id set" << endl;
		m_valid = false;
		return;
	}

	if (!vport.isValid()) {
		kdDebug() << "Kinetd cannot load service "<<m_serviceName
			  <<": invalid port" << endl;
		m_valid = false;
		return;
	}

	m_serviceName = vid.toString();
	m_serviceLifetime = vslifetime.toInt();
	if (m_serviceLifetime < 120) // never less than 120 s
		m_serviceLifetime = 120;
	m_portBase = vport.toInt();
	if (vautoport.isValid())
		m_autoPortRange = vautoport.toInt();
	if (venabled.isValid())
		m_enabled = venabled.toBool();
	if (vargument.isValid())
		m_argument = vargument.toString();
	if (vmultiInstance.isValid())
		m_multiInstance = vmultiInstance.toBool();
	if (vurl.isValid()) {
		m_serviceURL = vurl.toString();
		m_registerService = true;
	}
	else {
		m_serviceURL = TQString();
		m_registerService = false;
	}
	if (vsattributes.isValid()) {
		m_serviceAttributes = vsattributes.toString();
	}
	else
		m_serviceAttributes = "";
	if (vddata.isValid()) {
		TQStringList attrs = vddata.toStringList();
		for (TQStringList::iterator it=attrs.begin();
		it!=attrs.end();it++) {
		    TQString key = (*it).section('=',0,0);
		    TQString value =  processServiceTemplate((*it).section('=',1))[0];
		    if (!key.isEmpty()) m_dnssdData[key]=value;
		    }
	}
	if (vdname.isValid() && vdtype.isValid()) {
		m_dnssdName = processServiceTemplate(vdname.toString())[0];
		m_dnssdType = vdtype.toString();
		m_dnssdRegister = true;
		kdDebug() << "DNS-SD register is enabled\n";
	}
	else 
	        m_dnssdRegister = false;
		

	m_slpLifetimeEnd = TQDateTime::tqcurrentDateTime().addSecs(m_serviceLifetime);
	m_defaultPortBase = m_portBase;
	m_defaultAutoPortRange = m_autoPortRange;

	m_config->setGroup("ListenerConfig");
	m_enabled = m_config->readBoolEntry("enabled_" + m_serviceName,
					    m_enabled);
	m_portBase = m_config->readNumEntry("port_base_" + m_serviceName,
					    m_portBase);
	m_autoPortRange = m_config->readNumEntry("auto_port_range_" + m_serviceName,
						 m_autoPortRange);
	TQDateTime nullTime;
	m_expirationTime = m_config->readDateTimeEntry("enabled_expiration_"+m_serviceName,
						     &nullTime);
	if ((!m_expirationTime.isNull()) && (m_expirationTime < TQDateTime::tqcurrentDateTime()))
		m_enabled = false;
	m_registerService = m_config->readBoolEntry("enabled_srvreg_"+m_serviceName,
						     m_registerService);
}

void PortListener::accepted(KSocket *sock) {
	TQString host, port;
	KSocketAddress *ksa = KExtendedSocket::peerAddress(sock->socket());
	if ((!ksa) || !ksa->address()) {
		delete sock;
		return;
	}
	KExtendedSocket::resolve(ksa, host, port);
	KNotifyClient::event("IncomingConnection",
		i18n("Connection from %1").tqarg(host));
	delete ksa;

	if ((!m_enabled) ||
	   ((!m_multiInstance) && m_process.isRunning())) {
		delete sock;
		return;
	}

	// disable CLOEXEC flag, fixes #77412
	fcntl(sock->socket(), F_SETFD, fcntl(sock->socket(), F_GETFD) & ~FD_CLOEXEC);

	m_process.clearArguments();
	m_process << m_execPath << m_argument << TQString::number(sock->socket());
	if (!m_process.start(KProcess::DontCare)) {
		KNotifyClient::event("ProcessFailed",
			i18n("Call \"%1 %2 %3\" failed").tqarg(m_execPath)
				.tqarg(m_argument)
				.tqarg(sock->socket()));
	}

	delete sock;
}

bool PortListener::isValid() {
	return m_valid;
}

bool PortListener::isEnabled() {
	return m_enabled && m_valid;
}

int PortListener::port() {
	return m_port;
}

TQStringList PortListener::processServiceTemplate(const TQString &a) {
	TQStringList l;
	TQValueVector<KInetInterface> v = KInetInterface::getAllInterfaces(false);
	TQValueVector<KInetInterface>::Iterator it = v.begin();
	while (it != v.end()) {
		KInetSocketAddress *address = (*(it++)).address();
		if (!address)
			continue;
		TQString hostName = address->nodeName();
		KUser u;
		TQString x = a; // replace does not work in const TQString. Why??
		l.append(x.tqreplace(TQRegExp("%h"), KServiceRegistry::encodeAttributeValue(hostName))
			 .tqreplace(TQRegExp("%p"), TQString::number(m_port))
			 .tqreplace(TQRegExp("%u"), KServiceRegistry::encodeAttributeValue(u.loginName()))
			 .tqreplace(TQRegExp("%i"), KServiceRegistry::encodeAttributeValue(m_uuid))
			 .tqreplace(TQRegExp("%f"), KServiceRegistry::encodeAttributeValue(u.fullName())));
	}
	return l;
}

bool PortListener::setPort(int port, int autoPortRange) {
	if ((port == m_portBase) && (autoPortRange == m_autoPortRange))
		return (m_port != -1);

	m_config->setGroup("ListenerConfig");
	if (port > 0) {
		m_portBase = port;
		m_autoPortRange = autoPortRange;

		m_config->writeEntry("port_base_" + m_serviceName, m_portBase);
		m_config->writeEntry("auto_port_range_"+m_serviceName, m_autoPortRange);
	}
	else {
		m_portBase = m_defaultPortBase;
		m_autoPortRange = m_defaultAutoPortRange;

		m_config->deleteEntry("port_base_" + m_serviceName);
		m_config->deleteEntry("auto_port_range_"+m_serviceName);
	}

	m_config->sync();
	if (m_enabled)
		return acquirePort();
	else
		return false;
}

void PortListener::setEnabled(bool e) {
	setEnabledInternal(e, TQDateTime());
}

void PortListener::setEnabledInternal(bool e, const TQDateTime &ex) {
	m_config->setGroup("ListenerConfig");
	m_config->writeEntry("enabled_" + m_serviceName, e);
	m_config->writeEntry("enabled_expiration_"+m_serviceName, ex);
	m_config->sync();

	m_expirationTime = ex;

	if (e) {
		if (m_port < 0)
			acquirePort();
		m_enabled = m_port >= 0;

	}
	else {
		freePort();
		m_enabled = false;
	}
}

void PortListener::setEnabled(const TQDateTime &ex) {
	setEnabledInternal(true, ex);
}

bool PortListener::isServiceRegistrationEnabled() {
	return m_registerService;
}

void PortListener::setServiceRegistrationEnabled(bool e) {
	setServiceRegistrationEnabledInternal(e);
	dnssdRegister(e && m_enabled);
	m_config->setGroup("ListenerConfig");
	m_config->writeEntry("enable_srvreg_" + m_serviceName, e);
	m_config->sync();
}

void PortListener::setServiceRegistrationEnabledInternal(bool e) {
	m_registerService = e;

	if ((!m_srvreg) || m_serviceURL.isNull())
		return;
	if (m_serviceRegistered == (m_enabled && e))
		return;

        if (m_enabled && e) {
		m_registeredServiceURLs = processServiceTemplate(m_serviceURL);
		TQStringList attributes = processServiceTemplate(m_serviceAttributes);
		TQStringList::Iterator it = m_registeredServiceURLs.begin();
		TQStringList::Iterator it2 = attributes.begin();
		while ((it != m_registeredServiceURLs.end()) &&
		       (it2 != attributes.end())) {
			 if (!m_srvreg->registerService(
				     *(it++),
				     *(it2++),
				     m_serviceLifetime))
				 kdDebug(7021) << "Failure registering SLP service (no slpd running?)"<< endl;
		}
		m_serviceRegistered = true;
		// make lifetime 30s shorter, because the timeout is not precise
		m_slpLifetimeEnd = TQDateTime::tqcurrentDateTime().addSecs(m_serviceLifetime-30);
	} else {
		TQStringList::Iterator it = m_registeredServiceURLs.begin();
		while (it != m_registeredServiceURLs.end())
			m_srvreg->unregisterService(*(it++));
		m_serviceRegistered = false;
	}
}

void PortListener::dnssdRegister(bool e) {
	if (m_dnssdName.isNull() || m_dnssdType.isNull())
		return;
	if (m_dnssdRegistered ==  e)
		return;
	if (e) {
		m_dnssdRegistered=true;
		m_dnssdreg = new DNSSD::PublicService(m_dnssdName,m_dnssdType,m_port);
		m_dnssdreg->setTextData(m_dnssdData);
		m_dnssdreg->publishAsync();
	} else {
		m_dnssdRegistered=false;
		delete m_dnssdreg;
		m_dnssdreg=0;
	}
}

void PortListener::refreshRegistration() {
	if (m_serviceRegistered && (m_slpLifetimeEnd.addSecs(-90) < TQDateTime::tqcurrentDateTime())) {
		setServiceRegistrationEnabledInternal(false);
		setServiceRegistrationEnabledInternal(true);
	}
}

TQDateTime PortListener::expiration() {
	return m_expirationTime;
}

TQDateTime PortListener::serviceLifetimeEnd() {
	if (m_serviceRegistered)
		return m_slpLifetimeEnd;
	else
		return TQDateTime();
}

TQString PortListener::name() {
	return m_serviceName;
}

PortListener::~PortListener() {
	setServiceRegistrationEnabledInternal(false);
	delete m_socket;
}


KInetD::KInetD(TQCString &n) :
	KDEDModule(n)
{
	m_config = new KConfig("kinetdrc");
	m_srvreg = new KServiceRegistry();
	if (!m_srvreg->available()) {
		kdDebug(7021) << "SLP not available"<< endl;
		delete m_srvreg;
		m_srvreg = 0;
	}
	m_portListeners.setAutoDelete(true);
	connect(&m_expirationTimer, TQT_SIGNAL(timeout()), TQT_SLOT(setExpirationTimer()));
	connect(&m_portRetryTimer, TQT_SIGNAL(timeout()), TQT_SLOT(portRetryTimer()));
	connect(&m_reregistrationTimer, TQT_SIGNAL(timeout()), TQT_SLOT(reregistrationTimer()));
	loadServiceList();
}

void KInetD::loadServiceList()
{
	m_portListeners.clear();


	KService::List kinetdModules =
		KServiceType::offers("KInetDModule");
	for(KService::List::ConstIterator it = kinetdModules.begin();
		it != kinetdModules.end();
		it++) {
		KService::Ptr s = *it;
		PortListener *pl = new PortListener(s, m_config, m_srvreg);
		if (pl->isValid())
			m_portListeners.append(pl);
		else
			delete pl;
	}

	setExpirationTimer();
	setPortRetryTimer(true);
	setReregistrationTimer();
}

void KInetD::expirationTimer() {
	setExpirationTimer();
	setReregistrationTimer();
}

void KInetD::setExpirationTimer() {
	TQDateTime nextEx = getNextExpirationTime(); // disables expired portlistener!
	if (!nextEx.isNull())
		m_expirationTimer.start(TQDateTime::tqcurrentDateTime().secsTo(nextEx)*1000 + 30000,
			false);
	else
		m_expirationTimer.stop();
}

void KInetD::portRetryTimer() {
	setPortRetryTimer(true);
	setReregistrationTimer();
}

void KInetD::setReregistrationTimer() {
	TQDateTime d;
	PortListener *pl = m_portListeners.first();
	while (pl) {
		TQDateTime d2 = pl->serviceLifetimeEnd();
		if (!d2.isNull()) {
			if (d2 < TQDateTime::tqcurrentDateTime()) {
				m_reregistrationTimer.start(0, true);
				return;
			}
			else if (d.isNull() || (d2 < d))
				d = d2;
		}
		pl = m_portListeners.next();
	}

	if (!d.isNull()) {
		int s = TQDateTime::tqcurrentDateTime().secsTo(d);
		if (s < 30)
			s = 30; // max frequency 30s
		m_reregistrationTimer.start(s*1000, true);
	}
	else
		m_reregistrationTimer.stop();
}

void KInetD::reregistrationTimer() {
	PortListener *pl = m_portListeners.first();
	while (pl) {
		pl->refreshRegistration();
		pl = m_portListeners.next();
	}
	setReregistrationTimer();
}

void KInetD::setPortRetryTimer(bool retry) {
	int unmappedPorts = 0;

	PortListener *pl = m_portListeners.first();
	while (pl) {
		if (pl->isEnabled() && (pl->port() < 0))
			if (retry) {
				if (!pl->acquirePort())
					unmappedPorts++;
			}
			else if (pl->port() < 0)
				unmappedPorts++;
		pl = m_portListeners.next();
	}

	if (unmappedPorts > 0)
		m_portRetryTimer.start(30000, false);
	else
		m_portRetryTimer.stop();
}

PortListener *KInetD::getListenerByName(TQString name)
{
	PortListener *pl = m_portListeners.first();
	while (pl) {
		if (pl->name() == name)
			return pl;
		pl = m_portListeners.next();
	}
	return pl;
}

// gets next expiration timer, SIDEEFFECT: disables expired portlisteners while doing this
TQDateTime KInetD::getNextExpirationTime()
{
	PortListener *pl = m_portListeners.first();
	TQDateTime d;
	while (pl) {
		TQDateTime d2 = pl->expiration();
		if (!d2.isNull()) {
			if (d2 < TQDateTime::tqcurrentDateTime())
				pl->setEnabled(false);
			else if (d.isNull() || (d2 < d))
				d = d2;
		}
		pl = m_portListeners.next();
	}
	return d;
}

TQStringList KInetD::services()
{
	TQStringList list;
	PortListener *pl = m_portListeners.first();
	while (pl) {
		list.append(pl->name());
		pl = m_portListeners.next();
	}
	return list;
}

bool KInetD::isEnabled(TQString service)
{
	PortListener *pl = getListenerByName(service);
	if (!pl)
		return false;

	return pl->isEnabled();
}

int KInetD::port(TQString service)
{
	PortListener *pl = getListenerByName(service);
	if (!pl)
		return -1;

	return pl->port();
}

bool KInetD::setPort(TQString service, int port, int autoPortRange)
{
	PortListener *pl = getListenerByName(service);
	if (!pl)
		return false;

	bool s = pl->setPort(port, autoPortRange);
	setPortRetryTimer(false);
	setReregistrationTimer();
	return s;
}

bool KInetD::isInstalled(TQString service)
{
	PortListener *pl = getListenerByName(service);
	return (pl != 0);
}

void KInetD::setEnabled(TQString service, bool enable)
{
	PortListener *pl = getListenerByName(service);
	if (!pl)
		return;

	pl->setEnabled(enable);
	setExpirationTimer();
	setReregistrationTimer();
}

void KInetD::setEnabled(TQString service, TQDateTime expiration)
{
	PortListener *pl = getListenerByName(service);
	if (!pl)
		return;

	pl->setEnabled(expiration);
	setExpirationTimer();
	setReregistrationTimer();
}

void KInetD::setServiceRegistrationEnabled(TQString service, bool enable)
{
	PortListener *pl = getListenerByName(service);
	if (!pl)
		return;

	pl->setServiceRegistrationEnabled(enable);
	setReregistrationTimer();
}

bool KInetD::isServiceRegistrationEnabled(TQString service)
{
	PortListener *pl = getListenerByName(service);
	if (!pl)
		return false;

	return pl->isServiceRegistrationEnabled();
}

KInetD::~KInetD() {
	m_portListeners.clear();
	delete m_config;
	if (m_srvreg)
		delete m_srvreg;
}

extern "C" {
	KDE_EXPORT KDEDModule *create_kinetd(TQCString &name)
	{
        KGlobal::locale()->insertCatalogue("kinetd");
		return new KInetD(name);
	}
}