lib: show offset and rectype in HexDumpParser
[barry.git] / tools / brawchannel.cc
blob0eb4d208e55090a828912d3f542e8d51dbba216c
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 <getopt.h>
34 #include <fstream>
35 #include <string.h>
36 #include <sys/types.h>
37 #include <sys/time.h>
38 #include <unistd.h>
39 #include <signal.h>
40 #include <errno.h>
41 #include <pthread.h>
43 #include "i18n.h"
44 #include "platform.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 << "Written " << writtenThisTime << " bytes over stdout" << 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 major, minor;
121 const char *Version = Barry::Version(major, minor);
123 cerr
124 << "brawchannel - Command line USB Blackberry raw channel interface\n"
125 << " Copyright 2010, RealVNC Ltd.\n"
126 << " Using: " << Version << "\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 << endl;
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.
144 class SignalRestorer
146 private:
147 int m_signum;
148 sighandler_t m_handler;
149 public:
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[])
157 INIT_I18N(PACKAGE);
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;
171 try {
172 uint32_t pin = 0;
173 bool data_dump = false;
174 string password;
176 // process command line options
177 for( ;; ) {
178 int cmd = getopt(argc, argv, "hp:P:v");
179 if( cmd == -1 ) {
180 break;
183 switch( cmd )
185 case 'p': // Blackberry PIN
186 pin = strtoul(optarg, NULL, 16);
187 break;
189 case 'P': // Device password
190 password = optarg;
191 break;
193 case 'v': // data dump on
194 data_dump = true;
195 break;
197 case 'h': // help
198 default:
199 Usage();
200 return 0;
204 argc -= optind;
205 argv += optind;
207 if( argc < 1 ) {
208 cerr << "Error: Missing raw channel name." << endl;
209 Usage();
210 return 1;
213 if( argc > 1 ) {
214 cerr << "Error: Too many arguments." << endl;
215 Usage();
216 return 1;
219 // Fetch command from remaining arguments
220 string channelName = argv[0];
221 argc --;
222 argv ++;
225 if( data_dump ) {
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;
230 if( val ) {
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
240 // anything else.
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
246 Barry::Probe probe;
247 int activeDevice = probe.FindActive(pin);
248 if( activeDevice == -1 ) {
249 cerr << "No device selected, or PIN not found" << endl;
250 return 1;
253 // Now get setup to open the channel.
254 if( data_dump ) {
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
265 // the BlackBerry.
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];
283 fd_set rfds;
284 struct timeval tv;
285 FD_ZERO(&rfds);
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
291 // down.
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;
300 tv.tv_usec = 0;
302 int ret = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);
303 if( ret < 0 ) {
304 cerr << "Select failed with errno: " << errno << endl;
305 running = false;
307 else if ( ret && FD_ISSET(STDIN_FILENO, &rfds) ) {
308 ssize_t haveRead = read(STDIN_FILENO, buf, bufSize);
309 if( haveRead > 0 ) {
310 Data toWrite(buf, haveRead);
311 if( data_dump ) {
312 cerr.setf(ios::dec, ios::basefield);
313 cerr << "Sending " << haveRead << " bytes stdin->USB\n";
314 cerr << "To BB: ";
315 toWrite.DumpHex(cerr);
316 cerr << "\n";
318 rawChannel.Send(toWrite);
319 if( data_dump ) {
320 cerr.setf(ios::dec, ios::basefield);
321 cerr << "Sent " << haveRead << " bytes stdin->USB\n";
324 else if( haveRead < 0 ) {
325 running = false;
330 catch( Usb::Error &ue ) {
331 cerr << "Usb::Error caught: " << ue.what() << endl;
332 return 1;
334 catch( Barry::Error &se ) {
335 cerr << "Barry::Error caught: " << se.what() << endl;
336 return 1;
338 catch( exception &e ) {
339 cerr << "exception caught: " << e.what() << endl;
340 return 1;
343 delete[] buf;
345 return 0;