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>
35 #include <sys/types.h>
44 #include "barrygetopt.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
)
83 cerr
<< _("From BB: ");
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
<< string_vprintf(_("Written %ld bytes over stdout"), (long int)writtenThisTime
) << 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;
120 int logical
, major
, minor
;
121 const char *Version
= Barry::Version(logical
, major
, minor
);
123 cerr
<< string_vprintf(
124 _("brawchannel - Command line USB Blackberry raw channel interface\n"
125 " Copyright 2010, RealVNC Ltd.\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"),
142 // Helper class to restore signal handlers when shutdown is occuring
143 // This class isn't responsible for setting up the signal handlers
144 // as they need to be restored before the Barry::Socket starts closing.
149 sighandler_t m_handler
;
151 SignalRestorer(int signum
, sighandler_t handler
)
152 : m_signum(signum
), m_handler(handler
) {}
153 ~SignalRestorer() { signal(m_signum
, m_handler
); }
156 int main(int argc
, char *argv
[])
160 // Setup signal handling
161 sighandler_t oldSigHup
= signal(SIGHUP
, &signalHandler
);
162 sighandler_t oldSigTerm
= signal(SIGTERM
, &signalHandler
);
163 sighandler_t oldSigInt
= signal(SIGINT
, &signalHandler
);
164 sighandler_t oldSigQuit
= signal(SIGQUIT
, &signalHandler
);
166 cerr
.sync_with_stdio(true); // since libusb uses
167 // stdio for debug messages
169 // Buffer to hold data read in from STDIN before sending it
170 // to the BlackBerry.
171 unsigned char *buf
= NULL
;
174 bool data_dump
= false;
177 // process command line options
179 int cmd
= getopt(argc
, argv
, "hp:P:v");
186 case 'p': // Blackberry PIN
187 pin
= strtoul(optarg
, NULL
, 16);
190 case 'P': // Device password
194 case 'v': // data dump on
209 cerr
<< _("Error: Missing raw channel name.") << endl
;
215 cerr
<< _("Error: Too many arguments.") << endl
;
220 // Fetch command from remaining arguments
221 string channelName
= argv
[0];
227 // Warn if USB_DEBUG isn't set to 0, 1 or 2
228 // as that usually means libusb will write to STDOUT
229 char *val
= getenv("USB_DEBUG");
230 int parsedValue
= -1;
232 parsedValue
= atoi(val
);
234 if( parsedValue
!= 0 && parsedValue
!= 1 && parsedValue
!= 2 ) {
235 cerr
<< _("Warning: Protocol dump enabled without setting USB_DEBUG to 0, 1 or 2.\n"
236 " libusb might log to STDOUT and ruin data stream.") << endl
;
240 // Initialize the barry library. Must be called before
242 Barry::Init(data_dump
, &cerr
);
244 // Probe the USB bus for Blackberry devices.
245 // If user has specified a PIN, search for it in the
246 // available device list here as well
248 int activeDevice
= probe
.FindActive(pin
);
249 if( activeDevice
== -1 ) {
250 cerr
<< _("No device selected, or PIN not found")
255 // Now get setup to open the channel.
257 cerr
<< _("Connected to device, starting read/write\n");
260 volatile bool running
= true;
262 // Create the thing which will write onto stdout
263 // and perform other callback duties.
264 CallbackHandler
callbackHandler(running
, data_dump
);
266 // Start a thread to handle any data arriving from
268 auto_ptr
<SocketRoutingQueue
> router
;
269 router
.reset(new SocketRoutingQueue());
270 router
->SpinoffSimpleReadThread();
272 // Create our controller object
273 Barry::Controller
con(probe
.Get(activeDevice
), *router
);
275 Barry::Mode::RawChannel
rawChannel(con
, callbackHandler
);
277 // Try to open the requested channel now everything is setup
278 rawChannel
.Open(password
.c_str(), channelName
.c_str());
280 // We now have a thread running to read from the
281 // BB and write over stdout; in this thread we'll
282 // read from stdin and write to the BB.
283 const size_t bufSize
= rawChannel
.MaximumSendSize();
284 buf
= new unsigned char[bufSize
];
289 // Set up the signal restorers to restore signal
290 // handling (in their destructors) before the socket
291 // starts to be closed. This allows, for example,
292 // double control-c presses to stop graceful close
294 SignalRestorer
srh(SIGHUP
, oldSigHup
);
295 SignalRestorer
srt(SIGTERM
, oldSigTerm
);
296 SignalRestorer
sri(SIGINT
, oldSigInt
);
297 SignalRestorer
srq(SIGQUIT
, oldSigQuit
);
299 while( running
&& !signalReceived
) {
300 FD_SET(STDIN_FILENO
, &rfds
);
301 tv
.tv_sec
= READ_TIMEOUT_SECONDS
;
304 int ret
= select(STDIN_FILENO
+ 1, &rfds
, NULL
, NULL
, &tv
);
306 cerr
<< _("Select failed with errno: ") << errno
<< endl
;
309 else if ( ret
&& FD_ISSET(STDIN_FILENO
, &rfds
) ) {
310 ssize_t haveRead
= read(STDIN_FILENO
, buf
, bufSize
);
312 Data
toWrite(buf
, haveRead
);
314 cerr
.setf(ios::dec
, ios::basefield
);
315 cerr
<< string_vprintf(_("Sending %ld bytes stdin->USB\n"), (long int)haveRead
);
316 cerr
<< _("To BB: ");
317 toWrite
.DumpHex(cerr
);
320 rawChannel
.Send(toWrite
);
322 cerr
.setf(ios::dec
, ios::basefield
);
323 cerr
<< string_vprintf(_("Sent %ld bytes stdin->USB\n"), (long int)haveRead
);
326 else if( haveRead
< 0 ) {
332 catch( Usb::Error
&ue
) {
333 cerr
<< _("Usb::Error caught: ") << ue
.what() << endl
;
336 catch( Barry::Error
&se
) {
337 cerr
<< _("Barry::Error caught: ") << se
.what() << endl
;
340 catch( exception
&e
) {
341 cerr
<< _("exception caught: ") << e
.what() << endl
;