summaryrefslogtreecommitdiffstats
path: root/tdecore/network/khttpproxysocketdevice.cpp
blob: 980fa39d5c5d7ea59d4a5efe4ee829f26f5221c7 (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
/*
 *  Copyright (C) 2003 Thiago Macieira <[email protected]>
 *
 *
 *  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 <sys/types.h>
#include <sys/socket.h>

#include <tqsocketnotifier.h>
#include <tqcstring.h>

#include "kresolver.h"
#include "tdesocketaddress.h"
#include "tdesocketdevice.h"
#include "khttpproxysocketdevice.h"

using namespace KNetwork;

KResolverEntry KHttpProxySocketDevice::defaultProxy;

class KNetwork::KHttpProxySocketDevicePrivate
{
public:
  KResolverEntry proxy;
  TQCString request;
  TQCString reply;
  TDESocketAddress peer;

  KHttpProxySocketDevicePrivate()
    : proxy(KHttpProxySocketDevice::defaultProxy)
  { }
};

KHttpProxySocketDevice::KHttpProxySocketDevice(const TDESocketBase* parent)
  : TDESocketDevice(parent), d(new KHttpProxySocketDevicePrivate)
{
}

KHttpProxySocketDevice::KHttpProxySocketDevice(const KResolverEntry& proxy)
  : d(new KHttpProxySocketDevicePrivate)
{
  d->proxy = proxy;
}

KHttpProxySocketDevice::~KHttpProxySocketDevice()
{
  // nothing special to be done during closing
  // TDESocketDevice::~TDESocketDevice closes the socket

  delete d;
}

int KHttpProxySocketDevice::capabilities() const
{
  return CanConnectString | CanNotBind | CanNotListen | CanNotUseDatagrams;
}

const KResolverEntry&
KHttpProxySocketDevice::proxyServer() const
{
  return d->proxy;
}

void KHttpProxySocketDevice::setProxyServer(const KResolverEntry& proxy)
{
  d->proxy = proxy;
}

void KHttpProxySocketDevice::close()
{
  d->reply = d->request = TQCString();
  d->peer = TDESocketAddress();
  TDESocketDevice::close();
}

TDESocketAddress KHttpProxySocketDevice::peerAddress() const
{
  if (isOpen())
    return d->peer;
  return TDESocketAddress();
}

TDESocketAddress KHttpProxySocketDevice::externalAddress() const
{
  return TDESocketAddress();
}

bool KHttpProxySocketDevice::connect(const KResolverEntry& address)
{
  if (d->proxy.family() == AF_UNSPEC)
    // no proxy server set !
    return TDESocketDevice::connect(address);

  if (isOpen())
    {
      // socket is already open
      resetError();
      return true;
    }

  if (m_sockfd == -1)
    // socket isn't created yet
    return connect(address.address().nodeName(), 
		   address.address().serviceName());

  d->peer = address.address();
  return parseServerReply();
}

bool KHttpProxySocketDevice::connect(const TQString& node, const TQString& service)
{
  // same safety checks as above
  if (m_sockfd == -1 && (d->proxy.family() == AF_UNSPEC ||
			 node.isEmpty() || service.isEmpty()))
    {
      // no proxy server set !
      setError(IO_ConnectError, NotSupported);
      return false;
    }

  if (isOpen())
    {
      // socket is already open
      return true;
    }

  if (m_sockfd == -1)
    {
      // must create the socket
      if (!TDESocketDevice::connect(d->proxy))
	return false;		// also unable to contact proxy server
      setState(0);		// unset open flag

      // prepare the request
      TQString request = TQString::fromLatin1("CONNECT %1:%2 HTTP/1.1\r\n"
					    "Cache-Control: no-cache\r\n"
					    "Host: \r\n"
					    "\r\n");
      TQString node2 = node;
      if (node.contains(':'))
	node2 = '[' + node + ']';

      d->request = TQString(request.arg(node2).arg(service)).latin1();
    }

  return parseServerReply();
}

bool KHttpProxySocketDevice::parseServerReply()
{
  // make sure we're connected
  if (!TDESocketDevice::connect(d->proxy)) {
    if (error() == InProgress) {
      return true;
    }
    else if (error() != NoError) {
      return false;
    }
  }

  if (!d->request.isEmpty())
    {
      // send request
      TQ_LONG written = writeBlock(d->request, d->request.length());
      if (written < 0)
	{
	  tqDebug("KHttpProxySocketDevice: would block writing request!");
	  if (error() == WouldBlock)
	    setError(IO_ConnectError, InProgress);
	  return error() == WouldBlock; // error
	}
      tqDebug("KHttpProxySocketDevice: request written");

      d->request.remove(0, written);

      if (!d->request.isEmpty())
	{
	  setError(IO_ConnectError, InProgress);
	  return true;		// still in progress
	}
    }

  // request header is sent
  // must parse reply, but must also be careful not to read too much
  // from the buffer

  int index;
  if (!blocking())
    {
      TQ_LONG avail = bytesAvailable();
      tqDebug("KHttpProxySocketDevice: %ld bytes available", avail);
      setState(0);
      if (avail == 0)
	{
	  setError(IO_ConnectError, InProgress);
	  return true;
	}
      else if (avail < 0)
	return false;		// error!

      TQByteArray buf(avail);
      if (peekBlock(buf.data(), avail) < 0)
	return false;		// error!

      TQCString fullHeaders = d->reply + buf.data();
      // search for the end of the headers
      index = fullHeaders.find("\r\n\r\n");
      if (index == -1)
	{
	  // no, headers not yet finished...
	  // consume data from socket
	  readBlock(buf.data(), avail);
	  d->reply += buf.data();
	  setError(IO_ConnectError, InProgress);
	  return true;
	}

      // headers are finished
      index -= d->reply.length();
      d->reply += fullHeaders.mid(d->reply.length(), index + 4);

      // consume from socket
      readBlock(buf.data(), index + 4);
    }
  else
    {
      int state = 0;
      if (d->reply.right(3) == "\r\n\r")
	state = 3;
      else if (d->reply.right(2) == "\r\n")
	state = 2;
      else if (d->reply.right(1) == "\r")
	state = 1;
      while (state != 4)
	{
	  char c = getch();
	  d->reply += c;

	  if ((state == 3 && c == '\n') ||
	      (state == 1 && c == '\n') ||
	      c == '\r')
	    ++state;
	  else
	    state = 0;
	}
    }	    

  // now really parse the reply
  tqDebug("KHttpProxySocketDevice: get reply: %s\n",
	 d->reply.left(d->reply.find('\r')).data());
  if (d->reply.left(7) != "HTTP/1." ||
      (index = d->reply.find(' ')) == -1 ||
      d->reply[index + 1] != '2')
    {
      setError(IO_ConnectError, NetFailure);
      return false;
    }

  // we've got it
  resetError();
  setState(IO_Open);
  return true;
}