summaryrefslogtreecommitdiffstats
path: root/kopete/protocols/jabber/libiris/cutestuff/network/httpconnect.cpp
blob: e9cc5781a6154061aed27d025ce8e99e168472f3 (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
/*
 * httpconnect.cpp - HTTP "CONNECT" proxy
 * Copyright (C) 2003  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 "httpconnect.h"

#include <tqstringlist.h>
#include "bsocket.h"
#include "base64.h"

#ifdef PROX_DEBUG
#include <stdio.h>
#endif

// CS_NAMESPACE_BEGIN

static TQString extractLine(TQByteArray *buf, bool *found)
{
	// scan for newline
	int n;
	for(n = 0; n < (int)buf->size()-1; ++n) {
		if(buf->at(n) == '\r' && buf->at(n+1) == '\n') {
			TQCString cstr;
			cstr.resize(n+1);
			memcpy(cstr.data(), buf->data(), n);
			n += 2; // hack off CR/LF

			memmove(buf->data(), buf->data() + n, buf->size() - n);
			buf->resize(buf->size() - n);
			TQString s = TQString::fromUtf8(cstr);

			if(found)
				*found = true;
			return s;
		}
	}

	if(found)
		*found = false;
	return "";
}

static bool extractMainHeader(const TQString &line, TQString *proto, int *code, TQString *msg)
{
	int n = line.find(' ');
	if(n == -1)
		return false;
	if(proto)
		*proto = line.mid(0, n);
	++n;
	int n2 = line.find(' ', n);
	if(n2 == -1)
		return false;
	if(code)
		*code = line.mid(n, n2-n).toInt();
	n = n2+1;
	if(msg)
		*msg = line.mid(n);
	return true;
}

class HttpConnect::Private
{
public:
	Private() {}

	BSocket sock;
	TQString host;
	int port;
	TQString user, pass;
	TQString real_host;
	int real_port;

	TQByteArray recvBuf;

	bool inHeader;
	TQStringList headerLines;

	int toWrite;
	bool active;
};

HttpConnect::HttpConnect(TQObject *parent)
:ByteStream(parent)
{
	d = new Private;
	connect(&d->sock, TQT_SIGNAL(connected()), TQT_SLOT(sock_connected()));
	connect(&d->sock, TQT_SIGNAL(connectionClosed()), TQT_SLOT(sock_connectionClosed()));
	connect(&d->sock, TQT_SIGNAL(delayedCloseFinished()), TQT_SLOT(sock_delayedCloseFinished()));
	connect(&d->sock, TQT_SIGNAL(readyRead()), TQT_SLOT(sock_readyRead()));
	connect(&d->sock, TQT_SIGNAL(bytesWritten(int)), TQT_SLOT(sock_bytesWritten(int)));
	connect(&d->sock, TQT_SIGNAL(error(int)), TQT_SLOT(sock_error(int)));

	reset(true);
}

HttpConnect::~HttpConnect()
{
	reset(true);
	delete d;
}

void HttpConnect::reset(bool clear)
{
	if(d->sock.state() != BSocket::Idle)
		d->sock.close();
	if(clear) {
		clearReadBuffer();
		d->recvBuf.resize(0);
	}
	d->active = false;
}

void HttpConnect::setAuth(const TQString &user, const TQString &pass)
{
	d->user = user;
	d->pass = pass;
}

void HttpConnect::connectToHost(const TQString &proxyHost, int proxyPort, const TQString &host, int port)
{
	reset(true);

	d->host = proxyHost;
	d->port = proxyPort;
	d->real_host = host;
	d->real_port = port;

#ifdef PROX_DEBUG
	fprintf(stderr, "HttpConnect: Connecting to %s:%d", proxyHost.latin1(), proxyPort);
	if(d->user.isEmpty())
		fprintf(stderr, "\n");
	else
		fprintf(stderr, ", auth {%s,%s}\n", d->user.latin1(), d->pass.latin1());
#endif
	d->sock.connectToHost(d->host, d->port);
}

bool HttpConnect::isOpen() const
{
	return d->active;
}

void HttpConnect::close()
{
	d->sock.close();
	if(d->sock.bytesToWrite() == 0)
		reset();
}

void HttpConnect::write(const TQByteArray &buf)
{
	if(d->active)
		d->sock.write(buf);
}

TQByteArray HttpConnect::read(int bytes)
{
	return ByteStream::read(bytes);
}

int HttpConnect::bytesAvailable() const
{
	return ByteStream::bytesAvailable();
}

int HttpConnect::bytesToWrite() const
{
	if(d->active)
		return d->sock.bytesToWrite();
	else
		return 0;
}

void HttpConnect::sock_connected()
{
#ifdef PROX_DEBUG
	fprintf(stderr, "HttpConnect: Connected\n");
#endif
	d->inHeader = true;
	d->headerLines.clear();

	// connected, now send the request
	TQString s;
	s += TQString("CONNECT ") + d->real_host + ':' + TQString::number(d->real_port) + " HTTP/1.0\r\n";
	if(!d->user.isEmpty()) {
		TQString str = d->user + ':' + d->pass;
		s += TQString("Proxy-Authorization: Basic ") + Base64::encodeString(str) + "\r\n";
	}
	s += "Proxy-Connection: Keep-Alive\r\n";
	s += "Pragma: no-cache\r\n";
	s += "\r\n";

	TQCString cs = s.utf8();
	TQByteArray block(cs.length());
	memcpy(block.data(), cs.data(), block.size());
	d->toWrite = block.size();
	d->sock.write(block);
}

void HttpConnect::sock_connectionClosed()
{
	if(d->active) {
		reset();
		connectionClosed();
	}
	else {
		error(ErrProxyNeg);
	}
}

void HttpConnect::sock_delayedCloseFinished()
{
	if(d->active) {
		reset();
		delayedCloseFinished();
	}
}

void HttpConnect::sock_readyRead()
{
	TQByteArray block = d->sock.read();

	if(!d->active) {
		ByteStream::appendArray(&d->recvBuf, block);

		if(d->inHeader) {
			// grab available lines
			while(1) {
				bool found;
				TQString line = extractLine(&d->recvBuf, &found);
				if(!found)
					break;
				if(line.isEmpty()) {
					d->inHeader = false;
					break;
				}
				d->headerLines += line;
			}

			// done with grabbing the header?
			if(!d->inHeader) {
				TQString str = d->headerLines.first();
				d->headerLines.remove(d->headerLines.begin());

				TQString proto;
				int code;
				TQString msg;
				if(!extractMainHeader(str, &proto, &code, &msg)) {
#ifdef PROX_DEBUG
					fprintf(stderr, "HttpConnect: invalid header!\n");
#endif
					reset(true);
					error(ErrProxyNeg);
					return;
				}
				else {
#ifdef PROX_DEBUG
					fprintf(stderr, "HttpConnect: header proto=[%s] code=[%d] msg=[%s]\n", proto.latin1(), code, msg.latin1());
					for(TQStringList::ConstIterator it = d->headerLines.begin(); it != d->headerLines.end(); ++it)
						fprintf(stderr, "HttpConnect: * [%s]\n", (*it).latin1());
#endif
				}

				if(code == 200) { // OK
#ifdef PROX_DEBUG
					fprintf(stderr, "HttpConnect: << Success >>\n");
#endif
					d->active = true;
					connected();

					if(!d->recvBuf.isEmpty()) {
						appendRead(d->recvBuf);
						d->recvBuf.resize(0);
						readyRead();
						return;
					}
				}
				else {
					int err;
					TQString errStr;
					if(code == 407) { // Authentication failed
						err = ErrProxyAuth;
						errStr = tr("Authentication failed");
					}
					else if(code == 404) { // Host not found
						err = ErrHostNotFound;
						errStr = tr("Host not found");
					}
					else if(code == 403) { // Access denied
						err = ErrProxyNeg;
						errStr = tr("Access denied");
					}
					else if(code == 503) { // Connection refused
						err = ErrConnectionRefused;
						errStr = tr("Connection refused");
					}
					else { // invalid reply
						err = ErrProxyNeg;
						errStr = tr("Invalid reply");
					}

#ifdef PROX_DEBUG
					fprintf(stderr, "HttpConnect: << Error >> [%s]\n", errStr.latin1());
#endif
					reset(true);
					error(err);
					return;
				}
			}
		}
	}
	else {
		appendRead(block);
		readyRead();
		return;
	}
}

void HttpConnect::sock_bytesWritten(int x)
{
	if(d->toWrite > 0) {
		int size = x;
		if(d->toWrite < x)
			size = d->toWrite;
		d->toWrite -= size;
		x -= size;
	}

	if(d->active && x > 0)
		bytesWritten(x);
}

void HttpConnect::sock_error(int x)
{
	if(d->active) {
		reset();
		error(ErrRead);
	}
	else {
		reset(true);
		if(x == BSocket::ErrHostNotFound)
			error(ErrProxyConnect);
		else if(x == BSocket::ErrConnectionRefused)
			error(ErrProxyConnect);
		else if(x == BSocket::ErrRead)
			error(ErrProxyNeg);
	}
}

// CS_NAMESPACE_END

#include "httpconnect.moc"