Upstream tarball 20080912
[amule.git] / src / libs / ec / cpp / ECSocket.cpp
blob1f8566ec8d0e67cce078f3bc9bb7117cbd2fc5a9
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2004-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2004-2008 Angel Vidal ( kry@amule.org )
6 //
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
9 // respective authors.
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.
20 //
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
26 #include "ECSocket.h"
28 #include <sstream>
29 #include <iostream>
30 #include <algorithm>
32 using namespace std;
34 #include "ECPacket.h" // Needed for CECPacket
36 #define EC_COMPRESSION_LEVEL Z_BEST_COMPRESSION
37 #define EC_MAX_UNCOMPRESSED 1024
39 #ifndef __GNUC__
40 #define __attribute__(x)
41 #endif
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 <=----------*/
50 * linux/fs/nls_base.c
54 * Sample implementation from Unicode home page.
55 * http://www.stonehand.com/unicode/standard/fss-utf.html
57 struct utf8_table {
58 int cmask;
59 int cval;
60 int shift;
61 uint32_t lmask;
62 uint32_t lval;
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)
78 uint32_t l;
79 int c0, c, nc;
80 struct utf8_table *t;
82 nc = 0;
83 c0 = *s;
84 l = c0;
85 for (t = utf8_table; t->cmask; t++) {
86 nc++;
87 if ((c0 & t->cmask) == t->cval) {
88 l &= t->lmask;
89 if (l < t->lval)
90 return -1;
91 *p = l;
92 return nc;
94 if (n <= nc)
95 return -1;
96 s++;
97 c = (*s ^ 0x80) & 0xFF;
98 if (c & 0xC0)
99 return -1;
100 l = (l << 6) | c;
102 return -1;
105 int utf8_wctomb(unsigned char *s, uint32_t wc, int maxlen)
107 uint32_t l;
108 int c, nc;
109 struct utf8_table *t;
111 l = wc;
112 nc = 0;
113 for (t = utf8_table; t->cmask && maxlen; t++, maxlen--) {
114 nc++;
115 if (l <= t->lmask) {
116 c = t->shift;
117 *s = t->cval | (l >> c);
118 while (c > 0) {
119 c -= 6;
120 s++;
121 *s = 0x80 | ((l >> c) & 0x3F);
123 return nc;
126 return -1;
128 /*----------=> End of Import <=----------*/
130 int utf8_mb_remain(char c)
132 int i;
133 for (i = 0; i < 5; ++i) {
134 if ((c & utf8_table[i].cmask) == utf8_table[i].cval) break;
136 return i;
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()) {
154 return;
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);
169 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
199 do {
200 // Give socket a 10 sec chance to recv more data.
201 if ( !sock->WaitSocketRead(10, 0) ) {
202 break;
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()) {
211 break;
213 } while (read_rem);
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"));
231 return len;
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),
258 m_output_queue(),
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)),
263 m_rx_flags(0),
264 m_tx_flags(0),
265 m_my_flags(0x20 | EC_FLAG_ZLIB | EC_FLAG_UTF8_NUMBERS | EC_FLAG_ACCEPTS),
266 // setup initial state: 4 flags + 4 length
267 m_bytes_needed(8),
268 m_in_header(true)
273 CECSocket::~CECSocket()
275 while (!m_output_queue.empty()) {
276 CQueuedData *data = m_output_queue.front();
277 m_output_queue.pop_front();
278 delete data;
282 bool CECSocket::ConnectSocket(uint32_t ip, uint16_t port)
284 bool res;
285 #if wxCHECK_VERSION(2, 8, 8)
286 res = InternalConnect(ip, port, !m_use_events);
287 #else
288 res = InternalConnect(ip, port, false);
289 if ( !m_use_events ) {
290 res = WaitSocketConnect(10, 0) && InternalIsConnected();
291 if ( res ) {
292 OnConnect();
293 } else {
294 OnLost();
297 #endif
298 return !SocketError() && res;
301 void CECSocket::SendPacket(const CECPacket *packet)
303 WritePacket(packet);
304 OnOutput();
307 const CECPacket *CECSocket::SendRecvPacket(const CECPacket *packet)
309 SendPacket(packet);
310 m_curr_rx_data->ReadFromSocketAll(this, 2 * sizeof(uint32_t));
311 if (SocketError() && !WouldBlock()) {
312 OnError();
313 return 0;
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()) {
326 OnError();
327 return 0;
329 const CECPacket *reply = ReadPacket();
330 m_curr_rx_data->Rewind();
331 return reply;
334 std::string CECSocket::GetLastErrorMsg()
336 int code = InternalGetLastError();
337 switch(code) {
338 case EC_ERROR_NOERROR:
339 return "No error happened";
340 case EC_ERROR_INVOP:
341 return "Invalid operation";
342 case EC_ERROR_IOERR:
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";
358 case EC_ERROR_DUMMY:
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()
368 #ifdef __DEBUG__
369 cout << GetLastErrorMsg() << endl;
370 #endif
373 void CECSocket::OnLost()
378 // Event handlers
380 void CECSocket::OnConnect()
384 void CECSocket::OnInput()
386 size_t bytes_rx = 0;
387 do {
388 if (m_curr_rx_data.get()) {
389 m_curr_rx_data->ReadFromSocket(this, m_bytes_needed);
390 } else {
391 return;
393 if (SocketError() && !WouldBlock()) {
394 OnError();
395 // socket already disconnected in this point
396 m_curr_rx_data.reset(0);
397 return;
399 bytes_rx = GetLastCount();
400 m_bytes_needed -= bytes_rx;
401 } while (m_bytes_needed && bytes_rx);
403 if (!m_bytes_needed) {
404 if (m_in_header) {
405 m_in_header = false;
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) {
422 CloseSocket();
423 return;
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?
431 } else {
432 //m_curr_rx_data->DumpMem();
433 std::auto_ptr<const CECPacket> packet(ReadPacket());
434 m_curr_rx_data->Rewind();
435 if (packet.get()) {
436 std::auto_ptr<const CECPacket> reply(OnPacketReceived(packet.get()));
437 if (reply.get()) {
438 SendPacket(reply.get());
441 m_bytes_needed = 8;
442 m_in_header = true;
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();
454 delete data;
456 if (SocketError()) {
457 if (WouldBlock()) {
458 if ( m_use_events ) {
459 return;
460 } else {
461 if ( !WaitSocketWrite(10, 0) ) {
462 if (WouldBlock()) {
463 continue;
464 } else {
465 OnError();
466 break;
470 } else {
471 OnError();
472 return;
477 // All outstanding data sent to socket
479 WriteDoneAndQueueEmpty();
482 bool CECSocket::DataPending()
484 return !m_output_queue.empty();
488 // Socket I/O
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
497 return 0;
499 m_curr_rx_data->Read(buffer, required_len);
500 return required_len;
503 void CECSocket::WriteBufferToSocket(const void *buffer, size_t len)
505 unsigned char *wr_ptr = (unsigned char *)buffer;
506 while ( len ) {
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);
511 len -= curr_free;
512 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));
515 } else {
516 m_curr_tx_data->Write(wr_ptr, len);
517 break;
524 // ZLib "error handler"
527 void ShowZError(int zerror, z_streamp strm)
529 const char *p = NULL;
531 switch (zerror) {
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) {
551 unsigned char mb[6];
552 uint32_t wc;
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
557 switch (len) {
558 case 1: PokeUInt8( buffer, wc ); break;
559 case 2: RawPokeUInt16( buffer, wc ); break;
560 case 4: RawPokeUInt32( buffer, wc ); break;
562 } else {
563 if ( !ReadBuffer(buffer, len) ) {
564 return false;
566 switch (len) {
567 case 2:
568 RawPokeUInt16( buffer, ENDIAN_NTOHS( RawPeekUInt16( buffer ) ) );
569 break;
570 case 4:
571 RawPokeUInt32( buffer, ENDIAN_NTOHL( RawPeekUInt32( buffer ) ) );
572 break;
575 return true;
578 bool CECSocket::WriteNumber(const void *buffer, size_t len)
580 if (m_tx_flags & EC_FLAG_UTF8_NUMBERS) {
581 unsigned char mb[6];
582 uint32_t wc = 0;
583 int mb_len;
584 switch (len) {
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);
592 } else {
593 char tmp[8];
595 switch (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
609 // buffered by now
610 return false;
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);
617 return false;
619 return true;
620 } else {
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;
631 do {
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;
636 len = 0;
637 } else {
638 memcpy(m_z.next_in+m_z.avail_in, rd_ptr, remain_in);
639 m_z.avail_in += remain_in;
640 len -= remain_in;
641 rd_ptr += remain_in;
642 // buffer is full, calling zlib
643 do {
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);
649 return false;
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];
658 } while ( len );
659 return true;
660 } else {
661 // using uncompressed buffered i/o
662 WriteBufferToSocket(buffer, len);
663 return true;
667 bool CECSocket::FlushBuffers()
669 if (m_tx_flags & EC_FLAG_ZLIB) {
670 do {
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);
676 return false;
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));
686 return true;
690 // Packet I/O
693 void CECSocket::WritePacket(const CECPacket *packet)
695 if (SocketError() && !WouldBlock()) {
696 OnError();
697 return;
700 uint32_t flags = 0x20;
702 if ( packet->GetPacketLength() > EC_MAX_UNCOMPRESSED ) {
703 flags |= EC_FLAG_ZLIB;
704 } else {
705 flags |= EC_FLAG_UTF8_NUMBERS;
708 flags &= m_my_flags;
709 m_tx_flags = flags;
711 if (flags & EC_FLAG_ZLIB) {
712 m_z.zalloc = Z_NULL;
713 m_z.zfree = Z_NULL;
714 m_z.opaque = Z_NULL;
715 m_z.avail_in = 0;
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);
737 FlushBuffers();
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
747 packet_len -= 8;
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);
759 return;
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;
774 CloseSocket();
775 return 0;
778 if (flags & EC_FLAG_ZLIB) {
780 m_z.zalloc = Z_NULL;
781 m_z.zfree = Z_NULL;
782 m_z.opaque = Z_NULL;
783 m_z.avail_in = 0;
784 m_z.next_in = 0;
786 int zerror = inflateInit(&m_z);
787 if (zerror != Z_OK) {
788 ShowZError(zerror, &m_z);
789 cout << "ReadPacket: failed zlib init" << endl;
790 CloseSocket();
791 return 0;
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;
801 delete packet;
802 packet = NULL;
803 CloseSocket();
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;
811 CloseSocket();
815 return packet;
818 const CECPacket *CECSocket::OnPacketReceived(const CECPacket *)
820 return 0;
822 // File_checked_for_headers