maint: removed ppa_build.sh per request by Martin Owens
[barry.git] / tools / brawchannel.cc
blob2fc2f9f084ec3d025b97209eacc632cd57a24cc1
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 <unistd.h>
37 #include <sys/types.h>
38 #include <signal.h>
39 #include <errno.h>
40 #include <pthread.h>
42 #include "i18n.h"
44 using namespace std;
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;
57 class CallbackHandler : public Barry::Mode::RawChannelDataCallback
59 private:
60 volatile bool *m_continuePtr;
61 bool m_verbose;
63 public:
64 CallbackHandler(volatile bool &keepGoing, bool verbose)
65 : m_continuePtr(&keepGoing)
66 , m_verbose(verbose)
71 public: // From RawChannelDataCallback
72 virtual void DataReceived(Data &data);
73 virtual void ChannelError(string msg);
74 virtual void ChannelClose();
78 void CallbackHandler::DataReceived(Data &data)
80 if( m_verbose ) {
81 cerr << "From BB: ";
82 data.DumpHex(cerr);
83 cerr << "\n";
86 size_t toWrite = data.GetSize();
87 size_t written = 0;
89 while( written < toWrite && *m_continuePtr ) {
90 ssize_t writtenThisTime = write(STDOUT_FILENO, &(data.GetData()[written]), toWrite - written);
91 if( m_verbose ) {
92 cerr.setf(ios::dec, ios::basefield);
93 cerr << "Written " << writtenThisTime << " bytes over stdout" << endl;
95 fflush(stdout);
96 if( writtenThisTime < 0 ) {
97 ChannelClose();
99 else {
100 written += writtenThisTime;
105 void CallbackHandler::ChannelError(string msg)
107 cerr << "CallbackHandler: Received error: " << msg << endl;
108 ChannelClose();
111 void CallbackHandler::ChannelClose()
113 *m_continuePtr = false;
116 void Usage()
118 int major, minor;
119 const char *Version = Barry::Version(major, minor);
121 cerr
122 << "brawchannel - Command line USB Blackberry raw channel interface\n"
123 << " Copyright 2010, RealVNC Ltd.\n"
124 << " Using: " << Version << "\n"
125 << "\n"
126 << "Usage:\n"
127 << "brawchannel [options] <channel name>\n"
128 << "\n"
129 << " -h This help\n"
130 << " -p pin PIN of device to talk with\n"
131 << " If only one device is plugged in, this flag is optional\n"
132 << " -P pass Simplistic method to specify device password\n"
133 << " -v Dump protocol data during operation\n"
134 << " This will cause libusb output to appear on STDOUT unless\n"
135 << " the environment variable USB_DEBUG is set to 0,1 or 2.\n"
136 << endl;
139 // Helper class to restore signal handlers when shutdown is occuring
140 // This class isn't responsible for setting up the signal handlers
141 // as they need to be restored before the Barry::Socket starts closing.
142 class SignalRestorer
144 private:
145 int m_signum;
146 sighandler_t m_handler;
147 public:
148 SignalRestorer(int signum, sighandler_t handler)
149 : m_signum(signum), m_handler(handler) {}
150 ~SignalRestorer() { signal(m_signum, m_handler); }
153 int main(int argc, char *argv[])
155 INIT_I18N(PACKAGE);
157 // Setup signal handling
158 sighandler_t oldSigHup = signal(SIGHUP, &signalHandler);
159 sighandler_t oldSigTerm = signal(SIGTERM, &signalHandler);
160 sighandler_t oldSigInt = signal(SIGINT, &signalHandler);
161 sighandler_t oldSigQuit = signal(SIGQUIT, &signalHandler);
163 cerr.sync_with_stdio(true); // since libusb uses
164 // stdio for debug messages
166 // Buffer to hold data read in from STDIN before sending it
167 // to the BlackBerry.
168 unsigned char *buf = NULL;
169 try {
170 uint32_t pin = 0;
171 bool data_dump = false;
172 string password;
174 // process command line options
175 for( ;; ) {
176 int cmd = getopt(argc, argv, "hp:P:v");
177 if( cmd == -1 ) {
178 break;
181 switch( cmd )
183 case 'p': // Blackberry PIN
184 pin = strtoul(optarg, NULL, 16);
185 break;
187 case 'P': // Device password
188 password = optarg;
189 break;
191 case 'v': // data dump on
192 data_dump = true;
193 break;
195 case 'h': // help
196 default:
197 Usage();
198 return 0;
202 argc -= optind;
203 argv += optind;
205 if( argc < 1 ) {
206 cerr << "Error: Missing raw channel name." << endl;
207 Usage();
208 return 1;
211 if( argc > 1 ) {
212 cerr << "Error: Too many arguments." << endl;
213 Usage();
214 return 1;
217 // Fetch command from remaining arguments
218 string channelName = argv[0];
219 argc --;
220 argv ++;
223 if( data_dump ) {
224 // Warn if USB_DEBUG isn't set to 0, 1 or 2
225 // as that usually means libusb will write to STDOUT
226 char *val = getenv("USB_DEBUG");
227 int parsedValue = -1;
228 if( val ) {
229 parsedValue = atoi(val);
231 if( parsedValue != 0 && parsedValue != 1 && parsedValue != 2 ) {
232 cerr << "Warning: Protocol dump enabled without setting USB_DEBUG to 0, 1 or 2.\n"
233 << " libusb might log to STDOUT and ruin data stream." << endl;
237 // Initialize the barry library. Must be called before
238 // anything else.
239 Barry::Init(data_dump, &cerr);
241 // Probe the USB bus for Blackberry devices.
242 // If user has specified a PIN, search for it in the
243 // available device list here as well
244 Barry::Probe probe;
245 int activeDevice = probe.FindActive(pin);
246 if( activeDevice == -1 ) {
247 cerr << "No device selected, or PIN not found" << endl;
248 return 1;
251 // Now get setup to open the channel.
252 if( data_dump ) {
253 cerr << "Connected to device, starting read/write\n";
256 volatile bool running = true;
258 // Create the thing which will write onto stdout
259 // and perform other callback duties.
260 CallbackHandler callbackHandler(running, data_dump);
262 // Start a thread to handle any data arriving from
263 // the BlackBerry.
264 auto_ptr<SocketRoutingQueue> router;
265 router.reset(new SocketRoutingQueue());
266 router->SpinoffSimpleReadThread();
268 // Create our controller object
269 Barry::Controller con(probe.Get(activeDevice), *router);
271 Barry::Mode::RawChannel rawChannel(con, callbackHandler);
273 // Try to open the requested channel now everything is setup
274 rawChannel.Open(password.c_str(), channelName.c_str());
276 // We now have a thread running to read from the
277 // BB and write over stdout; in this thread we'll
278 // read from stdin and write to the BB.
279 const size_t bufSize = rawChannel.MaximumSendSize();
280 buf = new unsigned char[bufSize];
281 fd_set rfds;
282 struct timeval tv;
283 FD_ZERO(&rfds);
285 // Set up the signal restorers to restore signal
286 // handling (in their destructors) before the socket
287 // starts to be closed. This allows, for example,
288 // double control-c presses to stop graceful close
289 // down.
290 SignalRestorer srh(SIGHUP, oldSigHup);
291 SignalRestorer srt(SIGTERM, oldSigTerm);
292 SignalRestorer sri(SIGINT, oldSigInt);
293 SignalRestorer srq(SIGQUIT, oldSigQuit);
295 while( running && !signalReceived ) {
296 FD_SET(STDIN_FILENO, &rfds);
297 tv.tv_sec = READ_TIMEOUT_SECONDS;
298 tv.tv_usec = 0;
300 int ret = select(1, &rfds, NULL, NULL, &tv);
301 if( ret < 0 ) {
302 cerr << "Select failed with errno: " << errno << endl;
303 running = false;
305 else if ( ret && FD_ISSET(STDIN_FILENO, &rfds) ) {
306 ssize_t haveRead = read(STDIN_FILENO, buf, bufSize);
307 if( haveRead > 0 ) {
308 Data toWrite(buf, haveRead);
309 if( data_dump ) {
310 cerr.setf(ios::dec, ios::basefield);
311 cerr << "Sending " << haveRead << " bytes stdin->USB\n";
312 cerr << "To BB: ";
313 toWrite.DumpHex(cerr);
314 cerr << "\n";
316 rawChannel.Send(toWrite);
317 if( data_dump ) {
318 cerr.setf(ios::dec, ios::basefield);
319 cerr << "Sent " << haveRead << " bytes stdin->USB\n";
322 else if( haveRead < 0 ) {
323 running = false;
328 catch( Usb::Error &ue ) {
329 cerr << "Usb::Error caught: " << ue.what() << endl;
330 return 1;
332 catch( Barry::Error &se ) {
333 cerr << "Barry::Error caught: " << se.what() << endl;
334 return 1;
336 catch( exception &e ) {
337 cerr << "exception caught: " << e.what() << endl;
338 return 1;
341 delete[] buf;
343 return 0;