]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/http.cpp
Wrappers for *ToText
[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#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
13 #pragma implementation "http.h"
14#endif
15
16// For compilers that support precompilation, includes "wx.h".
17#include "wx/wxprec.h"
18
19#ifdef __BORLANDC__
20 #pragma hdrstop
21#endif
22
23#if wxUSE_PROTOCOL_HTTP
24
25#include <stdio.h>
26#include <stdlib.h>
27#include "wx/string.h"
28#include "wx/tokenzr.h"
29#include "wx/socket.h"
30#include "wx/protocol/protocol.h"
31#include "wx/url.h"
32#include "wx/protocol/http.h"
33#include "wx/sckstrm.h"
34
35IMPLEMENT_DYNAMIC_CLASS(wxHTTP, wxProtocol)
36IMPLEMENT_PROTOCOL(wxHTTP, wxT("http"), wxT("80"), TRUE)
37
38#define HTTP_BSIZE 2048
39
40wxHTTP::wxHTTP()
41 : wxProtocol()
42{
43 m_addr = NULL;
44 m_read = FALSE;
45 m_proxy_mode = FALSE;
46 m_post_buf = wxEmptyString;
47 m_http_response = 0;
48
49 SetNotify(wxSOCKET_LOST_FLAG);
50}
51
52wxHTTP::~wxHTTP()
53{
54 ClearHeaders();
55
56 delete m_addr;
57}
58
59void wxHTTP::ClearHeaders()
60{
61 m_headers.clear();
62}
63
64wxString wxHTTP::GetContentType()
65{
66 return GetHeader(wxT("Content-Type"));
67}
68
69void wxHTTP::SetProxyMode(bool on)
70{
71 m_proxy_mode = on;
72}
73
74wxHTTP::wxHeaderIterator wxHTTP::FindHeader(const wxString& header)
75{
76 wxHeaderIterator it = m_headers.begin();
77 for ( wxHeaderIterator en = m_headers.end(); it != en; ++it )
78 {
79 if ( wxStricmp(it->first, header) == 0 )
80 break;
81 }
82
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 )
90 {
91 if ( wxStricmp(it->first, header) == 0 )
92 break;
93 }
94
95 return it;
96}
97
98void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
99{
100 if (m_read) {
101 ClearHeaders();
102 m_read = FALSE;
103 }
104
105 wxHeaderIterator it = FindHeader(header);
106 if (it != m_headers.end())
107 it->second = h_data;
108 else
109 m_headers[header] = h_data;
110}
111
112wxString wxHTTP::GetHeader(const wxString& header) const
113{
114 wxHeaderConstIterator it = FindHeader(header);
115
116 return it == m_headers.end() ? wxGetEmptyString() : it->second;
117}
118
119void wxHTTP::SetPostBuffer(const wxString& post_buf)
120{
121 m_post_buf = post_buf;
122}
123
124void wxHTTP::SendHeaders()
125{
126 typedef wxStringToStringHashMap::iterator iterator;
127 wxString buf;
128
129 for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it )
130 {
131 buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str());
132
133 const wxWX2MBbuf cbuf = buf.mb_str();
134 Write(cbuf, strlen(cbuf));
135 }
136}
137
138bool wxHTTP::ParseHeaders()
139{
140 wxString line;
141 wxStringTokenizer tokenzr;
142
143 ClearHeaders();
144 m_read = TRUE;
145
146#if defined(__VISAGECPP__)
147// VA just can't stand while(1)
148 bool bOs2var = TRUE;
149 while(bOs2var)
150#else
151 while (1)
152#endif
153 {
154 m_perr = GetLine(this, line);
155 if (m_perr != wxPROTO_NOERR)
156 return FALSE;
157
158 if (line.Length() == 0)
159 break;
160
161 wxString left_str = line.BeforeFirst(':');
162 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
163 }
164 return TRUE;
165}
166
167bool wxHTTP::Connect(const wxString& host, unsigned short port)
168{
169 wxIPV4address *addr;
170
171 if (m_addr) {
172 delete m_addr;
173 m_addr = NULL;
174 Close();
175 }
176
177 m_addr = addr = new wxIPV4address();
178
179 if (!addr->Hostname(host)) {
180 delete m_addr;
181 m_addr = NULL;
182 m_perr = wxPROTO_NETERR;
183 return FALSE;
184 }
185
186 if ( port ) 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 case wxHTTP_GET:
217 request = wxT("GET");
218 break;
219 case wxHTTP_POST:
220 request = wxT("POST");
221 if ( GetHeader( wxT("Content-Length") ).IsNull() )
222 SetHeader( wxT("Content-Length"), wxString::Format( wxT("%ld"), m_post_buf.Len() ) );
223 break;
224 default:
225 return FALSE;
226 }
227
228 m_http_response = 0;
229
230 // If there is no User-Agent defined, define it.
231 if (GetHeader(wxT("User-Agent")).IsNull())
232 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
233
234 SaveState();
235 SetFlags( wxThread::IsMain() ? wxSOCKET_NONE : 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;
251 m_perr = GetLine(this, tmp_str);
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 }
265
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 case wxT('1'):
277 /* INFORMATION / SUCCESS */
278 break;
279 case wxT('2'):
280 /* SUCCESS */
281 break;
282 case wxT('3'):
283 /* REDIRECTION */
284 break;
285 default:
286 m_perr = wxPROTO_NOFILE;
287 RestoreState();
288 return FALSE;
289 }
290
291 ret_value = ParseHeaders();
292 RestoreState();
293 return ret_value;
294}
295
296class wxHTTPStream : public wxSocketInputStream
297{
298public:
299 wxHTTP *m_http;
300 size_t m_httpsize;
301 unsigned long m_read_bytes;
302
303 wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
304 size_t GetSize() const { return m_httpsize; }
305 virtual ~wxHTTPStream(void) { m_http->Abort(); }
306
307protected:
308 size_t OnSysRead(void *buffer, size_t bufsize);
309
310 DECLARE_NO_COPY_CLASS(wxHTTPStream)
311};
312
313size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
314{
315 if (m_httpsize > 0 && m_read_bytes >= m_httpsize)
316 {
317 m_lasterror = wxSTREAM_EOF;
318 return 0;
319 }
320
321 size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
322 m_read_bytes += ret;
323
324 return ret;
325}
326
327bool wxHTTP::Abort(void)
328{
329 return wxSocketClient::Close();
330}
331
332wxInputStream *wxHTTP::GetInputStream(const wxString& path)
333{
334 wxHTTPStream *inp_stream;
335
336 wxString new_path;
337
338 m_perr = wxPROTO_CONNERR;
339 if (!m_addr)
340 return NULL;
341
342 // We set m_connected back to FALSE so wxSocketBase will know what to do.
343#ifdef __WXMAC__
344 wxSocketClient::Connect(*m_addr , FALSE );
345 wxSocketClient::WaitOnConnect(10);
346
347 if (!wxSocketClient::IsConnected())
348 return NULL;
349#else
350 if (!wxProtocol::Connect(*m_addr))
351 return NULL;
352#endif
353
354 if (!BuildRequest(path, m_post_buf.IsEmpty() ? wxHTTP_GET : wxHTTP_POST))
355 return NULL;
356
357 inp_stream = new wxHTTPStream(this);
358
359 if (!GetHeader(wxT("Content-Length")).IsEmpty())
360 inp_stream->m_httpsize = wxAtoi(WXSTRINGCAST GetHeader(wxT("Content-Length")));
361 else
362 inp_stream->m_httpsize = (size_t)-1;
363
364 inp_stream->m_read_bytes = 0;
365
366 Notify(FALSE);
367 SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL);
368
369 return inp_stream;
370}
371
372#endif // wxUSE_PROTOCOL_HTTP
373