2 // This file is part of the aMule Project.
4 // Copyright (c) 2004-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2004-2008 Angel Vidal ( kry@amule.org )
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
34 #include "ECPacket.h" // Needed for CECPacket
36 #define EC_COMPRESSION_LEVEL Z_BEST_COMPRESSION
37 #define EC_MAX_UNCOMPRESSED 1024
40 #define __attribute__(x)
43 // If your compiler gives errors on these lines, just remove them.
44 int utf8_mbtowc(wchar_t *p
, const unsigned char *s
, int n
) __attribute__((__visibility__("internal")));
45 int utf8_wctomb(unsigned char *s
, wchar_t wc
, int maxlen
) __attribute__((__visibility__("internal")));
46 int utf8_mb_remain(char c
) __attribute__((__pure__
));
48 /*----------=> Import from the Linux kernel <=----------*/
54 * Sample implementation from Unicode home page.
55 * http://www.stonehand.com/unicode/standard/fss-utf.html
65 static struct utf8_table utf8_table
[] =
67 {0x80, 0x00, 0*6, 0x7F, 0, /* 1 byte sequence */},
68 {0xE0, 0xC0, 1*6, 0x7FF, 0x80, /* 2 byte sequence */},
69 {0xF0, 0xE0, 2*6, 0xFFFF, 0x800, /* 3 byte sequence */},
70 {0xF8, 0xF0, 3*6, 0x1FFFFF, 0x10000, /* 4 byte sequence */},
71 {0xFC, 0xF8, 4*6, 0x3FFFFFF, 0x200000, /* 5 byte sequence */},
72 {0xFE, 0xFC, 5*6, 0x7FFFFFFF, 0x4000000, /* 6 byte sequence */},
73 {0, 0, 0, 0, 0, /* end of table */}
76 int utf8_mbtowc(uint32_t *p
, const unsigned char *s
, int n
)
85 for (t
= utf8_table
; t
->cmask
; t
++) {
87 if ((c0
& t
->cmask
) == t
->cval
) {
97 c
= (*s
^ 0x80) & 0xFF;
105 int utf8_wctomb(unsigned char *s
, uint32_t wc
, int maxlen
)
109 struct utf8_table
*t
;
113 for (t
= utf8_table
; t
->cmask
&& maxlen
; t
++, maxlen
--) {
117 *s
= t
->cval
| (l
>> c
);
121 *s
= 0x80 | ((l
>> c
) & 0x3F);
128 /*----------=> End of Import <=----------*/
130 int utf8_mb_remain(char c
)
133 for (i
= 0; i
< 5; ++i
) {
134 if ((c
& utf8_table
[i
].cmask
) == utf8_table
[i
].cval
) break;
140 void CQueuedData::Write(const void *data
, size_t len
)
142 const size_t canWrite
= std::min(GetRemLength(), len
);
143 wxASSERT(len
== canWrite
);
145 memcpy(m_wr_ptr
, data
, canWrite
);
146 m_wr_ptr
+= canWrite
;
150 void CQueuedData::WriteAt(const void *data
, size_t len
, size_t offset
)
152 wxASSERT(len
+ offset
<= m_data
.size());
153 if (offset
> m_data
.size()) {
155 } else if (offset
+ len
> m_data
.size()) {
156 len
= m_data
.size() - offset
;
159 memcpy(&m_data
[0] + offset
, data
, len
);
163 void CQueuedData::Read(void *data
, size_t len
)
165 const size_t canRead
= std::min(GetUnreadDataLength(), len
);
166 wxASSERT(len
== canRead
);
168 memcpy(data
, m_rd_ptr
, canRead
);
173 void CQueuedData::WriteToSocket(CECSocket
*sock
)
175 wxCHECK_RET(m_rd_ptr
< m_wr_ptr
,
176 wxT("Reading past written data in WriteToSocket"));
178 sock
->SocketWrite(m_rd_ptr
, GetUnreadDataLength());
179 m_rd_ptr
+= sock
->GetLastCount();
183 void CQueuedData::ReadFromSocket(CECSocket
*sock
, size_t len
)
185 const size_t canWrite
= std::min(GetRemLength(), len
);
186 wxASSERT(len
== canWrite
);
188 sock
->SocketRead(m_wr_ptr
, canWrite
);
189 m_wr_ptr
+= sock
->GetLastCount();
193 size_t CQueuedData::ReadFromSocketAll(CECSocket
*sock
, size_t len
)
195 size_t read_rem
= std::min(GetRemLength(), len
);
196 wxASSERT(read_rem
== len
);
198 // We get here when socket is truly blocking
200 // Give socket a 10 sec chance to recv more data.
201 if ( !sock
->WaitSocketRead(10, 0) ) {
205 wxASSERT(m_wr_ptr
+ read_rem
<= &m_data
[0] + m_data
.size());
206 sock
->SocketRead(m_wr_ptr
, read_rem
);
207 m_wr_ptr
+= sock
->GetLastCount();
208 read_rem
-= sock
->GetLastCount();
210 if (sock
->SocketError() && !sock
->WouldBlock()) {
215 return len
- read_rem
;
219 size_t CQueuedData::GetLength() const
221 return m_data
.size();
225 size_t CQueuedData::GetDataLength() const
227 const size_t len
= m_wr_ptr
- &m_data
[0];
228 wxCHECK_MSG(len
<= m_data
.size(), m_data
.size(),
229 wxT("Write-pointer past end of buffer"));
235 size_t CQueuedData::GetRemLength() const
237 return m_data
.size() - GetDataLength();
241 size_t CQueuedData::GetUnreadDataLength() const
243 wxCHECK_MSG(m_wr_ptr
>= m_rd_ptr
, 0,
244 wxT("Read position past write position."));
246 return m_wr_ptr
- m_rd_ptr
;
252 // CECSocket API - User interface functions
255 CECSocket::CECSocket(bool use_events
)
257 m_use_events(use_events
),
259 m_in_ptr(EC_SOCKET_BUFFER_SIZE
),
260 m_out_ptr(EC_SOCKET_BUFFER_SIZE
),
261 m_curr_rx_data(new CQueuedData(EC_SOCKET_BUFFER_SIZE
)),
262 m_curr_tx_data(new CQueuedData(EC_SOCKET_BUFFER_SIZE
)),
265 m_my_flags(0x20 | EC_FLAG_ZLIB
| EC_FLAG_UTF8_NUMBERS
| EC_FLAG_ACCEPTS
),
266 // setup initial state: 4 flags + 4 length
273 CECSocket::~CECSocket()
275 while (!m_output_queue
.empty()) {
276 CQueuedData
*data
= m_output_queue
.front();
277 m_output_queue
.pop_front();
282 bool CECSocket::ConnectSocket(uint32_t ip
, uint16_t port
)
285 #if wxCHECK_VERSION(2, 8, 8)
286 res
= InternalConnect(ip
, port
, !m_use_events
);
288 res
= InternalConnect(ip
, port
, false);
289 if ( !m_use_events
) {
290 res
= WaitSocketConnect(10, 0) && InternalIsConnected();
298 return !SocketError() && res
;
301 void CECSocket::SendPacket(const CECPacket
*packet
)
307 const CECPacket
*CECSocket::SendRecvPacket(const CECPacket
*packet
)
310 m_curr_rx_data
->ReadFromSocketAll(this, 2 * sizeof(uint32_t));
311 if (SocketError() && !WouldBlock()) {
316 m_curr_rx_data
->Read(&m_rx_flags
, sizeof(m_rx_flags
));
317 m_rx_flags
= ENDIAN_NTOHL(m_rx_flags
);
318 m_curr_rx_data
->Read(&m_curr_packet_len
, sizeof(m_curr_packet_len
));
319 m_curr_packet_len
= ENDIAN_NTOHL(m_curr_packet_len
);
321 if ( m_curr_rx_data
->GetLength() < (m_curr_packet_len
+2*sizeof(uint32_t)) ) {
322 m_curr_rx_data
.reset(new CQueuedData(m_curr_packet_len
));
324 m_curr_rx_data
->ReadFromSocketAll(this, m_curr_packet_len
);
325 if (SocketError() && !WouldBlock()) {
329 const CECPacket
*reply
= ReadPacket();
330 m_curr_rx_data
->Rewind();
334 std::string
CECSocket::GetLastErrorMsg()
336 int code
= InternalGetLastError();
338 case EC_ERROR_NOERROR
:
339 return "No error happened";
341 return "Invalid operation";
343 return "Input/Output error";
344 case EC_ERROR_INVADDR
:
345 return "Invalid address passed to wxSocket";
346 case EC_ERROR_INVSOCK
:
347 return "Invalid socket (uninitialized)";
348 case EC_ERROR_NOHOST
:
349 return "No corresponding host";
350 case EC_ERROR_INVPORT
:
351 return "Invalid port";
352 case EC_ERROR_WOULDBLOCK
:
353 return "The socket is non-blocking and the operation would block";
354 case EC_ERROR_TIMEDOUT
:
355 return "The timeout for this operation expired";
356 case EC_ERROR_MEMERR
:
357 return "Memory exhausted";
359 return "Dummy code - should not happen";
361 ostringstream error_string
;
362 error_string
<< "Error code " << code
<< " unknown.";
363 return error_string
.str();
366 void CECSocket::OnError()
369 cout
<< GetLastErrorMsg() << endl
;
373 void CECSocket::OnLost()
380 void CECSocket::OnConnect()
384 void CECSocket::OnInput()
388 if (m_curr_rx_data
.get()) {
389 m_curr_rx_data
->ReadFromSocket(this, m_bytes_needed
);
393 if (SocketError() && !WouldBlock()) {
395 // socket already disconnected in this point
396 m_curr_rx_data
.reset(0);
399 bytes_rx
= GetLastCount();
400 m_bytes_needed
-= bytes_rx
;
401 } while (m_bytes_needed
&& bytes_rx
);
403 if (!m_bytes_needed
) {
406 m_curr_rx_data
->Read(&m_rx_flags
, sizeof(m_rx_flags
));
407 m_rx_flags
= ENDIAN_NTOHL(m_rx_flags
);
408 if (m_rx_flags
& EC_FLAG_ACCEPTS
) {
409 // Client sends its capabilities, update the internal mask.
410 m_curr_rx_data
->Read(&m_my_flags
, sizeof(m_my_flags
));
411 m_my_flags
= ENDIAN_NTOHL(m_my_flags
);
412 //printf("Reading accepts mask: %x\n", m_my_flags);
413 wxASSERT(m_my_flags
& 0x20);
414 // There has to be 4 more bytes. THERE HAS TO BE, DAMN IT.
415 m_curr_rx_data
->ReadFromSocketAll(this, sizeof(m_curr_packet_len
));
417 m_curr_rx_data
->Read(&m_curr_packet_len
, sizeof(m_curr_packet_len
));
418 m_curr_packet_len
= ENDIAN_NTOHL(m_curr_packet_len
);
419 m_bytes_needed
= m_curr_packet_len
;
420 // packet bigger that 16Mb looks more like broken request
421 if (m_bytes_needed
> 16*1024*1024) {
425 size_t needed_size
= m_bytes_needed
+ ((m_rx_flags
& EC_FLAG_ACCEPTS
) ? 12 : 8);
426 if (!m_curr_rx_data
.get() ||
427 m_curr_rx_data
->GetLength() < needed_size
) {
428 m_curr_rx_data
.reset(new CQueuedData(needed_size
));
430 //#warning Kry TODO: Read packet?
432 //m_curr_rx_data->DumpMem();
433 std::auto_ptr
<const CECPacket
> packet(ReadPacket());
434 m_curr_rx_data
->Rewind();
436 std::auto_ptr
<const CECPacket
> reply(OnPacketReceived(packet
.get()));
438 SendPacket(reply
.get());
447 void CECSocket::OnOutput()
449 while (!m_output_queue
.empty()) {
450 CQueuedData
* data
= m_output_queue
.front();
451 data
->WriteToSocket(this);
452 if (!data
->GetUnreadDataLength()) {
453 m_output_queue
.pop_front();
458 if ( m_use_events
) {
461 if ( !WaitSocketWrite(10, 0) ) {
477 // All outstanding data sent to socket
479 WriteDoneAndQueueEmpty();
482 bool CECSocket::DataPending()
484 return !m_output_queue
.empty();
491 size_t CECSocket::ReadBufferFromSocket(void *buffer
, size_t required_len
)
493 wxASSERT(required_len
);
495 if (m_curr_rx_data
->GetUnreadDataLength() < required_len
) {
496 // need more data that we have. Looks like nothing will help here
499 m_curr_rx_data
->Read(buffer
, required_len
);
503 void CECSocket::WriteBufferToSocket(const void *buffer
, size_t len
)
505 unsigned char *wr_ptr
= (unsigned char *)buffer
;
507 size_t curr_free
= m_curr_tx_data
->GetRemLength();
508 if ( len
> curr_free
) {
510 m_curr_tx_data
->Write(wr_ptr
, curr_free
);
513 m_output_queue
.push_back(m_curr_tx_data
.release());
514 m_curr_tx_data
.reset(new CQueuedData(EC_SOCKET_BUFFER_SIZE
));
516 m_curr_tx_data
->Write(wr_ptr
, len
);
524 // ZLib "error handler"
527 void ShowZError(int zerror
, z_streamp strm
)
529 const char *p
= NULL
;
532 case Z_STREAM_END
: p
= "Z_STREAM_END"; break;
533 case Z_NEED_DICT
: p
= "Z_NEED_DICT"; break;
534 case Z_ERRNO
: p
= "Z_ERRNO"; break;
535 case Z_STREAM_ERROR
: p
= "Z_STREAM_ERROR"; break;
536 case Z_DATA_ERROR
: p
= "Z_DATA_ERROR"; break;
537 case Z_MEM_ERROR
: p
= "Z_MEM_ERROR"; break;
538 case Z_BUF_ERROR
: p
= "Z_BUF_ERROR"; break;
539 case Z_VERSION_ERROR
: p
= "Z_VERSION_ERROR"; break;
541 printf("ZLib operation returned %s\n", p
);
542 printf("ZLib error message: %s\n", strm
->msg
);
543 printf("zstream state:\n\tnext_in=%p\n\tavail_in=%u\n\ttotal_in=%lu\n\tnext_out=%p\n\tavail_out=%u\n\ttotal_out=%lu\n",
544 strm
->next_in
, strm
->avail_in
, strm
->total_in
, strm
->next_out
, strm
->avail_out
, strm
->total_out
);
548 bool CECSocket::ReadNumber(void *buffer
, size_t len
)
550 if (m_rx_flags
& EC_FLAG_UTF8_NUMBERS
) {
553 if (!ReadBuffer(mb
, 1)) return false;
554 int remains
= utf8_mb_remain(mb
[0]);
555 if (remains
) if (!ReadBuffer(&(mb
[1]), remains
)) return false;
556 if (utf8_mbtowc(&wc
, mb
, 6) == -1) return false; // Invalid UTF-8 code sequence
558 case 1: PokeUInt8( buffer
, wc
); break;
559 case 2: RawPokeUInt16( buffer
, wc
); break;
560 case 4: RawPokeUInt32( buffer
, wc
); break;
563 if ( !ReadBuffer(buffer
, len
) ) {
568 RawPokeUInt16( buffer
, ENDIAN_NTOHS( RawPeekUInt16( buffer
) ) );
571 RawPokeUInt32( buffer
, ENDIAN_NTOHL( RawPeekUInt32( buffer
) ) );
578 bool CECSocket::WriteNumber(const void *buffer
, size_t len
)
580 if (m_tx_flags
& EC_FLAG_UTF8_NUMBERS
) {
585 case 1: wc
= PeekUInt8( buffer
); break;
586 case 2: wc
= RawPeekUInt16( buffer
); break;
587 case 4: wc
= RawPeekUInt32( buffer
); break;
588 default: return false;
590 if ((mb_len
= utf8_wctomb(mb
, wc
, 6)) == -1) return false; // Something is terribly wrong...
591 return WriteBuffer(mb
, mb_len
);
596 case 1: PokeUInt8( tmp
, PeekUInt8( buffer
) ); break;
597 case 2: RawPokeUInt16( tmp
, ENDIAN_NTOHS( RawPeekUInt16( buffer
) ) ); break;
598 case 4: RawPokeUInt32( tmp
, ENDIAN_NTOHL( RawPeekUInt32( buffer
) ) ); break;
600 return WriteBuffer(tmp
, len
);
604 bool CECSocket::ReadBuffer(void *buffer
, size_t len
)
606 if (m_rx_flags
& EC_FLAG_ZLIB
) {
607 if ( !m_z
.avail_in
) {
608 // no reason for this situation: all packet should be
612 m_z
.avail_out
= (uInt
)len
;
613 m_z
.next_out
= (Bytef
*)buffer
;
614 int zerror
= inflate(&m_z
, Z_SYNC_FLUSH
);
615 if ((zerror
!= Z_OK
) && (zerror
!= Z_STREAM_END
)) {
616 ShowZError(zerror
, &m_z
);
621 // using uncompressed buffered i/o
622 return ReadBufferFromSocket(buffer
, len
) == len
;
626 bool CECSocket::WriteBuffer(const void *buffer
, size_t len
)
628 if (m_tx_flags
& EC_FLAG_ZLIB
) {
630 unsigned char *rd_ptr
= (unsigned char *)buffer
;
632 unsigned int remain_in
= EC_SOCKET_BUFFER_SIZE
- m_z
.avail_in
;
633 if ( remain_in
>= len
) {
634 memcpy(m_z
.next_in
+m_z
.avail_in
, rd_ptr
, len
);
635 m_z
.avail_in
+= (uInt
)len
;
638 memcpy(m_z
.next_in
+m_z
.avail_in
, rd_ptr
, remain_in
);
639 m_z
.avail_in
+= remain_in
;
642 // buffer is full, calling zlib
644 m_z
.next_out
= &m_out_ptr
[0];
645 m_z
.avail_out
= EC_SOCKET_BUFFER_SIZE
;
646 int zerror
= deflate(&m_z
, Z_NO_FLUSH
);
647 if ( zerror
!= Z_OK
) {
648 ShowZError(zerror
, &m_z
);
651 WriteBufferToSocket(&m_out_ptr
[0],
652 EC_SOCKET_BUFFER_SIZE
- m_z
.avail_out
);
653 } while ( m_z
.avail_out
== 0 );
654 // all input should be used by now
655 wxASSERT(m_z
.avail_in
== 0);
656 m_z
.next_in
= &m_in_ptr
[0];
661 // using uncompressed buffered i/o
662 WriteBufferToSocket(buffer
, len
);
667 bool CECSocket::FlushBuffers()
669 if (m_tx_flags
& EC_FLAG_ZLIB
) {
671 m_z
.next_out
= &m_out_ptr
[0];
672 m_z
.avail_out
= EC_SOCKET_BUFFER_SIZE
;
673 int zerror
= deflate(&m_z
, Z_FINISH
);
674 if ( zerror
== Z_STREAM_ERROR
) {
675 ShowZError(zerror
, &m_z
);
678 WriteBufferToSocket(&m_out_ptr
[0],
679 EC_SOCKET_BUFFER_SIZE
- m_z
.avail_out
);
680 } while ( m_z
.avail_out
== 0 );
682 if ( m_curr_tx_data
->GetDataLength() ) {
683 m_output_queue
.push_back(m_curr_tx_data
.release());
684 m_curr_tx_data
.reset(new CQueuedData(EC_SOCKET_BUFFER_SIZE
));
693 void CECSocket::WritePacket(const CECPacket
*packet
)
695 if (SocketError() && !WouldBlock()) {
700 uint32_t flags
= 0x20;
702 if ( packet
->GetPacketLength() > EC_MAX_UNCOMPRESSED
) {
703 flags
|= EC_FLAG_ZLIB
;
705 flags
|= EC_FLAG_UTF8_NUMBERS
;
711 if (flags
& EC_FLAG_ZLIB
) {
716 m_z
.next_in
= &m_in_ptr
[0];
717 int zerror
= deflateInit(&m_z
, EC_COMPRESSION_LEVEL
);
718 if (zerror
!= Z_OK
) {
719 // don't use zlib if init failed
720 flags
&= ~EC_FLAG_ZLIB
;
721 ShowZError(zerror
, &m_z
);
725 uint32_t tmp_flags
= ENDIAN_HTONL(flags
/* | EC_FLAG_ACCEPTS*/);
726 WriteBufferToSocket(&tmp_flags
, sizeof(uint32
));
728 /* uint32_t tmp_accepts_flags = ENDIAN_HTONL(m_my_flags);
729 WriteBufferToSocket(&tmp_accepts_flags, sizeof(uint32));*/
731 // preallocate 4 bytes in buffer for packet length
732 uint32_t packet_len
= 0;
733 WriteBufferToSocket(&packet_len
, sizeof(uint32
));
735 packet
->WritePacket(*this);
739 // now calculate actual size of data
740 wxASSERT(m_curr_tx_data
->GetDataLength() < 0xFFFFFFFF);
741 packet_len
= (uint32_t)m_curr_tx_data
->GetDataLength();
742 for(std::deque
<CQueuedData
*>::iterator i
= m_output_queue
.begin(); i
!= m_output_queue
.end(); i
++) {
743 wxASSERT(( packet_len
+ m_curr_tx_data
->GetDataLength()) < 0xFFFFFFFF);
744 packet_len
+= (uint32_t)(*i
)->GetDataLength();
746 // 4 flags and 4 length are not counted
748 // now write actual length @ offset 4
749 packet_len
= ENDIAN_HTONL(packet_len
);
751 CQueuedData
*first_buff
= m_output_queue
.front();
752 if ( !first_buff
) first_buff
= m_curr_tx_data
.get();
753 first_buff
->WriteAt(&packet_len
, sizeof(uint32_t), sizeof(uint32_t));
755 if (flags
& EC_FLAG_ZLIB
) {
756 int zerror
= deflateEnd(&m_z
);
757 if ( zerror
!= Z_OK
) {
758 ShowZError(zerror
, &m_z
);
765 const CECPacket
*CECSocket::ReadPacket()
767 CECPacket
*packet
= 0;
769 uint32_t flags
= m_rx_flags
;
771 if ( ((flags
& 0x60) != 0x20) || (flags
& EC_FLAG_UNKNOWN_MASK
) ) {
772 // Protocol error - other end might use an older protocol
773 cout
<< "ReadPacket: packet have invalid flags " << flags
<< endl
;
778 if (flags
& EC_FLAG_ZLIB
) {
786 int zerror
= inflateInit(&m_z
);
787 if (zerror
!= Z_OK
) {
788 ShowZError(zerror
, &m_z
);
789 cout
<< "ReadPacket: failed zlib init" << endl
;
795 m_curr_rx_data
->ToZlib(m_z
);
796 packet
= new CECPacket(*this);
797 packet
->ReadFromSocket(*this);
799 if (packet
->m_error
!= 0) {
800 cout
<< "ReadPacket: error " << packet
->m_error
<< "in packet read" << endl
;
806 if (flags
& EC_FLAG_ZLIB
) {
807 int zerror
= inflateEnd(&m_z
);
808 if ( zerror
!= Z_OK
) {
809 ShowZError(zerror
, &m_z
);
810 cout
<< "ReadPacket: failed zlib free" << endl
;
818 const CECPacket
*CECSocket::OnPacketReceived(const CECPacket
*)
822 // File_checked_for_headers