Barry debian version 0.18.5-1
[barry.git] / tools / brawchannel.cc
blob2d68f9118eec07176556574232363b3557295f0c
1 ///
2 /// \file brawchannel.cc
3 /// Directs a named raw channel over STDIN/STDOUT
4 ///
6 /*
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>
26 #include <iostream>
27 #include <vector>
28 #include <string>
29 #include <cstring>
30 #include <cstdio>
31 #include <cstdlib>
32 #include <algorithm>
33 #include <fstream>
34 #include <string.h>
35 #include <sys/types.h>
36 #include <sys/time.h>
37 #include <unistd.h>
38 #include <signal.h>
39 #include <errno.h>
40 #include <pthread.h>
42 #include "i18n.h"
43 #include "platform.h"
44 #include "barrygetopt.h"
46 using namespace std;
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
61 private:
62 volatile bool *m_continuePtr;
63 bool m_verbose;
65 public:
66 CallbackHandler(volatile bool &keepGoing, bool verbose)
67 : m_continuePtr(&keepGoing)
68 , m_verbose(verbose)
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)
82 if( m_verbose ) {
83 cerr << _("From BB: ");
84 data.DumpHex(cerr);
85 cerr << "\n";
88 size_t toWrite = data.GetSize();
89 size_t written = 0;
91 while( written < toWrite && *m_continuePtr ) {
92 ssize_t writtenThisTime = write(STDOUT_FILENO, &(data.GetData()[written]), toWrite - written);
93 if( m_verbose ) {
94 cerr.setf(ios::dec, ios::basefield);
95 cerr << string_vprintf(_("Written %ld bytes over stdout"), (long int)writtenThisTime) << endl;
97 fflush(stdout);
98 if( writtenThisTime < 0 ) {
99 ChannelClose();
101 else {
102 written += writtenThisTime;
107 void CallbackHandler::ChannelError(string msg)
109 cerr << _("CallbackHandler: Received error: ") << msg << endl;
110 ChannelClose();
113 void CallbackHandler::ChannelClose()
115 *m_continuePtr = false;
118 void Usage()
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"
126 " Using: %s\n"
127 "\n"
128 "Usage:\n"
129 "brawchannel [options] <channel name>\n"
130 "\n"
131 " -h This help\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"),
138 Version)
139 << endl;
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.
145 class SignalRestorer
147 private:
148 int m_signum;
149 sighandler_t m_handler;
150 public:
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[])
158 INIT_I18N(PACKAGE);
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;
172 try {
173 uint32_t pin = 0;
174 bool data_dump = false;
175 string password;
177 // process command line options
178 for( ;; ) {
179 int cmd = getopt(argc, argv, "hp:P:v");
180 if( cmd == -1 ) {
181 break;
184 switch( cmd )
186 case 'p': // Blackberry PIN
187 pin = strtoul(optarg, NULL, 16);
188 break;
190 case 'P': // Device password
191 password = optarg;
192 break;
194 case 'v': // data dump on
195 data_dump = true;
196 break;
198 case 'h': // help
199 default:
200 Usage();
201 return 0;
205 argc -= optind;
206 argv += optind;
208 if( argc < 1 ) {
209 cerr << _("Error: Missing raw channel name.") << endl;
210 Usage();
211 return 1;
214 if( argc > 1 ) {
215 cerr << _("Error: Too many arguments.") << endl;
216 Usage();
217 return 1;
220 // Fetch command from remaining arguments
221 string channelName = argv[0];
222 argc --;
223 argv ++;
226 if( data_dump ) {
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;
231 if( val ) {
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
241 // anything else.
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
247 Barry::Probe probe;
248 int activeDevice = probe.FindActive(pin);
249 if( activeDevice == -1 ) {
250 cerr << _("No device selected, or PIN not found")
251 << endl;
252 return 1;
255 // Now get setup to open the channel.
256 if( data_dump ) {
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
267 // the BlackBerry.
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];
285 fd_set rfds;
286 struct timeval tv;
287 FD_ZERO(&rfds);
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
293 // down.
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;
302 tv.tv_usec = 0;
304 int ret = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);
305 if( ret < 0 ) {
306 cerr << _("Select failed with errno: ") << errno << endl;
307 running = false;
309 else if ( ret && FD_ISSET(STDIN_FILENO, &rfds) ) {
310 ssize_t haveRead = read(STDIN_FILENO, buf, bufSize);
311 if( haveRead > 0 ) {
312 Data toWrite(buf, haveRead);
313 if( data_dump ) {
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);
318 cerr << "\n";
320 rawChannel.Send(toWrite);
321 if( data_dump ) {
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 ) {
327 running = false;
332 catch( Usb::Error &ue ) {
333 cerr << _("Usb::Error caught: ") << ue.what() << endl;
334 return 1;
336 catch( Barry::Error &se ) {
337 cerr << _("Barry::Error caught: ") << se.what() << endl;
338 return 1;
340 catch( exception &e ) {
341 cerr << _("exception caught: ") << e.what() << endl;
342 return 1;
345 delete[] buf;
347 return 0;