blob: 826baaa5fb8b3158ce4260aa8a4be6a09004c482 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004--2005, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifndef TALK_P2P_BASE_SESSION_H_
29#define TALK_P2P_BASE_SESSION_H_
30
31#include <list>
32#include <map>
33#include <string>
34#include <vector>
35
36#include "talk/base/refcount.h"
37#include "talk/base/scoped_ptr.h"
38#include "talk/base/scoped_ref_ptr.h"
39#include "talk/base/socketaddress.h"
40#include "talk/p2p/base/parsing.h"
41#include "talk/p2p/base/port.h"
42#include "talk/p2p/base/sessionclient.h"
43#include "talk/p2p/base/sessionmanager.h"
44#include "talk/p2p/base/sessionmessages.h"
45#include "talk/p2p/base/transport.h"
46#include "talk/xmllite/xmlelement.h"
47#include "talk/xmpp/constants.h"
48
49namespace cricket {
50
51class BaseSession;
52class P2PTransportChannel;
53class Transport;
54class TransportChannel;
55class TransportChannelProxy;
56class TransportChannelImpl;
57
58typedef talk_base::RefCountedObject<talk_base::scoped_ptr<Transport> >
59TransportWrapper;
60
61// Used for errors that will send back a specific error message to the
62// remote peer. We add "type" to the errors because it's needed for
63// SignalErrorMessage.
64struct MessageError : ParseError {
65 buzz::QName type;
66
67 // if unset, assume type is a parse error
68 MessageError() : ParseError(), type(buzz::QN_STANZA_BAD_REQUEST) {}
69
70 void SetType(const buzz::QName type) {
71 this->type = type;
72 }
73};
74
75// Used for errors that may be returned by public session methods that
76// can fail.
77// TODO: Use this error in Session::Initiate and
78// Session::Accept.
79struct SessionError : WriteError {
80};
81
82// Bundles a Transport and ChannelMap together. ChannelMap is used to
83// create transport channels before receiving or sending a session
84// initiate, and for speculatively connecting channels. Previously, a
85// session had one ChannelMap and transport. Now, with multiple
86// transports per session, we need multiple ChannelMaps as well.
87
88typedef std::map<int, TransportChannelProxy*> ChannelMap;
89
90class TransportProxy : public sigslot::has_slots<>,
91 public CandidateTranslator {
92 public:
93 TransportProxy(
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000094 talk_base::Thread* worker_thread,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095 const std::string& sid,
96 const std::string& content_name,
97 TransportWrapper* transport)
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000098 : worker_thread_(worker_thread),
99 sid_(sid),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100 content_name_(content_name),
101 transport_(transport),
102 connecting_(false),
103 negotiated_(false),
104 sent_candidates_(false),
105 candidates_allocated_(false) {
106 transport_->get()->SignalCandidatesReady.connect(
107 this, &TransportProxy::OnTransportCandidatesReady);
108 }
109 ~TransportProxy();
110
111 std::string content_name() const { return content_name_; }
112 // TODO(juberti): It's not good form to expose the object you're wrapping,
113 // since callers can mutate it. Can we make this return a const Transport*?
114 Transport* impl() const { return transport_->get(); }
115
116 std::string type() const;
117 bool negotiated() const { return negotiated_; }
118 const Candidates& sent_candidates() const { return sent_candidates_; }
119 const Candidates& unsent_candidates() const { return unsent_candidates_; }
120 bool candidates_allocated() const { return candidates_allocated_; }
121 void set_candidates_allocated(bool allocated) {
122 candidates_allocated_ = allocated;
123 }
124
125 TransportChannel* GetChannel(int component);
126 TransportChannel* CreateChannel(const std::string& channel_name,
127 int component);
128 bool HasChannel(int component);
129 void DestroyChannel(int component);
130
131 void AddSentCandidates(const Candidates& candidates);
132 void AddUnsentCandidates(const Candidates& candidates);
133 void ClearSentCandidates() { sent_candidates_.clear(); }
134 void ClearUnsentCandidates() { unsent_candidates_.clear(); }
135
136 // Start the connection process for any channels, creating impls if needed.
137 void ConnectChannels();
138 // Hook up impls to the proxy channels. Doesn't change connect state.
139 void CompleteNegotiation();
140
141 // Mux this proxy onto the specified proxy's transport.
142 bool SetupMux(TransportProxy* proxy);
143
144 // Simple functions that thunk down to the same functions on Transport.
mallinath@webrtc.orga5506692013-08-12 21:18:15 +0000145 void SetIceRole(IceRole role);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000146 void SetIdentity(talk_base::SSLIdentity* identity);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000147 bool SetLocalTransportDescription(const TransportDescription& description,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000148 ContentAction action,
149 std::string* error_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150 bool SetRemoteTransportDescription(const TransportDescription& description,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000151 ContentAction action,
152 std::string* error_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000153 void OnSignalingReady();
154 bool OnRemoteCandidates(const Candidates& candidates, std::string* error);
155
156 // CandidateTranslator methods.
157 virtual bool GetChannelNameFromComponent(
158 int component, std::string* channel_name) const;
159 virtual bool GetComponentFromChannelName(
160 const std::string& channel_name, int* component) const;
161
162 // Called when a transport signals that it has new candidates.
163 void OnTransportCandidatesReady(cricket::Transport* transport,
164 const Candidates& candidates) {
165 SignalCandidatesReady(this, candidates);
166 }
167
168 // Handles sending of ready candidates and receiving of remote candidates.
169 sigslot::signal2<TransportProxy*,
170 const std::vector<Candidate>&> SignalCandidatesReady;
171
172 private:
173 TransportChannelProxy* GetChannelProxy(int component) const;
174 TransportChannelProxy* GetChannelProxyByName(const std::string& name) const;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000175
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000176 TransportChannelImpl* GetOrCreateChannelProxyImpl(int component);
177 TransportChannelImpl* GetOrCreateChannelProxyImpl_w(int component);
178
179 // Manipulators of transportchannelimpl in channel proxy.
180 void SetupChannelProxy(int component,
181 TransportChannelProxy* proxy);
182 void SetupChannelProxy_w(int component,
183 TransportChannelProxy* proxy);
184 void ReplaceChannelProxyImpl(TransportChannelProxy* proxy,
185 TransportChannelImpl* impl);
186 void ReplaceChannelProxyImpl_w(TransportChannelProxy* proxy,
187 TransportChannelImpl* impl);
188
189 talk_base::Thread* worker_thread_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000190 std::string sid_;
191 std::string content_name_;
192 talk_base::scoped_refptr<TransportWrapper> transport_;
193 bool connecting_;
194 bool negotiated_;
195 ChannelMap channels_;
196 Candidates sent_candidates_;
197 Candidates unsent_candidates_;
198 bool candidates_allocated_;
199};
200
201typedef std::map<std::string, TransportProxy*> TransportMap;
202
203// Statistics for all the transports of this session.
204typedef std::map<std::string, TransportStats> TransportStatsMap;
205typedef std::map<std::string, std::string> ProxyTransportMap;
206
207struct SessionStats {
208 ProxyTransportMap proxy_to_transport;
209 TransportStatsMap transport_stats;
210};
211
212// A BaseSession manages general session state. This includes negotiation
213// of both the application-level and network-level protocols: the former
214// defines what will be sent and the latter defines how it will be sent. Each
215// network-level protocol is represented by a Transport object. Each Transport
216// participates in the network-level negotiation. The individual streams of
217// packets are represented by TransportChannels. The application-level protocol
218// is represented by SessionDecription objects.
219class BaseSession : public sigslot::has_slots<>,
220 public talk_base::MessageHandler {
221 public:
222 enum {
223 MSG_TIMEOUT = 0,
224 MSG_ERROR,
225 MSG_STATE,
226 };
227
228 enum State {
229 STATE_INIT = 0,
230 STATE_SENTINITIATE, // sent initiate, waiting for Accept or Reject
231 STATE_RECEIVEDINITIATE, // received an initiate. Call Accept or Reject
232 STATE_SENTPRACCEPT, // sent provisional Accept
233 STATE_SENTACCEPT, // sent accept. begin connecting transport
234 STATE_RECEIVEDPRACCEPT, // received provisional Accept, waiting for Accept
235 STATE_RECEIVEDACCEPT, // received accept. begin connecting transport
236 STATE_SENTMODIFY, // sent modify, waiting for Accept or Reject
237 STATE_RECEIVEDMODIFY, // received modify, call Accept or Reject
238 STATE_SENTREJECT, // sent reject after receiving initiate
239 STATE_RECEIVEDREJECT, // received reject after sending initiate
240 STATE_SENTREDIRECT, // sent direct after receiving initiate
241 STATE_SENTTERMINATE, // sent terminate (any time / either side)
242 STATE_RECEIVEDTERMINATE, // received terminate (any time / either side)
243 STATE_INPROGRESS, // session accepted and in progress
244 STATE_DEINIT, // session is being destroyed
245 };
246
247 enum Error {
248 ERROR_NONE = 0, // no error
249 ERROR_TIME = 1, // no response to signaling
250 ERROR_RESPONSE = 2, // error during signaling
251 ERROR_NETWORK = 3, // network error, could not allocate network resources
252 ERROR_CONTENT = 4, // channel errors in SetLocalContent/SetRemoteContent
253 ERROR_TRANSPORT = 5, // transport error of some kind
254 };
255
256 // Convert State to a readable string.
257 static std::string StateToString(State state);
258
259 BaseSession(talk_base::Thread* signaling_thread,
260 talk_base::Thread* worker_thread,
261 PortAllocator* port_allocator,
262 const std::string& sid,
263 const std::string& content_type,
264 bool initiator);
265 virtual ~BaseSession();
266
267 talk_base::Thread* signaling_thread() { return signaling_thread_; }
268 talk_base::Thread* worker_thread() { return worker_thread_; }
269 PortAllocator* port_allocator() { return port_allocator_; }
270
271 // The ID of this session.
272 const std::string& id() const { return sid_; }
273
274 // TODO(juberti): This data is largely redundant, as it can now be obtained
275 // from local/remote_description(). Remove these functions and members.
276 // Returns the XML namespace identifying the type of this session.
277 const std::string& content_type() const { return content_type_; }
278 // Returns the XML namespace identifying the transport used for this session.
279 const std::string& transport_type() const { return transport_type_; }
280
281 // Indicates whether we initiated this session.
282 bool initiator() const { return initiator_; }
283
284 // Returns the application-level description given by our client.
285 // If we are the recipient, this will be NULL until we send an accept.
286 const SessionDescription* local_description() const {
287 return local_description_;
288 }
289 // Returns the application-level description given by the other client.
290 // If we are the initiator, this will be NULL until we receive an accept.
291 const SessionDescription* remote_description() const {
292 return remote_description_;
293 }
294 SessionDescription* remote_description() {
295 return remote_description_;
296 }
297
298 // Takes ownership of SessionDescription*
299 bool set_local_description(const SessionDescription* sdesc) {
300 if (sdesc != local_description_) {
301 delete local_description_;
302 local_description_ = sdesc;
303 }
304 return true;
305 }
306
307 // Takes ownership of SessionDescription*
308 bool set_remote_description(SessionDescription* sdesc) {
309 if (sdesc != remote_description_) {
310 delete remote_description_;
311 remote_description_ = sdesc;
312 }
313 return true;
314 }
315
316 const SessionDescription* initiator_description() const {
317 if (initiator_) {
318 return local_description_;
319 } else {
320 return remote_description_;
321 }
322 }
323
324 // Returns the current state of the session. See the enum above for details.
325 // Each time the state changes, we will fire this signal.
326 State state() const { return state_; }
327 sigslot::signal2<BaseSession* , State> SignalState;
328
329 // Returns the last error in the session. See the enum above for details.
330 // Each time the an error occurs, we will fire this signal.
331 Error error() const { return error_; }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000332 const std::string& error_desc() const { return error_desc_; }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000333 sigslot::signal2<BaseSession* , Error> SignalError;
334
335 // Updates the state, signaling if necessary.
336 virtual void SetState(State state);
337
338 // Updates the error state, signaling if necessary.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000339 // TODO(ronghuawu): remove the SetError method that doesn't take |error_desc|.
340 virtual void SetError(Error error, const std::string& error_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000341
342 // Fired when the remote description is updated, with the updated
343 // contents.
344 sigslot::signal2<BaseSession* , const ContentInfos&>
345 SignalRemoteDescriptionUpdate;
346
347 // Fired when SetState is called (regardless if there's a state change), which
348 // indicates the session description might have be updated.
349 sigslot::signal2<BaseSession*, ContentAction> SignalNewLocalDescription;
350
351 // Fired when SetState is called (regardless if there's a state change), which
352 // indicates the session description might have be updated.
353 sigslot::signal2<BaseSession*, ContentAction> SignalNewRemoteDescription;
354
355 // Returns the transport that has been negotiated or NULL if
356 // negotiation is still in progress.
wu@webrtc.org4551b792013-10-09 15:37:36 +0000357 virtual Transport* GetTransport(const std::string& content_name);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000358
359 // Creates a new channel with the given names. This method may be called
360 // immediately after creating the session. However, the actual
361 // implementation may not be fixed until transport negotiation completes.
362 // This will usually be called from the worker thread, but that
363 // shouldn't be an issue since the main thread will be blocked in
364 // Send when doing so.
365 virtual TransportChannel* CreateChannel(const std::string& content_name,
366 const std::string& channel_name,
367 int component);
368
369 // Returns the channel with the given names.
370 virtual TransportChannel* GetChannel(const std::string& content_name,
371 int component);
372
373 // Destroys the channel with the given names.
374 // This will usually be called from the worker thread, but that
375 // shouldn't be an issue since the main thread will be blocked in
376 // Send when doing so.
377 virtual void DestroyChannel(const std::string& content_name,
378 int component);
379
380 // Returns stats for all channels of all transports.
381 // This avoids exposing the internal structures used to track them.
382 virtual bool GetStats(SessionStats* stats);
383
wu@webrtc.org91053e72013-08-10 07:18:04 +0000384 talk_base::SSLIdentity* identity() { return identity_; }
385
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000386 protected:
wu@webrtc.org91053e72013-08-10 07:18:04 +0000387 // Specifies the identity to use in this session.
388 bool SetIdentity(talk_base::SSLIdentity* identity);
389
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000390 bool PushdownTransportDescription(ContentSource source,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000391 ContentAction action,
392 std::string* error_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000393 void set_initiator(bool initiator) { initiator_ = initiator; }
394
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000395 const TransportMap& transport_proxies() const { return transports_; }
396 // Get a TransportProxy by content_name or transport. NULL if not found.
397 TransportProxy* GetTransportProxy(const std::string& content_name);
398 TransportProxy* GetTransportProxy(const Transport* transport);
399 TransportProxy* GetFirstTransportProxy();
400 void DestroyTransportProxy(const std::string& content_name);
401 // TransportProxy is owned by session. Return proxy just for convenience.
402 TransportProxy* GetOrCreateTransportProxy(const std::string& content_name);
403 // Creates the actual transport object. Overridable for testing.
404 virtual Transport* CreateTransport(const std::string& content_name);
405
406 void OnSignalingReady();
407 void SpeculativelyConnectAllTransportChannels();
408 // Helper method to provide remote candidates to the transport.
409 bool OnRemoteCandidates(const std::string& content_name,
410 const Candidates& candidates,
411 std::string* error);
412
413 // This method will mux transport channels by content_name.
414 // First content is used for muxing.
415 bool MaybeEnableMuxingSupport();
416
417 // Called when a transport requests signaling.
418 virtual void OnTransportRequestSignaling(Transport* transport) {
419 }
420
421 // Called when the first channel of a transport begins connecting. We use
422 // this to start a timer, to make sure that the connection completes in a
423 // reasonable amount of time.
424 virtual void OnTransportConnecting(Transport* transport) {
425 }
426
427 // Called when a transport changes its writable state. We track this to make
428 // sure that the transport becomes writable within a reasonable amount of
429 // time. If this does not occur, we signal an error.
430 virtual void OnTransportWritable(Transport* transport) {
431 }
432 virtual void OnTransportReadable(Transport* transport) {
433 }
434
mallinath@webrtc.org385857d2014-02-14 00:56:12 +0000435 // Called when a transport has found its steady-state connections.
436 virtual void OnTransportCompleted(Transport* transport) {
437 }
438
439 // Called when a transport has failed permanently.
440 virtual void OnTransportFailed(Transport* transport) {
441 }
442
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000443 // Called when a transport signals that it has new candidates.
444 virtual void OnTransportProxyCandidatesReady(TransportProxy* proxy,
445 const Candidates& candidates) {
446 }
447
448 // Called when a transport signals that it found an error in an incoming
449 // message.
450 virtual void OnTransportSendError(Transport* transport,
451 const buzz::XmlElement* stanza,
452 const buzz::QName& name,
453 const std::string& type,
454 const std::string& text,
455 const buzz::XmlElement* extra_info) {
456 }
457
458 virtual void OnTransportRouteChange(
459 Transport* transport,
460 int component,
461 const cricket::Candidate& remote_candidate) {
462 }
463
464 virtual void OnTransportCandidatesAllocationDone(Transport* transport);
465
466 // Called when all transport channels allocated required candidates.
467 // This method should be used as an indication of candidates gathering process
468 // is completed and application can now send local candidates list to remote.
469 virtual void OnCandidatesAllocationDone() {
470 }
471
472 // Handles the ice role change callback from Transport. This must be
473 // propagated to all the transports.
474 virtual void OnRoleConflict();
475
476 // Handles messages posted to us.
477 virtual void OnMessage(talk_base::Message *pmsg);
478
479 protected:
480 State state_;
481 Error error_;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000482 std::string error_desc_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000483
484 private:
485 // Helper methods to push local and remote transport descriptions.
486 bool PushdownLocalTransportDescription(
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000487 const SessionDescription* sdesc, ContentAction action,
488 std::string* error_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000489 bool PushdownRemoteTransportDescription(
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000490 const SessionDescription* sdesc, ContentAction action,
491 std::string* error_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000492
493 bool IsCandidateAllocationDone() const;
494 void MaybeCandidateAllocationDone();
495
496 // This method will delete the Transport and TransportChannelImpls and
497 // replace those with the selected Transport objects. Selection is done
498 // based on the content_name and in this case first MediaContent information
499 // is used for mux.
500 bool SetSelectedProxy(const std::string& content_name,
501 const ContentGroup* muxed_group);
502 // Log session state.
503 void LogState(State old_state, State new_state);
504
505 // Returns true and the TransportInfo of the given |content_name|
506 // from |description|. Returns false if it's not available.
507 bool GetTransportDescription(const SessionDescription* description,
508 const std::string& content_name,
509 TransportDescription* info);
510
511 // Fires the new description signal according to the current state.
512 void SignalNewDescription();
513
514 // Gets the ContentAction and ContentSource according to the session state.
515 bool GetContentAction(ContentAction* action, ContentSource* source);
516
517 talk_base::Thread* signaling_thread_;
518 talk_base::Thread* worker_thread_;
519 PortAllocator* port_allocator_;
520 std::string sid_;
521 std::string content_type_;
522 std::string transport_type_;
523 bool initiator_;
524 talk_base::SSLIdentity* identity_;
525 const SessionDescription* local_description_;
526 SessionDescription* remote_description_;
527 uint64 ice_tiebreaker_;
528 // This flag will be set to true after the first role switch. This flag
529 // will enable us to stop any role switch during the call.
530 bool role_switch_;
531 TransportMap transports_;
532};
533
534// A specific Session created by the SessionManager, using XMPP for protocol.
535class Session : public BaseSession {
536 public:
537 // Returns the manager that created and owns this session.
538 SessionManager* session_manager() const { return session_manager_; }
539
540 // Returns the client that is handling the application data of this session.
541 SessionClient* client() const { return client_; }
542
543 // Returns the JID of this client.
544 const std::string& local_name() const { return local_name_; }
545
546 // Returns the JID of the other peer in this session.
547 const std::string& remote_name() const { return remote_name_; }
548
549 // Set the JID of the other peer in this session.
550 // Typically the remote_name_ is set when the session is initiated.
551 // However, sometimes (e.g when a proxy is used) the peer name is
552 // known after the BaseSession has been initiated and it must be updated
553 // explicitly.
554 void set_remote_name(const std::string& name) { remote_name_ = name; }
555
556 // Set the JID of the initiator of this session. Allows for the overriding
557 // of the initiator to be a third-party, eg. the MUC JID when creating p2p
558 // sessions.
559 void set_initiator_name(const std::string& name) { initiator_name_ = name; }
560
561 // Indicates the JID of the entity who initiated this session.
562 // In special cases, may be different than both local_name and remote_name.
563 const std::string& initiator_name() const { return initiator_name_; }
564
565 SignalingProtocol current_protocol() const { return current_protocol_; }
566
567 void set_current_protocol(SignalingProtocol protocol) {
568 current_protocol_ = protocol;
569 }
570
571 // Updates the error state, signaling if necessary.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000572 virtual void SetError(Error error, const std::string& error_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573
574 // When the session needs to send signaling messages, it beings by requesting
575 // signaling. The client should handle this by calling OnSignalingReady once
576 // it is ready to send the messages.
577 // (These are called only by SessionManager.)
578 sigslot::signal1<Session*> SignalRequestSignaling;
579 void OnSignalingReady() { BaseSession::OnSignalingReady(); }
580
581 // Takes ownership of session description.
582 // TODO: Add an error argument to pass back to the caller.
583 bool Initiate(const std::string& to,
584 const SessionDescription* sdesc);
585
586 // When we receive an initiate, we create a session in the
587 // RECEIVEDINITIATE state and respond by accepting or rejecting.
588 // Takes ownership of session description.
589 // TODO: Add an error argument to pass back to the caller.
590 bool Accept(const SessionDescription* sdesc);
591 bool Reject(const std::string& reason);
592 bool Terminate() {
593 return TerminateWithReason(STR_TERMINATE_SUCCESS);
594 }
595 bool TerminateWithReason(const std::string& reason);
596 // Fired whenever we receive a terminate message along with a reason
597 sigslot::signal2<Session*, const std::string&> SignalReceivedTerminateReason;
598
599 // The two clients in the session may also send one another
600 // arbitrary XML messages, which are called "info" messages. Sending
601 // takes ownership of the given elements. The signal does not; the
602 // parent element will be deleted after the signal.
wu@webrtc.org364f2042013-11-20 21:49:41 +0000603 bool SendInfoMessage(const XmlElements& elems,
604 const std::string& remote_name);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605 bool SendDescriptionInfoMessage(const ContentInfos& contents);
606 sigslot::signal2<Session*, const buzz::XmlElement*> SignalInfoMessage;
607
608 private:
609 // Creates or destroys a session. (These are called only SessionManager.)
610 Session(SessionManager *session_manager,
611 const std::string& local_name, const std::string& initiator_name,
612 const std::string& sid, const std::string& content_type,
613 SessionClient* client);
614 ~Session();
615 // For each transport info, create a transport proxy. Can fail for
616 // incompatible transport types.
617 bool CreateTransportProxies(const TransportInfos& tinfos,
618 SessionError* error);
619 bool OnRemoteCandidates(const TransportInfos& tinfos,
620 ParseError* error);
621 // Returns a TransportInfo without candidates for each content name.
622 // Uses the transport_type_ of the session.
623 TransportInfos GetEmptyTransportInfos(const ContentInfos& contents) const;
624
625 // Maps passed to serialization functions.
626 TransportParserMap GetTransportParsers();
627 ContentParserMap GetContentParsers();
628 CandidateTranslatorMap GetCandidateTranslators();
629
630 virtual void OnTransportRequestSignaling(Transport* transport);
631 virtual void OnTransportConnecting(Transport* transport);
632 virtual void OnTransportWritable(Transport* transport);
633 virtual void OnTransportProxyCandidatesReady(TransportProxy* proxy,
634 const Candidates& candidates);
635 virtual void OnTransportSendError(Transport* transport,
636 const buzz::XmlElement* stanza,
637 const buzz::QName& name,
638 const std::string& type,
639 const std::string& text,
640 const buzz::XmlElement* extra_info);
641 virtual void OnMessage(talk_base::Message *pmsg);
642
643 // Send various kinds of session messages.
644 bool SendInitiateMessage(const SessionDescription* sdesc,
645 SessionError* error);
646 bool SendAcceptMessage(const SessionDescription* sdesc, SessionError* error);
647 bool SendRejectMessage(const std::string& reason, SessionError* error);
648 bool SendTerminateMessage(const std::string& reason, SessionError* error);
649 bool SendTransportInfoMessage(const TransportInfo& tinfo,
650 SessionError* error);
651 bool SendTransportInfoMessage(const TransportProxy* transproxy,
652 const Candidates& candidates,
653 SessionError* error);
654
655 bool ResendAllTransportInfoMessages(SessionError* error);
656 bool SendAllUnsentTransportInfoMessages(SessionError* error);
657
wu@webrtc.org364f2042013-11-20 21:49:41 +0000658 // All versions of SendMessage send a message of the given type to
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659 // the other client. Can pass either a set of elements or an
660 // "action", which must have a WriteSessionAction method to go along
661 // with it. Sending with an action supports sending a "hybrid"
662 // message. Sending with elements must be sent as Jingle or Gingle.
663
664 // When passing elems, must be either Jingle or Gingle protocol.
665 // Takes ownership of action_elems.
666 bool SendMessage(ActionType type, const XmlElements& action_elems,
667 SessionError* error);
wu@webrtc.org364f2042013-11-20 21:49:41 +0000668 // Sends a messge, but overrides the remote name.
669 bool SendMessage(ActionType type, const XmlElements& action_elems,
670 const std::string& remote_name,
671 SessionError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672 // When passing an action, may be Hybrid protocol.
673 template <typename Action>
674 bool SendMessage(ActionType type, const Action& action,
675 SessionError* error);
676
677 // Helper methods to write the session message stanza.
678 template <typename Action>
679 bool WriteActionMessage(ActionType type, const Action& action,
680 buzz::XmlElement* stanza, WriteError* error);
681 template <typename Action>
682 bool WriteActionMessage(SignalingProtocol protocol,
683 ActionType type, const Action& action,
684 buzz::XmlElement* stanza, WriteError* error);
685
686 // Sending messages in hybrid form requires being able to write them
687 // on a per-protocol basis with a common method signature, which all
688 // of these have.
689 bool WriteSessionAction(SignalingProtocol protocol,
690 const SessionInitiate& init,
691 XmlElements* elems, WriteError* error);
692 bool WriteSessionAction(SignalingProtocol protocol,
693 const TransportInfo& tinfo,
694 XmlElements* elems, WriteError* error);
695 bool WriteSessionAction(SignalingProtocol protocol,
696 const SessionTerminate& term,
697 XmlElements* elems, WriteError* error);
698
699 // Sends a message back to the other client indicating that we have received
700 // and accepted their message.
701 void SendAcknowledgementMessage(const buzz::XmlElement* stanza);
702
703 // Once signaling is ready, the session will use this signal to request the
704 // sending of each message. When messages are received by the other client,
705 // they should be handed to OnIncomingMessage.
706 // (These are called only by SessionManager.)
707 sigslot::signal2<Session* , const buzz::XmlElement*> SignalOutgoingMessage;
708 void OnIncomingMessage(const SessionMessage& msg);
709
710 void OnIncomingResponse(const buzz::XmlElement* orig_stanza,
711 const buzz::XmlElement* response_stanza,
712 const SessionMessage& msg);
713 void OnInitiateAcked();
714 void OnFailedSend(const buzz::XmlElement* orig_stanza,
715 const buzz::XmlElement* error_stanza);
716
717 // Invoked when an error is found in an incoming message. This is translated
718 // into the appropriate XMPP response by SessionManager.
719 sigslot::signal6<BaseSession*,
720 const buzz::XmlElement*,
721 const buzz::QName&,
722 const std::string&,
723 const std::string&,
724 const buzz::XmlElement*> SignalErrorMessage;
725
726 // Handlers for the various types of messages. These functions may take
727 // pointers to the whole stanza or to just the session element.
728 bool OnInitiateMessage(const SessionMessage& msg, MessageError* error);
729 bool OnAcceptMessage(const SessionMessage& msg, MessageError* error);
730 bool OnRejectMessage(const SessionMessage& msg, MessageError* error);
731 bool OnInfoMessage(const SessionMessage& msg);
732 bool OnTerminateMessage(const SessionMessage& msg, MessageError* error);
733 bool OnTransportInfoMessage(const SessionMessage& msg, MessageError* error);
734 bool OnTransportAcceptMessage(const SessionMessage& msg, MessageError* error);
735 bool OnDescriptionInfoMessage(const SessionMessage& msg, MessageError* error);
736 bool OnRedirectError(const SessionRedirect& redirect, SessionError* error);
737
738 // Verifies that we are in the appropriate state to receive this message.
739 bool CheckState(State state, MessageError* error);
740
741 SessionManager* session_manager_;
742 bool initiate_acked_;
743 std::string local_name_;
744 std::string initiator_name_;
745 std::string remote_name_;
746 SessionClient* client_;
747 TransportParser* transport_parser_;
748 // Keeps track of what protocol we are speaking.
749 SignalingProtocol current_protocol_;
750
751 friend class SessionManager; // For access to constructor, destructor,
752 // and signaling related methods.
753};
754
755} // namespace cricket
756
757#endif // TALK_P2P_BASE_SESSION_H_