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