lib: avoiding non-const references
[barry.git] / src / socket.cc
blob5704cafc1fa77a67f95aef1d4dc7a14cd3c4eca9
1 ///
2 /// \file socket.cc
3 /// Class wrapper to encapsulate the Blackberry USB logical socket
4 ///
6 /*
7 Copyright (C) 2005-2010, Net Direct Inc. (http://www.netdirect.ca/)
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
22 #include "socket.h"
23 #include "usbwrap.h"
24 #include "data.h"
25 #include "protocol.h"
26 #include "protostructs.h"
27 #include "endian.h"
28 #include "debug.h"
29 #include "packet.h"
30 #include "sha1.h"
31 #include <sstream>
32 #include <string.h>
34 using namespace Usb;
37 namespace Barry {
40 //////////////////////////////////////////////////////////////////////////////
41 // SocketZero class
43 SocketZero::SocketZero( SocketRoutingQueue &queue,
44 int writeEndpoint,
45 uint8_t zeroSocketSequenceStart)
46 : m_dev(0),
47 m_queue(&queue),
48 m_writeEp(writeEndpoint),
49 m_readEp(0),
50 m_zeroSocketSequence(zeroSocketSequenceStart),
51 m_sequenceId(0),
52 m_halfOpen(false),
53 m_challengeSeed(0),
54 m_remainingTries(0),
55 m_hideSequencePacket(true),
56 m_resetOnClose(false)
60 SocketZero::SocketZero( Device &dev,
61 int writeEndpoint, int readEndpoint,
62 uint8_t zeroSocketSequenceStart)
63 : m_dev(&dev),
64 m_queue(0),
65 m_writeEp(writeEndpoint),
66 m_readEp(readEndpoint),
67 m_zeroSocketSequence(zeroSocketSequenceStart),
68 m_sequenceId(0),
69 m_halfOpen(false),
70 m_challengeSeed(0),
71 m_remainingTries(0),
72 m_hideSequencePacket(true),
73 m_resetOnClose(false)
77 SocketZero::~SocketZero()
79 // nothing to close for socket zero
83 ///////////////////////////////////////
84 // Socket Zero static calls
86 // appends fragment to whole... if whole is empty, simply copies, and
87 // sets command to DATA instead of FRAGMENTED. Always updates the
88 // packet size of whole, to reflect the total size
89 void SocketZero::AppendFragment(Data &whole, const Data &fragment)
91 if( whole.GetSize() == 0 ) {
92 // empty, so just copy
93 whole = fragment;
95 else {
96 // has some data already, so just append
97 int size = whole.GetSize();
98 unsigned char *buf = whole.GetBuffer(size + fragment.GetSize());
99 MAKE_PACKET(fpack, fragment);
100 int fragsize = fragment.GetSize() - SB_FRAG_HEADER_SIZE;
102 memcpy(buf+size, &fpack->u.db.u.fragment, fragsize);
103 whole.ReleaseBuffer(size + fragsize);
106 // update whole's size and command type for future sanity
107 Barry::Protocol::Packet *wpack = (Barry::Protocol::Packet *) whole.GetBuffer();
108 wpack->size = htobs((uint16_t) whole.GetSize());
109 wpack->command = SB_COMMAND_DB_DATA;
110 // don't need to call ReleaseBuffer here, since we're not changing
111 // the real data size, and ReleaseBuffer was called above during copy
114 // If offset is 0, starts fresh, taking the first fragment packet size chunk
115 // out of whole and creating a sendable packet in fragment. Returns the
116 // next offset if there is still more data, or 0 if finished.
117 unsigned int SocketZero::MakeNextFragment(const Data &whole, Data &fragment, unsigned int offset)
119 // sanity check
120 if( whole.GetSize() < SB_FRAG_HEADER_SIZE ) {
121 eout("Whole packet too short to fragment: " << whole.GetSize());
122 throw Error("Socket: Whole packet too short to fragment");
125 // calculate size
126 unsigned int todo = whole.GetSize() - SB_FRAG_HEADER_SIZE - offset;
127 unsigned int nextOffset = 0;
128 if( todo > (MAX_PACKET_SIZE - SB_FRAG_HEADER_SIZE) ) {
129 todo = MAX_PACKET_SIZE - SB_FRAG_HEADER_SIZE;
130 nextOffset = offset + todo;
133 // create fragment header
134 unsigned char *buf = fragment.GetBuffer(SB_FRAG_HEADER_SIZE + todo);
135 memcpy(buf, whole.GetData(), SB_FRAG_HEADER_SIZE);
137 // copy over a fragment size of data
138 memcpy(buf + SB_FRAG_HEADER_SIZE, whole.GetData() + SB_FRAG_HEADER_SIZE + offset, todo);
140 // update fragment's size and command type
141 Barry::Protocol::Packet *wpack = (Barry::Protocol::Packet *) buf;
142 wpack->size = htobs((uint16_t) (todo + SB_FRAG_HEADER_SIZE));
143 if( nextOffset )
144 wpack->command = SB_COMMAND_DB_FRAGMENTED;
145 else
146 wpack->command = SB_COMMAND_DB_DATA;
148 // adjust the new fragment size
149 fragment.ReleaseBuffer(SB_FRAG_HEADER_SIZE + todo);
151 // return next round
152 return nextOffset;
156 ///////////////////////////////////////
157 // SocketZero private API
160 // FIXME - not sure yet whether sequence ID's are per socket or not... if
161 // they are per socket, then this global sequence behaviour will not work,
162 // and we need to track m_sequenceId on a Socket level.
164 void SocketZero::CheckSequence(uint16_t socket, const Data &seq)
166 MAKE_PACKET(spack, seq);
167 if( (unsigned int) seq.GetSize() < SB_SEQUENCE_PACKET_SIZE ) {
168 eout("Short sequence packet:\n" << seq);
169 throw Error("Socket: invalid sequence packet");
172 // we'll cheat here... if the packet's sequence is 0, we'll
173 // silently restart, otherwise, fail
174 uint32_t sequenceId = btohl(spack->u.sequence.sequenceId);
175 if( sequenceId == 0 ) {
176 // silently restart (will advance below)
177 m_sequenceId = 0;
179 else {
180 if( sequenceId != m_sequenceId ) {
181 if( socket != 0 ) {
182 std::ostringstream oss;
183 oss << "Socket 0x" << std::hex << (unsigned int)socket
184 << ": out of sequence. "
185 << "(Global sequence: " << m_sequenceId
186 << ". Packet sequence: " << sequenceId
187 << ")";
188 eout(oss.str());
189 throw Error(oss.str());
191 else {
192 dout("Bad sequence on socket 0: expected: "
193 << m_sequenceId
194 << ". Packet sequence: " << sequenceId);
199 // advance!
200 m_sequenceId++;
203 void SocketZero::SendOpen(uint16_t socket, Data &receive)
205 // build open command
206 Barry::Protocol::Packet packet;
207 packet.socket = 0;
208 packet.size = htobs(SB_SOCKET_PACKET_HEADER_SIZE);
209 packet.command = SB_COMMAND_OPEN_SOCKET;
210 packet.u.socket.socket = htobs(socket);
211 packet.u.socket.sequence = m_zeroSocketSequence;// overwritten by Send()
213 Data send(&packet, SB_SOCKET_PACKET_HEADER_SIZE);
214 try {
215 RawSend(send);
216 RawReceive(receive);
217 } catch( Usb::Error & ) {
218 eeout(send, receive);
219 throw;
222 // check sequence ID
223 Protocol::CheckSize(receive, SB_PACKET_HEADER_SIZE);
224 if( IS_COMMAND(receive, SB_COMMAND_SEQUENCE_HANDSHAKE) ) {
225 CheckSequence(0, receive);
227 // still need our ACK
228 RawReceive(receive);
231 // receive now holds the Open response
234 // SHA1 hashing logic based on Rick Scott's XmBlackBerry's send_password()
235 void SocketZero::SendPasswordHash(uint16_t socket, const char *password, Data &receive)
237 unsigned char pwdigest[SHA_DIGEST_LENGTH];
238 unsigned char prefixedhash[SHA_DIGEST_LENGTH + 4];
240 // first, hash the password by itself
241 SHA1((unsigned char *) password, strlen(password), pwdigest);
243 // prefix the resulting hash with the provided seed
244 uint32_t seed = htobl(m_challengeSeed);
245 memcpy(&prefixedhash[0], &seed, sizeof(uint32_t));
246 memcpy(&prefixedhash[4], pwdigest, SHA_DIGEST_LENGTH);
248 // hash again
249 SHA1((unsigned char *) prefixedhash, SHA_DIGEST_LENGTH + 4, pwdigest);
252 size_t size = SB_SOCKET_PACKET_HEADER_SIZE + PASSWORD_CHALLENGE_SIZE;
254 // build open command
255 Barry::Protocol::Packet packet;
256 packet.socket = 0;
257 packet.size = htobs(size);
258 packet.command = SB_COMMAND_PASSWORD;
259 packet.u.socket.socket = htobs(socket);
260 packet.u.socket.sequence = m_zeroSocketSequence;// overwritten by Send()
261 packet.u.socket.u.password.remaining_tries = 0;
262 packet.u.socket.u.password.unknown = 0;
263 packet.u.socket.u.password.param = htobs(0x14); // FIXME - what does this mean?
264 memcpy(packet.u.socket.u.password.u.hash, pwdigest,
265 sizeof(packet.u.socket.u.password.u.hash));
267 // blank password hashes as we don't need these anymore
268 memset(pwdigest, 0, sizeof(pwdigest));
269 memset(prefixedhash, 0, sizeof(prefixedhash));
271 Data send(&packet, size);
272 RawSend(send);
273 RawReceive(receive);
275 // blank password hash as we don't need this anymore either
276 memset(packet.u.socket.u.password.u.hash, 0,
277 sizeof(packet.u.socket.u.password.u.hash));
278 send.Zap();
280 // check sequence ID
281 Protocol::CheckSize(receive, SB_PACKET_HEADER_SIZE);
282 if( IS_COMMAND(receive, SB_COMMAND_SEQUENCE_HANDSHAKE) ) {
283 CheckSequence(0, receive);
285 // still need our ACK
286 RawReceive(receive);
289 // receive now holds the Password response
292 void SocketZero::RawSend(Data &send, int timeout)
294 Usb::Device *dev = m_queue ? m_queue->GetUsbDevice() : m_dev;
296 // Special case: it seems that sending packets with a size that's an
297 // exact multiple of 0x40 causes the device to get confused.
299 // To get around that, it is observed in the captures that the size
300 // is sent in a special 3 byte packet before the real packet.
301 // Check for this case here.
303 if( (send.GetSize() % 0x40) == 0 ) {
304 Protocol::SizePacket packet;
305 packet.size = htobs(send.GetSize());
306 packet.buffer[2] = 0; // zero the top byte
307 Data sizeCommand(&packet, 3);
309 dev->BulkWrite(m_writeEp, sizeCommand);
312 dev->BulkWrite(m_writeEp, send);
315 void SocketZero::RawReceive(Data &receive, int timeout)
317 do {
318 if( m_queue ) {
319 if( !m_queue->DefaultRead(receive, timeout) )
320 throw Timeout("SocketZero::RawReceive: queue DefaultRead returned false (likely a timeout)");
322 else {
323 m_dev->BulkRead(m_readEp, receive, timeout);
325 ddout("SocketZero::RawReceive: Endpoint "
326 << (m_queue ? m_queue->GetReadEp() : m_readEp)
327 << "\nReceived:\n" << receive);
328 } while( SequencePacket(receive) );
332 // SequencePacket
334 /// Returns true if this is a sequence packet that should be ignored.
335 /// This function is used in SocketZero::RawReceive() in order
336 /// to determine whether to keep reading or not. By default,
337 /// this function checks whether the packet is a sequence packet
338 /// or not, and returns true if so. Also, if it is a sequence
339 /// packet, it checks the validity of the sequence number.
341 /// If sequence packets become important in the future, this
342 /// function could be changed to call a user-defined callback,
343 /// in order to handle these things out of band.
345 bool SocketZero::SequencePacket(const Data &data)
347 // Begin -- Test quiet durty :(
348 if (m_hideSequencePacket == false) {
349 return false;
351 // End -- Test quiet durty :(
353 if( data.GetSize() >= MIN_PACKET_SIZE ) {
354 MAKE_PACKET(rpack, data);
355 if( rpack->socket == 0 &&
356 rpack->command == SB_COMMAND_SEQUENCE_HANDSHAKE )
358 CheckSequence(0, data);
359 return true;
362 return false; // not a sequence packet
366 ///////////////////////////////////////
367 // SocketZero public API
369 void SocketZero::SetRoutingQueue(SocketRoutingQueue &queue)
371 // replace the current queue pointer
372 m_queue = &queue;
375 void SocketZero::UnlinkRoutingQueue()
377 m_queue = 0;
380 void SocketZero::Send(Data &send, int timeout)
382 // force the socket number to 0
383 if( send.GetSize() >= SB_SOCKET_PACKET_HEADER_SIZE ) {
384 MAKE_PACKETPTR_BUF(spack, send.GetBuffer());
385 spack->socket = 0;
388 // This is a socket 0 packet, so force the send packet data's
389 // socket 0 sequence number to something correct.
390 if( send.GetSize() >= SB_SOCKET_PACKET_HEADER_SIZE ) {
391 MAKE_PACKETPTR_BUF(spack, send.GetBuffer());
392 spack->u.socket.sequence = m_zeroSocketSequence;
393 m_zeroSocketSequence++;
396 RawSend(send, timeout);
399 void SocketZero::Send(Data &send, Data &receive, int timeout)
401 Send(send, timeout);
402 RawReceive(receive, timeout);
405 void SocketZero::Send(Barry::Packet &packet, int timeout)
407 Send(packet.m_send, packet.m_receive, timeout);
410 void SocketZero::Receive(Data &receive, int timeout)
412 RawReceive(receive, timeout);
417 // Open
419 /// Open a logical socket on the device.
421 /// Both the socket number and the flag are based on the response to the
422 /// SELECT_MODE command. See Controller::SelectMode() for more info
423 /// on this.
425 /// The packet sequence is normal for most socket operations.
427 /// - Down: command packet with OPEN_SOCKET
428 /// - Up: optional sequence handshake packet
429 /// - Up: command response, which repeats the socket and flag data
430 /// as confirmation
432 /// \exception Barry::Error
433 /// Thrown on protocol error.
435 /// \exception Barry::BadPassword
436 /// Thrown on invalid password, or not enough retries left
437 /// on device.
439 SocketHandle SocketZero::Open(uint16_t socket, const char *password)
441 // Things get a little funky here, as we may be left in an
442 // intermediate state in the case of a failed password.
443 // This function should support being called as many times
444 // as needed to handle the password
446 Data send, receive;
447 ZeroPacket packet(send, receive);
449 // save sequence for later close
450 uint8_t closeFlag = GetZeroSocketSequence();
452 if( !m_halfOpen ) {
453 // starting fresh
454 m_remainingTries = 0;
456 SendOpen(socket, receive);
458 // check for password challenge, or success
459 if( packet.Command() == SB_COMMAND_PASSWORD_CHALLENGE ) {
460 m_halfOpen = true;
461 m_challengeSeed = packet.ChallengeSeed();
462 m_remainingTries = packet.RemainingTries();
465 // fall through to challenge code...
468 if( m_halfOpen ) {
469 // half open, device is expecting a password hash... do we
470 // have a password?
471 if( !password ) {
472 throw BadPassword("No password specified.", m_remainingTries, false);
475 // only allow password attempts if there are
476 // BARRY_MIN_PASSWORD_TRIES or more tries remaining...
477 // we want to give the user at least some chance on a
478 // Windows machine before the device commits suicide.
479 if( m_remainingTries < BARRY_MIN_PASSWORD_TRIES ) {
480 throw BadPassword("Fewer than " BARRY_MIN_PASSWORD_TRIES_ASC " password tries remaining in device. Refusing to proceed, to avoid device zapping itself. Use a Windows client, or re-cradle the device.",
481 m_remainingTries,
482 true);
485 // save sequence for later close (again after SendOpen())
486 closeFlag = GetZeroSocketSequence();
488 SendPasswordHash(socket, password, receive);
490 if( packet.Command() == SB_COMMAND_PASSWORD_FAILED ) {
491 m_halfOpen = true;
492 m_challengeSeed = packet.ChallengeSeed();
493 m_remainingTries = packet.RemainingTries();
494 throw BadPassword("Password rejected by device.", m_remainingTries, false);
497 // if we get this far, we are no longer in half-open password
498 // mode, so we can reset our flags
499 m_halfOpen = false;
501 // fall through to success check...
504 if( packet.Command() == SB_COMMAND_CLOSE_SOCKET )
506 eout("Packet:\n" << receive);
507 throw Error("Socket: Socket closed when trying to open");
510 if( packet.Command() != SB_COMMAND_OPENED_SOCKET ||
511 packet.SocketResponse() != socket ||
512 packet.SocketSequence() != closeFlag )
514 eout("Packet:\n" << receive);
515 throw Error("Socket: Bad OPENED packet in Open");
518 // success! save the socket
519 return SocketHandle(new Socket(*this, socket, closeFlag));
523 // Close
525 /// Closes a non-default socket (i.e. non-zero socket number)
527 /// The packet sequence is just like Open(), except the command is
528 /// CLOSE_SOCKET.
530 /// \exception Barry::Error
532 void SocketZero::Close(Socket &socket)
534 if( socket.GetSocket() == 0 )
535 return; // nothing to do
537 // build close command
538 Barry::Protocol::Packet packet;
539 packet.socket = 0;
540 packet.size = htobs(SB_SOCKET_PACKET_HEADER_SIZE);
541 packet.command = SB_COMMAND_CLOSE_SOCKET;
542 packet.u.socket.socket = htobs(socket.GetSocket());
543 packet.u.socket.sequence = socket.GetCloseFlag();
545 Data command(&packet, SB_SOCKET_PACKET_HEADER_SIZE);
546 Data response;
547 try {
548 Send(command, response);
550 catch( Usb::Error & ) {
551 // reset so this won't be called again
552 socket.ForceClosed();
554 eeout(command, response);
555 throw;
558 // starting fresh, reset sequence ID
559 Protocol::CheckSize(response, SB_PACKET_HEADER_SIZE);
560 if( IS_COMMAND(response, SB_COMMAND_SEQUENCE_HANDSHAKE) ) {
561 CheckSequence(0, response);
563 // still need our ACK
564 RawReceive(response);
567 Protocol::CheckSize(response, SB_SOCKET_PACKET_HEADER_SIZE);
568 MAKE_PACKET(rpack, response);
569 if( rpack->command != SB_COMMAND_CLOSED_SOCKET ||
570 btohs(rpack->u.socket.socket) != socket.GetSocket() ||
571 rpack->u.socket.sequence != socket.GetCloseFlag() )
573 // reset so this won't be called again
574 socket.ForceClosed();
576 if( rpack->command == SB_COMMAND_REMOTE_CLOSE_SOCKET ) {
577 eout("Remote end closed connection");
578 throw BadPacket(rpack->command, "Socket: Remote close packet in Close");
580 else {
581 eout("Packet:\n" << response);
582 throw BadPacket(rpack->command, "Socket: Bad CLOSED packet in Close");
586 if( m_resetOnClose ) {
587 Data send, receive;
588 ZeroPacket reset_packet(send, receive);
589 reset_packet.Reset();
591 Send(reset_packet);
592 if( reset_packet.CommandResponse() != SB_COMMAND_RESET_REPLY ) {
593 throw BadPacket(reset_packet.CommandResponse(),
594 "Socket: Missing RESET_REPLY in Close");
598 // // and finally, there always seems to be an extra read of
599 // // an empty packet at the end... just throw it away
600 // try {
601 // RawReceive(response, 1);
602 // }
603 // catch( Usb::Timeout & ) {
604 // }
606 // reset socket and flag
607 socket.ForceClosed();
611 // ClearHalt
613 /// Clears the USB Halt bit on both the read and write endpoints
615 void SocketZero::ClearHalt()
617 // clear the read endpoint
618 if( m_queue ) {
619 m_dev->ClearHalt(m_queue->GetReadEp());
621 else {
622 m_dev->ClearHalt(m_readEp);
625 // clear the write endpoint
626 m_dev->ClearHalt(m_writeEp);
634 //////////////////////////////////////////////////////////////////////////////
635 // Socket class
637 Socket::Socket( SocketZero &zero,
638 uint16_t socket,
639 uint8_t closeFlag)
640 : m_zero(&zero)
641 , m_socket(socket)
642 , m_closeFlag(closeFlag)
643 , m_registered(false)
647 Socket::~Socket()
649 // trap exceptions in the destructor
650 try {
651 // a non-default socket has been opened, close it
652 Close();
654 catch( std::runtime_error &re ) {
655 // do nothing... log it?
656 dout("Exception caught in ~Socket: " << re.what());
661 ////////////////////////////////////
662 // Socket protected API
664 void Socket::CheckSequence(const Data &seq)
666 m_zero->CheckSequence(m_socket, seq);
669 void Socket::ForceClosed()
671 m_socket = 0;
672 m_closeFlag = 0;
676 ////////////////////////////////////
677 // Socket public API
679 void Socket::Close()
681 UnregisterInterest();
682 m_zero->Close(*this);
687 // Send
689 /// Sends 'send' data to device, no receive.
691 /// \returns void
693 /// \exception Usb::Error on underlying bus errors.
695 void Socket::Send(Data &send, int timeout)
697 // force the socket number to this socket
698 if( send.GetSize() >= SB_PACKET_HEADER_SIZE ) {
699 MAKE_PACKETPTR_BUF(spack, send.GetBuffer());
700 spack->socket = htobs(m_socket);
702 m_zero->RawSend(send, timeout);
706 // Send
708 /// Sends 'send' data to device, and waits for response.
710 /// \returns void
712 /// \exception Usb::Error on underlying bus errors.
714 void Socket::Send(Data &send, Data &receive, int timeout)
716 Send(send, timeout);
717 Receive(receive, timeout);
720 void Socket::Send(Barry::Packet &packet, int timeout)
722 Send(packet.m_send, packet.m_receive, timeout);
725 void Socket::Receive(Data &receive, int timeout)
727 if( m_registered ) {
728 if( m_zero->m_queue ) {
729 if( !m_zero->m_queue->SocketRead(m_socket, receive, timeout) )
730 throw Timeout("Socket::Receive: queue SocketRead returned false (likely a timeout)");
732 else {
733 throw std::logic_error("NULL queue pointer in a registered socket read.");
736 else {
737 m_zero->RawReceive(receive, timeout);
742 // FIXME - find a better way to do this?
743 void Socket::ReceiveData(Data &receive, int timeout)
745 HideSequencePacket(false);
746 Receive(receive);
747 HideSequencePacket(true);
750 void Socket::ClearHalt()
752 m_zero->ClearHalt();
756 // FIXME - find a better way to do this?
757 void Socket::InitSequence(int timeout)
759 Data receive;
760 receive.Zap();
762 HideSequencePacket(false);
763 Receive(receive);
764 HideSequencePacket(true);
766 Protocol::CheckSize(receive, SB_PACKET_HEADER_SIZE);
767 CheckSequence(receive);
771 // sends the send packet down to the device
772 // Blocks until response received or timed out in Usb::Device
774 // This function is used to send packet to JVM
775 void Socket::PacketJVM(Data &send, Data &receive, int timeout)
777 if( ( send.GetSize() < MIN_PACKET_DATA_SIZE ) ||
778 ( send.GetSize() > MAX_PACKET_DATA_SIZE ) ) {
779 // we don't do that around here
780 throw std::logic_error("Socket: unknown send data in PacketJVM()");
783 Data &inFrag = receive;
784 receive.Zap();
786 // send non-fragmented
787 Send(send, inFrag, timeout);
789 bool done = false;
790 int blankCount = 0;
792 while( !done ) {
793 // check the packet's validity
794 if( inFrag.GetSize() > 6 ) {
795 MAKE_PACKET(rpack, inFrag);
797 blankCount = 0;
799 Protocol::CheckSize(inFrag, SB_PACKET_HEADER_SIZE);
801 switch( rpack->command )
803 case SB_COMMAND_SEQUENCE_HANDSHAKE:
804 CheckSequence(inFrag);
805 break;
807 default: {
808 std::ostringstream oss;
809 oss << "Socket: (read) unhandled packet in Packet(): 0x" << std::hex << (unsigned int)rpack->command;
810 eout(oss.str());
811 throw Error(oss.str());
813 break;
816 else if( inFrag.GetSize() == 6 ) {
817 done = true;
819 else {
820 blankCount++;
822 //std::cerr << "Blank! " << blankCount << std::endl;
823 if( blankCount == 10 ) {
824 // only ask for more data on stalled sockets
825 // for so long
826 throw Error("Socket: 10 blank packets received");
830 if( !done ) {
831 // not done yet, ask for another read
832 Receive(inFrag);
837 // sends the send packet down to the device
838 // Blocks until response received or timed out in Usb::Device
839 void Socket::PacketData(Data &send, Data &receive, int timeout)
841 if( ( send.GetSize() < MIN_PACKET_DATA_SIZE ) ||
842 ( send.GetSize() > MAX_PACKET_DATA_SIZE ) ) {
843 // we don't do that around here
844 throw std::logic_error("Socket: unknown send data in PacketData()");
847 Data &inFrag = receive;
848 receive.Zap();
850 // send non-fragmented
851 Send(send, inFrag, timeout);
853 bool done = false;
854 int blankCount = 0;
856 while( !done ) {
857 // check the packet's validity
858 if( inFrag.GetSize() > 0 ) {
859 MAKE_PACKET(rpack, inFrag);
861 blankCount = 0;
863 Protocol::CheckSize(inFrag, SB_PACKET_HEADER_SIZE);
865 switch( rpack->command )
867 case SB_COMMAND_SEQUENCE_HANDSHAKE:
868 CheckSequence(inFrag);
869 if (!m_zero->IsSequencePacketHidden())
870 done = true;
871 break;
873 case SB_COMMAND_JL_READY:
874 case SB_COMMAND_JL_ACK:
875 case SB_COMMAND_JL_HELLO_ACK:
876 case SB_COMMAND_JL_RESET_REQUIRED:
877 done = true;
878 break;
880 case SB_COMMAND_JL_GET_DATA_ENTRY: // This response means that the next packet is the stream
881 done = true;
882 break;
884 case SB_DATA_JL_INVALID:
885 throw BadPacket(rpack->command, "file is not a valid Java code file");
886 break;
888 case SB_COMMAND_JL_NOT_SUPPORTED:
889 throw BadPacket(rpack->command, "device does not support requested command");
890 break;
892 default:
893 // unknown packet, pass it up to the
894 // next higher code layer
895 done = true;
896 break;
899 else {
900 blankCount++;
901 //std::cerr << "Blank! " << blankCount << std::endl;
902 if( blankCount == 10 ) {
903 // only ask for more data on stalled sockets
904 // for so long
905 throw Error("Socket: 10 blank packets received");
909 if( !done ) {
910 // not done yet, ask for another read
911 Receive(inFrag);
916 // sends the send packet down to the device, fragmenting if
917 // necessary, and returns the response in receive, defragmenting
918 // if needed
919 // Blocks until response received or timed out in Usb::Device
921 // This is primarily for Desktop Database packets... Javaloader
922 // packets use PacketData().
924 void Socket::Packet(Data &send, Data &receive, int timeout)
926 MAKE_PACKET(spack, send);
927 if( send.GetSize() < MIN_PACKET_SIZE ||
928 (spack->command != SB_COMMAND_DB_DATA &&
929 spack->command != SB_COMMAND_DB_DONE) )
931 // we don't do that around here
932 eout("unknown send data in Packet(): " << send);
933 throw std::logic_error("Socket: unknown send data in Packet()");
936 Data inFrag;
937 receive.Zap();
939 if( send.GetSize() <= MAX_PACKET_SIZE ) {
940 // send non-fragmented
941 Send(send, inFrag, timeout);
943 else {
944 // send fragmented
945 unsigned int offset = 0;
946 Data outFrag;
948 // You haven't to sequence packet while the whole packet isn't sent
949 // a) No sequence received packet
950 // b) 1°) Sent framgment 1/N
951 // 2°) Sent framgment 2/N
952 // ...
953 // N°) Before sent fragment N/N, I enable the sequence packet process.
954 // Sent framgment N/N
955 HideSequencePacket(false);
957 do {
958 offset = SocketZero::MakeNextFragment(send, outFrag, offset);
960 // Is last packet ?
961 MAKE_PACKET(spack, outFrag);
963 if (spack->command != SB_COMMAND_DB_FRAGMENTED)
964 HideSequencePacket(true);
966 Send(outFrag, inFrag, timeout);
968 // only process sequence handshakes... once we
969 // get to the last fragment, we fall through to normal
970 // processing below
971 if (spack->command != SB_COMMAND_DB_FRAGMENTED) {
972 MAKE_PACKET(rpack, inFrag);
974 if( offset && inFrag.GetSize() > 0 ) {
975 Protocol::CheckSize(inFrag, SB_PACKET_HEADER_SIZE);
977 switch( rpack->command )
979 case SB_COMMAND_SEQUENCE_HANDSHAKE:
980 CheckSequence(inFrag);
981 break;
983 default: {
984 std::ostringstream oss;
985 oss << "Socket: (send) unhandled packet in Packet(): 0x" << std::hex << (unsigned int)rpack->command;
986 eout(oss.str());
987 throw Error(oss.str());
989 break;
994 } while( offset > 0 );
996 // To be sure that it's clean...
997 HideSequencePacket(true);
1000 bool done = false, frag = false;
1001 int blankCount = 0;
1002 while( !done ) {
1003 MAKE_PACKET(rpack, inFrag);
1005 // check the packet's validity
1006 if( inFrag.GetSize() > 0 ) {
1007 blankCount = 0;
1009 Protocol::CheckSize(inFrag, SB_PACKET_HEADER_SIZE);
1011 switch( rpack->command )
1013 case SB_COMMAND_SEQUENCE_HANDSHAKE:
1014 CheckSequence(inFrag);
1015 break;
1017 case SB_COMMAND_DB_DATA:
1018 if( frag ) {
1019 SocketZero::AppendFragment(receive, inFrag);
1021 else {
1022 receive = inFrag;
1024 done = true;
1025 break;
1027 case SB_COMMAND_DB_FRAGMENTED:
1028 SocketZero::AppendFragment(receive, inFrag);
1029 frag = true;
1030 break;
1032 case SB_COMMAND_DB_DONE:
1033 receive = inFrag;
1034 done = true;
1035 break;
1037 default: {
1038 std::ostringstream oss;
1039 oss << "Socket: (read) unhandled packet in Packet(): 0x" << std::hex << (unsigned int)rpack->command;
1040 eout(oss.str());
1041 throw Error(oss.str());
1043 break;
1046 else {
1047 blankCount++;
1048 //std::cerr << "Blank! " << blankCount << std::endl;
1049 if( blankCount == 10 ) {
1050 // only ask for more data on stalled sockets
1051 // for so long
1052 throw Error("Socket: 10 blank packets received");
1056 if( !done ) {
1057 // not done yet, ask for another read
1058 Receive(inFrag);
1063 void Socket::Packet(Barry::Packet &packet, int timeout)
1065 Packet(packet.m_send, packet.m_receive, timeout);
1068 void Socket::Packet(Barry::JLPacket &packet, int timeout)
1070 if( packet.HasData() ) {
1071 HideSequencePacket(false);
1072 PacketData(packet.m_cmd, packet.m_receive, timeout);
1073 HideSequencePacket(true);
1074 PacketData(packet.m_data, packet.m_receive, timeout);
1076 else {
1077 PacketData(packet.m_cmd, packet.m_receive, timeout);
1081 void Socket::Packet(Barry::JVMPacket &packet, int timeout)
1083 HideSequencePacket(false);
1084 PacketJVM(packet.m_cmd, packet.m_receive, timeout);
1085 HideSequencePacket(true);
1088 void Socket::NextRecord(Data &receive)
1090 Barry::Protocol::Packet packet;
1091 packet.socket = htobs(GetSocket());
1092 packet.size = htobs(7);
1093 packet.command = SB_COMMAND_DB_DONE;
1094 packet.u.db.tableCmd = 0;
1095 packet.u.db.u.command.operation = 0;
1097 Data command(&packet, 7);
1098 Packet(command, receive);
1101 void Socket::RegisterInterest(std::tr1::shared_ptr<SocketRoutingQueue::SocketDataHandler> handler)
1103 if( !m_zero->m_queue )
1104 throw std::logic_error("SocketRoutingQueue required in SocketZero in order to call Socket::RegisterInterest()");
1106 if( m_registered )
1107 throw std::logic_error("Socket already registered in Socket::RegisterInterest()!");
1109 m_zero->m_queue->RegisterInterest(m_socket, handler);
1110 m_registered = true;
1113 void Socket::UnregisterInterest()
1115 if( m_registered ) {
1116 if( m_zero->m_queue )
1117 m_zero->m_queue->UnregisterInterest(m_socket);
1118 m_registered = false;
1123 } // namespace Barry