2 /// \file brawchannel.cc
3 /// Directs a named raw channel over STDIN/STDOUT
7 Copyright (C) 2010, RealVNC Ltd.
9 Some parts are inspired from bjavaloader.cc
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 See the GNU General Public License in the COPYING file at the
21 root directory of this project for more details.
25 #include <barry/barry.h>
37 #include <sys/types.h>
45 using namespace Barry
;
47 // How long to wait between reads before checking if should shutdown
48 #define READ_TIMEOUT_SECONDS 1
50 static volatile bool signalReceived
= false;
52 static void signalHandler(int signum
)
54 signalReceived
= true;
59 // Wrapper for pthread_mutex_t
64 pthread_mutex_t m_mutex
;
74 : m_initialized(false)
76 int ret
= pthread_mutex_init(&m_mutex
, NULL
);
78 throw Barry::Error("Mutex: failed to create mutex");
86 int ret
= pthread_mutex_destroy(&m_mutex
);
88 cerr
<< "Failed to destroy mutex with error: " << ret
<< endl
;
95 int ret
= pthread_mutex_lock(&m_mutex
);
97 throw Barry::Error("Mutex: failed to lock mutex");
103 int ret
= pthread_mutex_unlock(&m_mutex
);
105 throw Barry::Error("Mutex: failed to unlock mutex");
109 // RAII wrapper for locking Mutex class
116 MutexLock(Mutex
& mutex
)
119 { mutex
.Lock(); m_locked
= true; };
127 ~MutexLock() { Unlock(); }
130 // Wrapper for pthread_cont_t
139 void Wait(Mutex
& mutex
);
144 : m_initialized(false)
146 int ret
= pthread_cond_init(&m_cv
, NULL
);
148 throw Barry::Error("Condvar: failed to create condvar");
150 m_initialized
= true;
155 if( m_initialized
) {
156 int ret
= pthread_cond_destroy(&m_cv
);
158 cerr
<< "Failed to destroy condvar with error: " << ret
<< endl
;
162 void Condvar::Wait(Mutex
& mutex
)
164 int ret
= pthread_cond_wait(&m_cv
, &mutex
.m_mutex
);
166 throw Barry::Error("Condvar: failed to wait on condvar");
170 void Condvar::Signal()
172 int ret
= pthread_cond_signal(&m_cv
);
174 throw Barry::Error("Condvar: failed to signal condvar");
178 // Semaphore class for signalling between threads
186 Semaphore(int initialVal
= 0);
188 void WaitForSignal();
192 Semaphore::Semaphore(int initialVal
)
193 : m_value(initialVal
)
199 Semaphore::~Semaphore()
203 void Semaphore::WaitForSignal()
205 MutexLock
lock(m_mutex
);
206 while( m_value
<= 0 ) {
213 void Semaphore::Signal()
215 MutexLock
lock(m_mutex
);
221 class CallbackHandler
: public Barry::Mode::RawChannelDataCallback
224 volatile bool* m_continuePtr
;
226 Semaphore
& m_semaphore
;
229 CallbackHandler(volatile bool& keepGoing
, bool verbose
, Semaphore
& semaphore
)
230 : m_continuePtr(&keepGoing
)
232 , m_semaphore(semaphore
)
237 public: // From RawChannelDataCallback
238 virtual void DataReceived(Data
& data
);
239 virtual void DataSendAck();
240 virtual void ChannelError(string msg
);
241 virtual void ChannelClose();
245 void CallbackHandler::DataReceived(Data
& data
)
253 size_t toWrite
= data
.GetSize();
256 while( written
< toWrite
&& *m_continuePtr
) {
257 ssize_t writtenThisTime
= write(STDOUT_FILENO
, &(data
.GetData()[written
]), toWrite
- written
);
259 cerr
.setf(ios::dec
, ios::basefield
);
260 cerr
<< "Written " << writtenThisTime
<< " bytes over stdout" << endl
;
263 if( writtenThisTime
< 0 ) {
267 written
+= writtenThisTime
;
272 void CallbackHandler::DataSendAck()
274 m_semaphore
.Signal();
277 void CallbackHandler::ChannelError(string msg
)
279 cerr
<< "CallbackHandler: Received error: " << msg
<< endl
;
283 void CallbackHandler::ChannelClose()
285 *m_continuePtr
= false;
286 m_semaphore
.Signal();
289 // Class which extends the functionality of SocketRoutingQueue to add
290 // error detection and setting of a continue boolean to false when an
291 // error is detected.
292 // This code is heavily based on the thread
293 // creation code of SocketRoutingQueue, which sadly has too many
294 // private variables to just sub-class.
295 class ErrorHandlingSocketRoutingQueue
298 static void* ReadThreadFunction(void* userPtr
)
300 ErrorHandlingSocketRoutingQueue
*q
= (ErrorHandlingSocketRoutingQueue
*)userPtr
;
302 // read from USB and write to stdout until finished
304 while( q
->m_runningThread
) {
305 if( !q
->m_socketRoutingQueue
.DoRead(msg
, READ_TIMEOUT_SECONDS
* 1000) &&
306 // Only report the first failure, so check m_continuePtr
307 *q
->m_continuePtr
) {
308 cerr
<< "Error in ReadThread: " << msg
<< endl
;
309 *q
->m_continuePtr
= false;
310 q
->m_semaphore
.Signal();
316 SocketRoutingQueue m_socketRoutingQueue
;
317 volatile bool* m_continuePtr
;
318 volatile bool m_runningThread
;
319 pthread_t m_usb_read_thread
;
320 Semaphore
& m_semaphore
;
322 ErrorHandlingSocketRoutingQueue(volatile bool& continuePtr
, Semaphore
& semaphore
)
323 : m_socketRoutingQueue()
324 , m_continuePtr(&continuePtr
)
325 , m_runningThread(false)
326 , m_semaphore(semaphore
)
331 ~ErrorHandlingSocketRoutingQueue()
333 // Is the read thread still running
334 if( m_runningThread
) {
335 m_runningThread
= false;
336 pthread_join(m_usb_read_thread
, NULL
);
340 // Utility function to make it easier to create the
341 // USB pure-read thread.
342 // Throws Barry::ErrnoError on thread creation error.
343 void SpinoffReadThread()
345 // signal that it's ok to run inside the thread
346 if( m_runningThread
)
347 return; // already running
348 m_runningThread
= true;
350 // Start USB read thread, to handle all routing
351 int ret
= pthread_create(&m_usb_read_thread
, NULL
, &ReadThreadFunction
, this);
353 m_runningThread
= false;
354 throw Barry::ErrnoError("SocketRoutingQueue: Error creating USB read thread.", ret
);
358 SocketRoutingQueue
* GetSocketRoutingQueue()
360 return &m_socketRoutingQueue
;
367 const char *Version
= Barry::Version(major
, minor
);
370 << "brawchannel - Command line USB Blackberry raw channel interface\n"
371 << " Copyright 2010, RealVNC Ltd.\n"
372 << " Using: " << Version
<< "\n"
375 << "brawchannel [options] <channel name>\n"
378 << " -p pin PIN of device to talk with\n"
379 << " If only one device is plugged in, this flag is optional\n"
380 << " -P pass Simplistic method to specify device password\n"
381 << " -v Dump protocol data during operation\n"
382 << " This will cause libusb output to appear on STDOUT unless\n"
383 << " the environment variable USB_DEBUG is set to 0,1 or 2.\n"
387 // Helper class to restore signal handlers when shutdown is occuring
388 // This class isn't responsible for setting up the signal handlers
389 // as they need to be restored before the Barry::Socket starts closing.
394 sighandler_t m_handler
;
396 SignalRestorer(int signum
, sighandler_t handler
)
397 : m_signum(signum
), m_handler(handler
) {}
398 ~SignalRestorer() { signal(m_signum
, m_handler
); }
401 int main(int argc
, char *argv
[])
405 // Setup signal handling
406 sighandler_t oldSigHup
= signal(SIGHUP
, &signalHandler
);
407 sighandler_t oldSigTerm
= signal(SIGTERM
, &signalHandler
);
408 sighandler_t oldSigInt
= signal(SIGINT
, &signalHandler
);
409 sighandler_t oldSigQuit
= signal(SIGQUIT
, &signalHandler
);
411 cerr
.sync_with_stdio(true); // since libusb uses
412 // stdio for debug messages
414 // Buffer to hold data read in from STDIN before sending it
415 // to the BlackBerry.
416 unsigned char* buf
= NULL
;
419 bool data_dump
= false;
422 // process command line options
424 int cmd
= getopt(argc
, argv
, "hp:P:v");
431 case 'p': // Blackberry PIN
432 pin
= strtoul(optarg
, NULL
, 16);
435 case 'P': // Device password
439 case 'v': // data dump on
454 cerr
<< "Error: Missing raw channel name." << endl
;
460 cerr
<< "Error: Too many arguments." << endl
;
465 // Fetch command from remaining arguments
466 string channelName
= argv
[0];
472 // Warn if USB_DEBUG isn't set to 0, 1 or 2
473 // as that usually means libusb will write to STDOUT
474 char* val
= getenv("USB_DEBUG");
475 int parsedValue
= -1;
477 parsedValue
= atoi(val
);
479 if( parsedValue
!= 0 && parsedValue
!= 1 && parsedValue
!= 2 ) {
480 cerr
<< "Warning: Protocol dump enabled without setting USB_DEBUG to 0, 1 or 2.\n"
481 << " libusb might log to STDOUT and ruin data stream." << endl
;
485 // Initialize the barry library. Must be called before
487 Barry::Init(data_dump
, &cerr
);
489 // Probe the USB bus for Blackberry devices.
490 // If user has specified a PIN, search for it in the
491 // available device list here as well
493 int activeDevice
= probe
.FindActive(pin
);
494 if( activeDevice
== -1 ) {
495 cerr
<< "No device selected, or PIN not found" << endl
;
499 // Now get setup to open the channel.
501 cerr
<< "Connected to device, starting read/write\n";
504 volatile bool running
= true;
508 // Create the thing which will write onto stdout
509 // and perform other callback duties.
510 CallbackHandler
callbackHandler(running
, data_dump
, sem
);
512 // Start a thread to handle any data arriving from
514 auto_ptr
<ErrorHandlingSocketRoutingQueue
> router
;
515 router
.reset(new ErrorHandlingSocketRoutingQueue(running
, sem
));
516 router
->SpinoffReadThread();
518 // Create our controller object
519 Barry::Controller
con(probe
.Get(activeDevice
), *router
->GetSocketRoutingQueue());
521 Barry::Mode::RawChannel
rawChannel(con
, callbackHandler
);
523 // Try to open the requested channel now everything is setup
524 rawChannel
.Open(password
.c_str(), channelName
.c_str());
526 // We now have a thread running to read from the
527 // BB and write over stdout; in this thread we'll
528 // read from stdin and write to the BB.
529 const size_t bufSize
= rawChannel
.MaximumSendSize();
530 buf
= new unsigned char[bufSize
];
535 // Set up the signal restorers to restore signal
536 // handling (in their destructors) before the socket
537 // starts to be closed. This allows, for example,
538 // double control-c presses to stop graceful close
540 SignalRestorer
srh(SIGHUP
, oldSigHup
);
541 SignalRestorer
srt(SIGTERM
, oldSigTerm
);
542 SignalRestorer
sri(SIGINT
, oldSigInt
);
543 SignalRestorer
srq(SIGQUIT
, oldSigQuit
);
545 while( running
&& !signalReceived
) {
546 FD_SET(STDIN_FILENO
, &rfds
);
547 tv
.tv_sec
= READ_TIMEOUT_SECONDS
;
550 int ret
= select(1, &rfds
, NULL
, NULL
, &tv
);
552 cerr
<< "Select failed with errno: " << errno
<< endl
;
555 else if ( ret
&& FD_ISSET(STDIN_FILENO
, &rfds
) ) {
556 ssize_t haveRead
= read(STDIN_FILENO
, buf
, bufSize
);
558 Data
toWrite(buf
, haveRead
);
560 cerr
.setf(ios::dec
, ios::basefield
);
561 cerr
<< "Sending " << haveRead
<< " bytes stdin->USB\n";
563 toWrite
.DumpHex(cerr
);
566 rawChannel
.Send(toWrite
);
568 cerr
.setf(ios::dec
, ios::basefield
);
569 cerr
<< "Sent " << ios::dec
<< haveRead
<< " bytes stdin->USB\n";
571 // Wait for the write to be completed before reading
572 // the next data to send.
575 else if( haveRead
< 0 ) {
581 catch( Usb::Error
&ue
) {
582 cerr
<< "Usb::Error caught: " << ue
.what() << endl
;
585 catch( Barry::Error
&se
) {
586 cerr
<< "Barry::Error caught: " << se
.what() << endl
;
589 catch( exception
&e
) {
590 cerr
<< "exception caught: " << e
.what() << endl
;