lib: wrap shared_ptr<> in a typedef as SocketDataHandlerPtr
[barry.git] / src / router.cc
blob99ecdc59b275cd7324cc517d16ef197abf29c498
1 ///
2 /// \file router.cc
3 /// Support classes for the pluggable socket routing system.
4 ///
6 /*
7 Copyright (C) 2008-2010, Net Direct Inc. (http://www.netdirect.ca/)
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
22 #include "router.h"
23 #include "scoped_lock.h"
24 #include "data.h"
25 #include "protostructs.h"
26 #include "usbwrap.h"
27 #include "endian.h"
28 #include "debug.h"
29 #include <unistd.h>
31 namespace Barry {
33 ///////////////////////////////////////////////////////////////////////////////
34 // SocketDataHandler default methods
36 void SocketRoutingQueue::SocketDataHandler::Error(Barry::Error &error)
38 // Just log the error
39 dout("SocketDataHandler: Error: " << error.what());
40 (void) error;
43 SocketRoutingQueue::SocketDataHandler::~SocketDataHandler()
45 // Nothing to destroy
48 ///////////////////////////////////////////////////////////////////////////////
49 // SocketRoutingQueue constructors
51 SocketRoutingQueue::SocketRoutingQueue(int prealloc_buffer_count)
52 : m_dev(0)
53 , m_writeEp(0)
54 , m_readEp(0)
55 , m_interest(false)
56 , m_seen_usb_error(false)
57 , m_continue_reading(false)
59 pthread_mutex_init(&m_mutex, NULL);
61 pthread_mutex_init(&m_readwaitMutex, NULL);
62 pthread_cond_init(&m_readwaitCond, NULL);
64 AllocateBuffers(prealloc_buffer_count);
67 SocketRoutingQueue::~SocketRoutingQueue()
69 // thread running?
70 if( m_continue_reading ) {
71 m_continue_reading = false;
72 pthread_join(m_usb_read_thread, NULL);
76 ///////////////////////////////////////////////////////////////////////////////
77 // protected members
80 // ReturnBuffer
82 /// Provides a method of returning a buffer to the free queue
83 /// after processing. The DataHandle class calls this automatically
84 /// from its destructor.
85 void SocketRoutingQueue::ReturnBuffer(Data *buf)
87 // don't need to lock here, since m_free handles its own locking
88 m_free.push(buf);
92 // SimpleReadThread()
94 /// Convenience thread to handle USB read activity.
95 ///
96 void *SocketRoutingQueue::SimpleReadThread(void *userptr)
98 SocketRoutingQueue *q = (SocketRoutingQueue *)userptr;
100 // read from USB and write to stdout until finished
101 q->m_seen_usb_error = false;
102 while( q->m_continue_reading ) {
103 q->DoRead(1000); // timeout in milliseconds
105 return 0;
109 ///////////////////////////////////////////////////////////////////////////////
110 // public API
112 // These functions connect the router to an external Usb::Device
113 // object. Normally this is handled automatically by the
114 // Controller class, but are public here in case they are needed.
115 void SocketRoutingQueue::SetUsbDevice(Usb::Device *dev, int writeEp, int readEp)
117 scoped_lock lock(m_mutex);
118 m_dev = dev;
119 m_writeEp = writeEp;
120 m_readEp = readEp;
123 void SocketRoutingQueue::ClearUsbDevice()
125 scoped_lock lock(m_mutex);
126 m_dev = 0;
127 lock.unlock();
129 // wait for the DoRead cycle to finish, so the external
130 // Usb::Device object doesn't close before we're done with it
131 scoped_lock wait(m_readwaitMutex);
132 pthread_cond_wait(&m_readwaitCond, &m_readwaitMutex);
135 bool SocketRoutingQueue::UsbDeviceReady()
137 scoped_lock lock(m_mutex);
138 return m_dev != 0;
142 // AllocateBuffers
144 /// This class starts out with no buffers, and will grow one buffer
145 /// at a time if needed. Call this to allocate count buffers
146 /// all at once and place them on the free queue. After calling
147 /// this function, at least count buffers will exist in the free
148 /// queue. If there are already count buffers, none will be added.
150 void SocketRoutingQueue::AllocateBuffers(int count)
152 int todo = count - m_free.size();
154 for( int i = 0; i < todo; i++ ) {
155 // m_free handles its own locking
156 m_free.push( new Data );
161 // DefaultRead (both variations)
163 /// Returns the data for the next unregistered socket.
164 /// Blocks until timeout or data is available.
165 /// Returns false (or null pointer) on timeout and no data.
166 /// With the return version of the function, there is no
167 /// copying performed.
169 /// This version performs a copy.
171 bool SocketRoutingQueue::DefaultRead(Data &receive, int timeout)
173 DataHandle buf = DefaultRead(timeout);
174 if( !buf.get() )
175 return false;
177 // copy to desired buffer
178 receive = *buf.get();
179 return true;
183 /// This version does not perform a copy.
185 DataHandle SocketRoutingQueue::DefaultRead(int timeout)
187 // m_default handles its own locking
188 Data *buf = m_default.wait_pop(timeout);
189 return DataHandle(*this, buf);
193 // RegisterInterest
195 /// Register an interest in data from a certain socket. To read
196 /// from that socket, use the SocketRead() function from then on.
198 /// Any non-registered socket goes in the default queue
199 /// and must be read by DefaultRead()
201 /// If not null, handler is called when new data is read. It will
202 /// be called in the same thread instance that DoRead() is called from.
203 /// Handler is passed the DataQueue Data pointer, and so no
204 /// copying is done. Once the handler returns, the data is
205 /// considered processed and not added to the interested queue,
206 /// but instead returned to m_free.
208 /// Throws std::logic_error if already registered.
210 void SocketRoutingQueue::RegisterInterest(SocketId socket,
211 SocketDataHandlerPtr handler)
213 // modifying our own std::map, need a lock
214 scoped_lock lock(m_mutex);
216 SocketQueueMap::iterator qi = m_socketQueues.find(socket);
217 if( qi != m_socketQueues.end() )
218 throw std::logic_error("RegisterInterest requesting a previously registered socket.");
220 m_socketQueues[socket] = QueueEntryPtr( new QueueEntry(handler) );
221 m_interest = true;
225 // UnregisterInterest
227 /// Unregisters interest in data from the given socket, and discards
228 /// any existing data in its interest queue. Any new incoming data
229 /// for this socket will be placed in the default queue.
231 void SocketRoutingQueue::UnregisterInterest(SocketId socket)
233 // modifying our own std::map, need a lock
234 scoped_lock lock(m_mutex);
236 SocketQueueMap::iterator qi = m_socketQueues.find(socket);
237 if( qi == m_socketQueues.end() )
238 return; // nothing registered, done
240 // salvage all our data buffers
241 m_free.append_from( qi->second->m_queue );
243 // remove the QueueEntryPtr from the map
244 m_socketQueues.erase( qi );
246 // check the interest flag
247 m_interest = m_socketQueues.size() > 0;
251 // SocketRead
253 /// Reads data from the interested socket cache. Can only read
254 /// from sockets that have been previously registered.
256 /// Blocks until timeout or data is available.
258 /// Returns false (or null pointer) on timeout and no data.
259 /// With the return version of the function, there is no
260 /// copying performed.
262 /// Throws std::logic_error if a socket was requested that was
263 /// not previously registered.
265 /// Copying is performed with this function.
267 bool SocketRoutingQueue::SocketRead(SocketId socket, Data &receive, int timeout)
269 DataHandle buf = SocketRead(socket, timeout);
270 if( !buf.get() )
271 return false;
273 // copy to desired buffer
274 receive = *buf.get();
275 return true;
279 /// Copying is not performed with this function.
281 /// Throws std::logic_error if a socket was requested that was
282 /// not previously registered.
284 DataHandle SocketRoutingQueue::SocketRead(SocketId socket, int timeout)
286 QueueEntryPtr qep;
287 DataQueue *dq = 0;
289 // accessing our own std::map, need a lock
291 scoped_lock lock(m_mutex);
292 SocketQueueMap::iterator qi = m_socketQueues.find(socket);
293 if( qi == m_socketQueues.end() )
294 throw std::logic_error("SocketRead requested data from unregistered socket.");
296 // got our queue, save the whole QueueEntryPtr (shared_ptr),
297 // and unlock, since we will be waiting on the DataQueue,
298 // not the socketQueues map
300 // This is safe, since even if UnregisterInterest is called,
301 // our pointer won't be deleted until our shared_ptr
302 // (QueueEntryPtr) goes out of scope.
304 // The remaining problem is that wait_pop() might wait
305 // forever if there is no timeout... c'est la vie.
306 // Should'a used a timeout. :-)
307 qep = qi->second;
308 dq = &qep->m_queue;
311 // get data from DataQueue
312 Data *buf = dq->wait_pop(timeout);
314 // specifically delete our copy of shared pointer, in a locked
315 // environment
317 scoped_lock lock(m_mutex);
318 qep.reset();
321 return DataHandle(*this, buf);
324 // Returns true if data is available for that socket.
325 bool SocketRoutingQueue::IsAvailable(SocketId socket) const
327 scoped_lock lock(m_mutex);
328 SocketQueueMap::const_iterator qi = m_socketQueues.find(socket);
329 if( qi == m_socketQueues.end() )
330 return false;
331 return qi->second->m_queue.size() > 0;
335 // DoRead
337 /// Called by the application's "read thread" to read the next usb
338 /// packet and route it to the correct queue. Returns after every
339 /// read, even if a handler is associated with a queue.
340 /// Note: this function is safe to call before SetUsbDevice() is
341 /// called... it just doesn't do anything if there is no usb
342 /// device to work with.
344 /// Timeout is in milliseconds.
345 void SocketRoutingQueue::DoRead(int timeout)
347 class ReadWaitSignal
349 pthread_mutex_t &m_Mutex;
350 pthread_cond_t &m_Cond;
351 public:
352 ReadWaitSignal(pthread_mutex_t &mut, pthread_cond_t &cond)
353 : m_Mutex(mut), m_Cond(cond)
355 ~ReadWaitSignal()
357 scoped_lock wait(m_Mutex);
358 pthread_cond_signal(&m_Cond);
360 } readwait(m_readwaitMutex, m_readwaitCond);
362 Usb::Device * volatile dev = 0;
363 int readEp;
364 DataHandle buf(*this, 0);
366 // if we are not connected to a USB device yet, just wait
368 scoped_lock lock(m_mutex);
370 if( !m_dev || m_seen_usb_error ) {
371 lock.unlock(); // unlock early, since we're sleeping
372 // sleep only a short time, since things could be
373 // in the process of setup or teardown
374 usleep(125000);
375 return;
378 dev = m_dev;
379 readEp = m_readEp;
381 // fetch a free buffer
382 Data *raw = m_free.pop();
383 if( !raw )
384 buf = DataHandle(*this, new Data);
385 else
386 buf = DataHandle(*this, raw);
389 // take a chance and do the read unlocked, as this has the potential
390 // for blocking for a while
391 try {
393 Data &data = *buf.get();
395 if( !dev->BulkRead(readEp, data, timeout) )
396 return; // no data, done!
398 MAKE_PACKET(pack, data);
400 // make sure the size is right
401 if( data.GetSize() < sizeof(pack->socket) )
402 return; // bad size, just skip
404 // extract the socket from the packet
405 uint16_t socket = btohs(pack->socket);
407 // we have data, now lock up again to place it
408 // in the right queue
409 scoped_lock lock(m_mutex);
411 // search for registration of socket
412 if( m_interest ) {
413 SocketQueueMap::iterator qi = m_socketQueues.find(socket);
414 if( qi != m_socketQueues.end() ) {
415 SocketDataHandlerPtr &sdh = qi->second->m_handler;
417 // is there a handler?
418 if( sdh ) {
419 // unlock & let the handler process it
420 lock.unlock();
421 sdh->DataReceived(*buf.get());
422 return;
424 else {
425 qi->second->m_queue.push(buf.release());
426 return;
430 // fall through
433 // safe to unlock now, we are done with the map
434 lock.unlock();
436 // if we get here, send to default queue
437 m_default.push(buf.release());
439 catch( Usb::Timeout & ) {
440 // this is expected... just ignore
442 catch( Usb::Error &ue ) {
443 // this is unexpected, but we're in a thread here...
444 // Need to iterate through all the registered handlers
445 // calling their error callback.
446 // Can't be locked when calling the callback, so need
447 // to make a list of them first.
448 scoped_lock lock(m_mutex);
449 std::vector<SocketDataHandlerPtr> handlers;
450 SocketQueueMap::iterator qi = m_socketQueues.begin();
451 while( qi != m_socketQueues.end() ) {
452 SocketDataHandlerPtr &sdh = qi->second->m_handler;
453 // is there a handler?
454 if( sdh ) {
455 handlers.push_back(sdh);
457 ++qi;
459 lock.unlock();
460 std::vector<SocketDataHandlerPtr>::iterator hi = handlers.begin();
461 while( hi != handlers.end() ) {
462 (*hi)->Error(ue);
463 ++hi;
465 m_seen_usb_error = true;
469 void SocketRoutingQueue::SpinoffSimpleReadThread()
471 // signal that it's ok to run inside the thread
472 if( m_continue_reading )
473 return; // already running
474 m_continue_reading = true;
476 // Start USB read thread, to handle all routing
477 int ret = pthread_create(&m_usb_read_thread, NULL, &SimpleReadThread, this);
478 if( ret ) {
479 m_continue_reading = false;
480 throw Barry::ErrnoError("SocketRoutingQueue: Error creating USB read thread.", ret);
484 } // namespace Barry