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