]> git.saurik.com Git - wxWidgets.git/blame - src/common/http.cpp
Do not use Tooltips if they are disabled
[wxWidgets.git] / src / common / http.cpp
CommitLineData
f4ada568 1/////////////////////////////////////////////////////////////////////////////
670f9935 2// Name: src/common/http.cpp
f4ada568
GL
3// Purpose: HTTP protocol
4// Author: Guilhem Lavaux
dbccd1c2 5// Modified by: Simo Virokannas (authentication, Dec 2005)
f4ada568
GL
6// Created: August 1997
7// RCS-ID: $Id$
8// Copyright: (c) 1997, 1998 Guilhem Lavaux
65571936 9// Licence: wxWindows licence
f4ada568
GL
10/////////////////////////////////////////////////////////////////////////////
11
fcc6dddd
JS
12// For compilers that support precompilation, includes "wx.h".
13#include "wx/wxprec.h"
14
15#ifdef __BORLANDC__
670f9935 16 #pragma hdrstop
fcc6dddd
JS
17#endif
18
a5d46b73 19#if wxUSE_PROTOCOL_HTTP
ce4169a4 20
f4ada568
GL
21#include <stdio.h>
22#include <stdlib.h>
a8d628fc
DS
23
24#ifndef WX_PRECOMP
670f9935
WS
25 #include "wx/string.h"
26 #include "wx/app.h"
a8d628fc
DS
27#endif
28
f4ada568
GL
29#include "wx/tokenzr.h"
30#include "wx/socket.h"
31#include "wx/protocol/protocol.h"
fae05df5 32#include "wx/url.h"
f4ada568
GL
33#include "wx/protocol/http.h"
34#include "wx/sckstrm.h"
204abcd4 35#include "wx/thread.h"
f4ada568 36
730b772b
FM
37
38// ----------------------------------------------------------------------------
39// wxHTTP
40// ----------------------------------------------------------------------------
41
f4ada568 42IMPLEMENT_DYNAMIC_CLASS(wxHTTP, wxProtocol)
5d3e7b52 43IMPLEMENT_PROTOCOL(wxHTTP, wxT("http"), wxT("80"), true)
f4ada568 44
f4ada568 45wxHTTP::wxHTTP()
df5168c4 46 : wxProtocol()
f4ada568 47{
48f7ffbe
WS
48 m_addr = NULL;
49 m_read = false;
50 m_proxy_mode = false;
51 m_post_buf = wxEmptyString;
52 m_http_response = 0;
f4ada568 53
48f7ffbe 54 SetNotify(wxSOCKET_LOST_FLAG);
f4ada568
GL
55}
56
57wxHTTP::~wxHTTP()
2fb203e6
VZ
58{
59 ClearHeaders();
60
61 delete m_addr;
62}
63
64void wxHTTP::ClearHeaders()
f4ada568 65{
730b772b 66 m_headers.clear();
f4ada568
GL
67}
68
730b772b 69wxString wxHTTP::GetContentType() const
f4ada568 70{
48f7ffbe 71 return GetHeader(wxT("Content-Type"));
f4ada568
GL
72}
73
f61815af
GL
74void wxHTTP::SetProxyMode(bool on)
75{
48f7ffbe 76 m_proxy_mode = on;
f61815af
GL
77}
78
bdcade0a 79wxHTTP::wxHeaderIterator wxHTTP::FindHeader(const wxString& header)
71414756 80{
bdcade0a
MB
81 wxHeaderIterator it = m_headers.begin();
82 for ( wxHeaderIterator en = m_headers.end(); it != en; ++it )
83 {
86501081 84 if ( header.CmpNoCase(it->first) == 0 )
bdcade0a
MB
85 break;
86 }
71414756 87
bdcade0a
MB
88 return it;
89}
90
91wxHTTP::wxHeaderConstIterator wxHTTP::FindHeader(const wxString& header) const
92{
93 wxHeaderConstIterator it = m_headers.begin();
94 for ( wxHeaderConstIterator en = m_headers.end(); it != en; ++it )
71414756 95 {
86501081 96 if ( header.CmpNoCase(it->first) == 0 )
71414756
VZ
97 break;
98 }
99
100 return it;
101}
102
f4ada568
GL
103void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
104{
48f7ffbe
WS
105 if (m_read) {
106 ClearHeaders();
107 m_read = false;
108 }
f4ada568 109
48f7ffbe
WS
110 wxHeaderIterator it = FindHeader(header);
111 if (it != m_headers.end())
112 it->second = h_data;
113 else
114 m_headers[header] = h_data;
f4ada568
GL
115}
116
71414756 117wxString wxHTTP::GetHeader(const wxString& header) const
f4ada568 118{
bdcade0a 119 wxHeaderConstIterator it = FindHeader(header);
f4ada568 120
01482482 121 return it == m_headers.end() ? wxGetEmptyString() : it->second;
f4ada568
GL
122}
123
dbccd1c2
JS
124wxString wxHTTP::GenerateAuthString(const wxString& user, const wxString& pass) const
125{
126 static const char *base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
127
128 wxString buf;
129 wxString toencode;
130
131 buf.Printf(wxT("Basic "));
132
133 toencode.Printf(wxT("%s:%s"),user.c_str(),pass.c_str());
134
670f9935 135 size_t len = toencode.length();
dbccd1c2
JS
136 const wxChar *from = toencode.c_str();
137 while (len >= 3) { // encode full blocks first
138 buf << wxString::Format(wxT("%c%c"), base64[(from[0] >> 2) & 0x3f], base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)]);
139 buf << wxString::Format(wxT("%c%c"), base64[((from[1] << 2) & 0x3c) | ((from[2] >> 6) & 0x3)], base64[from[2] & 0x3f]);
140 from += 3;
141 len -= 3;
142 }
143 if (len > 0) { // pad the remaining characters
144 buf << wxString::Format(wxT("%c"), base64[(from[0] >> 2) & 0x3f]);
145 if (len == 1) {
146 buf << wxString::Format(wxT("%c="), base64[(from[0] << 4) & 0x30]);
147 } else {
886f61ca 148 buf << wxString::Format(wxT("%c%c"), base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)], base64[(from[1] << 2) & 0x3c]);
dbccd1c2 149 }
2523e9b7 150 buf << wxT("=");
dbccd1c2
JS
151 }
152
153 return buf;
154}
155
f9133b32
VZ
156void wxHTTP::SetPostBuffer(const wxString& post_buf)
157{
71414756 158 m_post_buf = post_buf;
f9133b32
VZ
159}
160
f4ada568
GL
161void wxHTTP::SendHeaders()
162{
48f7ffbe
WS
163 typedef wxStringToStringHashMap::iterator iterator;
164 wxString buf;
f4ada568 165
48f7ffbe
WS
166 for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it )
167 {
168 buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str());
53c6e7cc 169
48f7ffbe
WS
170 const wxWX2MBbuf cbuf = buf.mb_str();
171 Write(cbuf, strlen(cbuf));
172 }
f4ada568
GL
173}
174
175bool wxHTTP::ParseHeaders()
176{
48f7ffbe
WS
177 wxString line;
178 wxStringTokenizer tokenzr;
f4ada568 179
48f7ffbe
WS
180 ClearHeaders();
181 m_read = true;
f4ada568 182
a09f8377 183 for ( ;; )
48f7ffbe 184 {
730b772b
FM
185 m_lastError = ReadLine(this, line);
186 if (m_lastError != wxPROTO_NOERR)
48f7ffbe
WS
187 return false;
188
670f9935 189 if (line.length() == 0)
48f7ffbe
WS
190 break;
191
192 wxString left_str = line.BeforeFirst(':');
193 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
194 }
195 return true;
f4ada568
GL
196}
197
f9133b32 198bool wxHTTP::Connect(const wxString& host, unsigned short port)
f4ada568 199{
48f7ffbe 200 wxIPV4address *addr;
f4ada568 201
48f7ffbe
WS
202 if (m_addr) {
203 delete m_addr;
204 m_addr = NULL;
205 Close();
206 }
f4ada568 207
48f7ffbe 208 m_addr = addr = new wxIPV4address();
f4ada568 209
48f7ffbe
WS
210 if (!addr->Hostname(host)) {
211 delete m_addr;
212 m_addr = NULL;
730b772b 213 m_lastError = wxPROTO_NETERR;
48f7ffbe
WS
214 return false;
215 }
f4ada568 216
48f7ffbe
WS
217 if ( port )
218 addr->Service(port);
219 else if (!addr->Service(wxT("http")))
220 addr->Service(80);
ce22d615 221
1c7a6772
VZ
222 wxString hostHdr = host;
223 if ( port && port != 80 )
224 hostHdr << wxT(":") << port;
225 SetHeader(wxT("Host"), hostHdr);
f4ada568 226
730b772b 227 m_lastError = wxPROTO_NOERR;
48f7ffbe 228 return true;
f4ada568
GL
229}
230
ddc7f0c9 231bool wxHTTP::Connect(const wxSockAddress& addr, bool WXUNUSED(wait))
f4ada568 232{
48f7ffbe
WS
233 if (m_addr) {
234 delete m_addr;
235 Close();
236 }
f4ada568 237
48f7ffbe 238 m_addr = addr.Clone();
acd15a3f 239
48f7ffbe 240 wxIPV4address *ipv4addr = wxDynamicCast(&addr, wxIPV4address);
1c7a6772
VZ
241 if ( ipv4addr )
242 {
243 wxString hostHdr = ipv4addr->OrigHostname();
244 unsigned short port = ipv4addr->Service();
245 if ( port && port != 80 )
246 hostHdr << wxT(":") << port;
247 SetHeader(wxT("Host"), hostHdr);
248 }
5b96a71a 249
730b772b 250 m_lastError = wxPROTO_NOERR;
48f7ffbe 251 return true;
f4ada568
GL
252}
253
254bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req)
255{
48f7ffbe 256 const wxChar *request;
f9133b32 257
48f7ffbe
WS
258 switch (req)
259 {
260 case wxHTTP_GET:
261 request = wxT("GET");
262 break;
263
264 case wxHTTP_POST:
265 request = wxT("POST");
266 if ( GetHeader( wxT("Content-Length") ).IsNull() )
267 SetHeader( wxT("Content-Length"), wxString::Format( wxT("%lu"), (unsigned long)m_post_buf.Len() ) );
268 break;
269
270 default:
271 return false;
272 }
273
274 m_http_response = 0;
275
276 // If there is no User-Agent defined, define it.
277 if (GetHeader(wxT("User-Agent")).IsNull())
278 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
279
dbccd1c2 280 // Send authentication information
670f9935 281 if (!m_username.empty() || !m_password.empty()) {
dbccd1c2
JS
282 SetHeader(wxT("Authorization"), GenerateAuthString(m_username, m_password));
283 }
284
48f7ffbe
WS
285 SaveState();
286
287 // we may use non blocking sockets only if we can dispatch events from them
288 SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
289 : wxSOCKET_BLOCK );
290 Notify(false);
291
292 wxString buf;
293 buf.Printf(wxT("%s %s HTTP/1.0\r\n"), request, path.c_str());
86501081
VS
294 const wxWX2MBbuf pathbuf = buf.mb_str();
295 Write(pathbuf, strlen(pathbuf));
48f7ffbe
WS
296 SendHeaders();
297 Write("\r\n", 2);
298
299 if ( req == wxHTTP_POST ) {
300 Write(m_post_buf.mbc_str(), m_post_buf.Len());
301 m_post_buf = wxEmptyString;
302 }
303
304 wxString tmp_str;
730b772b
FM
305 m_lastError = ReadLine(this, tmp_str);
306 if (m_lastError != wxPROTO_NOERR) {
48f7ffbe
WS
307 RestoreState();
308 return false;
309 }
310
311 if (!tmp_str.Contains(wxT("HTTP/"))) {
312 // TODO: support HTTP v0.9 which can have no header.
313 // FIXME: tmp_str is not put back in the in-queue of the socket.
730b772b 314 m_lastError = wxPROTO_NOERR;
48f7ffbe
WS
315 SetHeader(wxT("Content-Length"), wxT("-1"));
316 SetHeader(wxT("Content-Type"), wxT("none/none"));
317 RestoreState();
318 return true;
319 }
f4ada568 320
48f7ffbe
WS
321 wxStringTokenizer token(tmp_str,wxT(' '));
322 wxString tmp_str2;
323 bool ret_value;
324
325 token.NextToken();
326 tmp_str2 = token.NextToken();
327
328 m_http_response = wxAtoi(tmp_str2);
329
c9f78968 330 switch ( tmp_str2[0u].GetValue() )
48f7ffbe
WS
331 {
332 case wxT('1'):
333 /* INFORMATION / SUCCESS */
334 break;
335
336 case wxT('2'):
337 /* SUCCESS */
338 break;
339
340 case wxT('3'):
341 /* REDIRECTION */
342 break;
343
344 default:
730b772b 345 m_lastError = wxPROTO_NOFILE;
48f7ffbe
WS
346 RestoreState();
347 return false;
348 }
349
730b772b 350 m_lastError = wxPROTO_NOERR;
48f7ffbe
WS
351 ret_value = ParseHeaders();
352 RestoreState();
353 return ret_value;
f4ada568
GL
354}
355
730b772b
FM
356bool wxHTTP::Abort(void)
357{
358 return wxSocketClient::Close();
359}
360
361// ----------------------------------------------------------------------------
362// wxHTTPStream and wxHTTP::GetInputStream
363// ----------------------------------------------------------------------------
364
fc4b32c2
GRG
365class wxHTTPStream : public wxSocketInputStream
366{
f4ada568 367public:
48f7ffbe
WS
368 wxHTTP *m_http;
369 size_t m_httpsize;
370 unsigned long m_read_bytes;
9a1b2c28 371
48f7ffbe
WS
372 wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
373 size_t GetSize() const { return m_httpsize; }
374 virtual ~wxHTTPStream(void) { m_http->Abort(); }
a324a7bc
GL
375
376protected:
48f7ffbe 377 size_t OnSysRead(void *buffer, size_t bufsize);
22f3361e 378
c0c133e1 379 wxDECLARE_NO_COPY_CLASS(wxHTTPStream);
f4ada568
GL
380};
381
a324a7bc
GL
382size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
383{
32013d27
VZ
384 if (m_httpsize > 0 && m_read_bytes >= m_httpsize)
385 {
386 m_lasterror = wxSTREAM_EOF;
387 return 0;
388 }
a324a7bc 389
32013d27
VZ
390 size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
391 m_read_bytes += ret;
a324a7bc 392
8b6b8e21
SC
393 if (m_httpsize==(size_t)-1 && m_lasterror == wxSTREAM_READ_ERROR )
394 {
395 // if m_httpsize is (size_t) -1 this means read until connection closed
396 // which is equivalent to getting a READ_ERROR, for clients however this
397 // must be translated into EOF, as it is the expected way of signalling
398 // end end of the content
730b772b 399 m_lasterror = wxSTREAM_EOF;
8b6b8e21
SC
400 }
401
32013d27 402 return ret;
a324a7bc
GL
403}
404
f4ada568
GL
405wxInputStream *wxHTTP::GetInputStream(const wxString& path)
406{
48f7ffbe 407 wxHTTPStream *inp_stream;
8f5bda17 408
48f7ffbe 409 wxString new_path;
f4ada568 410
730b772b 411 m_lastError = wxPROTO_CONNERR; // all following returns share this type of error
48f7ffbe
WS
412 if (!m_addr)
413 return NULL;
f4ada568 414
48f7ffbe 415 // We set m_connected back to false so wxSocketBase will know what to do.
ad8b8498 416#ifdef __WXMAC__
48f7ffbe
WS
417 wxSocketClient::Connect(*m_addr , false );
418 wxSocketClient::WaitOnConnect(10);
ad8b8498
SC
419
420 if (!wxSocketClient::IsConnected())
421 return NULL;
422#else
48f7ffbe
WS
423 if (!wxProtocol::Connect(*m_addr))
424 return NULL;
ad8b8498 425#endif
f4ada568 426
48f7ffbe
WS
427 if (!BuildRequest(path, m_post_buf.empty() ? wxHTTP_GET : wxHTTP_POST))
428 return NULL;
f4ada568 429
48f7ffbe 430 inp_stream = new wxHTTPStream(this);
8f5bda17 431
48f7ffbe 432 if (!GetHeader(wxT("Content-Length")).empty())
86501081 433 inp_stream->m_httpsize = wxAtoi(GetHeader(wxT("Content-Length")));
48f7ffbe
WS
434 else
435 inp_stream->m_httpsize = (size_t)-1;
a324a7bc 436
48f7ffbe 437 inp_stream->m_read_bytes = 0;
a324a7bc 438
48f7ffbe
WS
439 Notify(false);
440 SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL);
9a1b2c28 441
730b772b
FM
442 // no error; reset m_lastError
443 m_lastError = wxPROTO_NOERR;
48f7ffbe 444 return inp_stream;
f4ada568 445}
35a4dab7 446
a5d46b73 447#endif // wxUSE_PROTOCOL_HTTP