3 /// Class wrapper to encapsulate the Blackberry USB logical socket
7 Copyright (C) 2005-2008, 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.
26 #include "protostructs.h"
40 //////////////////////////////////////////////////////////////////////////////
43 SocketZero::SocketZero( SocketRoutingQueue
&queue
,
45 uint8_t zeroSocketSequenceStart
)
48 m_writeEp(writeEndpoint
),
50 m_zeroSocketSequence(zeroSocketSequenceStart
),
58 SocketZero::SocketZero( Device
&dev
,
59 int writeEndpoint
, int readEndpoint
,
60 uint8_t zeroSocketSequenceStart
)
63 m_writeEp(writeEndpoint
),
64 m_readEp(readEndpoint
),
65 m_zeroSocketSequence(zeroSocketSequenceStart
),
73 SocketZero::~SocketZero()
75 // nothing to close for socket zero
79 ///////////////////////////////////////
80 // Socket Zero static calls
82 // appends fragment to whole... if whole is empty, simply copies, and
83 // sets command to DATA instead of FRAGMENTED. Always updates the
84 // packet size of whole, to reflect the total size
85 void SocketZero::AppendFragment(Data
&whole
, const Data
&fragment
)
87 if( whole
.GetSize() == 0 ) {
88 // empty, so just copy
92 // has some data already, so just append
93 int size
= whole
.GetSize();
94 unsigned char *buf
= whole
.GetBuffer(size
+ fragment
.GetSize());
95 MAKE_PACKET(fpack
, fragment
);
96 int fragsize
= fragment
.GetSize() - SB_FRAG_HEADER_SIZE
;
98 memcpy(buf
+size
, &fpack
->u
.db
.u
.fragment
, fragsize
);
99 whole
.ReleaseBuffer(size
+ fragsize
);
102 // update whole's size and command type for future sanity
103 Barry::Protocol::Packet
*wpack
= (Barry::Protocol::Packet
*) whole
.GetBuffer();
104 wpack
->size
= htobs((uint16_t) whole
.GetSize());
105 wpack
->command
= SB_COMMAND_DB_DATA
;
106 // don't need to call ReleaseBuffer here, since we're not changing
107 // the real data size, and ReleaseBuffer was called above during copy
110 // If offset is 0, starts fresh, taking the first fragment packet size chunk
111 // out of whole and creating a sendable packet in fragment. Returns the
112 // next offset if there is still more data, or 0 if finished.
113 unsigned int SocketZero::MakeNextFragment(const Data
&whole
, Data
&fragment
, unsigned int offset
)
116 if( whole
.GetSize() < SB_FRAG_HEADER_SIZE
) {
117 eout("Whole packet too short to fragment: " << whole
.GetSize());
118 throw Error("Socket: Whole packet too short to fragment");
122 unsigned int todo
= whole
.GetSize() - SB_FRAG_HEADER_SIZE
- offset
;
123 unsigned int nextOffset
= 0;
124 if( todo
> (MAX_PACKET_SIZE
- SB_FRAG_HEADER_SIZE
) ) {
125 todo
= MAX_PACKET_SIZE
- SB_FRAG_HEADER_SIZE
;
126 nextOffset
= offset
+ todo
;
129 // create fragment header
130 unsigned char *buf
= fragment
.GetBuffer(SB_FRAG_HEADER_SIZE
+ todo
);
131 memcpy(buf
, whole
.GetData(), SB_FRAG_HEADER_SIZE
);
133 // copy over a fragment size of data
134 memcpy(buf
+ SB_FRAG_HEADER_SIZE
, whole
.GetData() + SB_FRAG_HEADER_SIZE
+ offset
, todo
);
136 // update fragment's size and command type
137 Barry::Protocol::Packet
*wpack
= (Barry::Protocol::Packet
*) buf
;
138 wpack
->size
= htobs((uint16_t) (todo
+ SB_FRAG_HEADER_SIZE
));
140 wpack
->command
= SB_COMMAND_DB_FRAGMENTED
;
142 wpack
->command
= SB_COMMAND_DB_DATA
;
144 // adjust the new fragment size
145 fragment
.ReleaseBuffer(SB_FRAG_HEADER_SIZE
+ todo
);
152 ///////////////////////////////////////
153 // SocketZero private API
156 // FIXME - not sure yet whether sequence ID's are per socket or not... if
157 // they are per socket, then this global sequence behaviour will not work,
158 // and we need to track m_sequenceId on a Socket level.
160 void SocketZero::CheckSequence(uint16_t socket
, const Data
&seq
)
162 MAKE_PACKET(spack
, seq
);
163 if( (unsigned int) seq
.GetSize() < SB_SEQUENCE_PACKET_SIZE
) {
164 eout("Short sequence packet:\n" << seq
);
165 throw Error("Socket: invalid sequence packet");
168 // we'll cheat here... if the packet's sequence is 0, we'll
169 // silently restart, otherwise, fail
170 uint32_t sequenceId
= btohl(spack
->u
.sequence
.sequenceId
);
171 if( sequenceId
== 0 ) {
172 // silently restart (will advance below)
176 if( sequenceId
!= m_sequenceId
) {
178 std::ostringstream oss
;
179 oss
<< "Socket 0x" << std::hex
<< (unsigned int)socket
180 << ": out of sequence. "
181 << "(Global sequence: " << m_sequenceId
182 << ". Packet sequence: " << sequenceId
185 throw Error(oss
.str());
188 dout("Bad sequence on socket 0: expected: "
190 << ". Packet sequence: " << sequenceId
);
199 void SocketZero::SendOpen(uint16_t socket
, Data
&receive
)
201 // build open command
202 Barry::Protocol::Packet packet
;
204 packet
.size
= htobs(SB_SOCKET_PACKET_HEADER_SIZE
);
205 packet
.command
= SB_COMMAND_OPEN_SOCKET
;
206 packet
.u
.socket
.socket
= htobs(socket
);
207 packet
.u
.socket
.sequence
= m_zeroSocketSequence
;// overwritten by Send()
209 Data
send(&packet
, SB_SOCKET_PACKET_HEADER_SIZE
);
213 } catch( Usb::Error
& ) {
214 eeout(send
, receive
);
219 Protocol::CheckSize(receive
);
220 if( IS_COMMAND(receive
, SB_COMMAND_SEQUENCE_HANDSHAKE
) ) {
221 CheckSequence(0, receive
);
223 // still need our ACK
227 // receive now holds the Open response
230 // SHA1 hashing logic based on Rick Scott's XmBlackBerry's send_password()
231 void SocketZero::SendPasswordHash(uint16_t socket
, const char *password
, Data
&receive
)
233 unsigned char pwdigest
[SHA_DIGEST_LENGTH
];
234 unsigned char prefixedhash
[SHA_DIGEST_LENGTH
+ 4];
236 // first, hash the password by itself
237 SHA1((unsigned char *) password
, strlen(password
), pwdigest
);
239 // prefix the resulting hash with the provided seed
240 uint32_t seed
= htobl(m_challengeSeed
);
241 memcpy(&prefixedhash
[0], &seed
, sizeof(uint32_t));
242 memcpy(&prefixedhash
[4], pwdigest
, SHA_DIGEST_LENGTH
);
245 SHA1((unsigned char *) prefixedhash
, SHA_DIGEST_LENGTH
+ 4, pwdigest
);
248 size_t size
= SB_SOCKET_PACKET_HEADER_SIZE
+ PASSWORD_CHALLENGE_SIZE
;
250 // build open command
251 Barry::Protocol::Packet packet
;
253 packet
.size
= htobs(size
);
254 packet
.command
= SB_COMMAND_PASSWORD
;
255 packet
.u
.socket
.socket
= htobs(socket
);
256 packet
.u
.socket
.sequence
= m_zeroSocketSequence
;// overwritten by Send()
257 packet
.u
.socket
.u
.password
.remaining_tries
= 0;
258 packet
.u
.socket
.u
.password
.unknown
= 0;
259 packet
.u
.socket
.u
.password
.param
= htobs(0x14); // FIXME - what does this mean?
260 memcpy(packet
.u
.socket
.u
.password
.u
.hash
, pwdigest
,
261 sizeof(packet
.u
.socket
.u
.password
.u
.hash
));
263 // blank password hashes as we don't need these anymore
264 memset(pwdigest
, 0, sizeof(pwdigest
));
265 memset(prefixedhash
, 0, sizeof(prefixedhash
));
267 Data
send(&packet
, size
);
271 // blank password hash as we don't need this anymore either
272 memset(packet
.u
.socket
.u
.password
.u
.hash
, 0,
273 sizeof(packet
.u
.socket
.u
.password
.u
.hash
));
277 Protocol::CheckSize(receive
);
278 if( IS_COMMAND(receive
, SB_COMMAND_SEQUENCE_HANDSHAKE
) ) {
279 CheckSequence(0, receive
);
281 // still need our ACK
285 // receive now holds the Password response
288 void SocketZero::RawSend(Data
&send
, int timeout
)
290 Usb::Device
*dev
= m_queue
? m_queue
->GetUsbDevice() : m_dev
;
292 // Special case: it seems that sending packets with a size that's an
293 // exact multiple of 0x40 causes the device to get confused.
295 // To get around that, it is observed in the captures that the size
296 // is sent in a special 3 byte packet before the real packet.
297 // Check for this case here.
299 if( (send
.GetSize() % 0x40) == 0 ) {
300 Protocol::SizePacket packet
;
301 packet
.size
= htobs(send
.GetSize());
302 packet
.buffer
[2] = 0; // zero the top byte
303 Data
sizeCommand(&packet
, 3);
305 dev
->BulkWrite(m_writeEp
, sizeCommand
);
308 dev
->BulkWrite(m_writeEp
, send
);
311 void SocketZero::RawReceive(Data
&receive
, int timeout
)
315 if( !m_queue
->DefaultRead(receive
, timeout
) )
316 throw Timeout("SocketZero::RawReceive: queue DefaultRead returned false (likely a timeout)");
319 m_dev
->BulkRead(m_readEp
, receive
, timeout
);
321 ddout("SocketZero::RawReceive: Endpoint " << m_readEp
322 << "\nReceived:\n" << receive
);
323 } while( SequencePacket(receive
) );
329 /// Returns true if this is a sequence packet that should be ignored.
330 /// This function is used in SocketZero::RawReceive() in order
331 /// to determine whether to keep reading or not. By default,
332 /// this function checks whether the packet is a sequence packet
333 /// or not, and returns true if so. Also, if it is a sequence
334 /// packet, it checks the validity of the sequence number.
336 /// If sequence packets become important in the future, this
337 /// function could be changed to call a user-defined callback,
338 /// in order to handle these things out of band.
340 bool SocketZero::SequencePacket(const Data
&data
)
342 if( data
.GetSize() >= MIN_PACKET_SIZE
) {
343 if( IS_COMMAND(data
, SB_COMMAND_SEQUENCE_HANDSHAKE
) ) {
344 CheckSequence(0, data
);
348 return false; // not a sequence packet
352 ///////////////////////////////////////
353 // SocketZero public API
355 void SocketZero::SetRoutingQueue(SocketRoutingQueue
&queue
)
357 // replace the current queue pointer
361 void SocketZero::UnlinkRoutingQueue()
366 void SocketZero::Send(Data
&send
, int timeout
)
368 // force the socket number to 0
369 if( send
.GetSize() >= SB_SOCKET_PACKET_HEADER_SIZE
) {
370 MAKE_PACKETPTR_BUF(spack
, send
.GetBuffer());
374 // This is a socket 0 packet, so force the send packet data's
375 // socket 0 sequence number to something correct.
376 if( send
.GetSize() >= SB_SOCKET_PACKET_HEADER_SIZE
) {
377 MAKE_PACKETPTR_BUF(spack
, send
.GetBuffer());
378 spack
->u
.socket
.sequence
= m_zeroSocketSequence
;
379 m_zeroSocketSequence
++;
382 RawSend(send
, timeout
);
385 void SocketZero::Send(Data
&send
, Data
&receive
, int timeout
)
388 RawReceive(receive
, timeout
);
391 void SocketZero::Send(Barry::Packet
&packet
, int timeout
)
393 Send(packet
.m_send
, packet
.m_receive
, timeout
);
400 /// Open a logical socket on the device.
402 /// Both the socket number and the flag are based on the response to the
403 /// SELECT_MODE command. See Controller::SelectMode() for more info
406 /// The packet sequence is normal for most socket operations.
408 /// - Down: command packet with OPEN_SOCKET
409 /// - Up: optional sequence handshake packet
410 /// - Up: command response, which repeats the socket and flag data
413 /// \exception Barry::Error
414 /// Thrown on protocol error.
416 /// \exception Barry::BadPassword
417 /// Thrown on invalid password, or not enough retries left
420 SocketHandle
SocketZero::Open(uint16_t socket
, const char *password
)
422 // Things get a little funky here, as we may be left in an
423 // intermediate state in the case of a failed password.
424 // This function should support being called as many times
425 // as needed to handle the password
428 ZeroPacket
packet(send
, receive
);
430 // save sequence for later close
431 uint8_t closeFlag
= GetZeroSocketSequence();
435 m_remainingTries
= 0;
437 SendOpen(socket
, receive
);
439 // check for password challenge, or success
440 if( packet
.Command() == SB_COMMAND_PASSWORD_CHALLENGE
) {
442 m_challengeSeed
= packet
.ChallengeSeed();
443 m_remainingTries
= packet
.RemainingTries();
446 // fall through to challenge code...
450 // half open, device is expecting a password hash... do we
453 throw BadPassword("No password specified.", m_remainingTries
, false);
456 // only allow password attempts if there are
457 // BARRY_MIN_PASSWORD_TRIES or more tries remaining...
458 // we want to give the user at least some chance on a
459 // Windows machine before the device commits suicide.
460 if( m_remainingTries
< BARRY_MIN_PASSWORD_TRIES
) {
461 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.",
466 // save sequence for later close (again after SendOpen())
467 closeFlag
= GetZeroSocketSequence();
469 SendPasswordHash(socket
, password
, receive
);
471 if( packet
.Command() == SB_COMMAND_PASSWORD_FAILED
) {
473 m_challengeSeed
= packet
.ChallengeSeed();
474 m_remainingTries
= packet
.RemainingTries();
475 throw BadPassword("Password rejected by device.", m_remainingTries
, false);
478 // if we get this far, we are no longer in half-open password
479 // mode, so we can reset our flags
482 // fall through to success check...
485 if( packet
.Command() != SB_COMMAND_OPENED_SOCKET
||
486 packet
.SocketResponse() != socket
||
487 packet
.SocketSequence() != closeFlag
)
489 eout("Packet:\n" << receive
);
490 throw Error("Socket: Bad OPENED packet in Open");
493 // success! save the socket
494 return SocketHandle(new Socket(*this, socket
, closeFlag
));
500 /// Closes a non-default socket (i.e. non-zero socket number)
502 /// The packet sequence is just like Open(), except the command is
505 /// \exception Barry::Error
507 void SocketZero::Close(Socket
&socket
)
509 if( socket
.GetSocket() == 0 )
510 return; // nothing to do
512 // build close command
513 Barry::Protocol::Packet packet
;
515 packet
.size
= htobs(SB_SOCKET_PACKET_HEADER_SIZE
);
516 packet
.command
= SB_COMMAND_CLOSE_SOCKET
;
517 packet
.u
.socket
.socket
= htobs(socket
.GetSocket());
518 packet
.u
.socket
.sequence
= socket
.GetCloseFlag();
520 Data
command(&packet
, SB_SOCKET_PACKET_HEADER_SIZE
);
523 Send(command
, response
);
525 catch( Usb::Error
& ) {
526 // reset so this won't be called again
527 socket
.ForceClosed();
529 eeout(command
, response
);
533 // starting fresh, reset sequence ID
534 Protocol::CheckSize(response
);
535 if( IS_COMMAND(response
, SB_COMMAND_SEQUENCE_HANDSHAKE
) ) {
536 CheckSequence(0, response
);
538 // still need our ACK
539 RawReceive(response
);
542 Protocol::CheckSize(response
, SB_SOCKET_PACKET_HEADER_SIZE
);
543 MAKE_PACKET(rpack
, response
);
544 if( rpack
->command
!= SB_COMMAND_CLOSED_SOCKET
||
545 btohs(rpack
->u
.socket
.socket
) != socket
.GetSocket() ||
546 rpack
->u
.socket
.sequence
!= socket
.GetCloseFlag() )
548 // reset so this won't be called again
549 socket
.ForceClosed();
551 eout("Packet:\n" << response
);
552 throw Error("Socket: Bad CLOSED packet in Close");
555 // // and finally, there always seems to be an extra read of
556 // // an empty packet at the end... just throw it away
558 // RawReceive(response, 1);
560 // catch( Usb::Timeout & ) {
563 // reset socket and flag
564 socket
.ForceClosed();
572 //////////////////////////////////////////////////////////////////////////////
575 Socket::Socket( SocketZero
&zero
,
580 , m_closeFlag(closeFlag
)
581 , m_registered(false)
587 // trap exceptions in the destructor
589 // a non-default socket has been opened, close it
592 catch( std::runtime_error
&re
) {
593 // do nothing... log it?
594 dout("Exception caught in ~Socket: " << re
.what());
599 ////////////////////////////////////
600 // Socket protected API
602 void Socket::CheckSequence(const Data
&seq
)
604 m_zero
->CheckSequence(m_socket
, seq
);
607 void Socket::ForceClosed()
614 ////////////////////////////////////
619 UnregisterInterest();
620 m_zero
->Close(*this);
627 /// Sends 'send' data to device, no receive.
631 /// \exception Usb::Error on underlying bus errors.
633 void Socket::Send(Data
&send
, int timeout
)
635 // force the socket number to this socket
636 if( send
.GetSize() >= SB_PACKET_HEADER_SIZE
) {
637 MAKE_PACKETPTR_BUF(spack
, send
.GetBuffer());
638 spack
->socket
= htobs(m_socket
);
640 m_zero
->RawSend(send
, timeout
);
646 /// Sends 'send' data to device, and waits for response.
650 /// \exception Usb::Error on underlying bus errors.
652 void Socket::Send(Data
&send
, Data
&receive
, int timeout
)
655 Receive(receive
, timeout
);
658 void Socket::Send(Barry::Packet
&packet
, int timeout
)
660 Send(packet
.m_send
, packet
.m_receive
, timeout
);
663 void Socket::Receive(Data
&receive
, int timeout
)
666 if( m_zero
->m_queue
) {
667 if( !m_zero
->m_queue
->SocketRead(m_socket
, receive
, timeout
) )
668 throw Timeout("Socket::Receive: queue SocketRead returned false (likely a timeout)");
671 throw std::logic_error("NULL queue pointer in a registered socket read.");
675 m_zero
->RawReceive(receive
, timeout
);
679 // sends the send packet down to the device, fragmenting if
680 // necessary, and returns the response in receive, defragmenting
682 // Blocks until response received or timed out in Usb::Device
683 void Socket::Packet(Data
&send
, Data
&receive
, int timeout
)
686 // FIXME - this might be a good idea someday, or perhaps provide a wrapper
687 // function that forces the socket number to the correct current value,
688 // but putting it here means a copy on every packet.
690 // force socket to our socket
691 Data send = sendorig;
692 Barry::Protocol::Packet *sspack = (Barry::Protocol::Packet *)send.GetBuffer(2);
693 sspack->socket = htobs(GetSocket());
696 MAKE_PACKET(spack
, send
);
697 if( send
.GetSize() < MIN_PACKET_SIZE
||
698 (spack
->command
!= SB_COMMAND_DB_DATA
&&
699 spack
->command
!= SB_COMMAND_DB_DONE
) )
701 // we don't do that around here
702 throw std::logic_error("Socket: unknown send data in Packet()");
708 if( send
.GetSize() <= MAX_PACKET_SIZE
) {
709 // send non-fragmented
710 Send(send
, inFrag
, timeout
);
714 unsigned int offset
= 0;
718 offset
= SocketZero::MakeNextFragment(send
, outFrag
, offset
);
719 Send(outFrag
, inFrag
, timeout
);
721 MAKE_PACKET(rpack
, inFrag
);
722 // only process sequence handshakes... once we
723 // get to the last fragment, we fall through to normal
725 if( offset
&& inFrag
.GetSize() > 0 ) {
727 Protocol::CheckSize(inFrag
);
729 switch( rpack
->command
)
731 case SB_COMMAND_SEQUENCE_HANDSHAKE
:
732 CheckSequence(inFrag
);
736 std::ostringstream oss
;
737 oss
<< "Socket: unhandled packet in Packet() (send): 0x" << std::hex
<< (unsigned int)rpack
->command
;
739 throw Error(oss
.str());
746 } while( offset
> 0 );
749 bool done
= false, frag
= false;
752 MAKE_PACKET(rpack
, inFrag
);
754 // check the packet's validity
755 if( inFrag
.GetSize() > 0 ) {
758 Protocol::CheckSize(inFrag
);
760 switch( rpack
->command
)
762 case SB_COMMAND_SEQUENCE_HANDSHAKE
:
763 CheckSequence(inFrag
);
766 case SB_COMMAND_DB_DATA
:
768 SocketZero::AppendFragment(receive
, inFrag
);
776 case SB_COMMAND_DB_FRAGMENTED
:
777 SocketZero::AppendFragment(receive
, inFrag
);
781 case SB_COMMAND_DB_DONE
:
787 std::ostringstream oss
;
788 oss
<< "Socket: unhandled packet in Packet() (read): 0x" << std::hex
<< (unsigned int)rpack
->command
;
790 throw Error(oss
.str());
797 //std::cerr << "Blank! " << blankCount << std::endl;
798 if( blankCount
== 10 ) {
799 // only ask for more data on stalled sockets
801 throw Error("Socket: 10 blank packets received");
806 // not done yet, ask for another read
812 void Socket::Packet(Barry::Packet
&packet
, int timeout
)
814 Packet(packet
.m_send
, packet
.m_receive
, timeout
);
817 void Socket::NextRecord(Data
&receive
)
819 Barry::Protocol::Packet packet
;
820 packet
.socket
= htobs(GetSocket());
821 packet
.size
= htobs(7);
822 packet
.command
= SB_COMMAND_DB_DONE
;
823 packet
.u
.db
.tableCmd
= 0;
824 packet
.u
.db
.u
.command
.operation
= 0;
826 Data
command(&packet
, 7);
827 Packet(command
, receive
);
830 void Socket::RegisterInterest(SocketRoutingQueue::SocketDataHandler handler
,
833 if( !m_zero
->m_queue
)
834 throw std::logic_error("SocketRoutingQueue required in SocketZero in order to call Socket::RegisterInterest()");
837 throw std::logic_error("Socket already registered in Socket::RegisterInterest()!");
839 m_zero
->m_queue
->RegisterInterest(m_socket
, handler
, context
);
843 void Socket::UnregisterInterest()
846 if( m_zero
->m_queue
)
847 m_zero
->m_queue
->UnregisterInterest(m_socket
);
848 m_registered
= false;