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>
36 #include <sys/types.h>
47 using namespace Barry
;
49 // How long to wait between reads before checking if should shutdown
50 #define READ_TIMEOUT_SECONDS 1
52 static volatile bool signalReceived
= false;
54 static void signalHandler(int signum
)
56 signalReceived
= true;
59 class CallbackHandler
: public Barry::Mode::RawChannelDataCallback
62 volatile bool *m_continuePtr
;
66 CallbackHandler(volatile bool &keepGoing
, bool verbose
)
67 : m_continuePtr(&keepGoing
)
73 public: // From RawChannelDataCallback
74 virtual void DataReceived(Data
&data
);
75 virtual void ChannelError(string msg
);
76 virtual void ChannelClose();
80 void CallbackHandler::DataReceived(Data
&data
)
88 size_t toWrite
= data
.GetSize();
91 while( written
< toWrite
&& *m_continuePtr
) {
92 ssize_t writtenThisTime
= write(STDOUT_FILENO
, &(data
.GetData()[written
]), toWrite
- written
);
94 cerr
.setf(ios::dec
, ios::basefield
);
95 cerr
<< "Written " << writtenThisTime
<< " bytes over stdout" << endl
;
98 if( writtenThisTime
< 0 ) {
102 written
+= writtenThisTime
;
107 void CallbackHandler::ChannelError(string msg
)
109 cerr
<< "CallbackHandler: Received error: " << msg
<< endl
;
113 void CallbackHandler::ChannelClose()
115 *m_continuePtr
= false;
121 const char *Version
= Barry::Version(major
, minor
);
124 << "brawchannel - Command line USB Blackberry raw channel interface\n"
125 << " Copyright 2010, RealVNC Ltd.\n"
126 << " Using: " << Version
<< "\n"
129 << "brawchannel [options] <channel name>\n"
132 << " -p pin PIN of device to talk with\n"
133 << " If only one device is plugged in, this flag is optional\n"
134 << " -P pass Simplistic method to specify device password\n"
135 << " -v Dump protocol data during operation\n"
136 << " This will cause libusb output to appear on STDOUT unless\n"
137 << " the environment variable USB_DEBUG is set to 0,1 or 2.\n"
141 // Helper class to restore signal handlers when shutdown is occuring
142 // This class isn't responsible for setting up the signal handlers
143 // as they need to be restored before the Barry::Socket starts closing.
148 sighandler_t m_handler
;
150 SignalRestorer(int signum
, sighandler_t handler
)
151 : m_signum(signum
), m_handler(handler
) {}
152 ~SignalRestorer() { signal(m_signum
, m_handler
); }
155 int main(int argc
, char *argv
[])
159 // Setup signal handling
160 sighandler_t oldSigHup
= signal(SIGHUP
, &signalHandler
);
161 sighandler_t oldSigTerm
= signal(SIGTERM
, &signalHandler
);
162 sighandler_t oldSigInt
= signal(SIGINT
, &signalHandler
);
163 sighandler_t oldSigQuit
= signal(SIGQUIT
, &signalHandler
);
165 cerr
.sync_with_stdio(true); // since libusb uses
166 // stdio for debug messages
168 // Buffer to hold data read in from STDIN before sending it
169 // to the BlackBerry.
170 unsigned char *buf
= NULL
;
173 bool data_dump
= false;
176 // process command line options
178 int cmd
= getopt(argc
, argv
, "hp:P:v");
185 case 'p': // Blackberry PIN
186 pin
= strtoul(optarg
, NULL
, 16);
189 case 'P': // Device password
193 case 'v': // data dump on
208 cerr
<< "Error: Missing raw channel name." << endl
;
214 cerr
<< "Error: Too many arguments." << endl
;
219 // Fetch command from remaining arguments
220 string channelName
= argv
[0];
226 // Warn if USB_DEBUG isn't set to 0, 1 or 2
227 // as that usually means libusb will write to STDOUT
228 char *val
= getenv("USB_DEBUG");
229 int parsedValue
= -1;
231 parsedValue
= atoi(val
);
233 if( parsedValue
!= 0 && parsedValue
!= 1 && parsedValue
!= 2 ) {
234 cerr
<< "Warning: Protocol dump enabled without setting USB_DEBUG to 0, 1 or 2.\n"
235 << " libusb might log to STDOUT and ruin data stream." << endl
;
239 // Initialize the barry library. Must be called before
241 Barry::Init(data_dump
, &cerr
);
243 // Probe the USB bus for Blackberry devices.
244 // If user has specified a PIN, search for it in the
245 // available device list here as well
247 int activeDevice
= probe
.FindActive(pin
);
248 if( activeDevice
== -1 ) {
249 cerr
<< "No device selected, or PIN not found" << endl
;
253 // Now get setup to open the channel.
255 cerr
<< "Connected to device, starting read/write\n";
258 volatile bool running
= true;
260 // Create the thing which will write onto stdout
261 // and perform other callback duties.
262 CallbackHandler
callbackHandler(running
, data_dump
);
264 // Start a thread to handle any data arriving from
266 auto_ptr
<SocketRoutingQueue
> router
;
267 router
.reset(new SocketRoutingQueue());
268 router
->SpinoffSimpleReadThread();
270 // Create our controller object
271 Barry::Controller
con(probe
.Get(activeDevice
), *router
);
273 Barry::Mode::RawChannel
rawChannel(con
, callbackHandler
);
275 // Try to open the requested channel now everything is setup
276 rawChannel
.Open(password
.c_str(), channelName
.c_str());
278 // We now have a thread running to read from the
279 // BB and write over stdout; in this thread we'll
280 // read from stdin and write to the BB.
281 const size_t bufSize
= rawChannel
.MaximumSendSize();
282 buf
= new unsigned char[bufSize
];
287 // Set up the signal restorers to restore signal
288 // handling (in their destructors) before the socket
289 // starts to be closed. This allows, for example,
290 // double control-c presses to stop graceful close
292 SignalRestorer
srh(SIGHUP
, oldSigHup
);
293 SignalRestorer
srt(SIGTERM
, oldSigTerm
);
294 SignalRestorer
sri(SIGINT
, oldSigInt
);
295 SignalRestorer
srq(SIGQUIT
, oldSigQuit
);
297 while( running
&& !signalReceived
) {
298 FD_SET(STDIN_FILENO
, &rfds
);
299 tv
.tv_sec
= READ_TIMEOUT_SECONDS
;
302 int ret
= select(STDIN_FILENO
+ 1, &rfds
, NULL
, NULL
, &tv
);
304 cerr
<< "Select failed with errno: " << errno
<< endl
;
307 else if ( ret
&& FD_ISSET(STDIN_FILENO
, &rfds
) ) {
308 ssize_t haveRead
= read(STDIN_FILENO
, buf
, bufSize
);
310 Data
toWrite(buf
, haveRead
);
312 cerr
.setf(ios::dec
, ios::basefield
);
313 cerr
<< "Sending " << haveRead
<< " bytes stdin->USB\n";
315 toWrite
.DumpHex(cerr
);
318 rawChannel
.Send(toWrite
);
320 cerr
.setf(ios::dec
, ios::basefield
);
321 cerr
<< "Sent " << haveRead
<< " bytes stdin->USB\n";
324 else if( haveRead
< 0 ) {
330 catch( Usb::Error
&ue
) {
331 cerr
<< "Usb::Error caught: " << ue
.what() << endl
;
334 catch( Barry::Error
&se
) {
335 cerr
<< "Barry::Error caught: " << se
.what() << endl
;
338 catch( exception
&e
) {
339 cerr
<< "exception caught: " << e
.what() << endl
;