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