1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/http.cpp
3 // Purpose: HTTP protocol
4 // Author: Guilhem Lavaux
5 // Modified by: Simo Virokannas (authentication, Dec 2005)
6 // Created: August 1997
8 // Copyright: (c) 1997, 1998 Guilhem Lavaux
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
19 #if wxUSE_PROTOCOL_HTTP
25 #include "wx/string.h"
29 #include "wx/tokenzr.h"
30 #include "wx/socket.h"
31 #include "wx/protocol/protocol.h"
33 #include "wx/protocol/http.h"
34 #include "wx/sckstrm.h"
35 #include "wx/thread.h"
38 // ----------------------------------------------------------------------------
40 // ----------------------------------------------------------------------------
42 IMPLEMENT_DYNAMIC_CLASS(wxHTTP
, wxProtocol
)
43 IMPLEMENT_PROTOCOL(wxHTTP
, wxT("http"), wxT("80"), true)
51 m_post_buf
= wxEmptyString
;
54 SetNotify(wxSOCKET_LOST_FLAG
);
64 void wxHTTP::ClearHeaders()
69 wxString
wxHTTP::GetContentType() const
71 return GetHeader(wxT("Content-Type"));
74 void wxHTTP::SetProxyMode(bool on
)
79 wxHTTP::wxHeaderIterator
wxHTTP::FindHeader(const wxString
& header
)
81 wxHeaderIterator it
= m_headers
.begin();
82 for ( wxHeaderIterator en
= m_headers
.end(); it
!= en
; ++it
)
84 if ( header
.CmpNoCase(it
->first
) == 0 )
91 wxHTTP::wxHeaderConstIterator
wxHTTP::FindHeader(const wxString
& header
) const
93 wxHeaderConstIterator it
= m_headers
.begin();
94 for ( wxHeaderConstIterator en
= m_headers
.end(); it
!= en
; ++it
)
96 if ( header
.CmpNoCase(it
->first
) == 0 )
103 void wxHTTP::SetHeader(const wxString
& header
, const wxString
& h_data
)
110 wxHeaderIterator it
= FindHeader(header
);
111 if (it
!= m_headers
.end())
114 m_headers
[header
] = h_data
;
117 wxString
wxHTTP::GetHeader(const wxString
& header
) const
119 wxHeaderConstIterator it
= FindHeader(header
);
121 return it
== m_headers
.end() ? wxGetEmptyString() : it
->second
;
124 wxString
wxHTTP::GenerateAuthString(const wxString
& user
, const wxString
& pass
) const
126 static const char *base64
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
131 buf
.Printf(wxT("Basic "));
133 toencode
.Printf(wxT("%s:%s"),user
.c_str(),pass
.c_str());
135 size_t len
= toencode
.length();
136 const wxChar
*from
= toencode
.c_str();
137 while (len
>= 3) { // encode full blocks first
138 buf
<< wxString::Format(wxT("%c%c"), base64
[(from
[0] >> 2) & 0x3f], base64
[((from
[0] << 4) & 0x30) | ((from
[1] >> 4) & 0xf)]);
139 buf
<< wxString::Format(wxT("%c%c"), base64
[((from
[1] << 2) & 0x3c) | ((from
[2] >> 6) & 0x3)], base64
[from
[2] & 0x3f]);
143 if (len
> 0) { // pad the remaining characters
144 buf
<< wxString::Format(wxT("%c"), base64
[(from
[0] >> 2) & 0x3f]);
146 buf
<< wxString::Format(wxT("%c="), base64
[(from
[0] << 4) & 0x30]);
148 buf
<< wxString::Format(wxT("%c%c"), base64
[((from
[0] << 4) & 0x30) | ((from
[1] >> 4) & 0xf)], base64
[(from
[1] << 2) & 0x3c]);
156 void wxHTTP::SetPostBuffer(const wxString
& post_buf
)
158 m_post_buf
= post_buf
;
161 void wxHTTP::SendHeaders()
163 typedef wxStringToStringHashMap::iterator iterator
;
166 for (iterator it
= m_headers
.begin(), en
= m_headers
.end(); it
!= en
; ++it
)
168 buf
.Printf(wxT("%s: %s\r\n"), it
->first
.c_str(), it
->second
.c_str());
170 const wxWX2MBbuf cbuf
= buf
.mb_str();
171 Write(cbuf
, strlen(cbuf
));
175 bool wxHTTP::ParseHeaders()
178 wxStringTokenizer tokenzr
;
185 m_lastError
= ReadLine(this, line
);
186 if (m_lastError
!= wxPROTO_NOERR
)
189 if (line
.length() == 0)
192 wxString left_str
= line
.BeforeFirst(':');
193 m_headers
[left_str
] = line
.AfterFirst(':').Strip(wxString::both
);
198 bool wxHTTP::Connect(const wxString
& host
, unsigned short port
)
208 m_addr
= addr
= new wxIPV4address();
210 if (!addr
->Hostname(host
)) {
213 m_lastError
= wxPROTO_NETERR
;
219 else if (!addr
->Service(wxT("http")))
222 wxString hostHdr
= host
;
223 if ( port
&& port
!= 80 )
224 hostHdr
<< wxT(":") << port
;
225 SetHeader(wxT("Host"), hostHdr
);
227 m_lastError
= wxPROTO_NOERR
;
231 bool wxHTTP::Connect(const wxSockAddress
& addr
, bool WXUNUSED(wait
))
238 m_addr
= addr
.Clone();
240 wxIPV4address
*ipv4addr
= wxDynamicCast(&addr
, wxIPV4address
);
243 wxString hostHdr
= ipv4addr
->OrigHostname();
244 unsigned short port
= ipv4addr
->Service();
245 if ( port
&& port
!= 80 )
246 hostHdr
<< wxT(":") << port
;
247 SetHeader(wxT("Host"), hostHdr
);
250 m_lastError
= wxPROTO_NOERR
;
254 bool wxHTTP::BuildRequest(const wxString
& path
, wxHTTP_Req req
)
256 const wxChar
*request
;
261 request
= wxT("GET");
265 request
= wxT("POST");
266 if ( GetHeader( wxT("Content-Length") ).IsNull() )
267 SetHeader( wxT("Content-Length"), wxString::Format( wxT("%lu"), (unsigned long)m_post_buf
.Len() ) );
276 // If there is no User-Agent defined, define it.
277 if (GetHeader(wxT("User-Agent")).IsNull())
278 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
280 // Send authentication information
281 if (!m_username
.empty() || !m_password
.empty()) {
282 SetHeader(wxT("Authorization"), GenerateAuthString(m_username
, m_password
));
287 // we may use non blocking sockets only if we can dispatch events from them
288 SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
293 buf
.Printf(wxT("%s %s HTTP/1.0\r\n"), request
, path
.c_str());
294 const wxWX2MBbuf pathbuf
= buf
.mb_str();
295 Write(pathbuf
, strlen(pathbuf
));
299 if ( req
== wxHTTP_POST
) {
300 Write(m_post_buf
.mbc_str(), m_post_buf
.Len());
301 m_post_buf
= wxEmptyString
;
305 m_lastError
= ReadLine(this, tmp_str
);
306 if (m_lastError
!= wxPROTO_NOERR
) {
311 if (!tmp_str
.Contains(wxT("HTTP/"))) {
312 // TODO: support HTTP v0.9 which can have no header.
313 // FIXME: tmp_str is not put back in the in-queue of the socket.
314 m_lastError
= wxPROTO_NOERR
;
315 SetHeader(wxT("Content-Length"), wxT("-1"));
316 SetHeader(wxT("Content-Type"), wxT("none/none"));
321 wxStringTokenizer
token(tmp_str
,wxT(' '));
326 tmp_str2
= token
.NextToken();
328 m_http_response
= wxAtoi(tmp_str2
);
330 switch ( tmp_str2
[0u].GetValue() )
333 /* INFORMATION / SUCCESS */
345 m_lastError
= wxPROTO_NOFILE
;
350 m_lastError
= wxPROTO_NOERR
;
351 ret_value
= ParseHeaders();
356 bool wxHTTP::Abort(void)
358 return wxSocketClient::Close();
361 // ----------------------------------------------------------------------------
362 // wxHTTPStream and wxHTTP::GetInputStream
363 // ----------------------------------------------------------------------------
365 class wxHTTPStream
: public wxSocketInputStream
370 unsigned long m_read_bytes
;
372 wxHTTPStream(wxHTTP
*http
) : wxSocketInputStream(*http
), m_http(http
) {}
373 size_t GetSize() const { return m_httpsize
; }
374 virtual ~wxHTTPStream(void) { m_http
->Abort(); }
377 size_t OnSysRead(void *buffer
, size_t bufsize
);
379 wxDECLARE_NO_COPY_CLASS(wxHTTPStream
);
382 size_t wxHTTPStream::OnSysRead(void *buffer
, size_t bufsize
)
384 if (m_httpsize
> 0 && m_read_bytes
>= m_httpsize
)
386 m_lasterror
= wxSTREAM_EOF
;
390 size_t ret
= wxSocketInputStream::OnSysRead(buffer
, bufsize
);
393 if (m_httpsize
==(size_t)-1 && m_lasterror
== wxSTREAM_READ_ERROR
)
395 // if m_httpsize is (size_t) -1 this means read until connection closed
396 // which is equivalent to getting a READ_ERROR, for clients however this
397 // must be translated into EOF, as it is the expected way of signalling
398 // end end of the content
399 m_lasterror
= wxSTREAM_EOF
;
405 wxInputStream
*wxHTTP::GetInputStream(const wxString
& path
)
407 wxHTTPStream
*inp_stream
;
411 m_lastError
= wxPROTO_CONNERR
; // all following returns share this type of error
415 // We set m_connected back to false so wxSocketBase will know what to do.
417 wxSocketClient::Connect(*m_addr
, false );
418 wxSocketClient::WaitOnConnect(10);
420 if (!wxSocketClient::IsConnected())
423 if (!wxProtocol::Connect(*m_addr
))
427 if (!BuildRequest(path
, m_post_buf
.empty() ? wxHTTP_GET
: wxHTTP_POST
))
430 inp_stream
= new wxHTTPStream(this);
432 if (!GetHeader(wxT("Content-Length")).empty())
433 inp_stream
->m_httpsize
= wxAtoi(GetHeader(wxT("Content-Length")));
435 inp_stream
->m_httpsize
= (size_t)-1;
437 inp_stream
->m_read_bytes
= 0;
440 SetFlags(wxSOCKET_BLOCK
| wxSOCKET_WAITALL
);
442 // no error; reset m_lastError
443 m_lastError
= wxPROTO_NOERR
;
447 #endif // wxUSE_PROTOCOL_HTTP