stream.cpp 33.7 KB
Newer Older
1 2
/*
 * stream.cpp - handles a client stream
3
 * Copyright (C) 2003  Justin Karneges
4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 19 20 21 22
 *
 */

/*
  Notes:
23
	- For Non-SASL auth (JEP-0078), username and resource fields are required.
24 25

  TODO:
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
	- sasl needParams is totally jacked?  PLAIN requires authzid, etc
	- server error handling
	  - reply with protocol errors if the client send something wrong
	  - don't necessarily disconnect on protocol error.  prepare for more.
	- server function
	  - deal with stream 'to' attribute dynamically
	  - flag tls/sasl/binding support dynamically (have the ability to specify extra stream:features)
	  - inform the caller about the user authentication information
	  - sasl security settings
	  - resource-binding interaction
	  - timeouts
	- allow exchanges of non-standard stanzas
	- send </stream:stream> even if we close prematurely?
	- ensure ClientStream and child classes are fully deletable after signals
	- xml:lang in root (<stream>) element
	- sasl external
	- sasl anonymous
43 44
*/

45
#include "xmpp.h"
46

47 48 49 50
#include <qtextstream.h>
#include <qpointer.h>
#include <qtimer.h>
#include <QList>
51
#include <QByteArray>
52 53 54
#include <stdlib.h>
#include "bytestream.h"
#include <QtCrypto>
55
#include <QUrl>
56
#include "simplesasl.h"
57 58
#include "securestream.h"
#include "protocol.h"
59

60 61 62 63
#ifndef NO_IRISNET
#include "irisnetglobal_p.h"
#endif

64
#ifdef XMPP_TEST
65
#include "td.h"
66 67 68 69 70 71 72
#endif

//#define XMPP_DEBUG

using namespace XMPP;

static Debug *debug_ptr = 0;
73
void XMPP::setDebug(Debug *p)
74 75 76 77 78 79
{
	debug_ptr = p;
}

static QByteArray randomArray(int size)
{
80 81
	QByteArray a;
	a.resize(size);
82 83 84 85 86 87 88 89
	for(int n = 0; n < size; ++n)
		a[n] = (char)(256.0*rand()/(RAND_MAX+1.0));
	return a;
}

static QString genId()
{
	// need SHA1 here
90 91
	//if(!QCA::isSupported(QCA::CAP_SHA1))
	//	QCA::insertProvider(createProviderHash());
92

93
	return QCA::Hash("sha1").hashToString(randomArray(128));
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
}

//----------------------------------------------------------------------------
// Stream
//----------------------------------------------------------------------------
static XmlProtocol *foo = 0;
Stream::Stream(QObject *parent)
:QObject(parent)
{
}

Stream::~Stream()
{
}

Stanza Stream::createStanza(Stanza::Kind k, const Jid &to, const QString &type, const QString &id)
{
	return Stanza(this, k, to, type, id);
}

Stanza Stream::createStanza(const QDomElement &e)
{
	return Stanza(this, e);
}

QString Stream::xmlToString(const QDomElement &e, bool clip)
{
	if(!foo)
122
	{
123
		foo = new CoreProtocol;
124 125 126 127
#ifndef NO_IRISNET
		irisNetAddPostRoutine(cleanup);
#endif
	}
128 129 130
	return foo->elementToString(e, clip);
}

131 132 133 134 135 136
void Stream::cleanup()
{
	delete foo;
	foo = 0;
}

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
//----------------------------------------------------------------------------
// ClientStream
//----------------------------------------------------------------------------
enum {
	Idle,
	Connecting,
	WaitVersion,
	WaitTLS,
	NeedParams,
	Active,
	Closing
};

enum {
	Client,
	Server
};

class ClientStream::Private
{
public:
	Private()
	{
		conn = 0;
		bs = 0;
		ss = 0;
		tlsHandler = 0;
		tls = 0;
165
		sasl = 0;
166 167

		oldOnly = false;
168
		allowPlain = NoAllowPlain;
169 170 171 172 173
		mutualAuth = false;
		haveLocalAddr = false;
		minimumSSF = 0;
		maximumSSF = 0;
		doBinding = true;
174
		doCompress = false;
175
		lang = "";
176

177 178
		in_rrsig = false;

179 180 181 182 183 184 185 186
		reset();
	}

	void reset()
	{
		state = Idle;
		notify = 0;
		newStanzas = false;
187
		sasl_ssf = 0;
188 189 190 191 192 193 194
		tls_warned = false;
		using_tls = false;
	}

	Jid jid;
	QString server;
	bool oldOnly;
195 196
	bool mutualAuth;
	AllowPlainType allowPlain;
197 198
	bool haveLocalAddr;
	QHostAddress localAddr;
199 200
	quint16 localPort;
	QString connectHost;
201
	int minimumSSF, maximumSSF;
202
	QString sasl_mech;
203
	QMap<QString,QString> mechProviders; // mech to provider map
204 205
	bool doBinding;

206 207
	bool in_rrsig;

208 209 210 211
	Connector *conn;
	ByteStream *bs;
	TLSHandler *tlsHandler;
	QCA::TLS *tls;
212
	QCA::SASL *sasl;
213 214 215
	SecureStream *ss;
	CoreProtocol client;
	CoreProtocol srv;
216
	QString lang;
217 218 219 220 221 222 223

	QString defRealm;

	int mode;
	int state;
	int notify;
	bool newStanzas;
224
	int sasl_ssf;
225 226
	bool tls_warned, using_tls;
	bool doAuth;
227
	bool doCompress;
228

229
	QStringList sasl_mechlist;
230 231 232 233 234

	int errCond;
	QString errText;
	QDomElement errAppSpec;

235
	QList<Stanza*> in;
236

237
	QTimer timeout_timer;
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
	QTimer noopTimer;
	int noop_time;
};

ClientStream::ClientStream(Connector *conn, TLSHandler *tlsHandler, QObject *parent)
:Stream(parent)
{
	d = new Private;
	d->mode = Client;
	d->conn = conn;
	connect(d->conn, SIGNAL(connected()), SLOT(cr_connected()));
	connect(d->conn, SIGNAL(error()), SLOT(cr_error()));

	d->noop_time = 0;
	connect(&d->noopTimer, SIGNAL(timeout()), SLOT(doNoop()));

	d->tlsHandler = tlsHandler;
}

ClientStream::ClientStream(const QString &host, const QString &defRealm, ByteStream *bs, QCA::TLS *tls, QObject *parent)
:Stream(parent)
{
	d = new Private;
	d->mode = Server;
	d->bs = bs;
	connect(d->bs, SIGNAL(connectionClosed()), SLOT(bs_connectionClosed()));
	connect(d->bs, SIGNAL(delayedCloseFinished()), SLOT(bs_delayedCloseFinished()));
	connect(d->bs, SIGNAL(error(int)), SLOT(bs_error(int)));

267
	QByteArray spare = d->bs->readAll();
268 269 270

	d->ss = new SecureStream(d->bs);
	connect(d->ss, SIGNAL(readyRead()), SLOT(ss_readyRead()));
271
	connect(d->ss, SIGNAL(bytesWritten(qint64)), SLOT(ss_bytesWritten(qint64)));
272 273 274 275 276 277 278 279 280 281 282 283 284 285
	connect(d->ss, SIGNAL(tlsHandshaken()), SLOT(ss_tlsHandshaken()));
	connect(d->ss, SIGNAL(tlsClosed()), SLOT(ss_tlsClosed()));
	connect(d->ss, SIGNAL(error(int)), SLOT(ss_error(int)));

	d->server = host;
	d->defRealm = defRealm;

	d->tls = tls;

	d->srv.startClientIn(genId());
	//d->srv.startServerIn(genId());
	//d->state = Connecting;
	//d->jid = Jid();
	//d->server = QString();
286 287

	connect(&(d->timeout_timer), SIGNAL(timeout()), SLOT(sm_timeout()));
288 289 290 291 292 293
}

ClientStream::~ClientStream()
{
	reset();
	delete d;
294
	//fprintf(stderr, "\tClientStream::~ClientStream\n");
295 296 297 298 299 300 301 302 303 304 305 306
}

void ClientStream::reset(bool all)
{
	d->reset();
	d->noopTimer.stop();

	// delete securestream
	delete d->ss;
	d->ss = 0;

	// reset sasl
307 308
	delete d->sasl;
	d->sasl = 0;
309 310 311 312

	// client
	if(d->mode == Client) {
		// reset tls
313 314 315
		// FIXME: Temporarily disabled
		//if(d->tlsHandler)
		//	d->tlsHandler->reset();
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339

		// reset connector
		if(d->bs) {
			d->bs->close();
			d->bs = 0;
		}
		d->conn->done();

		// reset state machine
		d->client.reset();
	}
	// server
	else {
		if(d->tls)
			d->tls->reset();

		if(d->bs) {
			d->bs->close();
			d->bs = 0;
		}

		d->srv.reset();
	}

340 341 342 343 344
	if(all) {
		while (!d->in.isEmpty()) {
			delete d->in.takeFirst();
		}
	}
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
}

Jid ClientStream::jid() const
{
	return d->jid;
}

void ClientStream::connectToServer(const Jid &jid, bool auth)
{
	reset(true);
	d->state = Connecting;
	d->jid = jid;
	d->doAuth = auth;
	d->server = d->jid.domain();

	d->conn->connectToServer(d->server);
}

void ClientStream::continueAfterWarning()
{
	if(d->state == WaitVersion) {
		// if we don't have TLS yet, then we're never going to get it
		if(!d->tls_warned && !d->using_tls) {
			d->tls_warned = true;
			d->state = WaitTLS;
			warning(WarnNoTLS);
			return;
		}
		d->state = Connecting;
		processNext();
	}
	else if(d->state == WaitTLS) {
		d->state = Connecting;
		processNext();
	}
}

void ClientStream::accept()
{
	d->srv.host = d->server;
	processNext();
}

bool ClientStream::isActive() const
{
	return (d->state != Idle) ? true: false;
}

bool ClientStream::isAuthenticated() const
{
	return (d->state == Active) ? true: false;
}

void ClientStream::setUsername(const QString &s)
{
400 401
	if(d->sasl)
		d->sasl->setUsername(s);
402 403 404 405 406 407 408 409
}

void ClientStream::setPassword(const QString &s)
{
	if(d->client.old) {
		d->client.setPassword(s);
	}
	else {
410
		if(d->sasl)
411
			d->sasl->setPassword(QCA::SecureArray(s.toUtf8()));
412 413 414 415 416
	}
}

void ClientStream::setRealm(const QString &s)
{
417 418
	if(d->sasl)
		d->sasl->setRealm(s);
419 420
}

421 422 423 424 425 426
void ClientStream::setAuthzid(const QString &s)
{
	if(d->sasl)
		d->sasl->setAuthzid(s);
}

427 428 429 430 431 432 433
void ClientStream::continueAfterParams()
{
	if(d->state == NeedParams) {
		d->state = Connecting;
		if(d->client.old) {
			processNext();
		}
434 435 436 437
		else {
			if(d->sasl)
				d->sasl->continueAfterParams();
		}
438 439 440
	}
}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
void ClientStream::setSaslMechanismProvider(const QString &m, const QString &p)
{
	d->mechProviders.insert(m, p);
}

QString ClientStream::saslMechanismProvider(const QString &m) const
{
	return d->mechProviders.value(m);
}

QCA::Provider::Context *ClientStream::currentSASLContext() const
{
	if (d->sasl) {
		return d->sasl->context();
	}
	return 0;
}

459 460 461 462 463 464 465 466 467 468 469 470
void ClientStream::setSCRAMStoredSaltedHash(const QString &s) {
	QCA::SASLContext *context = (QCA::SASLContext *)(d->sasl->context());
	if (context) {
		context->setProperty("scram-salted-password-base64", s);
	}
}

const QString ClientStream::getSCRAMStoredSaltedHash() {
	QCA::SASLContext *context = (QCA::SASLContext *)(d->sasl->context());
	if (context) {
		return context->property("scram-salted-password-base64").toString();
	}
471
	return QString();
472 473
}

474 475 476 477 478
void ClientStream::setResourceBinding(bool b)
{
	d->doBinding = b;
}

479 480 481 482 483
void ClientStream::setLang(const QString& lang)
{
	d->lang = lang;
}

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
void ClientStream::setNoopTime(int mills)
{
	d->noop_time = mills;

	if(d->state != Active)
		return;

	if(d->noop_time == 0) {
		d->noopTimer.stop();
		return;
	}
	d->noopTimer.start(d->noop_time);
}

QString ClientStream::saslMechanism() const
{
500
	return d->client.saslMech();
501 502 503 504
}

int ClientStream::saslSSF() const
{
505
	return d->sasl_ssf;
506 507 508 509
}

void ClientStream::setSASLMechanism(const QString &s)
{
510
	d->sasl_mech = s;
511 512
}

513
void ClientStream::setLocalAddr(const QHostAddress &addr, quint16 port)
514 515 516 517 518 519
{
	d->haveLocalAddr = true;
	d->localAddr = addr;
	d->localPort = port;
}

520
void ClientStream::setCompress(bool compress)
521 522 523 524
{
	d->doCompress = compress;
}

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
int ClientStream::errorCondition() const
{
	return d->errCond;
}

QString ClientStream::errorText() const
{
	return d->errText;
}

QDomElement ClientStream::errorAppSpec() const
{
	return d->errAppSpec;
}

bool ClientStream::old() const
{
	return d->client.old;
}

void ClientStream::close()
{
	if(d->state == Active) {
		d->state = Closing;
		d->client.shutdown();
		processNext();
	}
	else if(d->state != Idle && d->state != Closing) {
		reset();
	}
}

QDomDocument & ClientStream::doc() const
{
	return d->client.doc;
}

QString ClientStream::baseNS() const
{
	return NS_CLIENT;
}

567
void ClientStream::setAllowPlain(AllowPlainType a)
568
{
569
	d->allowPlain = a;
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
}

void ClientStream::setRequireMutualAuth(bool b)
{
	d->mutualAuth = b;
}

void ClientStream::setSSFRange(int low, int high)
{
	d->minimumSSF = low;
	d->maximumSSF = high;
}

void ClientStream::setOldOnly(bool b)
{
	d->oldOnly = b;
}

bool ClientStream::stanzaAvailable() const
{
	return (!d->in.isEmpty());
}

Stanza ClientStream::read()
{
	if(d->in.isEmpty())
		return Stanza();
	else {
598
		Stanza *sp = d->in.takeFirst();
599
		Stanza s = *sp;
600
		delete sp;
601 602 603 604
		return s;
	}
}

605
void ClientStream::write(const Stanza &s, bool notify)
606 607
{
	if(d->state == Active) {
608
		d->client.sendStanza(s.element(), notify);
609 610 611 612 613 614
		processNext();
	}
}

void ClientStream::cr_connected()
{
615
	d->connectHost = d->conn->host();
616 617 618 619
	d->bs = d->conn->stream();
	connect(d->bs, SIGNAL(connectionClosed()), SLOT(bs_connectionClosed()));
	connect(d->bs, SIGNAL(delayedCloseFinished()), SLOT(bs_delayedCloseFinished()));

620
	QByteArray spare = d->bs->readAll();
621 622 623

	d->ss = new SecureStream(d->bs);
	connect(d->ss, SIGNAL(readyRead()), SLOT(ss_readyRead()));
624
	connect(d->ss, SIGNAL(bytesWritten(qint64)), SLOT(ss_bytesWritten(qint64)));
625 626 627 628 629 630 631
	connect(d->ss, SIGNAL(tlsHandshaken()), SLOT(ss_tlsHandshaken()));
	connect(d->ss, SIGNAL(tlsClosed()), SLOT(ss_tlsClosed()));
	connect(d->ss, SIGNAL(error(int)), SLOT(ss_error(int)));

	//d->client.startDialbackOut("andbit.net", "im.pyxa.org");
	//d->client.startServerOut(d->server);

632
	d->client.startClientOut(d->jid, d->oldOnly, d->conn->useSSL(), d->doAuth, d->doCompress);
633 634
	d->client.setAllowTLS(d->tlsHandler ? true: false);
	d->client.setAllowBind(d->doBinding);
635
	d->client.setAllowPlain(d->allowPlain == AllowPlain || (d->allowPlain == AllowPlainOverTLS && d->conn->useSSL()));
636
	d->client.setLang(d->lang);
637 638 639 640 641 642 643 644 645

	/*d->client.jid = d->jid;
	d->client.server = d->server;
	d->client.allowPlain = d->allowPlain;
	d->client.oldOnly = d->oldOnly;
	d->client.sasl_mech = d->sasl_mech;
	d->client.doTLS = d->tlsHandler ? true: false;
	d->client.doBinding = d->doBinding;*/

Matt Rogers's avatar
Matt Rogers committed
646
	QPointer<QObject> self = this;
647
	emit connected();
648 649
	if(!self)
		return;
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

	// immediate SSL?
	if(d->conn->useSSL()) {
		d->using_tls = true;
		d->ss->startTLSClient(d->tlsHandler, d->server, spare);
	}
	else {
		d->client.addIncomingData(spare);
		processNext();
	}
}

void ClientStream::cr_error()
{
	reset();
	error(ErrConnection);
}

void ClientStream::bs_connectionClosed()
{
	reset();
	connectionClosed();
}

void ClientStream::bs_delayedCloseFinished()
{
	// we don't care about this (we track all important data ourself)
}

void ClientStream::bs_error(int)
{
	// TODO
}

void ClientStream::ss_readyRead()
{
686
	QByteArray a = d->ss->readAll();
687

688
#ifdef XMPP_DEBUG
689
	qDebug("ClientStream: recv: %d [%s]\n", a.size(), a.data());
690
#endif
691 692 693 694 695 696 697

	if(d->mode == Client)
		d->client.addIncomingData(a);
	else
		d->srv.addIncomingData(a);
	if(d->notify & CoreProtocol::NRecv) {
#ifdef XMPP_DEBUG
698
		qDebug("We needed data, so let's process it\n");
699 700 701 702 703
#endif
		processNext();
	}
}

704
void ClientStream::ss_bytesWritten(qint64 bytes)
705 706 707 708 709 710 711 712
{
	if(d->mode == Client)
		d->client.outgoingDataWritten(bytes);
	else
		d->srv.outgoingDataWritten(bytes);

	if(d->notify & CoreProtocol::NSend) {
#ifdef XMPP_DEBUG
713
		qDebug("We were waiting for data to be written, so let's process\n");
714 715 716 717 718 719 720
#endif
		processNext();
	}
}

void ClientStream::ss_tlsHandshaken()
{
Matt Rogers's avatar
Matt Rogers committed
721
	QPointer<QObject> self = this;
722
	securityLayerActivated(LayerTLS);
723 724
	if(!self)
		return;
725
	d->client.setAllowPlain(d->allowPlain == AllowPlain || d->allowPlain == AllowPlainOverTLS);
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
	processNext();
}

void ClientStream::ss_tlsClosed()
{
	reset();
	connectionClosed();
}

void ClientStream::ss_error(int x)
{
	if(x == SecureStream::ErrTLS) {
		reset();
		d->errCond = TLSFail;
		error(ErrTLS);
	}
	else {
		reset();
		error(ErrSecurityLayer);
	}
}

748
void ClientStream::sasl_clientFirstStep(bool, const QByteArray& ba)
749
{
750
	d->client.setSASLFirst(d->sasl->mechanism(), ba);
751 752 753 754 755 756 757 758 759
	//d->client.sasl_mech = mech;
	//d->client.sasl_firstStep = stepData ? true : false;
	//d->client.sasl_step = stepData ? *stepData : QByteArray();

	processNext();
}

void ClientStream::sasl_nextStep(const QByteArray &stepData)
{
760 761
	if(d->mode == Client)
		d->client.setSASLNext(stepData);
762
		//d->client.sasl_step = stepData;
763 764
	else
		d->srv.setSASLNext(stepData);
765 766
		//d->srv.sasl_step = stepData;

767
	processNext();
768 769
}

770
void ClientStream::sasl_needParams(const QCA::SASL::Params& p)
771 772
{
#ifdef XMPP_DEBUG
773 774
	qDebug("need params: needUsername: %d, canSendAuthzid: %d, needPassword: %d, canSendRealm: %d\n",
		   p.needUsername()?1:0, p.canSendAuthzid()? 1:0, p.needPassword()? 1:0, p.canSendRealm()? 1:0);
775
#endif
776
	/*if(p.authzid && !p.user) {
777 778
		d->sasl->setAuthzid(d->jid.bare());
		//d->sasl->setAuthzid("infiniti.homelesshackers.org");
779
	}*/
Isaac Clerencia's avatar
Isaac Clerencia committed
780
	if(p.needUsername() || p.needPassword() || p.canSendRealm()) {
781
		d->state = NeedParams;
Isaac Clerencia's avatar
Isaac Clerencia committed
782
		needAuthParams(p.needUsername(), p.needPassword(), p.canSendRealm());
783 784
	}
	else
785
		d->sasl->continueAfterParams();
786 787 788 789 790
}

void ClientStream::sasl_authCheck(const QString &user, const QString &)
{
//#ifdef XMPP_DEBUG
791
//	qDebug("authcheck: [%s], [%s]\n", user.latin1(), authzid.latin1());
792
//#endif
793
	QString u = user;
794
	int n = u.indexOf('@');
795 796 797
	if(n != -1)
		u.truncate(n);
	d->srv.user = u;
798
	d->sasl->continueAfterAuthCheck();
799 800 801 802 803
}

void ClientStream::sasl_authenticated()
{
#ifdef XMPP_DEBUG
804
	qDebug("sasl authed!!\n");
805
#endif
806
	d->sasl_ssf = d->sasl->ssf();
807 808 809 810

	if(d->mode == Server) {
		d->srv.setSASLAuthed();
		processNext();
811
	}
812 813
}

814
void ClientStream::sasl_error()
815
{
816
#ifdef XMPP_DEBUG
817
	qDebug("sasl error: %d\n", d->sasl->authCondition());
818
#endif
819
	// has to be auth error
820
	int x = convertedSASLCond();
821
	d->errText = tr("Offered mechanisms: ") + d->client.features.sasl_mechs.join(", ");
822 823
	reset();
	d->errCond = x;
824
	error(ErrAuth);
825 826 827 828 829
}

void ClientStream::srvProcessNext()
{
	while(1) {
830
		qDebug("Processing step...\n");
831 832 833 834 835
		if(!d->srv.processStep()) {
			int need = d->srv.need;
			if(need == CoreProtocol::NNotify) {
				d->notify = d->srv.notify;
				if(d->notify & CoreProtocol::NSend)
836
					qDebug("More data needs to be written to process next step\n");
837
				if(d->notify & CoreProtocol::NRecv)
838
					qDebug("More data is needed to process next step\n");
839 840
			}
			else if(need == CoreProtocol::NSASLMechs) {
841
				if(!d->sasl) {
842
					d->sasl = new QCA::SASL;
843 844
					connect(d->sasl, SIGNAL(authCheck(QString,QString)), SLOT(sasl_authCheck(QString,QString)));
					connect(d->sasl, SIGNAL(nextStep(QByteArray)), SLOT(sasl_nextStep(QByteArray)));
845
					connect(d->sasl, SIGNAL(authenticated()), SLOT(sasl_authenticated()));
846
					connect(d->sasl, SIGNAL(error()), SLOT(sasl_error()));
847 848 849 850

					//d->sasl->setAllowAnonymous(false);
					//d->sasl->setRequirePassCredentials(true);
					//d->sasl->setExternalAuthID("localhost");
851
					QCA::SASL::AuthFlags auth_flags = (QCA::SASL::AuthFlags) 0;
852
					d->sasl->setConstraints(auth_flags,0,256);
853 854 855

					QStringList list;
					// TODO: d->server is probably wrong here
856
					d->sasl->startServer("xmpp", d->server, d->defRealm, QCA::SASL::AllowServerSendLast);
857 858
					d->sasl_mechlist = list;
				}
859
				d->srv.setSASLMechList(d->sasl_mechlist);
860 861 862
				continue;
			}
			else if(need == CoreProtocol::NStartTLS) {
863
				qDebug("Need StartTLS\n");
864 865
				//if(!d->tls->startServer()) {
				d->tls->startServer();
866 867 868 869
				QByteArray a = d->srv.spare;
				d->ss->startTLSServer(d->tls, a);
			}
			else if(need == CoreProtocol::NSASLFirst) {
870
				qDebug("Need SASL First Step\n");
871
				QByteArray a = d->srv.saslStep();
872
				d->sasl->putServerFirstStep(d->srv.saslMech(), a);
873 874
			}
			else if(need == CoreProtocol::NSASLNext) {
875
				qDebug("Need SASL Next Step\n");
876
				QByteArray a = d->srv.saslStep();
877
				qDebug("[%s]\n", a.data());
878
				d->sasl->putStep(a);
879 880 881 882 883 884 885 886 887 888 889 890 891
			}
			else if(need == CoreProtocol::NSASLLayer) {
			}

			// now we can announce stanzas
			//if(!d->in.isEmpty())
			//	readyRead();
			return;
		}

		d->notify = 0;

		int event = d->srv.event;
892
		qDebug("event: %d\n", event);
893 894
		switch(event) {
			case CoreProtocol::EError: {
895
				qDebug("Error! Code=%d\n", d->srv.errorCode);
896 897 898 899 900 901 902
				reset();
				error(ErrProtocol);
				//handleError();
				return;
			}
			case CoreProtocol::ESend: {
				QByteArray a = d->srv.takeOutgoingData();
903
				qDebug("Need Send: {%s}\n", a.data());
904 905 906 907
				d->ss->write(a);
				break;
			}
			case CoreProtocol::ERecvOpen: {
908
				qDebug("Break (RecvOpen)\n");
909 910

				// calculate key
911
				QByteArray str = QCA::Hash("sha1").hashToString("secret").toUtf8();
912 913
				str = QCA::Hash("sha1").hashToString(QByteArray(str + "im.pyxa.org")).toUtf8();
				str = QCA::Hash("sha1").hashToString(QByteArray(str + d->srv.id.toUtf8())).toUtf8();
914 915 916 917 918 919 920 921 922 923 924 925 926
				d->srv.setDialbackKey(str);

				//d->srv.setDialbackKey("3c5d721ea2fcc45b163a11420e4e358f87e3142a");

				if(d->srv.to != d->server) {
					// host-gone, host-unknown, see-other-host
					d->srv.shutdownWithError(CoreProtocol::HostUnknown);
				}
				else
					d->srv.setFrom(d->server);
				break;
			}
			case CoreProtocol::ESASLSuccess: {
927
				qDebug("Break SASL Success\n");
928 929 930
				disconnect(d->sasl, SIGNAL(error()), this, SLOT(sasl_error()));
				QByteArray a = d->srv.spare;
				d->ss->setLayerSASL(d->sasl, a);
931 932 933 934
				break;
			}
			case CoreProtocol::EPeerClosed: {
				// TODO: this isn' an error
935
				qDebug("peer closed\n");
936 937 938 939 940 941 942 943
				reset();
				error(ErrProtocol);
				return;
			}
		}
	}
}

944 945
void ClientStream::doReadyRead()
{
946
	//QGuardedPtr<QObject> self = this;
947 948
	if (isActive())
		emit readyRead();
949 950 951 952 953
	//if(!self)
	//	return;
	//d->in_rrsig = false;
}

954 955 956 957 958 959 960
void ClientStream::processNext()
{
	if(d->mode == Server) {
		srvProcessNext();
		return;
	}

Matt Rogers's avatar
Matt Rogers committed
961
	QPointer<QObject> self = this;
962

963 964
	while(1) {
#ifdef XMPP_DEBUG
965
		qDebug("Processing step...\n");
966
#endif
Till Gerken's avatar
Till Gerken committed
967 968
		bool ok = d->client.processStep();
		// deal with send/received items
969
		foreach (const XmlProtocol::TransferItem &i, d->client.transferItemList) {
Till Gerken's avatar
Till Gerken committed
970 971 972 973 974
			if(i.isExternal)
				continue;
			QString str;
			if(i.isString) {
				// skip whitespace pings
975
				if(i.str.trimmed().isEmpty())
Till Gerken's avatar
Till Gerken committed
976 977 978 979 980 981
					continue;
				str = i.str;
			}
			else
				str = d->client.elementToString(i.elem);
			if(i.isSent)
982
				emit outgoingXml(str);
Till Gerken's avatar
Till Gerken committed
983
			else
984
				emit incomingXml(str);
Till Gerken's avatar
Till Gerken committed
985 986
		}

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
#ifdef XMPP_DEBUG
		qDebug("\tNOTIFY: %d\n", d->client.notify);
#endif
		if (d->client.notify & CoreProtocol::NTimeout ) {
#ifdef XMPP_DEBUG
			qDebug() << "Time = "<< d->client.timeout_sec;
#endif
			d->timeout_timer.setSingleShot(true);
			d->timeout_timer.start(d->client.timeout_sec * 1000);
			d->client.notify &= ~ CoreProtocol::NTimeout;
#ifdef XMPP_DEBUG
			qDebug() << "\tNTimeout received | Start timer";
#endif
		}

Till Gerken's avatar
Till Gerken committed
1002
		if(!ok) {
1003 1004 1005
			bool cont = handleNeed();

			// now we can announce stanzas
1006 1007 1008 1009 1010
			//if(!d->in_rrsig && !d->in.isEmpty()) {
			if(!d->in.isEmpty()) {
				//d->in_rrsig = true;
				QTimer::singleShot(0, this, SLOT(doReadyRead()));
			}
1011 1012 1013 1014 1015 1016 1017

			if(cont)
				continue;
			return;
		}

		int event = d->client.event;
1018
		d->notify = 0;
1019 1020 1021
		switch(event) {
			case CoreProtocol::EError: {
#ifdef XMPP_DEBUG
1022
				qDebug("Error! Code=%d\n", d->client.errorCode);
1023 1024 1025 1026 1027 1028 1029
#endif
				handleError();
				return;
			}
			case CoreProtocol::ESend: {
				QByteArray a = d->client.takeOutgoingData();
#ifdef XMPP_DEBUG
1030
				qDebug("Need Send: {%s}\n", a.data());
1031 1032 1033 1034 1035 1036
#endif
				d->ss->write(a);
				break;
			}
			case CoreProtocol::ERecvOpen: {
#ifdef XMPP_DEBUG
1037
				qDebug("Break (RecvOpen)\n");
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
#endif

#ifdef XMPP_TEST
				QString s = QString("handshake success (lang=[%1]").arg(d->client.lang);
				if(!d->client.from.isEmpty())
					s += QString(", from=[%1]").arg(d->client.from);
				s += ')';
				TD::msg(s);
#endif

				if(d->client.old) {
					d->state = WaitVersion;
					warning(WarnOldVersion);
					return;
				}
				break;
			}
			case CoreProtocol::EFeatures: {
#ifdef XMPP_DEBUG
1057
				qDebug("Break (Features)\n");
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
#endif
				if(!d->tls_warned && !d->using_tls && !d->client.features.tls_supported) {
					d->tls_warned = true;
					d->state = WaitTLS;
					warning(WarnNoTLS);
					return;
				}
				break;
			}
			case CoreProtocol::ESASLSuccess: {
#ifdef XMPP_DEBUG
1069
				qDebug("Break SASL Success\n");
1070 1071 1072 1073 1074
#endif
				break;
			}
			case CoreProtocol::EReady: {
#ifdef XMPP_DEBUG
1075
				qDebug("Done!\n");
1076 1077
#endif
				// grab the JID, in case it changed
1078
				d->jid = d->client.jid();
1079 1080 1081
				d->state = Active;
				setNoopTime(d->noop_time);
				authenticated();
1082 1083
				if(!self)
					return;
1084 1085 1086 1087
				break;
			}
			case CoreProtocol::EPeerClosed: {
#ifdef XMPP_DEBUG
1088
				qDebug("DocumentClosed\n");
1089 1090 1091 1092 1093 1094 1095
#endif
				reset();
				connectionClosed();
				return;
			}
			case CoreProtocol::EStanzaReady: {
#ifdef XMPP_DEBUG
1096
				qDebug("StanzaReady\n");
1097 1098
#endif
				// store the stanza for now, announce after processing all events
1099
				// TODO: add a method to the stanza to mark them handled.
1100
				Stanza s = createStanza(d->client.recvStanza());
1101
				unsigned long sm_id = d->client.getNewSMId();
1102 1103
				if(s.isNull())
					break;
1104
				if (s.kind() == Stanza::Presence || s.kind() == Stanza::IQ) d->client.markStanzaHandled(sm_id);
1105 1106 1107 1108 1109
				d->in.append(new Stanza(s));
				break;
			}
			case CoreProtocol::EStanzaSent: {
#ifdef XMPP_DEBUG
1110
				qDebug("StanzasSent\n");
1111 1112
#endif
				stanzaWritten();
1113 1114
				if(!self)
					return;
1115 1116 1117 1118
				break;
			}
			case CoreProtocol::EClosed: {
#ifdef XMPP_DEBUG
1119
				qDebug("Closed\n");
1120 1121 1122 1123 1124
#endif
				reset();
				delayedCloseFinished();
				return;
			}
1125 1126 1127 1128 1129 1130
			case CoreProtocol::EAck: {
#ifdef XMPP_DEBUG
				qDebug() << "Received ack response: " << d->client.getNotableStanzasAcked();
#endif
				emit stanzasAcked(d->client.getNotableStanzasAcked());
			}
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
		}
	}
}

bool ClientStream::handleNeed()
{
	int need = d->client.need;
	if(need == CoreProtocol::NNotify) {
		d->notify = d->client.notify;
#ifdef XMPP_DEBUG
		if(d->notify & CoreProtocol::NSend)
1142
			qDebug("More data needs to be written to process next step\n");
1143
		if(d->notify & CoreProtocol::NRecv)
1144
			qDebug("More data is needed to process next step\n");
1145 1146 1147 1148 1149 1150 1151 1152
#endif
		return false;
	}

	d->notify = 0;
	switch(need) {
		case CoreProtocol::NStartTLS: {
#ifdef XMPP_DEBUG
1153
			qDebug("Need StartTLS\n");
1154 1155 1156 1157 1158
#endif
			d->using_tls = true;
			d->ss->startTLSClient(d->tlsHandler, d->server, d->client.spare);
			return false;
		}
1159 1160
		case CoreProtocol::NCompress: {
#ifdef XMPP_DEBUG
1161
			qDebug("Need compress\n");
1162 1163 1164 1165
#endif
			d->ss->setLayerCompress(d->client.spare);
			return true;
		}
1166 1167
		case CoreProtocol::NSASLFirst: {
#ifdef XMPP_DEBUG
1168
			qDebug("Need SASL First Step\n");
1169
#endif
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

			// ensure simplesasl provider is installed
			bool found = false;
			foreach(QCA::Provider *p, QCA::providers()) {
				if(p->name() == "simplesasl") {
					found = true;
					break;
				}
			}
			if(!found) {
				// install with low-priority
1181
				QCA::insertProvider(createProviderSimpleSASL());
1182
				QCA::setProviderPriority("simplesasl", 10);
1183 1184
			}

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
			QStringList ml;
			if(!d->sasl_mech.isEmpty())
				ml += d->sasl_mech;
			else
				ml = d->client.features.sasl_mechs;

			QString saslProvider;
			foreach (const QString &mech, d->mechProviders.keys()) {
				if (ml.contains(mech)) {
					saslProvider = d->mechProviders[mech];
					break;
				}
			}

			d->sasl = new QCA::SASL(0, saslProvider);
1200 1201 1202
			connect(d->sasl, SIGNAL(clientStarted(bool,QByteArray)), SLOT(sasl_clientFirstStep(bool,QByteArray)));
			connect(d->sasl, SIGNAL(nextStep(QByteArray)), SLOT(sasl_nextStep(QByteArray)));
			connect(d->sasl, SIGNAL(needParams(QCA::SASL::Params)), SLOT(sasl_needParams(QCA::SASL::Params)));
1203 1204 1205 1206
			connect(d->sasl, SIGNAL(authenticated()), SLOT(sasl_authenticated()));
			connect(d->sasl, SIGNAL(error()), SLOT(sasl_error()));

			if(d->haveLocalAddr)
1207
				d->sasl->setLocalAddress(d->localAddr.toString(), d->localPort);
1208
			if(d->conn->havePeerAddress())
1209
				d->sasl->setRemoteAddress(d->conn->peerAddress().toString(), d->conn->peerPort());
1210 1211 1212 1213 1214 1215 1216

			//d->sasl_mech = "ANONYMOUS";
			//d->sasl->setRequirePassCredentials(true);
			//d->sasl->setExternalAuthID("localhost");
			//d->sasl->setExternalSSF(64);
			//d->sasl_mech = "EXTERNAL";

1217
			QCA::SASL::AuthFlags auth_flags = (QCA::SASL::AuthFlags) 0;
1218
			if (d->allowPlain == AllowPlain || (d->allowPlain == AllowPlainOverTLS && d->using_tls))
1219 1220 1221 1222 1223
				auth_flags = (QCA::