Added documentation comment for LoadALXFile's enable flag
[barry.git] / src / socket.cc
blob69a4f8ebf1f9b33c5ebf84f08f0b4a9792bf3e5c
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;
295 if( !dev )
296 throw Error("SocketZero: No device available for RawSend");
298 // Special case: it seems that sending packets with a size that's an
299 // exact multiple of 0x40 causes the device to get confused.
301 // To get around that, it is observed in the captures that the size
302 // is sent in a special 3 byte packet before the real packet.
303 // Check for this case here.
305 if( (send.GetSize() % 0x40) == 0 ) {
306 Protocol::SizePacket packet;
307 packet.size = htobs(send.GetSize());
308 packet.buffer[2] = 0; // zero the top byte
309 Data sizeCommand(&packet, 3);
311 dev->BulkWrite(m_writeEp, sizeCommand, timeout);
314 dev->BulkWrite(m_writeEp, send, timeout);
317 void SocketZero::RawReceive(Data &receive, int timeout)
319 do {
320 if( m_queue ) {
321 if( !m_queue->DefaultRead(receive, timeout) )
322 throw Timeout("SocketZero::RawReceive: queue DefaultRead returned false (likely a timeout)");
324 else {
325 m_dev->BulkRead(m_readEp, receive, timeout);
327 ddout("SocketZero::RawReceive: Endpoint "
328 << (m_queue ? m_queue->GetReadEp() : m_readEp)
329 << "\nReceived:\n" << receive);
330 } while( SequencePacket(receive) );
334 // SequencePacket
336 /// Returns true if this is a sequence packet that should be ignored.
337 /// This function is used in SocketZero::RawReceive() in order
338 /// to determine whether to keep reading or not. By default,
339 /// this function checks whether the packet is a sequence packet
340 /// or not, and returns true if so. Also, if it is a sequence
341 /// packet, it checks the validity of the sequence number.
343 /// If sequence packets become important in the future, this
344 /// function could be changed to call a user-defined callback,
345 /// in order to handle these things out of band.
347 bool SocketZero::SequencePacket(const Data &data)
349 // Begin -- Test quiet durty :(
350 if (m_hideSequencePacket == false) {
351 return false;
353 // End -- Test quiet durty :(
355 if( data.GetSize() >= MIN_PACKET_SIZE ) {
356 MAKE_PACKET(rpack, data);
357 if( rpack->socket == 0 &&
358 rpack->command == SB_COMMAND_SEQUENCE_HANDSHAKE )
360 CheckSequence(0, data);
361 return true;
364 return false; // not a sequence packet
368 ///////////////////////////////////////
369 // SocketZero public API
371 void SocketZero::SetRoutingQueue(SocketRoutingQueue &queue)
373 // replace the current queue pointer
374 m_queue = &queue;
377 void SocketZero::UnlinkRoutingQueue()
379 m_queue = 0;
382 void SocketZero::Send(Data &send, int timeout)
384 // force the socket number to 0
385 if( send.GetSize() >= SB_SOCKET_PACKET_HEADER_SIZE ) {
386 MAKE_PACKETPTR_BUF(spack, send.GetBuffer());
387 spack->socket = 0;
390 // This is a socket 0 packet, so force the send packet data's
391 // socket 0 sequence number to something correct.
392 if( send.GetSize() >= SB_SOCKET_PACKET_HEADER_SIZE ) {
393 MAKE_PACKETPTR_BUF(spack, send.GetBuffer());
394 spack->u.socket.sequence = m_zeroSocketSequence;
395 m_zeroSocketSequence++;
398 RawSend(send, timeout);
401 void SocketZero::Send(Data &send, Data &receive, int timeout)
403 Send(send, timeout);
404 RawReceive(receive, timeout);
407 void SocketZero::Send(Barry::Packet &packet, int timeout)
409 Send(packet.m_send, *packet.m_receive, timeout);
412 void SocketZero::Receive(Data &receive, int timeout)
414 RawReceive(receive, timeout);
419 // Open
421 /// Open a logical socket on the device.
423 /// Both the socket number and the flag are based on the response to the
424 /// SELECT_MODE command. See Controller::SelectMode() for more info
425 /// on this.
427 /// The packet sequence is normal for most socket operations.
429 /// - Down: command packet with OPEN_SOCKET
430 /// - Up: optional sequence handshake packet
431 /// - Up: command response, which repeats the socket and flag data
432 /// as confirmation
434 /// \exception Barry::Error
435 /// Thrown on protocol error.
437 /// \exception Barry::BadPassword
438 /// Thrown on invalid password, or not enough retries left
439 /// on device.
441 SocketHandle SocketZero::Open(uint16_t socket, const char *password)
443 // Things get a little funky here, as we may be left in an
444 // intermediate state in the case of a failed password.
445 // This function should support being called as many times
446 // as needed to handle the password
448 Data send, receive;
449 ZeroPacket packet(send, receive);
451 // save sequence for later close
452 uint8_t closeFlag = GetZeroSocketSequence();
454 if( !m_halfOpen ) {
455 // starting fresh
456 m_remainingTries = 0;
458 SendOpen(socket, receive);
460 // check for password challenge, or success
461 if( packet.Command() == SB_COMMAND_PASSWORD_CHALLENGE ) {
462 m_halfOpen = true;
463 m_challengeSeed = packet.ChallengeSeed();
464 m_remainingTries = packet.RemainingTries();
467 // fall through to challenge code...
470 if( m_halfOpen ) {
471 // half open, device is expecting a password hash... do we
472 // have a password?
473 if( !password ) {
474 throw BadPassword("No password specified.", m_remainingTries, false);
477 // only allow password attempts if there are
478 // BARRY_MIN_PASSWORD_TRIES or more tries remaining...
479 // we want to give the user at least some chance on a
480 // Windows machine before the device commits suicide.
481 if( m_remainingTries < BARRY_MIN_PASSWORD_TRIES ) {
482 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.",
483 m_remainingTries,
484 true);
487 // save sequence for later close (again after SendOpen())
488 closeFlag = GetZeroSocketSequence();
490 SendPasswordHash(socket, password, receive);
492 if( packet.Command() == SB_COMMAND_PASSWORD_FAILED ) {
493 m_halfOpen = true;
494 m_challengeSeed = packet.ChallengeSeed();
495 m_remainingTries = packet.RemainingTries();
496 throw BadPassword("Password rejected by device.", m_remainingTries, false);
499 // if we get this far, we are no longer in half-open password
500 // mode, so we can reset our flags
501 m_halfOpen = false;
503 // fall through to success check...
506 // If the device thinks that the socket was already open then
507 // it will tell us by sending an SB_COMMAND_CLOSE_SOCKET.
509 // This happens most commonly when using raw channels which
510 // haven't been cleanly closed (such as by killing the process
511 // running Barry) and so the device still thinks the socket
512 // is open.
514 // Retrying the open will usually succeed, but relies on the
515 // device software re-creating the channel after it's closed
516 // so return an error here instead of automatically retrying.
517 if( packet.Command() == SB_COMMAND_CLOSE_SOCKET )
519 throw Error("Socket: Device closed socket when trying to open");
522 if( packet.Command() != SB_COMMAND_OPENED_SOCKET ||
523 packet.SocketResponse() != socket ||
524 packet.SocketSequence() != closeFlag )
526 eout("Packet:\n" << receive);
527 throw Error("Socket: Bad OPENED packet in Open");
530 // success! save the socket
531 return SocketHandle(new Socket(*this, socket, closeFlag));
535 // Close
537 /// Closes a non-default socket (i.e. non-zero socket number)
539 /// The packet sequence is just like Open(), except the command is
540 /// CLOSE_SOCKET.
542 /// \exception Barry::Error
544 void SocketZero::Close(Socket &socket)
546 if( socket.GetSocket() == 0 )
547 return; // nothing to do
549 // build close command
550 Barry::Protocol::Packet packet;
551 packet.socket = 0;
552 packet.size = htobs(SB_SOCKET_PACKET_HEADER_SIZE);
553 packet.command = SB_COMMAND_CLOSE_SOCKET;
554 packet.u.socket.socket = htobs(socket.GetSocket());
555 packet.u.socket.sequence = socket.GetCloseFlag();
557 Data command(&packet, SB_SOCKET_PACKET_HEADER_SIZE);
558 Data response;
559 try {
560 Send(command, response);
562 catch( Usb::Error & ) {
563 // reset so this won't be called again
564 socket.ForceClosed();
566 eeout(command, response);
567 throw;
570 // starting fresh, reset sequence ID
571 Protocol::CheckSize(response, SB_PACKET_HEADER_SIZE);
572 if( IS_COMMAND(response, SB_COMMAND_SEQUENCE_HANDSHAKE) ) {
573 CheckSequence(0, response);
575 // still need our ACK
576 RawReceive(response);
579 Protocol::CheckSize(response, SB_SOCKET_PACKET_HEADER_SIZE);
580 MAKE_PACKET(rpack, response);
581 // The reply will be SB_COMMAND_CLOSED_SOCKET if the device
582 // has closed the socket in response to our request.
584 // It's also possible for the reply to be
585 // SB_COMMAND_REMOTE_CLOSE_SOCKET if the device wanted to
586 // close the socket at the same time, such as if the channel
587 // API is being used by the device.
588 if( ( rpack->command != SB_COMMAND_CLOSED_SOCKET &&
589 rpack->command != SB_COMMAND_REMOTE_CLOSE_SOCKET ) ||
590 btohs(rpack->u.socket.socket) != socket.GetSocket() ||
591 rpack->u.socket.sequence != socket.GetCloseFlag() )
593 // reset so this won't be called again
594 socket.ForceClosed();
596 eout("Packet:\n" << response);
597 throw BadPacket(rpack->command, "Socket: Bad CLOSED packet in Close");
600 if( m_resetOnClose ) {
601 Data send, receive;
602 ZeroPacket reset_packet(send, receive);
603 reset_packet.Reset();
605 Send(reset_packet);
606 if( reset_packet.CommandResponse() != SB_COMMAND_RESET_REPLY ) {
607 throw BadPacket(reset_packet.CommandResponse(),
608 "Socket: Missing RESET_REPLY in Close");
612 // // and finally, there always seems to be an extra read of
613 // // an empty packet at the end... just throw it away
614 // try {
615 // RawReceive(response, 1);
616 // }
617 // catch( Usb::Timeout & ) {
618 // }
620 // reset socket and flag
621 socket.ForceClosed();
625 // ClearHalt
627 /// Clears the USB Halt bit on both the read and write endpoints
629 void SocketZero::ClearHalt()
631 Usb::Device *dev = m_queue ? m_queue->GetUsbDevice() : m_dev;
632 if( !dev )
633 throw Error("SocketZero: No device available for ClearHalt");
635 // clear the read endpoint
636 if( m_queue ) {
637 dev->ClearHalt(m_queue->GetReadEp());
639 else {
640 dev->ClearHalt(m_readEp);
643 // clear the write endpoint
644 dev->ClearHalt(m_writeEp);
652 //////////////////////////////////////////////////////////////////////////////
653 // Socket class
655 Socket::Socket( SocketZero &zero,
656 uint16_t socket,
657 uint8_t closeFlag)
658 : m_zero(&zero)
659 , m_socket(socket)
660 , m_closeFlag(closeFlag)
661 , m_registered(false)
665 Socket::~Socket()
667 // trap exceptions in the destructor
668 try {
669 // a non-default socket has been opened, close it
670 Close();
672 catch( std::runtime_error &re ) {
673 // do nothing... log it?
674 dout("Exception caught in ~Socket: " << re.what());
679 ////////////////////////////////////
680 // Socket protected API
682 void Socket::CheckSequence(const Data &seq)
684 m_zero->CheckSequence(m_socket, seq);
687 void Socket::ForceClosed()
689 m_socket = 0;
690 m_closeFlag = 0;
694 ////////////////////////////////////
695 // Socket public API
697 void Socket::Close()
699 UnregisterInterest();
700 m_zero->Close(*this);
705 // Send
707 /// Sends 'send' data to device, no receive.
709 /// \returns void
711 /// \exception Usb::Error on underlying bus errors.
713 void Socket::Send(Data &send, int timeout)
715 // force the socket number to this socket
716 if( send.GetSize() >= SB_PACKET_HEADER_SIZE ) {
717 MAKE_PACKETPTR_BUF(spack, send.GetBuffer());
718 spack->socket = htobs(m_socket);
720 m_zero->RawSend(send, timeout);
724 // Send
726 /// Sends 'send' data to device, and waits for response.
728 /// \returns void
730 /// \exception Usb::Error on underlying bus errors.
732 void Socket::Send(Data &send, Data &receive, int timeout)
734 Send(send, timeout);
735 Receive(receive, timeout);
738 void Socket::Send(Barry::Packet &packet, int timeout)
740 Send(packet.m_send, *packet.m_receive, timeout);
743 void Socket::Receive(Data &receive, int timeout)
745 if( m_registered ) {
746 if( m_zero->m_queue ) {
747 if( !m_zero->m_queue->SocketRead(m_socket, receive, timeout) )
748 throw Timeout("Socket::Receive: queue SocketRead returned false (likely a timeout)");
750 else {
751 throw std::logic_error("NULL queue pointer in a registered socket read.");
754 else {
755 m_zero->RawReceive(receive, timeout);
760 // FIXME - find a better way to do this?
761 void Socket::ReceiveData(Data &receive, int timeout)
763 HideSequencePacket(false);
764 Receive(receive);
765 HideSequencePacket(true);
768 void Socket::ClearHalt()
770 m_zero->ClearHalt();
774 // FIXME - find a better way to do this?
775 void Socket::InitSequence(int timeout)
777 Data receive;
778 receive.Zap();
780 HideSequencePacket(false);
781 Receive(receive);
782 HideSequencePacket(true);
784 Protocol::CheckSize(receive, SB_PACKET_HEADER_SIZE);
785 CheckSequence(receive);
789 // sends the send packet down to the device
790 // Blocks until response received or timed out in Usb::Device
792 // This function is used to send packet to JVM
793 void Socket::PacketJVM(Data &send, Data &receive, int timeout)
795 if( ( send.GetSize() < MIN_PACKET_DATA_SIZE ) ||
796 ( send.GetSize() > MAX_PACKET_DATA_SIZE ) ) {
797 // we don't do that around here
798 throw std::logic_error("Socket: unknown send data in PacketJVM()");
801 Data &inFrag = receive;
802 receive.Zap();
804 // send non-fragmented
805 Send(send, inFrag, timeout);
807 bool done = false;
808 int blankCount = 0;
810 while( !done ) {
811 // check the packet's validity
812 if( inFrag.GetSize() > 6 ) {
813 MAKE_PACKET(rpack, inFrag);
815 blankCount = 0;
817 Protocol::CheckSize(inFrag, SB_PACKET_HEADER_SIZE);
819 switch( rpack->command )
821 case SB_COMMAND_SEQUENCE_HANDSHAKE:
822 CheckSequence(inFrag);
823 break;
825 default: {
826 std::ostringstream oss;
827 oss << "Socket: (read) unhandled packet in Packet(): 0x" << std::hex << (unsigned int)rpack->command;
828 eout(oss.str());
829 throw Error(oss.str());
831 break;
834 else if( inFrag.GetSize() == 6 ) {
835 done = true;
837 else {
838 blankCount++;
840 //std::cerr << "Blank! " << blankCount << std::endl;
841 if( blankCount == 10 ) {
842 // only ask for more data on stalled sockets
843 // for so long
844 throw Error("Socket: 10 blank packets received");
848 if( !done ) {
849 // not done yet, ask for another read
850 Receive(inFrag);
855 // sends the send packet down to the device
856 // Blocks until response received or timed out in Usb::Device
857 void Socket::PacketData(Data &send, Data &receive, int timeout)
859 if( ( send.GetSize() < MIN_PACKET_DATA_SIZE ) ||
860 ( send.GetSize() > MAX_PACKET_DATA_SIZE ) ) {
861 // we don't do that around here
862 throw std::logic_error("Socket: unknown send data in PacketData()");
865 Data &inFrag = receive;
866 receive.Zap();
868 // send non-fragmented
869 Send(send, inFrag, timeout);
871 bool done = false;
872 int blankCount = 0;
874 while( !done ) {
875 // check the packet's validity
876 if( inFrag.GetSize() > 0 ) {
877 MAKE_PACKET(rpack, inFrag);
879 blankCount = 0;
881 Protocol::CheckSize(inFrag, SB_PACKET_HEADER_SIZE);
883 switch( rpack->command )
885 case SB_COMMAND_SEQUENCE_HANDSHAKE:
886 CheckSequence(inFrag);
887 if (!m_zero->IsSequencePacketHidden())
888 done = true;
889 break;
891 case SB_COMMAND_JL_READY:
892 case SB_COMMAND_JL_ACK:
893 case SB_COMMAND_JL_HELLO_ACK:
894 case SB_COMMAND_JL_RESET_REQUIRED:
895 done = true;
896 break;
898 case SB_COMMAND_JL_GET_DATA_ENTRY: // This response means that the next packet is the stream
899 done = true;
900 break;
902 case SB_DATA_JL_INVALID:
903 throw BadPacket(rpack->command, "file is not a valid Java code file");
904 break;
906 case SB_COMMAND_JL_NOT_SUPPORTED:
907 throw BadPacket(rpack->command, "device does not support requested command");
908 break;
910 default:
911 // unknown packet, pass it up to the
912 // next higher code layer
913 done = true;
914 break;
917 else {
918 blankCount++;
919 //std::cerr << "Blank! " << blankCount << std::endl;
920 if( blankCount == 10 ) {
921 // only ask for more data on stalled sockets
922 // for so long
923 throw Error("Socket: 10 blank packets received");
927 if( !done ) {
928 // not done yet, ask for another read
929 Receive(inFrag);
934 // sends the send packet down to the device, fragmenting if
935 // necessary, and returns the response in receive, defragmenting
936 // if needed
937 // Blocks until response received or timed out in Usb::Device
939 // This is primarily for Desktop Database packets... Javaloader
940 // packets use PacketData().
942 void Socket::Packet(Data &send, Data &receive, int timeout)
944 MAKE_PACKET(spack, send);
945 if( send.GetSize() < MIN_PACKET_SIZE ||
946 (spack->command != SB_COMMAND_DB_DATA &&
947 spack->command != SB_COMMAND_DB_DONE) )
949 // we don't do that around here
950 eout("unknown send data in Packet(): " << send);
951 throw std::logic_error("Socket: unknown send data in Packet()");
954 // assume the common case of no fragmentation,
955 // and use the receive buffer for input... allocate a frag buffer
956 // later if necessary
957 Data *inputBuf = &receive;
958 receive.Zap();
960 if( send.GetSize() <= MAX_PACKET_SIZE ) {
961 // send non-fragmented
962 Send(send, *inputBuf, timeout);
964 else {
965 // send fragmented
966 unsigned int offset = 0;
967 Data outFrag;
969 // You haven't to sequence packet while the whole packet isn't sent
970 // a) No sequence received packet
971 // b) 1°) Sent framgment 1/N
972 // 2°) Sent framgment 2/N
973 // ...
974 // N°) Before sent fragment N/N, I enable the sequence packet process.
975 // Sent framgment N/N
976 HideSequencePacket(false);
978 do {
979 offset = SocketZero::MakeNextFragment(send, outFrag, offset);
981 // Is last packet ?
982 MAKE_PACKET(spack, outFrag);
984 if (spack->command != SB_COMMAND_DB_FRAGMENTED)
985 HideSequencePacket(true);
987 Send(outFrag, *inputBuf, timeout);
989 // only process sequence handshakes... once we
990 // get to the last fragment, we fall through to normal
991 // processing below
992 if (spack->command != SB_COMMAND_DB_FRAGMENTED) {
993 MAKE_PACKET(rpack, *inputBuf);
995 if( offset && inputBuf->GetSize() > 0 ) {
996 Protocol::CheckSize(*inputBuf, SB_PACKET_HEADER_SIZE);
998 switch( rpack->command )
1000 case SB_COMMAND_SEQUENCE_HANDSHAKE:
1001 CheckSequence(*inputBuf);
1002 break;
1004 default: {
1005 std::ostringstream oss;
1006 oss << "Socket: (send) unhandled packet in Packet(): 0x" << std::hex << (unsigned int)rpack->command;
1007 eout(oss.str());
1008 throw Error(oss.str());
1010 break;
1015 } while( offset > 0 );
1017 // To be sure that it's clean...
1018 HideSequencePacket(true);
1021 std::auto_ptr<Data> inFrag;
1022 bool done = false, frag = false;
1023 int blankCount = 0;
1024 while( !done ) {
1025 MAKE_PACKET(rpack, *inputBuf);
1027 // check the packet's validity
1028 if( inputBuf->GetSize() > 0 ) {
1029 blankCount = 0;
1031 Protocol::CheckSize(*inputBuf, SB_PACKET_HEADER_SIZE);
1033 switch( rpack->command )
1035 case SB_COMMAND_SEQUENCE_HANDSHAKE:
1036 CheckSequence(*inputBuf);
1037 break;
1039 case SB_COMMAND_DB_DATA:
1040 if( frag ) {
1041 SocketZero::AppendFragment(receive, *inputBuf);
1043 else {
1044 // no copy needed, already in receive,
1045 // since inputBuf starts out that way
1047 done = true;
1048 break;
1050 case SB_COMMAND_DB_FRAGMENTED:
1051 // only copy if frag is true, since the
1052 // first time through, receive == inputBuf
1053 if( frag ) {
1054 SocketZero::AppendFragment(receive, *inputBuf);
1056 frag = true;
1057 break;
1059 case SB_COMMAND_DB_DONE:
1060 // no copy needed, already in receive
1061 done = true;
1062 break;
1064 default: {
1065 std::ostringstream oss;
1066 oss << "Socket: (read) unhandled packet in Packet(): 0x" << std::hex << (unsigned int)rpack->command;
1067 eout(oss.str());
1068 throw Error(oss.str());
1070 break;
1073 else {
1074 blankCount++;
1075 //std::cerr << "Blank! " << blankCount << std::endl;
1076 if( blankCount == 10 ) {
1077 // only ask for more data on stalled sockets
1078 // for so long
1079 throw Error("Socket: 10 blank packets received");
1083 if( !done ) {
1084 // not done yet, ask for another read, and
1085 // create new buffer for fragmented reads
1086 if( !inFrag.get() ) {
1087 inFrag.reset( new Data );
1088 inputBuf = inFrag.get();
1090 Receive(*inputBuf);
1095 void Socket::Packet(Barry::Packet &packet, int timeout)
1097 Packet(packet.m_send, *packet.m_receive, timeout);
1100 void Socket::Packet(Barry::JLPacket &packet, int timeout)
1102 if( packet.HasData() ) {
1103 HideSequencePacket(false);
1104 PacketData(packet.m_cmd, *packet.m_receive, timeout);
1105 HideSequencePacket(true);
1106 PacketData(packet.m_data, *packet.m_receive, timeout);
1108 else {
1109 PacketData(packet.m_cmd, *packet.m_receive, timeout);
1113 void Socket::Packet(Barry::JVMPacket &packet, int timeout)
1115 HideSequencePacket(false);
1116 PacketJVM(packet.m_cmd, *packet.m_receive, timeout);
1117 HideSequencePacket(true);
1120 void Socket::NextRecord(Data &receive)
1122 Barry::Protocol::Packet packet;
1123 packet.socket = htobs(GetSocket());
1124 packet.size = htobs(7);
1125 packet.command = SB_COMMAND_DB_DONE;
1126 packet.u.db.tableCmd = 0;
1127 packet.u.db.u.command.operation = 0;
1129 Data command(&packet, 7);
1130 Packet(command, receive);
1133 void Socket::RegisterInterest(SocketRoutingQueue::SocketDataHandlerPtr handler)
1135 if( !m_zero->m_queue )
1136 throw std::logic_error("SocketRoutingQueue required in SocketZero in order to call Socket::RegisterInterest()");
1138 if( m_registered )
1139 throw std::logic_error("Socket already registered in Socket::RegisterInterest()!");
1141 m_zero->m_queue->RegisterInterest(m_socket, handler);
1142 m_registered = true;
1145 void Socket::UnregisterInterest()
1147 if( m_registered ) {
1148 if( m_zero->m_queue )
1149 m_zero->m_queue->UnregisterInterest(m_socket);
1150 m_registered = false;
1155 } // namespace Barry