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 void wxHTTP::ClearCookies()
74 wxString
wxHTTP::GetContentType() const
76 return GetHeader(wxT("Content-Type"));
79 void wxHTTP::SetProxyMode(bool on
)
84 wxHTTP::wxHeaderIterator
wxHTTP::FindHeader(const wxString
& header
)
86 wxHeaderIterator it
= m_headers
.begin();
87 for ( wxHeaderIterator en
= m_headers
.end(); it
!= en
; ++it
)
89 if ( header
.CmpNoCase(it
->first
) == 0 )
96 wxHTTP::wxHeaderConstIterator
wxHTTP::FindHeader(const wxString
& header
) const
98 wxHeaderConstIterator it
= m_headers
.begin();
99 for ( wxHeaderConstIterator en
= m_headers
.end(); it
!= en
; ++it
)
101 if ( header
.CmpNoCase(it
->first
) == 0 )
108 wxHTTP::wxCookieIterator
wxHTTP::FindCookie(const wxString
& cookie
)
110 wxCookieIterator it
= m_cookies
.begin();
111 for ( wxCookieIterator en
= m_cookies
.end(); it
!= en
; ++it
)
113 if ( cookie
.CmpNoCase(it
->first
) == 0 )
120 wxHTTP::wxCookieConstIterator
wxHTTP::FindCookie(const wxString
& cookie
) const
122 wxCookieConstIterator it
= m_cookies
.begin();
123 for ( wxCookieConstIterator en
= m_cookies
.end(); it
!= en
; ++it
)
125 if ( cookie
.CmpNoCase(it
->first
) == 0 )
132 void wxHTTP::SetHeader(const wxString
& header
, const wxString
& h_data
)
139 wxHeaderIterator it
= FindHeader(header
);
140 if (it
!= m_headers
.end())
143 m_headers
[header
] = h_data
;
146 wxString
wxHTTP::GetHeader(const wxString
& header
) const
148 wxHeaderConstIterator it
= FindHeader(header
);
150 return it
== m_headers
.end() ? wxGetEmptyString() : it
->second
;
153 wxString
wxHTTP::GetCookie(const wxString
& cookie
) const
155 wxCookieConstIterator it
= FindCookie(cookie
);
157 return it
== m_cookies
.end() ? wxGetEmptyString() : it
->second
;
160 wxString
wxHTTP::GenerateAuthString(const wxString
& user
, const wxString
& pass
) const
162 static const char *base64
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
167 buf
.Printf(wxT("Basic "));
169 toencode
.Printf(wxT("%s:%s"),user
.c_str(),pass
.c_str());
171 size_t len
= toencode
.length();
172 const wxChar
*from
= toencode
.c_str();
173 while (len
>= 3) { // encode full blocks first
174 buf
<< wxString::Format(wxT("%c%c"), base64
[(from
[0] >> 2) & 0x3f], base64
[((from
[0] << 4) & 0x30) | ((from
[1] >> 4) & 0xf)]);
175 buf
<< wxString::Format(wxT("%c%c"), base64
[((from
[1] << 2) & 0x3c) | ((from
[2] >> 6) & 0x3)], base64
[from
[2] & 0x3f]);
179 if (len
> 0) { // pad the remaining characters
180 buf
<< wxString::Format(wxT("%c"), base64
[(from
[0] >> 2) & 0x3f]);
182 buf
<< wxString::Format(wxT("%c="), base64
[(from
[0] << 4) & 0x30]);
184 buf
<< wxString::Format(wxT("%c%c"), base64
[((from
[0] << 4) & 0x30) | ((from
[1] >> 4) & 0xf)], base64
[(from
[1] << 2) & 0x3c]);
192 void wxHTTP::SetPostBuffer(const wxString
& post_buf
)
194 m_post_buf
= post_buf
;
197 void wxHTTP::SendHeaders()
199 typedef wxStringToStringHashMap::iterator iterator
;
202 for (iterator it
= m_headers
.begin(), en
= m_headers
.end(); it
!= en
; ++it
)
204 buf
.Printf(wxT("%s: %s\r\n"), it
->first
.c_str(), it
->second
.c_str());
206 const wxWX2MBbuf cbuf
= buf
.mb_str();
207 Write(cbuf
, strlen(cbuf
));
211 bool wxHTTP::ParseHeaders()
214 wxStringTokenizer tokenzr
;
222 m_lastError
= ReadLine(this, line
);
223 if (m_lastError
!= wxPROTO_NOERR
)
226 if (line
.length() == 0)
229 wxString left_str
= line
.BeforeFirst(':');
230 if(!left_str
.CmpNoCase("Set-Cookie"))
232 wxString cookieName
= line
.AfterFirst(':').Strip(wxString::both
).BeforeFirst('=');
233 wxString cookieValue
= line
.AfterFirst(':').Strip(wxString::both
).AfterFirst('=').BeforeFirst(';');
234 m_cookies
[cookieName
] = cookieValue
;
237 m_headers
[left_str
] = line
.AfterFirst(':').Strip(wxString::both
);
241 m_headers
[left_str
] = line
.AfterFirst(':').Strip(wxString::both
);
247 bool wxHTTP::Connect(const wxString
& host
, unsigned short port
)
257 m_addr
= addr
= new wxIPV4address();
259 if (!addr
->Hostname(host
)) {
262 m_lastError
= wxPROTO_NETERR
;
268 else if (!addr
->Service(wxT("http")))
271 wxString hostHdr
= host
;
272 if ( port
&& port
!= 80 )
273 hostHdr
<< wxT(":") << port
;
274 SetHeader(wxT("Host"), hostHdr
);
276 m_lastError
= wxPROTO_NOERR
;
280 bool wxHTTP::Connect(const wxSockAddress
& addr
, bool WXUNUSED(wait
))
287 m_addr
= addr
.Clone();
289 wxIPV4address
*ipv4addr
= wxDynamicCast(&addr
, wxIPV4address
);
292 wxString hostHdr
= ipv4addr
->OrigHostname();
293 unsigned short port
= ipv4addr
->Service();
294 if ( port
&& port
!= 80 )
295 hostHdr
<< wxT(":") << port
;
296 SetHeader(wxT("Host"), hostHdr
);
299 m_lastError
= wxPROTO_NOERR
;
303 bool wxHTTP::BuildRequest(const wxString
& path
, wxHTTP_Req req
)
305 const wxChar
*request
;
310 request
= wxT("GET");
314 request
= wxT("POST");
315 if ( GetHeader( wxT("Content-Length") ).IsNull() )
316 SetHeader( wxT("Content-Length"), wxString::Format( wxT("%lu"), (unsigned long)m_post_buf
.Len() ) );
325 // If there is no User-Agent defined, define it.
326 if (GetHeader(wxT("User-Agent")).IsNull())
327 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
329 // Send authentication information
330 if (!m_username
.empty() || !m_password
.empty()) {
331 SetHeader(wxT("Authorization"), GenerateAuthString(m_username
, m_password
));
336 // we may use non blocking sockets only if we can dispatch events from them
337 SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
342 buf
.Printf(wxT("%s %s HTTP/1.0\r\n"), request
, path
.c_str());
343 const wxWX2MBbuf pathbuf
= buf
.mb_str();
344 Write(pathbuf
, strlen(pathbuf
));
348 if ( req
== wxHTTP_POST
) {
349 Write(m_post_buf
.mbc_str(), m_post_buf
.Len());
350 m_post_buf
= wxEmptyString
;
354 m_lastError
= ReadLine(this, tmp_str
);
355 if (m_lastError
!= wxPROTO_NOERR
) {
360 if (!tmp_str
.Contains(wxT("HTTP/"))) {
361 // TODO: support HTTP v0.9 which can have no header.
362 // FIXME: tmp_str is not put back in the in-queue of the socket.
363 m_lastError
= wxPROTO_NOERR
;
364 SetHeader(wxT("Content-Length"), wxT("-1"));
365 SetHeader(wxT("Content-Type"), wxT("none/none"));
370 wxStringTokenizer
token(tmp_str
,wxT(' '));
375 tmp_str2
= token
.NextToken();
377 m_http_response
= wxAtoi(tmp_str2
);
379 switch ( tmp_str2
[0u].GetValue() )
382 /* INFORMATION / SUCCESS */
394 m_lastError
= wxPROTO_NOFILE
;
399 m_lastError
= wxPROTO_NOERR
;
400 ret_value
= ParseHeaders();
405 bool wxHTTP::Abort(void)
407 return wxSocketClient::Close();
410 // ----------------------------------------------------------------------------
411 // wxHTTPStream and wxHTTP::GetInputStream
412 // ----------------------------------------------------------------------------
414 class wxHTTPStream
: public wxSocketInputStream
419 unsigned long m_read_bytes
;
421 wxHTTPStream(wxHTTP
*http
) : wxSocketInputStream(*http
), m_http(http
) {}
422 size_t GetSize() const { return m_httpsize
; }
423 virtual ~wxHTTPStream(void) { m_http
->Abort(); }
426 size_t OnSysRead(void *buffer
, size_t bufsize
);
428 wxDECLARE_NO_COPY_CLASS(wxHTTPStream
);
431 size_t wxHTTPStream::OnSysRead(void *buffer
, size_t bufsize
)
433 if (m_read_bytes
>= m_httpsize
)
435 m_lasterror
= wxSTREAM_EOF
;
439 size_t ret
= wxSocketInputStream::OnSysRead(buffer
, bufsize
);
442 if (m_httpsize
==(size_t)-1 && m_lasterror
== wxSTREAM_READ_ERROR
)
444 // if m_httpsize is (size_t) -1 this means read until connection closed
445 // which is equivalent to getting a READ_ERROR, for clients however this
446 // must be translated into EOF, as it is the expected way of signalling
447 // end end of the content
448 m_lasterror
= wxSTREAM_EOF
;
454 wxInputStream
*wxHTTP::GetInputStream(const wxString
& path
)
456 wxHTTPStream
*inp_stream
;
460 m_lastError
= wxPROTO_CONNERR
; // all following returns share this type of error
464 // We set m_connected back to false so wxSocketBase will know what to do.
466 wxSocketClient::Connect(*m_addr
, false );
467 wxSocketClient::WaitOnConnect(10);
469 if (!wxSocketClient::IsConnected())
472 if (!wxProtocol::Connect(*m_addr
))
476 if (!BuildRequest(path
, m_post_buf
.empty() ? wxHTTP_GET
: wxHTTP_POST
))
479 inp_stream
= new wxHTTPStream(this);
481 if (!GetHeader(wxT("Content-Length")).empty())
482 inp_stream
->m_httpsize
= wxAtoi(GetHeader(wxT("Content-Length")));
484 inp_stream
->m_httpsize
= (size_t)-1;
486 inp_stream
->m_read_bytes
= 0;
489 SetFlags(wxSOCKET_BLOCK
| wxSOCKET_WAITALL
);
491 // no error; reset m_lastError
492 m_lastError
= wxPROTO_NOERR
;
496 #endif // wxUSE_PROTOCOL_HTTP