3 /// Class wrapper to encapsulate the Blackberry USB logical socket
7 Copyright (C) 2005-2007, 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.
25 #include "protostructs.h"
31 #include <openssl/sha.h>
39 Socket::Socket( Device
&dev
,
40 int writeEndpoint
, int readEndpoint
,
41 uint8_t zeroSocketSequenceStart
)
43 m_writeEp(writeEndpoint
),
44 m_readEp(readEndpoint
),
46 m_zeroSocketSequence(zeroSocketSequenceStart
),
57 // trap exceptions in the destructor
59 // a non-default socket has been opened, close it
62 catch( std::runtime_error
&re
) {
63 // do nothing... log it?
64 dout("Exception caught in ~Socket: " << re
.what());
68 void Socket::SendOpen(uint16_t socket
, Data
&receive
)
71 Barry::Protocol::Packet packet
;
73 packet
.size
= htobs(SB_SOCKET_PACKET_HEADER_SIZE
);
74 packet
.command
= SB_COMMAND_OPEN_SOCKET
;
75 packet
.u
.socket
.socket
= htobs(socket
);
76 packet
.u
.socket
.sequence
= m_zeroSocketSequence
;// overwritten by Send()
78 // save sequence for later close, and inc
79 m_flag
= m_zeroSocketSequence
;
81 Data
send(&packet
, SB_SOCKET_PACKET_HEADER_SIZE
);
84 } catch( Usb::Error
& ) {
90 Protocol::CheckSize(receive
);
91 if( IS_COMMAND(receive
, SB_COMMAND_SEQUENCE_HANDSHAKE
) ) {
92 CheckSequence(receive
);
98 // receive now holds the Open response
101 // SHA1 hashing logic based on Rick Scott's XmBlackBerry's send_password()
102 void Socket::SendPasswordHash(uint16_t socket
, const char *password
, Data
&receive
)
104 unsigned char pwdigest
[SHA_DIGEST_LENGTH
];
105 unsigned char prefixedhash
[SHA_DIGEST_LENGTH
+ 4];
107 // first, hash the password by itself
108 SHA1((unsigned char *) password
, strlen(password
), pwdigest
);
110 // prefix the resulting hash with the provided seed
111 uint32_t seed
= htobl(m_challengeSeed
);
112 memcpy(&prefixedhash
[0], &seed
, sizeof(uint32_t));
113 memcpy(&prefixedhash
[4], pwdigest
, SHA_DIGEST_LENGTH
);
116 SHA1((unsigned char *) prefixedhash
, SHA_DIGEST_LENGTH
+ 4, pwdigest
);
119 size_t size
= SB_SOCKET_PACKET_HEADER_SIZE
+ PASSWORD_CHALLENGE_SIZE
;
121 // build open command
122 Barry::Protocol::Packet packet
;
124 packet
.size
= htobs(size
);
125 packet
.command
= SB_COMMAND_PASSWORD
;
126 packet
.u
.socket
.socket
= htobs(socket
);
127 packet
.u
.socket
.sequence
= m_zeroSocketSequence
;// overwritten by Send()
128 packet
.u
.socket
.u
.password
.remaining_tries
= 0;
129 packet
.u
.socket
.u
.password
.unknown
= 0;
130 packet
.u
.socket
.u
.password
.param
= htobs(0x14); // FIXME - what does this mean?
131 memcpy(packet
.u
.socket
.u
.password
.u
.hash
, pwdigest
,
132 sizeof(packet
.u
.socket
.u
.password
.u
.hash
));
134 // blank password hashes as we don't need these anymore
135 memset(pwdigest
, 0, sizeof(pwdigest
));
136 memset(prefixedhash
, 0, sizeof(prefixedhash
));
138 // save sequence for later close, and inc
139 m_flag
= m_zeroSocketSequence
;
141 Data
send(&packet
, size
);
144 // blank password hash as we don't need this anymore either
145 memset(packet
.u
.socket
.u
.password
.u
.hash
, 0,
146 sizeof(packet
.u
.socket
.u
.password
.u
.hash
));
150 Protocol::CheckSize(receive
);
151 if( IS_COMMAND(receive
, SB_COMMAND_SEQUENCE_HANDSHAKE
) ) {
152 CheckSequence(receive
);
154 // still need our ACK
158 // receive now holds the Password response
165 /// Open a logical socket on the device.
167 /// Both the socket number and the flag are based on the response to the
168 /// SELECT_MODE command. See Controller::SelectMode() for more info
171 /// The packet sequence is normal for most socket operations.
173 /// - Down: command packet with OPEN_SOCKET
174 /// - Up: optional sequence handshake packet
175 /// - Up: command response, which repeats the socket and flag data
178 /// \exception Barry::Error
179 /// Thrown on protocol error.
181 /// \exception Barry::BadPassword
182 /// Thrown on invalid password, or not enough retries left
185 void Socket::Open(uint16_t socket
, const char *password
)
187 if( m_socket
!= 0 ) {
189 throw Error("Socket: already open");
192 // Things get a little funky here, as we may be left in an
193 // intermediate state in the case of a failed password.
194 // This function should support being called as many times
195 // as needed to handle the password
198 ZeroPacket
packet(send
, receive
);
202 m_remainingTries
= 0;
204 SendOpen(socket
, receive
);
206 // check for password challenge, or success
207 if( packet
.Command() == SB_COMMAND_PASSWORD_CHALLENGE
) {
209 m_challengeSeed
= packet
.ChallengeSeed();
210 m_remainingTries
= packet
.RemainingTries();
213 // fall through to challenge code...
217 // half open, device is expecting a password hash... do we
220 throw BadPassword("No password specified.", m_remainingTries
);
223 // only allow password attempts if there are 6 or more
224 // tries remaining... we want to give the user at least
225 // 5 chances on a Windows machine before the device
227 if( m_remainingTries
< 6 ) {
228 throw BadPassword("Fewer than 6 password tries "
229 "remaining in device. Refusing to proceed, "
230 "to avoid device zapping itself. Use a "
231 "Windows client, or re-cradle the device.",
235 SendPasswordHash(socket
, password
, receive
);
237 if( packet
.Command() == SB_COMMAND_PASSWORD_FAILED
) {
239 m_challengeSeed
= packet
.ChallengeSeed();
240 m_remainingTries
= packet
.RemainingTries();
241 throw BadPassword("Password rejected by device.", m_remainingTries
);
244 // if we get this far, we are no longer in half-open password
245 // mode, so we can reset our flags
248 // fall through to success check...
251 if( packet
.Command() != SB_COMMAND_OPENED_SOCKET
||
252 packet
.SocketResponse() != socket
||
253 packet
.SocketSequence() != m_flag
)
255 eout("Packet:\n" << receive
);
256 throw Error("Socket: Bad OPENED packet in Open");
259 // success! save the socket
266 /// Closes a non-default socket (i.e. non-zero socket number)
268 /// The packet sequence is just like Open(), except the command is
271 /// \exception Barry::Error
275 if( m_socket
!= 0 ) {
276 // only close non-default sockets
278 // build close command
279 Barry::Protocol::Packet packet
;
281 packet
.size
= htobs(SB_SOCKET_PACKET_HEADER_SIZE
);
282 packet
.command
= SB_COMMAND_CLOSE_SOCKET
;
283 packet
.u
.socket
.socket
= htobs(m_socket
);
284 packet
.u
.socket
.sequence
= m_flag
;
286 Data
command(&packet
, SB_SOCKET_PACKET_HEADER_SIZE
);
289 Send(command
, response
);
291 catch( Usb::Error
& ) {
292 // reset so this won't be called again
296 eeout(command
, response
);
300 // starting fresh, reset sequence ID
301 Protocol::CheckSize(response
);
302 if( IS_COMMAND(response
, SB_COMMAND_SEQUENCE_HANDSHAKE
) ) {
303 CheckSequence(response
);
305 // still need our ACK
309 Protocol::CheckSize(response
, SB_SOCKET_PACKET_HEADER_SIZE
);
310 MAKE_PACKET(rpack
, response
);
311 if( rpack
->command
!= SB_COMMAND_CLOSED_SOCKET
||
312 btohs(rpack
->u
.socket
.socket
) != m_socket
||
313 rpack
->u
.socket
.sequence
!= m_flag
)
315 // reset so this won't be called again
319 eout("Packet:\n" << response
);
320 throw Error("Socket: Bad CLOSED packet in Close");
323 // and finally, there always seems to be an extra read of
324 // an empty packet at the end... just throw it away
325 // Receive(response);
327 // reset socket and flag
336 /// Sends 'send' data to device, and waits for response.
340 /// \exception Usb::Error on underlying bus errors.
342 void Socket::Send(Data
&send
, Data
&receive
, int timeout
)
344 // Special case: it seems that sending packets with a size that's an
345 // exact multiple of 0x40 causes the device to get confused.
347 // To get around that, it is observed in the captures that the size
348 // is sent in a special 3 byte packet before the real packet.
349 // Check for this case here.
351 if( (send
.GetSize() % 0x40) == 0 ) {
352 Protocol::SizePacket packet
;
353 packet
.size
= htobs(send
.GetSize());
354 packet
.buffer
[2] = 0; // zero the top byte
355 Data
sizeCommand(&packet
, 3);
357 m_dev
.BulkWrite(m_writeEp
, sizeCommand
);
360 // If this is a socket 0 packet, force the send packet data's
361 // socket 0 sequence number to something correct.
362 if( m_socket
== 0 && send
.GetSize() >= SB_SOCKET_PACKET_HEADER_SIZE
) {
363 MAKE_PACKETPTR_BUF(spack
, send
.GetBuffer());
364 spack
->u
.socket
.sequence
= m_zeroSocketSequence
;
365 m_zeroSocketSequence
++;
368 m_dev
.BulkWrite(m_writeEp
, send
);
369 m_dev
.BulkRead(m_readEp
, receive
, timeout
);
371 ddout("Socket::Send: Endpoint " << m_readEp
<< "\nReceived:\n" << receive
);
374 void Socket::Send(Barry::Packet
&packet
, int timeout
)
376 Send(packet
.m_send
, packet
.m_receive
, timeout
);
379 void Socket::Receive(Data
&receive
, int timeout
)
381 m_dev
.BulkRead(m_readEp
, receive
, timeout
);
383 ddout("Socket::Receive: Endpoint " << m_readEp
<< "\nReceived:\n" << receive
);
386 // appends fragment to whole... if whole is empty, simply copies, and
387 // sets command to DATA instead of FRAGMENTED. Always updates the
388 // packet size of whole, to reflect the total size
389 void Socket::AppendFragment(Data
&whole
, const Data
&fragment
)
391 if( whole
.GetSize() == 0 ) {
392 // empty, so just copy
396 // has some data already, so just append
397 int size
= whole
.GetSize();
398 unsigned char *buf
= whole
.GetBuffer(size
+ fragment
.GetSize());
399 MAKE_PACKET(fpack
, fragment
);
400 int fragsize
= fragment
.GetSize() - SB_FRAG_HEADER_SIZE
;
402 memcpy(buf
+size
, &fpack
->u
.db
.u
.fragment
, fragsize
);
403 whole
.ReleaseBuffer(size
+ fragsize
);
406 // update whole's size and command type for future sanity
407 Barry::Protocol::Packet
*wpack
= (Barry::Protocol::Packet
*) whole
.GetBuffer();
408 wpack
->size
= htobs((uint16_t) whole
.GetSize());
409 wpack
->command
= SB_COMMAND_DB_DATA
;
410 // don't need to call ReleaseBuffer here, since we're not changing
411 // the real size size
414 // If offset is 0, starts fresh, taking the first fragment packet size chunk
415 // out of whole and creating a sendable packet in fragment. Returns the
416 // next offset if there is still more data, or 0 if finished.
417 unsigned int Socket::MakeNextFragment(const Data
&whole
, Data
&fragment
, unsigned int offset
)
420 if( whole
.GetSize() < SB_FRAG_HEADER_SIZE
) {
421 eout("Whole packet too short to fragment: " << whole
.GetSize());
422 throw Error("Socket: Whole packet too short to fragment");
426 unsigned int todo
= whole
.GetSize() - SB_FRAG_HEADER_SIZE
- offset
;
427 unsigned int nextOffset
= 0;
428 if( todo
> (MAX_PACKET_SIZE
- SB_FRAG_HEADER_SIZE
) ) {
429 todo
= MAX_PACKET_SIZE
- SB_FRAG_HEADER_SIZE
;
430 nextOffset
= offset
+ todo
;
433 // create fragment header
434 unsigned char *buf
= fragment
.GetBuffer(SB_FRAG_HEADER_SIZE
+ todo
);
435 memcpy(buf
, whole
.GetData(), SB_FRAG_HEADER_SIZE
);
437 // copy over a fragment size of data
438 memcpy(buf
+ SB_FRAG_HEADER_SIZE
, whole
.GetData() + SB_FRAG_HEADER_SIZE
+ offset
, todo
);
440 // update fragment's size and command type
441 Barry::Protocol::Packet
*wpack
= (Barry::Protocol::Packet
*) buf
;
442 wpack
->size
= htobs((uint16_t) (todo
+ SB_FRAG_HEADER_SIZE
));
444 wpack
->command
= SB_COMMAND_DB_FRAGMENTED
;
446 wpack
->command
= SB_COMMAND_DB_DATA
;
448 // adjust the new fragment size
449 fragment
.ReleaseBuffer(SB_FRAG_HEADER_SIZE
+ todo
);
455 void Socket::CheckSequence(const Data
&seq
)
457 // if( m_socket == 0 ) {
458 // // don't do any sequence checking on socket 0
462 MAKE_PACKET(spack
, seq
);
463 if( (unsigned int) seq
.GetSize() < SB_SEQUENCE_PACKET_SIZE
) {
464 eout("Short sequence packet:\n" << seq
);
465 throw Error("Socket: invalid sequence packet");
468 // we'll cheat here... if the packet's sequence is 0, we'll
469 // silently restart, otherwise, fail
470 uint32_t sequenceId
= btohl(spack
->u
.sequence
.sequenceId
);
471 if( sequenceId
== 0 ) {
472 // silently restart (will advance below)
476 if( sequenceId
!= m_sequenceId
) {
477 if( m_socket
!= 0 ) {
478 eout("Socket sequence: " << m_sequenceId
479 << ". Packet sequence: " << sequenceId
);
480 throw Error("Socket: out of sequence");
483 dout("Bad sequence on socket 0: expected: "
485 << ". Packet sequence: " << sequenceId
);
494 // sends the send packet down to the device, fragmenting if
495 // necessary, and returns the response in receive, defragmenting
497 // Blocks until response received or timed out in Usb::Device
498 void Socket::Packet(Data
&send
, Data
&receive
, int timeout
)
501 // FIXME - this might be a good idea someday, or perhaps provide a wrapper
502 // function that forces the socket number to the correct current value,
503 // but putting it here means a copy on every packet.
505 // force socket to our socket
506 Data send = sendorig;
507 Barry::Protocol::Packet *sspack = (Barry::Protocol::Packet *)send.GetBuffer(2);
508 sspack->socket = htobs(GetSocket());
511 MAKE_PACKET(spack
, send
);
512 if( send
.GetSize() < MIN_PACKET_SIZE
||
513 (spack
->command
!= SB_COMMAND_DB_DATA
&&
514 spack
->command
!= SB_COMMAND_DB_DONE
) )
516 // we don't do that around here
517 throw std::logic_error("Socket: unknown send data in Packet()");
523 if( send
.GetSize() <= MAX_PACKET_SIZE
) {
524 // send non-fragmented
525 Send(send
, inFrag
, timeout
);
529 unsigned int offset
= 0;
533 offset
= MakeNextFragment(send
, outFrag
, offset
);
534 Send(outFrag
, inFrag
, timeout
);
536 MAKE_PACKET(rpack
, inFrag
);
537 // only process sequence handshakes... once we
538 // get to the last fragment, we fall through to normal
540 if( offset
&& inFrag
.GetSize() > 0 ) {
542 Protocol::CheckSize(inFrag
);
544 switch( rpack
->command
)
546 case SB_COMMAND_SEQUENCE_HANDSHAKE
:
547 CheckSequence(inFrag
);
551 eout("Command: " << std::setbase(16) << (unsigned int)rpack
->command
<< inFrag
);
552 throw Error("Socket: unhandled packet in Packet()");
558 } while( offset
> 0 );
561 bool done
= false, frag
= false;
564 MAKE_PACKET(rpack
, inFrag
);
566 // check the packet's validity
567 if( inFrag
.GetSize() > 0 ) {
570 Protocol::CheckSize(inFrag
);
572 switch( rpack
->command
)
574 case SB_COMMAND_SEQUENCE_HANDSHAKE
:
575 CheckSequence(inFrag
);
578 case SB_COMMAND_DB_DATA
:
580 AppendFragment(receive
, inFrag
);
588 case SB_COMMAND_DB_FRAGMENTED
:
589 AppendFragment(receive
, inFrag
);
593 case SB_COMMAND_DB_DONE
:
599 eout("Command: " << std::setbase(16) << (unsigned int)rpack
->command
<< inFrag
);
600 throw Error("Socket: unhandled packet in Packet()");
606 //std::cerr << "Blank! " << blankCount << std::endl;
607 if( blankCount
== 10 ) {
608 // only ask for more data on stalled sockets
610 throw Error("Socket: 10 blank packets received");
615 // not done yet, ask for another read
621 void Socket::Packet(Barry::Packet
&packet
, int timeout
)
623 Packet(packet
.m_send
, packet
.m_receive
, timeout
);
626 void Socket::NextRecord(Data
&receive
)
628 Barry::Protocol::Packet packet
;
629 packet
.socket
= htobs(GetSocket());
630 packet
.size
= htobs(7);
631 packet
.command
= SB_COMMAND_DB_DONE
;
632 packet
.u
.db
.tableCmd
= 0;
633 packet
.u
.db
.u
.command
.operation
= 0;
635 Data
command(&packet
, 7);
636 Packet(command
, receive
);