- build system tweaks for opensync-plugin, and added a buildgen.sh for it
[barry.git] / src / socket.cc
blob945131e4b6699d1e881a1fb343c3ae798a12a289
1 ///
2 /// \file socket.cc
3 /// Class wrapper to encapsulate the Blackberry USB logical socket
4 ///
6 /*
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.
22 #include "socket.h"
23 #include "usbwrap.h"
24 #include "protocol.h"
25 #include "protostructs.h"
26 #include "debug.h"
27 #include "data.h"
28 #include "error.h"
29 #include "packet.h"
30 #include "endian.h"
31 #include <openssl/sha.h>
34 using namespace Usb;
37 namespace Barry {
39 Socket::Socket( Device &dev,
40 int writeEndpoint, int readEndpoint,
41 uint8_t zeroSocketSequenceStart)
42 : m_dev(dev),
43 m_writeEp(writeEndpoint),
44 m_readEp(readEndpoint),
45 m_socket(0),
46 m_zeroSocketSequence(zeroSocketSequenceStart),
47 m_flag(0),
48 m_sequenceId(0),
49 m_halfOpen(false),
50 m_challengeSeed(0),
51 m_remainingTries(0)
55 Socket::~Socket()
57 // trap exceptions in the destructor
58 try {
59 // a non-default socket has been opened, close it
60 Close();
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)
70 // build open command
71 Barry::Protocol::Packet packet;
72 packet.socket = 0;
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);
82 try {
83 Send(send, receive);
84 } catch( Usb::Error & ) {
85 eeout(send, receive);
86 throw;
89 // check sequence ID
90 Protocol::CheckSize(receive);
91 if( IS_COMMAND(receive, SB_COMMAND_SEQUENCE_HANDSHAKE) ) {
92 CheckSequence(receive);
94 // still need our ACK
95 Receive(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);
115 // hash again
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;
123 packet.socket = 0;
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);
142 Send(send, receive);
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));
147 send.Zap();
149 // check sequence ID
150 Protocol::CheckSize(receive);
151 if( IS_COMMAND(receive, SB_COMMAND_SEQUENCE_HANDSHAKE) ) {
152 CheckSequence(receive);
154 // still need our ACK
155 Receive(receive);
158 // receive now holds the Password response
163 // Open
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
169 /// on this.
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
176 /// as confirmation
178 /// \exception Barry::Error
179 /// Thrown on protocol error.
181 /// \exception Barry::BadPassword
182 /// Thrown on invalid password, or not enough retries left
183 /// on device.
185 void Socket::Open(uint16_t socket, const char *password)
187 if( m_socket != 0 ) {
188 // already open
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
197 Data send, receive;
198 ZeroPacket packet(send, receive);
200 if( !m_halfOpen ) {
201 // starting fresh
202 m_remainingTries = 0;
204 SendOpen(socket, receive);
206 // check for password challenge, or success
207 if( packet.Command() == SB_COMMAND_PASSWORD_CHALLENGE ) {
208 m_halfOpen = true;
209 m_challengeSeed = packet.ChallengeSeed();
210 m_remainingTries = packet.RemainingTries();
213 // fall through to challenge code...
216 if( m_halfOpen ) {
217 // half open, device is expecting a password hash... do we
218 // have a password?
219 if( !password ) {
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
226 // commits suicide.
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.",
232 m_remainingTries);
235 SendPasswordHash(socket, password, receive);
237 if( packet.Command() == SB_COMMAND_PASSWORD_FAILED ) {
238 m_halfOpen = true;
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
246 m_halfOpen = false;
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
260 m_socket = socket;
264 // Close
266 /// Closes a non-default socket (i.e. non-zero socket number)
268 /// The packet sequence is just like Open(), except the command is
269 /// CLOSE_SOCKET.
271 /// \exception Barry::Error
273 void Socket::Close()
275 if( m_socket != 0 ) {
276 // only close non-default sockets
278 // build close command
279 Barry::Protocol::Packet packet;
280 packet.socket = 0;
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);
287 Data response;
288 try {
289 Send(command, response);
291 catch( Usb::Error & ) {
292 // reset so this won't be called again
293 m_socket = 0;
294 m_flag = 0;
296 eeout(command, response);
297 throw;
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
306 Receive(response);
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
316 m_socket = 0;
317 m_flag = 0;
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
328 m_socket = 0;
329 m_flag = 0;
334 // Send
336 /// Sends 'send' data to device, and waits for response.
338 /// \returns void
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
393 whole = fragment;
395 else {
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)
419 // sanity check
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");
425 // calculate size
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));
443 if( nextOffset )
444 wpack->command = SB_COMMAND_DB_FRAGMENTED;
445 else
446 wpack->command = SB_COMMAND_DB_DATA;
448 // adjust the new fragment size
449 fragment.ReleaseBuffer(SB_FRAG_HEADER_SIZE + todo);
451 // return next round
452 return nextOffset;
455 void Socket::CheckSequence(const Data &seq)
457 // if( m_socket == 0 ) {
458 // // don't do any sequence checking on socket 0
459 // return;
460 // }
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)
473 m_sequenceId = 0;
475 else {
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");
482 else {
483 dout("Bad sequence on socket 0: expected: "
484 << msequenceId
485 << ". Packet sequence: " << sequenceId);
490 // advance!
491 m_sequenceId++;
494 // sends the send packet down to the device, fragmenting if
495 // necessary, and returns the response in receive, defragmenting
496 // if needed
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()");
520 Data inFrag;
521 receive.Zap();
523 if( send.GetSize() <= MAX_PACKET_SIZE ) {
524 // send non-fragmented
525 Send(send, inFrag, timeout);
527 else {
528 // send fragmented
529 unsigned int offset = 0;
530 Data outFrag;
532 do {
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
539 // processing below
540 if( offset && inFrag.GetSize() > 0 ) {
542 Protocol::CheckSize(inFrag);
544 switch( rpack->command )
546 case SB_COMMAND_SEQUENCE_HANDSHAKE:
547 CheckSequence(inFrag);
548 break;
550 default:
551 eout("Command: " << std::setbase(16) << (unsigned int)rpack->command << inFrag);
552 throw Error("Socket: unhandled packet in Packet()");
553 break;
558 } while( offset > 0 );
561 bool done = false, frag = false;
562 int blankCount = 0;
563 while( !done ) {
564 MAKE_PACKET(rpack, inFrag);
566 // check the packet's validity
567 if( inFrag.GetSize() > 0 ) {
568 blankCount = 0;
570 Protocol::CheckSize(inFrag);
572 switch( rpack->command )
574 case SB_COMMAND_SEQUENCE_HANDSHAKE:
575 CheckSequence(inFrag);
576 break;
578 case SB_COMMAND_DB_DATA:
579 if( frag ) {
580 AppendFragment(receive, inFrag);
582 else {
583 receive = inFrag;
585 done = true;
586 break;
588 case SB_COMMAND_DB_FRAGMENTED:
589 AppendFragment(receive, inFrag);
590 frag = true;
591 break;
593 case SB_COMMAND_DB_DONE:
594 receive = inFrag;
595 done = true;
596 break;
598 default:
599 eout("Command: " << std::setbase(16) << (unsigned int)rpack->command << inFrag);
600 throw Error("Socket: unhandled packet in Packet()");
601 break;
604 else {
605 blankCount++;
606 //std::cerr << "Blank! " << blankCount << std::endl;
607 if( blankCount == 10 ) {
608 // only ask for more data on stalled sockets
609 // for so long
610 throw Error("Socket: 10 blank packets received");
614 if( !done ) {
615 // not done yet, ask for another read
616 Receive(inFrag);
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);
640 } // namespace Barry