summaryrefslogtreecommitdiffstats
path: root/kopete/protocols/jabber/libiris/iris/xmpp-core/xmlprotocol.cpp
blob: d1650842246cd6c1480b56be75eda6e3871c8bdf (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
/*
 * xmlprotocol.cpp - state machine for 'jabber-like' protocols
 * Copyright (C) 2004  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
 *
 */

#include"xmlprotocol.h"

#include"bytestream.h"

using namespace XMPP;

// stripExtraNS
//
// This function removes namespace information from various nodes for
// display purposes only (the element is pretty much useless for processing
// after this).  We do this because TQXml is a bit overzealous about outputting
// redundant namespaces.
static TQDomElement stripExtraNS(const TQDomElement &e)
{
	// find closest parent with a namespace
	TQDomNode par = e.parentNode();
	while(!par.isNull() && par.namespaceURI().isNull())
		par = par.parentNode();
	bool noShowNS = false;
	if(!par.isNull() && par.namespaceURI() == e.namespaceURI())
		noShowNS = true;

	// build qName (prefix:localName)
	TQString qName;
	if(!e.prefix().isEmpty())
		qName = e.prefix() + ':' + e.localName();
	else
		qName = e.tagName();

	TQDomElement i;
	uint x;
	if(noShowNS)
		i = e.ownerDocument().createElement(qName);
	else
		i = e.ownerDocument().createElementNS(e.namespaceURI(), qName);

	// copy attributes
	TQDomNamedNodeMap al = e.attributes();
	for(x = 0; x < al.count(); ++x) {
		TQDomAttr a = al.item(x).cloneNode().toAttr();

		// don't show xml namespace
		if(a.namespaceURI() == NS_XML)
			i.setAttribute(TQString("xml:") + a.name(), a.value());
		else
			i.setAttributeNodeNS(a);
	}

	// copy tqchildren
	TQDomNodeList nl = e.childNodes();
	for(x = 0; x < nl.count(); ++x) {
		TQDomNode n = nl.item(x);
		if(n.isElement())
			i.appendChild(stripExtraNS(n.toElement()));
		else
			i.appendChild(n.cloneNode());
	}
	return i;
}

// xmlToString
//
// This function converts a TQDomElement into a TQString, using stripExtraNS
// to make it pretty.
static TQString xmlToString(const TQDomElement &e, const TQString &fakeNS, const TQString &fakeTQName, bool clip)
{
	TQDomElement i = e.cloneNode().toElement();

	// It seems TQDom can only have one namespace attribute at a time (see docElement 'HACK').
	// Fortunately we only need one kind depending on the input, so it is specified here.
	TQDomElement fake = e.ownerDocument().createElementNS(fakeNS, fakeTQName);
	fake.appendChild(i);
	fake = stripExtraNS(fake);
	TQString out;
	{
		TQTextStream ts(&out, IO_WriteOnly);
		fake.firstChild().save(ts, 0);
	}
	// 'clip' means to remove any unwanted (and unneeded) characters, such as a trailing newline
	if(clip) {
		int n = out.findRev('>');
		out.truncate(n+1);
	}
	return out;
}

// createRootXmlTags
//
// This function creates three TQStrings, one being an <?xml .. ?> processing
// instruction, and the others being the opening and closing tags of an
// element, <foo> and </foo>.  This basically allows us to get the raw XML
// text needed to open/close an XML stream, without resorting to generating
// the XML ourselves.  This function uses TQDom to do the generation, which
// ensures proper encoding and entity output.
static void createRootXmlTags(const TQDomElement &root, TQString *xmlHeader, TQString *tagOpen, TQString *tagClose)
{
	TQDomElement e = root.cloneNode(false).toElement();

	// insert a dummy element to ensure open and closing tags are generated
	TQDomElement dummy = e.ownerDocument().createElement("dummy");
	e.appendChild(dummy);

	// convert to xml->text
	TQString str;
	{
		TQTextStream ts(&str, IO_WriteOnly);
		e.save(ts, 0);
	}

	// parse the tags out
	int n = str.find('<');
	int n2 = str.find('>', n);
	++n2;
	*tagOpen = str.mid(n, n2-n);
	n2 = str.findRev('>');
	n = str.findRev('<');
	++n2;
	*tagClose = str.mid(n, n2-n);

	// generate a nice xml processing header
	*xmlHeader = "<?xml version=\"1.0\"?>";
}

//----------------------------------------------------------------------------
// Protocol
//----------------------------------------------------------------------------
XmlProtocol::TransferItem::TransferItem()
{
}

XmlProtocol::TransferItem::TransferItem(const TQString &_str, bool sent, bool external)
{
	isString = true;
	isSent = sent;
	isExternal = external;
	str = _str;
}

XmlProtocol::TransferItem::TransferItem(const TQDomElement &_elem, bool sent, bool external)
{
	isString = false;
	isSent = sent;
	isExternal = external;
	elem = _elem;
}

XmlProtocol::XmlProtocol()
{
	init();
}

XmlProtocol::~XmlProtocol()
{
}

void XmlProtocol::init()
{
	incoming = false;
	peerClosed = false;
	closeWritten = false;
}

void XmlProtocol::reset()
{
	init();

	elem = TQDomElement();
	tagOpen = TQString();
	tagClose = TQString();
	xml.reset();
	outData.resize(0);
	trackQueue.clear();
	transferItemList.clear();
}

void XmlProtocol::addIncomingData(const TQByteArray &a)
{
	xml.appendData(a);
}

TQByteArray XmlProtocol::takeOutgoingData()
{
	TQByteArray a = outData.copy();
	outData.resize(0);
	return a;
}

void XmlProtocol::outgoingDataWritten(int bytes)
{
	for(TQValueList<TrackItem>::Iterator it = trackQueue.begin(); it != trackQueue.end();) {
		TrackItem &i = *it;

		// enough bytes?
		if(bytes < i.size) {
			i.size -= bytes;
			break;
		}
		int type = i.type;
		int id = i.id;
		int size = i.size;
		bytes -= i.size;
		it = trackQueue.remove(it);

		if(type == TrackItem::Raw) {
			// do nothing
		}
		else if(type == TrackItem::Close) {
			closeWritten = true;
		}
		else if(type == TrackItem::Custom) {
			itemWritten(id, size);
		}
	}
}

bool XmlProtocol::processStep()
{
	Parser::Event pe;
	notify = 0;
	transferItemList.clear();

	if(state != Closing && (state == RecvOpen || stepAdvancesParser())) {
		// if we get here, then it's because we're in some step that advances the parser
		pe = xml.readNext();
		if(!pe.isNull()) {
			// note: error/close events should be handled for ALL steps, so do them here
			switch(pe.type()) {
				case Parser::Event::DocumentOpen: {
					transferItemList += TransferItem(pe.actualString(), false);

					//stringRecv(pe.actualString());
					break;
				}
				case Parser::Event::DocumentClose: {
					transferItemList += TransferItem(pe.actualString(), false);

					//stringRecv(pe.actualString());
					if(incoming) {
						sendTagClose();
						event = ESend;
						peerClosed = true;
						state = Closing;
					}
					else {
						event = EPeerClosed;
					}
					return true;
				}
				case Parser::Event::Element: {
					transferItemList += TransferItem(pe.element(), false);

					//elementRecv(pe.element());
					break;
				}
				case Parser::Event::Error: {
					if(incoming) {
						// If we get a parse error during the initial element exchange,
						// flip immediately into 'open' mode so that we can report an error.
						if(state == RecvOpen) {
							sendTagOpen();
							state = Open;
						}
						return handleError();
					}
					else {
						event = EError;
						errorCode = ErrParse;
						return true;
					}
				}
			}
		}
		else {
			if(state == RecvOpen || stepRequiresElement()) {
				need = NNotify;
				notify |= NRecv;
				return false;
			}
		}
	}

	return baseStep(pe);
}

TQString XmlProtocol::xmlEncoding() const
{
	return xml.encoding();
}

TQString XmlProtocol::elementToString(const TQDomElement &e, bool clip)
{
	if(elem.isNull())
		elem = elemDoc.importNode(docElement(), true).toElement();

	// Determine the appropriate 'fakeNS' to use
	TQString ns;

	// first, check root namespace
	TQString pre = e.prefix();
	if(pre.isNull())
		pre = "";
	if(pre == elem.prefix()) {
		ns = elem.namespaceURI();
	}
	else {
		// scan the root attributes for 'xmlns' (oh joyous hacks)
		TQDomNamedNodeMap al = elem.attributes();
		uint n;
		for(n = 0; n < al.count(); ++n) {
			TQDomAttr a = al.item(n).toAttr();
			TQString s = a.name();
			int x = s.find(':');
			if(x != -1)
				s = s.mid(x+1);
			else
				s = "";
			if(pre == s) {
				ns = a.value();
				break;
			}
		}
		if(n >= al.count()) {
			// if we get here, then no appropriate ns was found.  use root then..
			ns = elem.namespaceURI();
		}
	}

	// build qName
	TQString qn;
	if(!elem.prefix().isEmpty())
		qn = elem.prefix() + ':';
	qn += elem.localName();

	// make the string
	return xmlToString(e, ns, qn, clip);
}

bool XmlProtocol::stepRequiresElement() const
{
	// default returns false
	return false;
}

void XmlProtocol::itemWritten(int, int)
{
	// default does nothing
}

void XmlProtocol::stringSend(const TQString &)
{
	// default does nothing
}

void XmlProtocol::stringRecv(const TQString &)
{
	// default does nothing
}

void XmlProtocol::elementSend(const TQDomElement &)
{
	// default does nothing
}

void XmlProtocol::elementRecv(const TQDomElement &)
{
	// default does nothing
}

void XmlProtocol::startConnect()
{
	incoming = false;
	state = SendOpen;
}

void XmlProtocol::startAccept()
{
	incoming = true;
	state = RecvOpen;
}

bool XmlProtocol::close()
{
	sendTagClose();
	event = ESend;
	state = Closing;
	return true;
}

int XmlProtocol::writeString(const TQString &s, int id, bool external)
{
	transferItemList += TransferItem(s, true, external);
	return internalWriteString(s, TrackItem::Custom, id);
}

int XmlProtocol::writeElement(const TQDomElement &e, int id, bool external, bool clip)
{
	if(e.isNull())
		return 0;
	transferItemList += TransferItem(e, true, external);

	//elementSend(e);
	TQString out = elementToString(e, clip);
	return internalWriteString(out, TrackItem::Custom, id);
}

TQByteArray XmlProtocol::resetStream()
{
	// reset the state
	if(incoming)
		state = RecvOpen;
	else
		state = SendOpen;

	// grab unprocessed data before resetting
	TQByteArray spare = xml.unprocessed();
	xml.reset();
	return spare;
}

int XmlProtocol::internalWriteData(const TQByteArray &a, TrackItem::Type t, int id)
{
	TrackItem i;
	i.type = t;
	i.id = id;
	i.size = a.size();
	trackQueue += i;

	ByteStream::appendArray(&outData, a);
	return a.size();
}

int XmlProtocol::internalWriteString(const TQString &s, TrackItem::Type t, int id)
{
	TQCString cs = s.utf8();
	TQByteArray a(cs.length());
	memcpy(a.data(), cs.data(), a.size());
	return internalWriteData(a, t, id);
}

void XmlProtocol::sendTagOpen()
{
	if(elem.isNull())
		elem = elemDoc.importNode(docElement(), true).toElement();

	TQString xmlHeader;
	createRootXmlTags(elem, &xmlHeader, &tagOpen, &tagClose);

	TQString s;
	s += xmlHeader + '\n';
	s += tagOpen + '\n';

	transferItemList += TransferItem(xmlHeader, true);
	transferItemList += TransferItem(tagOpen, true);

	//stringSend(xmlHeader);
	//stringSend(tagOpen);
	internalWriteString(s, TrackItem::Raw);
}

void XmlProtocol::sendTagClose()
{
	transferItemList += TransferItem(tagClose, true);

	//stringSend(tagClose);
	internalWriteString(tagClose, TrackItem::Close);
}

bool XmlProtocol::baseStep(const Parser::Event &pe)
{
	// Basic
	if(state == SendOpen) {
		sendTagOpen();
		event = ESend;
		if(incoming)
			state = Open;
		else
			state = RecvOpen;
		return true;
	}
	else if(state == RecvOpen) {
		if(incoming)
			state = SendOpen;
		else
			state = Open;

		// note: event will always be DocumentOpen here
		handleDocOpen(pe);
		event = ERecvOpen;
		return true;
	}
	else if(state == Open) {
		TQDomElement e;
		if(pe.type() == Parser::Event::Element)
			e = pe.element();
		return doStep(e);
	}
	// Closing
	else {
		if(closeWritten) {
			if(peerClosed) {
				event = EPeerClosed;
				return true;
			}
			else
				return handleCloseFinished();
		}

		need = NNotify;
		notify = NSend;
		return false;
	}
}

void XmlProtocol::setIncomingAsExternal()
{
	for(TQValueList<TransferItem>::Iterator it = transferItemList.begin(); it != transferItemList.end(); ++it) {
		TransferItem &i = *it;
		// look for elements received
		if(!i.isString && !i.isSent)
			i.isExternal = true;
	}
}