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
7 // Copyright: (c) 1997, 1998 Guilhem Lavaux
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
18 #if wxUSE_PROTOCOL_HTTP
24 #include "wx/string.h"
28 #include "wx/tokenzr.h"
29 #include "wx/socket.h"
30 #include "wx/protocol/protocol.h"
32 #include "wx/protocol/http.h"
33 #include "wx/sckstrm.h"
34 #include "wx/thread.h"
37 // ----------------------------------------------------------------------------
39 // ----------------------------------------------------------------------------
41 IMPLEMENT_DYNAMIC_CLASS(wxHTTP
, wxProtocol
)
42 IMPLEMENT_PROTOCOL(wxHTTP
, wxT("http"), wxT("80"), true)
52 SetNotify(wxSOCKET_LOST_FLAG
);
62 void wxHTTP::ClearHeaders()
67 void wxHTTP::ClearCookies()
72 wxString
wxHTTP::GetContentType() const
74 return GetHeader(wxT("Content-Type"));
77 void wxHTTP::SetProxyMode(bool on
)
82 wxHTTP::wxHeaderIterator
wxHTTP::FindHeader(const wxString
& header
)
84 wxHeaderIterator it
= m_headers
.begin();
85 for ( wxHeaderIterator en
= m_headers
.end(); it
!= en
; ++it
)
87 if ( header
.CmpNoCase(it
->first
) == 0 )
94 wxHTTP::wxHeaderConstIterator
wxHTTP::FindHeader(const wxString
& header
) const
96 wxHeaderConstIterator it
= m_headers
.begin();
97 for ( wxHeaderConstIterator en
= m_headers
.end(); it
!= en
; ++it
)
99 if ( header
.CmpNoCase(it
->first
) == 0 )
106 wxHTTP::wxCookieIterator
wxHTTP::FindCookie(const wxString
& cookie
)
108 wxCookieIterator it
= m_cookies
.begin();
109 for ( wxCookieIterator en
= m_cookies
.end(); it
!= en
; ++it
)
111 if ( cookie
.CmpNoCase(it
->first
) == 0 )
118 wxHTTP::wxCookieConstIterator
wxHTTP::FindCookie(const wxString
& cookie
) const
120 wxCookieConstIterator it
= m_cookies
.begin();
121 for ( wxCookieConstIterator en
= m_cookies
.end(); it
!= en
; ++it
)
123 if ( cookie
.CmpNoCase(it
->first
) == 0 )
130 void wxHTTP::SetHeader(const wxString
& header
, const wxString
& h_data
)
137 wxHeaderIterator it
= FindHeader(header
);
138 if (it
!= m_headers
.end())
141 m_headers
[header
] = h_data
;
144 wxString
wxHTTP::GetHeader(const wxString
& header
) const
146 wxHeaderConstIterator it
= FindHeader(header
);
148 return it
== m_headers
.end() ? wxGetEmptyString() : it
->second
;
151 wxString
wxHTTP::GetCookie(const wxString
& cookie
) const
153 wxCookieConstIterator it
= FindCookie(cookie
);
155 return it
== m_cookies
.end() ? wxGetEmptyString() : it
->second
;
158 wxString
wxHTTP::GenerateAuthString(const wxString
& user
, const wxString
& pass
) const
160 // TODO: Use wxBase64Encode() now that we have it instead of reproducing it
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 // Use To8BitData() for backwards compatibility in this deprecated method.
195 // The new code should use the other overload or SetPostText() and specify
196 // the encoding to use for the text explicitly.
197 wxScopedCharBuffer scb
= post_buf
.To8BitData();
200 m_postBuffer
.Clear();
201 m_postBuffer
.AppendData(scb
.data(), scb
.length());
206 wxHTTP::SetPostBuffer(const wxString
& contentType
,
207 const wxMemoryBuffer
& data
)
210 m_contentType
= contentType
;
212 return !m_postBuffer
.IsEmpty();
216 wxHTTP::SetPostText(const wxString
& contentType
,
217 const wxString
& data
,
218 const wxMBConv
& conv
)
221 wxScopedCharBuffer scb
= data
.mb_str(conv
);
222 const size_t len
= scb
.length();
223 const char* const buf
= scb
.data();
224 #else // !wxUSE_UNICODE
225 const size_t len
= data
.length();
226 const char* const buf
= data
.mb_str(conv
);
227 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
232 m_postBuffer
.Clear();
233 m_postBuffer
.AppendData(buf
, len
);
234 m_contentType
= contentType
;
239 void wxHTTP::SendHeaders()
241 typedef wxStringToStringHashMap::iterator iterator
;
244 for (iterator it
= m_headers
.begin(), en
= m_headers
.end(); it
!= en
; ++it
)
246 buf
.Printf(wxT("%s: %s\r\n"), it
->first
.c_str(), it
->second
.c_str());
248 const wxWX2MBbuf cbuf
= buf
.mb_str();
249 Write(cbuf
, strlen(cbuf
));
253 bool wxHTTP::ParseHeaders()
256 wxStringTokenizer tokenzr
;
264 m_lastError
= ReadLine(this, line
);
265 if (m_lastError
!= wxPROTO_NOERR
)
271 wxString left_str
= line
.BeforeFirst(':');
272 if(!left_str
.CmpNoCase("Set-Cookie"))
274 wxString cookieName
= line
.AfterFirst(':').Strip(wxString::both
).BeforeFirst('=');
275 wxString cookieValue
= line
.AfterFirst(':').Strip(wxString::both
).AfterFirst('=').BeforeFirst(';');
276 m_cookies
[cookieName
] = cookieValue
;
279 m_headers
[left_str
] = line
.AfterFirst(':').Strip(wxString::both
);
283 m_headers
[left_str
] = line
.AfterFirst(':').Strip(wxString::both
);
289 bool wxHTTP::Connect(const wxString
& host
, unsigned short port
)
298 m_addr
= addr
= new wxIPV4address();
300 if (!addr
->Hostname(host
)) {
302 m_lastError
= wxPROTO_NETERR
;
308 else if (!addr
->Service(wxT("http")))
311 wxString hostHdr
= host
;
312 if ( port
&& port
!= 80 )
313 hostHdr
<< wxT(":") << port
;
314 SetHeader(wxT("Host"), hostHdr
);
316 m_lastError
= wxPROTO_NOERR
;
320 bool wxHTTP::Connect(const wxSockAddress
& addr
, bool WXUNUSED(wait
))
327 m_addr
= addr
.Clone();
329 wxIPV4address
*ipv4addr
= wxDynamicCast(&addr
, wxIPV4address
);
332 wxString hostHdr
= ipv4addr
->OrigHostname();
333 unsigned short port
= ipv4addr
->Service();
334 if ( port
&& port
!= 80 )
335 hostHdr
<< wxT(":") << port
;
336 SetHeader(wxT("Host"), hostHdr
);
339 m_lastError
= wxPROTO_NOERR
;
343 bool wxHTTP::BuildRequest(const wxString
& path
, const wxString
& method
)
345 // Use the data in the post buffer, if any.
346 if ( !m_postBuffer
.IsEmpty() )
349 len
<< m_postBuffer
.GetDataLen();
351 // Content length must be correct, so always set, possibly
352 // overriding the value set explicitly by a previous call to
353 // SetHeader("Content-Length").
354 SetHeader(wxS("Content-Length"), len
);
356 // However if the user had explicitly set the content type, don't
357 // override it with the content type passed to SetPostText().
358 if ( !m_contentType
.empty() && GetContentType().empty() )
359 SetHeader(wxS("Content-Type"), m_contentType
);
364 // If there is no User-Agent defined, define it.
365 if ( GetHeader(wxT("User-Agent")).empty() )
366 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
368 // Send authentication information
369 if (!m_username
.empty() || !m_password
.empty()) {
370 SetHeader(wxT("Authorization"), GenerateAuthString(m_username
, m_password
));
375 // we may use non blocking sockets only if we can dispatch events from them
376 int flags
= wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
378 // and we must use wxSOCKET_WAITALL to ensure that all data is sent
379 flags
|= wxSOCKET_WAITALL
;
384 buf
.Printf(wxT("%s %s HTTP/1.0\r\n"), method
, path
);
385 const wxWX2MBbuf pathbuf
= buf
.mb_str();
386 Write(pathbuf
, strlen(pathbuf
));
390 if ( !m_postBuffer
.IsEmpty() ) {
391 Write(m_postBuffer
.GetData(), m_postBuffer
.GetDataLen());
393 m_postBuffer
.Clear();
397 m_lastError
= ReadLine(this, tmp_str
);
398 if (m_lastError
!= wxPROTO_NOERR
) {
403 if (!tmp_str
.Contains(wxT("HTTP/"))) {
404 // TODO: support HTTP v0.9 which can have no header.
405 // FIXME: tmp_str is not put back in the in-queue of the socket.
406 m_lastError
= wxPROTO_NOERR
;
407 SetHeader(wxT("Content-Length"), wxT("-1"));
408 SetHeader(wxT("Content-Type"), wxT("none/none"));
413 wxStringTokenizer
token(tmp_str
,wxT(' '));
418 tmp_str2
= token
.NextToken();
420 m_http_response
= wxAtoi(tmp_str2
);
422 switch ( tmp_str2
[0u].GetValue() )
425 /* INFORMATION / SUCCESS */
437 m_lastError
= wxPROTO_NOFILE
;
442 m_lastError
= wxPROTO_NOERR
;
443 ret_value
= ParseHeaders();
448 bool wxHTTP::Abort(void)
450 return wxSocketClient::Close();
453 // ----------------------------------------------------------------------------
454 // wxHTTPStream and wxHTTP::GetInputStream
455 // ----------------------------------------------------------------------------
457 class wxHTTPStream
: public wxSocketInputStream
462 unsigned long m_read_bytes
;
464 wxHTTPStream(wxHTTP
*http
) : wxSocketInputStream(*http
)
471 size_t GetSize() const { return m_httpsize
; }
472 virtual ~wxHTTPStream(void) { m_http
->Abort(); }
475 size_t OnSysRead(void *buffer
, size_t bufsize
);
477 wxDECLARE_NO_COPY_CLASS(wxHTTPStream
);
480 size_t wxHTTPStream::OnSysRead(void *buffer
, size_t bufsize
)
482 if (m_read_bytes
>= m_httpsize
)
484 m_lasterror
= wxSTREAM_EOF
;
488 size_t ret
= wxSocketInputStream::OnSysRead(buffer
, bufsize
);
491 if (m_httpsize
==(size_t)-1 && m_lasterror
== wxSTREAM_READ_ERROR
)
493 // if m_httpsize is (size_t) -1 this means read until connection closed
494 // which is equivalent to getting a READ_ERROR, for clients however this
495 // must be translated into EOF, as it is the expected way of signalling
496 // end end of the content
497 m_lasterror
= wxSTREAM_EOF
;
503 wxInputStream
*wxHTTP::GetInputStream(const wxString
& path
)
505 wxHTTPStream
*inp_stream
;
509 m_lastError
= wxPROTO_CONNERR
; // all following returns share this type of error
513 // We set m_connected back to false so wxSocketBase will know what to do.
515 wxSocketClient::Connect(*m_addr
, false );
516 wxSocketClient::WaitOnConnect(10);
518 if (!wxSocketClient::IsConnected())
521 if (!wxProtocol::Connect(*m_addr
))
525 // Use the user-specified method if any or determine the method to use
526 // automatically depending on whether we have anything to post or not.
527 wxString method
= m_method
;
529 method
= m_postBuffer
.IsEmpty() ? wxS("GET"): wxS("POST");
531 if (!BuildRequest(path
, method
))
534 inp_stream
= new wxHTTPStream(this);
536 if (!GetHeader(wxT("Content-Length")).empty())
537 inp_stream
->m_httpsize
= wxAtoi(GetHeader(wxT("Content-Length")));
539 inp_stream
->m_httpsize
= (size_t)-1;
541 inp_stream
->m_read_bytes
= 0;
544 SetFlags(wxSOCKET_BLOCK
| wxSOCKET_WAITALL
);
546 // no error; reset m_lastError
547 m_lastError
= wxPROTO_NOERR
;
551 #endif // wxUSE_PROTOCOL_HTTP