]> git.saurik.com Git - wxWidgets.git/blame - src/common/http.cpp
add strike-through font support to wxGraphicsContext on GTK
[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;
48f7ffbe 51 m_http_response = 0;
f4ada568 52
48f7ffbe 53 SetNotify(wxSOCKET_LOST_FLAG);
f4ada568
GL
54}
55
56wxHTTP::~wxHTTP()
2fb203e6
VZ
57{
58 ClearHeaders();
59
60 delete m_addr;
61}
62
63void wxHTTP::ClearHeaders()
f4ada568 64{
730b772b 65 m_headers.clear();
f4ada568
GL
66}
67
906cb3f1
JS
68void wxHTTP::ClearCookies()
69{
70 m_cookies.clear();
71}
72
730b772b 73wxString wxHTTP::GetContentType() const
f4ada568 74{
48f7ffbe 75 return GetHeader(wxT("Content-Type"));
f4ada568
GL
76}
77
f61815af
GL
78void wxHTTP::SetProxyMode(bool on)
79{
48f7ffbe 80 m_proxy_mode = on;
f61815af
GL
81}
82
bdcade0a 83wxHTTP::wxHeaderIterator wxHTTP::FindHeader(const wxString& header)
71414756 84{
bdcade0a
MB
85 wxHeaderIterator it = m_headers.begin();
86 for ( wxHeaderIterator en = m_headers.end(); it != en; ++it )
87 {
86501081 88 if ( header.CmpNoCase(it->first) == 0 )
bdcade0a
MB
89 break;
90 }
71414756 91
bdcade0a
MB
92 return it;
93}
94
95wxHTTP::wxHeaderConstIterator wxHTTP::FindHeader(const wxString& header) const
96{
97 wxHeaderConstIterator it = m_headers.begin();
98 for ( wxHeaderConstIterator en = m_headers.end(); it != en; ++it )
71414756 99 {
86501081 100 if ( header.CmpNoCase(it->first) == 0 )
71414756
VZ
101 break;
102 }
103
104 return it;
105}
106
906cb3f1
JS
107wxHTTP::wxCookieIterator wxHTTP::FindCookie(const wxString& cookie)
108{
109 wxCookieIterator it = m_cookies.begin();
110 for ( wxCookieIterator en = m_cookies.end(); it != en; ++it )
111 {
112 if ( cookie.CmpNoCase(it->first) == 0 )
113 break;
114 }
115
116 return it;
117}
118
119wxHTTP::wxCookieConstIterator wxHTTP::FindCookie(const wxString& cookie) const
120{
121 wxCookieConstIterator it = m_cookies.begin();
122 for ( wxCookieConstIterator en = m_cookies.end(); it != en; ++it )
123 {
124 if ( cookie.CmpNoCase(it->first) == 0 )
125 break;
126 }
127
128 return it;
129}
130
f4ada568
GL
131void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
132{
48f7ffbe
WS
133 if (m_read) {
134 ClearHeaders();
135 m_read = false;
136 }
f4ada568 137
48f7ffbe
WS
138 wxHeaderIterator it = FindHeader(header);
139 if (it != m_headers.end())
140 it->second = h_data;
141 else
142 m_headers[header] = h_data;
f4ada568
GL
143}
144
71414756 145wxString wxHTTP::GetHeader(const wxString& header) const
f4ada568 146{
bdcade0a 147 wxHeaderConstIterator it = FindHeader(header);
f4ada568 148
01482482 149 return it == m_headers.end() ? wxGetEmptyString() : it->second;
f4ada568
GL
150}
151
906cb3f1
JS
152wxString wxHTTP::GetCookie(const wxString& cookie) const
153{
154 wxCookieConstIterator it = FindCookie(cookie);
155
156 return it == m_cookies.end() ? wxGetEmptyString() : it->second;
157}
158
dbccd1c2
JS
159wxString wxHTTP::GenerateAuthString(const wxString& user, const wxString& pass) const
160{
e97cbf83
VZ
161 // TODO: Use wxBase64Encode() now that we have it instead of reproducing it
162
dbccd1c2
JS
163 static const char *base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
164
165 wxString buf;
166 wxString toencode;
167
168 buf.Printf(wxT("Basic "));
169
170 toencode.Printf(wxT("%s:%s"),user.c_str(),pass.c_str());
171
670f9935 172 size_t len = toencode.length();
dbccd1c2
JS
173 const wxChar *from = toencode.c_str();
174 while (len >= 3) { // encode full blocks first
175 buf << wxString::Format(wxT("%c%c"), base64[(from[0] >> 2) & 0x3f], base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)]);
176 buf << wxString::Format(wxT("%c%c"), base64[((from[1] << 2) & 0x3c) | ((from[2] >> 6) & 0x3)], base64[from[2] & 0x3f]);
177 from += 3;
178 len -= 3;
179 }
180 if (len > 0) { // pad the remaining characters
181 buf << wxString::Format(wxT("%c"), base64[(from[0] >> 2) & 0x3f]);
182 if (len == 1) {
183 buf << wxString::Format(wxT("%c="), base64[(from[0] << 4) & 0x30]);
184 } else {
886f61ca 185 buf << wxString::Format(wxT("%c%c"), base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)], base64[(from[1] << 2) & 0x3c]);
dbccd1c2 186 }
2523e9b7 187 buf << wxT("=");
dbccd1c2
JS
188 }
189
190 return buf;
191}
192
f9133b32
VZ
193void wxHTTP::SetPostBuffer(const wxString& post_buf)
194{
ab9d6a4c
VZ
195 // Use To8BitData() for backwards compatibility in this deprecated method.
196 // The new code should use the other overload or SetPostText() and specify
197 // the encoding to use for the text explicitly.
198 wxScopedCharBuffer scb = post_buf.To8BitData();
199 if ( scb.length() )
200 {
201 m_postBuffer.Clear();
202 m_postBuffer.AppendData(scb.data(), scb.length());
203 }
204}
205
206bool
207wxHTTP::SetPostBuffer(const wxString& contentType,
208 const wxMemoryBuffer& data)
209{
210 m_postBuffer = data;
211 m_contentType = contentType;
212
213 return !m_postBuffer.IsEmpty();
214}
215
216bool
217wxHTTP::SetPostText(const wxString& contentType,
218 const wxString& data,
219 const wxMBConv& conv)
220{
221 wxScopedCharBuffer scb = data.mb_str(conv);
222 if ( !scb.length() )
223 return false;
224
225 m_postBuffer.Clear();
226 m_postBuffer.AppendData(scb.data(), scb.length());
227 m_contentType = contentType;
228
229 return true;
f9133b32
VZ
230}
231
f4ada568
GL
232void wxHTTP::SendHeaders()
233{
48f7ffbe
WS
234 typedef wxStringToStringHashMap::iterator iterator;
235 wxString buf;
f4ada568 236
48f7ffbe
WS
237 for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it )
238 {
239 buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str());
53c6e7cc 240
48f7ffbe
WS
241 const wxWX2MBbuf cbuf = buf.mb_str();
242 Write(cbuf, strlen(cbuf));
243 }
f4ada568
GL
244}
245
246bool wxHTTP::ParseHeaders()
247{
48f7ffbe
WS
248 wxString line;
249 wxStringTokenizer tokenzr;
f4ada568 250
48f7ffbe 251 ClearHeaders();
906cb3f1 252 ClearCookies();
48f7ffbe 253 m_read = true;
f4ada568 254
a09f8377 255 for ( ;; )
48f7ffbe 256 {
730b772b
FM
257 m_lastError = ReadLine(this, line);
258 if (m_lastError != wxPROTO_NOERR)
48f7ffbe
WS
259 return false;
260
6636ef8d 261 if ( line.empty() )
48f7ffbe
WS
262 break;
263
264 wxString left_str = line.BeforeFirst(':');
906cb3f1
JS
265 if(!left_str.CmpNoCase("Set-Cookie"))
266 {
267 wxString cookieName = line.AfterFirst(':').Strip(wxString::both).BeforeFirst('=');
268 wxString cookieValue = line.AfterFirst(':').Strip(wxString::both).AfterFirst('=').BeforeFirst(';');
269 m_cookies[cookieName] = cookieValue;
270
271 // For compatibility
272 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
273 }
274 else
275 {
276 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
277 }
48f7ffbe
WS
278 }
279 return true;
f4ada568
GL
280}
281
f9133b32 282bool wxHTTP::Connect(const wxString& host, unsigned short port)
f4ada568 283{
48f7ffbe 284 wxIPV4address *addr;
f4ada568 285
48f7ffbe 286 if (m_addr) {
5276b0a5 287 wxDELETE(m_addr);
48f7ffbe
WS
288 Close();
289 }
f4ada568 290
48f7ffbe 291 m_addr = addr = new wxIPV4address();
f4ada568 292
48f7ffbe 293 if (!addr->Hostname(host)) {
5276b0a5 294 wxDELETE(m_addr);
730b772b 295 m_lastError = wxPROTO_NETERR;
48f7ffbe
WS
296 return false;
297 }
f4ada568 298
48f7ffbe
WS
299 if ( port )
300 addr->Service(port);
301 else if (!addr->Service(wxT("http")))
302 addr->Service(80);
ce22d615 303
1c7a6772
VZ
304 wxString hostHdr = host;
305 if ( port && port != 80 )
306 hostHdr << wxT(":") << port;
307 SetHeader(wxT("Host"), hostHdr);
f4ada568 308
730b772b 309 m_lastError = wxPROTO_NOERR;
48f7ffbe 310 return true;
f4ada568
GL
311}
312
ddc7f0c9 313bool wxHTTP::Connect(const wxSockAddress& addr, bool WXUNUSED(wait))
f4ada568 314{
48f7ffbe
WS
315 if (m_addr) {
316 delete m_addr;
317 Close();
318 }
f4ada568 319
48f7ffbe 320 m_addr = addr.Clone();
acd15a3f 321
48f7ffbe 322 wxIPV4address *ipv4addr = wxDynamicCast(&addr, wxIPV4address);
1c7a6772
VZ
323 if ( ipv4addr )
324 {
325 wxString hostHdr = ipv4addr->OrigHostname();
326 unsigned short port = ipv4addr->Service();
327 if ( port && port != 80 )
328 hostHdr << wxT(":") << port;
329 SetHeader(wxT("Host"), hostHdr);
330 }
5b96a71a 331
730b772b 332 m_lastError = wxPROTO_NOERR;
48f7ffbe 333 return true;
f4ada568
GL
334}
335
336bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req)
337{
48f7ffbe 338 const wxChar *request;
f9133b32 339
48f7ffbe
WS
340 switch (req)
341 {
342 case wxHTTP_GET:
343 request = wxT("GET");
344 break;
345
346 case wxHTTP_POST:
347 request = wxT("POST");
ab9d6a4c
VZ
348 // Content length must be correct, so always set, possibly
349 // overriding the value set explicitly by a previous call to
350 // SetHeader("Content-Length").
351 if ( !m_postBuffer.IsEmpty() )
352 {
353 wxString len;
354 len << m_postBuffer.GetDataLen();
355
356 SetHeader(wxS("Content-Length"), len);
357 }
358
359 // However if the user had explicitly set the content type, don't
360 // override it with the content type passed to SetPostText().
361 if ( !m_contentType.empty() && GetContentType().empty() )
362 SetHeader(wxS("Content-Type"), m_contentType);
48f7ffbe
WS
363 break;
364
365 default:
366 return false;
367 }
368
369 m_http_response = 0;
370
371 // If there is no User-Agent defined, define it.
6636ef8d 372 if ( GetHeader(wxT("User-Agent")).empty() )
48f7ffbe
WS
373 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
374
dbccd1c2 375 // Send authentication information
670f9935 376 if (!m_username.empty() || !m_password.empty()) {
dbccd1c2
JS
377 SetHeader(wxT("Authorization"), GenerateAuthString(m_username, m_password));
378 }
379
48f7ffbe
WS
380 SaveState();
381
382 // we may use non blocking sockets only if we can dispatch events from them
383 SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
384 : wxSOCKET_BLOCK );
385 Notify(false);
386
387 wxString buf;
388 buf.Printf(wxT("%s %s HTTP/1.0\r\n"), request, path.c_str());
86501081
VS
389 const wxWX2MBbuf pathbuf = buf.mb_str();
390 Write(pathbuf, strlen(pathbuf));
48f7ffbe
WS
391 SendHeaders();
392 Write("\r\n", 2);
393
394 if ( req == wxHTTP_POST ) {
ab9d6a4c
VZ
395 if ( !m_postBuffer.IsEmpty() )
396 Write(m_postBuffer.GetData(), m_postBuffer.GetDataLen());
397
398 m_postBuffer.Clear();
48f7ffbe
WS
399 }
400
401 wxString tmp_str;
730b772b
FM
402 m_lastError = ReadLine(this, tmp_str);
403 if (m_lastError != wxPROTO_NOERR) {
48f7ffbe
WS
404 RestoreState();
405 return false;
406 }
407
408 if (!tmp_str.Contains(wxT("HTTP/"))) {
409 // TODO: support HTTP v0.9 which can have no header.
410 // FIXME: tmp_str is not put back in the in-queue of the socket.
730b772b 411 m_lastError = wxPROTO_NOERR;
48f7ffbe
WS
412 SetHeader(wxT("Content-Length"), wxT("-1"));
413 SetHeader(wxT("Content-Type"), wxT("none/none"));
414 RestoreState();
415 return true;
416 }
f4ada568 417
48f7ffbe
WS
418 wxStringTokenizer token(tmp_str,wxT(' '));
419 wxString tmp_str2;
420 bool ret_value;
421
422 token.NextToken();
423 tmp_str2 = token.NextToken();
424
425 m_http_response = wxAtoi(tmp_str2);
426
c9f78968 427 switch ( tmp_str2[0u].GetValue() )
48f7ffbe
WS
428 {
429 case wxT('1'):
430 /* INFORMATION / SUCCESS */
431 break;
432
433 case wxT('2'):
434 /* SUCCESS */
435 break;
436
437 case wxT('3'):
438 /* REDIRECTION */
439 break;
440
441 default:
730b772b 442 m_lastError = wxPROTO_NOFILE;
48f7ffbe
WS
443 RestoreState();
444 return false;
445 }
446
730b772b 447 m_lastError = wxPROTO_NOERR;
48f7ffbe
WS
448 ret_value = ParseHeaders();
449 RestoreState();
450 return ret_value;
f4ada568
GL
451}
452
730b772b
FM
453bool wxHTTP::Abort(void)
454{
455 return wxSocketClient::Close();
456}
457
458// ----------------------------------------------------------------------------
459// wxHTTPStream and wxHTTP::GetInputStream
460// ----------------------------------------------------------------------------
461
fc4b32c2
GRG
462class wxHTTPStream : public wxSocketInputStream
463{
f4ada568 464public:
48f7ffbe
WS
465 wxHTTP *m_http;
466 size_t m_httpsize;
467 unsigned long m_read_bytes;
9a1b2c28 468
48f7ffbe
WS
469 wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
470 size_t GetSize() const { return m_httpsize; }
471 virtual ~wxHTTPStream(void) { m_http->Abort(); }
a324a7bc
GL
472
473protected:
48f7ffbe 474 size_t OnSysRead(void *buffer, size_t bufsize);
22f3361e 475
c0c133e1 476 wxDECLARE_NO_COPY_CLASS(wxHTTPStream);
f4ada568
GL
477};
478
a324a7bc
GL
479size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
480{
ccc3a25d 481 if (m_read_bytes >= m_httpsize)
32013d27
VZ
482 {
483 m_lasterror = wxSTREAM_EOF;
484 return 0;
485 }
a324a7bc 486
32013d27
VZ
487 size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
488 m_read_bytes += ret;
a324a7bc 489
8b6b8e21
SC
490 if (m_httpsize==(size_t)-1 && m_lasterror == wxSTREAM_READ_ERROR )
491 {
492 // if m_httpsize is (size_t) -1 this means read until connection closed
493 // which is equivalent to getting a READ_ERROR, for clients however this
494 // must be translated into EOF, as it is the expected way of signalling
495 // end end of the content
730b772b 496 m_lasterror = wxSTREAM_EOF;
8b6b8e21
SC
497 }
498
32013d27 499 return ret;
a324a7bc
GL
500}
501
f4ada568
GL
502wxInputStream *wxHTTP::GetInputStream(const wxString& path)
503{
48f7ffbe 504 wxHTTPStream *inp_stream;
8f5bda17 505
48f7ffbe 506 wxString new_path;
f4ada568 507
730b772b 508 m_lastError = wxPROTO_CONNERR; // all following returns share this type of error
48f7ffbe
WS
509 if (!m_addr)
510 return NULL;
f4ada568 511
48f7ffbe 512 // We set m_connected back to false so wxSocketBase will know what to do.
ad8b8498 513#ifdef __WXMAC__
48f7ffbe
WS
514 wxSocketClient::Connect(*m_addr , false );
515 wxSocketClient::WaitOnConnect(10);
ad8b8498
SC
516
517 if (!wxSocketClient::IsConnected())
518 return NULL;
519#else
48f7ffbe
WS
520 if (!wxProtocol::Connect(*m_addr))
521 return NULL;
ad8b8498 522#endif
f4ada568 523
ab9d6a4c 524 if (!BuildRequest(path, m_postBuffer.IsEmpty() ? wxHTTP_GET : wxHTTP_POST))
48f7ffbe 525 return NULL;
f4ada568 526
48f7ffbe 527 inp_stream = new wxHTTPStream(this);
8f5bda17 528
48f7ffbe 529 if (!GetHeader(wxT("Content-Length")).empty())
86501081 530 inp_stream->m_httpsize = wxAtoi(GetHeader(wxT("Content-Length")));
48f7ffbe
WS
531 else
532 inp_stream->m_httpsize = (size_t)-1;
a324a7bc 533
48f7ffbe 534 inp_stream->m_read_bytes = 0;
a324a7bc 535
48f7ffbe
WS
536 Notify(false);
537 SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL);
9a1b2c28 538
730b772b
FM
539 // no error; reset m_lastError
540 m_lastError = wxPROTO_NOERR;
48f7ffbe 541 return inp_stream;
f4ada568 542}
35a4dab7 543
a5d46b73 544#endif // wxUSE_PROTOCOL_HTTP