Home | History | Annotate | Download | only in system
      1 // Copyright 2013 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef MOJO_SYSTEM_CHANNEL_H_
      6 #define MOJO_SYSTEM_CHANNEL_H_
      7 
      8 #include <stdint.h>
      9 
     10 #include "base/basictypes.h"
     11 #include "base/compiler_specific.h"
     12 #include "base/containers/hash_tables.h"
     13 #include "base/memory/ref_counted.h"
     14 #include "base/memory/scoped_ptr.h"
     15 #include "base/strings/string_piece.h"
     16 #include "base/synchronization/lock.h"
     17 #include "base/threading/thread_checker.h"
     18 #include "mojo/embedder/scoped_platform_handle.h"
     19 #include "mojo/public/c/system/types.h"
     20 #include "mojo/system/message_in_transit.h"
     21 #include "mojo/system/message_pipe.h"
     22 #include "mojo/system/raw_channel.h"
     23 #include "mojo/system/system_impl_export.h"
     24 
     25 namespace mojo {
     26 namespace system {
     27 
     28 // This class is mostly thread-safe. It must be created on an I/O thread.
     29 // |Init()| must be called on that same thread before it becomes thread-safe (in
     30 // particular, before references are given to any other thread) and |Shutdown()|
     31 // must be called on that same thread before destruction. Its public methods are
     32 // otherwise thread-safe. It may be destroyed on any thread, in the sense that
     33 // the last reference to it may be released on any thread, with the proviso that
     34 // |Shutdown()| must have been called first (so the pattern is that a "main"
     35 // reference is kept on its creation thread and is released after |Shutdown()|
     36 // is called, but other threads may have temporarily "dangling" references).
     37 //
     38 // Note that |MessagePipe| calls into |Channel| and the former's |lock_| must be
     39 // acquired before the latter's. When |Channel| wants to call into a
     40 // |MessagePipe|, it must obtain a reference to the |MessagePipe| (from
     41 // |local_id_to_endpoint_info_map_|) under |Channel::lock_| and then release the
     42 // lock.
     43 //
     44 // Also, care must be taken with respect to references: While a |Channel| has
     45 // references to |MessagePipe|s, |MessagePipe|s (via |ProxyMessagePipeEndpoint|)
     46 // may also have references to |Channel|s. These references are set up by
     47 // calling |AttachMessagePipeEndpoint()|. The reference to |MessagePipe| owned
     48 // by |Channel| must be removed by calling |DetachMessagePipeEndpoint()| (which
     49 // is done by |MessagePipe|/|ProxyMessagePipeEndpoint|, which simultaneously
     50 // removes its reference to |Channel|).
     51 class MOJO_SYSTEM_IMPL_EXPORT Channel
     52     : public base::RefCountedThreadSafe<Channel>,
     53       public RawChannel::Delegate {
     54  public:
     55   // The first message pipe endpoint attached will have this as its local ID.
     56   static const MessageInTransit::EndpointId kBootstrapEndpointId = 1;
     57 
     58   Channel();
     59 
     60   // This must be called on the creation thread before any other methods are
     61   // called, and before references to this object are given to any other
     62   // threads. |raw_channel| should be uninitialized. Returns true on success. On
     63   // failure, no other methods should be called (including |Shutdown()|).
     64   bool Init(scoped_ptr<RawChannel> raw_channel);
     65 
     66   // This must be called on the creation thread before destruction (which can
     67   // happen on any thread).
     68   void Shutdown();
     69 
     70   // Attaches the given message pipe/port's endpoint (which must be a
     71   // |ProxyMessagePipeEndpoint|) to this channel. This assigns it a local ID,
     72   // which it returns. The first message pipe endpoint attached will always have
     73   // |kBootstrapEndpointId| as its local ID. (For bootstrapping, this occurs on
     74   // both sides, so one should use |kBootstrapEndpointId| for the remote ID for
     75   // the first message pipe across a channel.) Returns |kInvalidEndpointId| on
     76   // failure.
     77   // TODO(vtl): Maybe limit the number of attached message pipes.
     78   MessageInTransit::EndpointId AttachMessagePipeEndpoint(
     79       scoped_refptr<MessagePipe> message_pipe,
     80       unsigned port);
     81 
     82   // Runs the message pipe with the given |local_id| (previously attached), with
     83   // the given |remote_id| (negotiated using some other means, e.g., over an
     84   // existing message pipe; see comments above for the bootstrap case). Returns
     85   // false on failure, in particular if no message pipe with |local_id| is
     86   // attached.
     87   bool RunMessagePipeEndpoint(MessageInTransit::EndpointId local_id,
     88                               MessageInTransit::EndpointId remote_id);
     89 
     90   // Tells the other side of the channel to run a message pipe endpoint (which
     91   // must already be attached); |local_id| and |remote_id| are relative to this
     92   // channel (i.e., |local_id| is the other side's remote ID and |remote_id| is
     93   // its local ID).
     94   // TODO(vtl): Maybe we should just have a flag argument to
     95   // |RunMessagePipeEndpoint()| that tells it to do this.
     96   void RunRemoteMessagePipeEndpoint(MessageInTransit::EndpointId local_id,
     97                                     MessageInTransit::EndpointId remote_id);
     98 
     99   // This forwards |message| verbatim to |raw_channel_|.
    100   bool WriteMessage(scoped_ptr<MessageInTransit> message);
    101 
    102   // See |RawChannel::IsWriteBufferEmpty()|.
    103   // TODO(vtl): Maybe we shouldn't expose this, and instead have a
    104   // |FlushWriteBufferAndShutdown()| or something like that.
    105   bool IsWriteBufferEmpty();
    106 
    107   // This removes the message pipe/port's endpoint (with the given local ID and
    108   // given remote ID, which should be |kInvalidEndpointId| if not yet running),
    109   // returned by |AttachMessagePipeEndpoint()| from this channel. After this is
    110   // called, |local_id| may be reused for another message pipe.
    111   void DetachMessagePipeEndpoint(MessageInTransit::EndpointId local_id,
    112                                  MessageInTransit::EndpointId remote_id);
    113 
    114   // See |RawChannel::GetSerializedPlatformHandleSize()|.
    115   size_t GetSerializedPlatformHandleSize() const;
    116 
    117  private:
    118   struct EndpointInfo {
    119     enum State {
    120       // Attached, possibly running or not.
    121       STATE_NORMAL,
    122       // "Zombie" states:
    123       // Waiting for |DetachMessagePipeEndpoint()| before removing.
    124       STATE_WAIT_LOCAL_DETACH,
    125       // Waiting for a |kSubtypeChannelRemoveMessagePipeEndpointAck| before
    126       // removing.
    127       STATE_WAIT_REMOTE_REMOVE_ACK,
    128       // Waiting for both of the above conditions before removing.
    129       STATE_WAIT_LOCAL_DETACH_AND_REMOTE_REMOVE_ACK,
    130     };
    131 
    132     EndpointInfo();
    133     EndpointInfo(scoped_refptr<MessagePipe> message_pipe, unsigned port);
    134     ~EndpointInfo();
    135 
    136     State state;
    137     scoped_refptr<MessagePipe> message_pipe;
    138     unsigned port;
    139   };
    140 
    141   friend class base::RefCountedThreadSafe<Channel>;
    142   virtual ~Channel();
    143 
    144   // |RawChannel::Delegate| implementation:
    145   virtual void OnReadMessage(
    146       const MessageInTransit::View& message_view,
    147       embedder::ScopedPlatformHandleVectorPtr platform_handles) OVERRIDE;
    148   virtual void OnFatalError(FatalError fatal_error) OVERRIDE;
    149 
    150   // Helpers for |OnReadMessage|:
    151   void OnReadMessageForDownstream(
    152       const MessageInTransit::View& message_view,
    153       embedder::ScopedPlatformHandleVectorPtr platform_handles);
    154   void OnReadMessageForChannel(
    155       const MessageInTransit::View& message_view,
    156       embedder::ScopedPlatformHandleVectorPtr platform_handles);
    157 
    158   // Removes the message pipe endpoint with the given local ID, which must exist
    159   // and be a zombie, and given remote ID. Returns false on failure, in
    160   // particular if no message pipe with |local_id| is attached.
    161   bool RemoveMessagePipeEndpoint(MessageInTransit::EndpointId local_id,
    162                                  MessageInTransit::EndpointId remote_id);
    163 
    164   // Handles errors (e.g., invalid messages) from the remote side.
    165   void HandleRemoteError(const base::StringPiece& error_message);
    166   // Handles internal errors/failures from the local side.
    167   void HandleLocalError(const base::StringPiece& error_message);
    168 
    169   // Helper to send channel control messages. Returns true on success. Should be
    170   // called *without* |lock_| held.
    171   bool SendControlMessage(MessageInTransit::Subtype subtype,
    172                           MessageInTransit::EndpointId source_id,
    173                           MessageInTransit::EndpointId destination_id);
    174 
    175   bool is_running_no_lock() const { return is_running_; }
    176 
    177   base::ThreadChecker creation_thread_checker_;
    178 
    179   // Note: |MessagePipe|s MUST NOT be used under |lock_|. I.e., |lock_| can only
    180   // be acquired after |MessagePipe::lock_|, never before. Thus to call into a
    181   // |MessagePipe|, a reference should be acquired from
    182   // |local_id_to_endpoint_info_map_| under |lock_| (e.g., by copying the
    183   // |EndpointInfo|) and then the lock released.
    184   base::Lock lock_;  // Protects the members below.
    185 
    186   scoped_ptr<RawChannel> raw_channel_;
    187   bool is_running_;
    188 
    189   typedef base::hash_map<MessageInTransit::EndpointId, EndpointInfo>
    190       IdToEndpointInfoMap;
    191   IdToEndpointInfoMap local_id_to_endpoint_info_map_;
    192   // The next local ID to try (when allocating new local IDs). Note: It should
    193   // be checked for existence before use.
    194   MessageInTransit::EndpointId next_local_id_;
    195 
    196   DISALLOW_COPY_AND_ASSIGN(Channel);
    197 };
    198 
    199 }  // namespace system
    200 }  // namespace mojo
    201 
    202 #endif  // MOJO_SYSTEM_CHANNEL_H_
    203