-
Notifications
You must be signed in to change notification settings - Fork 17
/
yjinglechan.cpp
4745 lines (4507 loc) · 154 KB
/
yjinglechan.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* yjinglechan.cpp
* This file is part of the YATE Project http://YATE.null.ro
*
* Jingle channel
*
* Yet Another Telephony Engine - a fully featured software PBX and IVR
* Copyright (C) 2004-2023 Null Team
* Author: Marian Podgoreanu
*
* This software is distributed under multiple licenses;
* see the COPYING file in the main directory for licensing
* information for this specific distribution.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
/*
============================================================================
TODO:
Check SRTP handling. Check if secure (mandatory) is handled properly
============================================================================
*/
#include <yatephone.h>
#include <yatemime.h>
#include <yateversn.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <yatejingle.h>
using namespace TelEngine;
namespace { // anonymous
class YJGEngine; // Jingle engine
class YJGEngineWorker; // Jingle engine worker
class YJGConnection; // Jingle channel
class YJGTransfer; // Transfer thread (route and execute)
class YJGMessageHandler; // Module message handlers
class YJGDriver; // The driver
// URI
#define BUILD_XMPP_URI(jid) (plugin.name() + ":" + jid)
/*
* YJGEngine
*/
class YJGEngine : public JGEngine
{
public:
// Send a session's stanza (dispatch a jabber.iq message)
virtual bool sendStanza(JGSession* session, XmlElement*& stanza);
// Event processor
virtual void processEvent(JGEvent* event);
};
/*
* YJGEngineWorker
*/
class YJGEngineWorker : public Thread
{
public:
inline YJGEngineWorker(Thread::Priority prio = Thread::Normal)
: Thread("YJGEngineWorker",prio)
{}
virtual void run();
};
/*
* YJGConnection
*/
class YJGConnection : public Channel
{
YCLASS(YJGConnection,Channel)
friend class YJGTransfer;
public:
enum State {
Pending,
Active,
Terminated,
};
// Flags controlling the state of the data source/consumer
enum DataFlags {
OnHoldRemote = 0x0001, // Put on hold by remote party
OnHoldLocal = 0x0002, // Put on hold by peer
OnHold = OnHoldRemote | OnHoldLocal,
};
// File transfer status
enum FileTransferStatus {
FTNone, // No file transfer allowed
FTIdle, // Nothing done yet
FTWaitEstablish, // Waiting for SOCKS to be negotiated
FTEstablished, // Transport succesfully setup
FTRunning, // Running
FTTerminated // Terminated
};
// File transfer host sender
enum FileTransferHostSender {
FTHostNone = 0,
FTHostLocal,
FTHostRemote,
};
// Ringing flags
enum RingFlags {
// Internal
RingRinging = 0x01, // call.ringing was handled
RingGotEarlyMedia = 0x02, // Gor early media from peer
RingContentSent = 0x04, // Ring content sent
// Settable
RingNone = 0x04, // Don't send ringing
RingNoEarlySession = 0x10, // Don't use early session content
RingWithContent = 0x20, // Attach session audio content if possible
RingWithContentOnly = 0x40, // Send ringing only if we have a content to sent
};
// Outgoing constructor
YJGConnection(Message& msg, const char* caller, const char* called, bool available,
const NamedList& caps, const char* file, const char* localip);
// Incoming contructor
YJGConnection(JGEvent* event);
virtual ~YJGConnection();
inline State state() const
{ return m_state; }
inline const JabberID& local() const
{ return m_local; }
inline const JabberID& remote() const
{ return m_remote; }
inline const String& reason() const
{ return m_reason; }
// Check session id
inline bool isSid(const String& sid) {
Lock lock(m_mutex);
return m_session && sid == m_session->sid();
}
// Get jingle session id
inline bool getSid(String& buf) {
Lock lock(m_mutex);
if (!m_session)
return false;
buf = m_session->sid();
return true;
}
// Check ring flag
inline bool ringFlag(int mask) const
{ return 0 != (m_ringFlags & mask); }
// Overloaded methods from Channel
virtual void callAccept(Message& msg);
virtual void callRejected(const char* error, const char* reason, const Message* msg);
virtual bool callRouted(Message& msg);
virtual void disconnected(bool final, const char* reason);
virtual bool msgProgress(Message& msg);
virtual bool msgRinging(Message& msg);
virtual bool msgAnswered(Message& msg);
virtual bool msgUpdate(Message& msg);
virtual bool msgText(Message& msg, const char* text);
virtual bool msgDrop(Message& msg, const char* reason);
virtual bool msgTone(Message& msg, const char* tone);
virtual bool msgTransfer(Message& msg);
inline bool disconnect(const char* reason) {
setReason(reason);
return Channel::disconnect(m_reason,parameters());
}
// Route an incoming call
bool route();
// Process Jingle and Terminated events
// Return false to terminate
bool handleEvent(JGEvent* event);
void hangup(const char* reason = 0, const char* text = 0,
JGSession::Reason send = JGSession::ReasonUnknown);
// Process remote user's presence changes.
// Make the call if outgoing and in Pending (waiting for presence information) state
// Hangup if the remote user is unavailbale
// Return true to disconnect
bool presenceChanged(bool available, NamedList* params = 0);
// Process a transfer request
// Return true if the event was accepted
bool processTransferRequest(JGEvent* event);
// Transfer terminated notification from transfer thread
void transferTerminated(bool ok, const char* reason = 0);
// Process chan.notify messages
// Handle SOCKS status changes for file transfer
bool processChanNotify(Message& msg);
// Check if a transfer can be initiated
inline bool canTransfer() const
{ return m_session && !m_transferring && isAnswered() && m_ftStatus == FTNone; }
inline void updateResource(const String& resource) {
if (!m_remote.resource() && resource)
m_remote.resource(resource);
}
inline void setReason(const char* reason) {
if (!m_reason)
m_reason = reason;
}
// Check the status of the given data flag(s)
inline bool dataFlags(int mask)
{ return 0 != (m_dataFlags & mask); }
// Ring flags names
static const TokenDict s_ringFlgName[];
// Retrieve ringing flags from string
// defVal: default value if flags list is empty
static int getRinging(const String& flags, DebugEnabler* enabler, int defVal = 0);
static inline int getRinging(NamedList& params, DebugEnabler* enabler, int defVal = 0)
{ return getRinging(params[YSTRING("jingle_ring")],enabler,defVal); }
protected:
// Process an ActContentAdd event
void processActionContentAdd(JGEvent* event);
// Process an ActContentAdd event
void processActionTransportInfo(JGEvent* event);
// Handle answer (session accept) events for non file transfer
void processActionAccept(JGEvent* ev);
// Handle stream hosts events
// Return false if the session was terminated
bool processStreamHosts(JGEvent* ev);
// Update a received candidate. Return true if changed
bool updateCandidate(unsigned int component, JGSessionContent& local,
JGSessionContent& recv);
// Add a new content to the list
void addContent(bool local, JGSessionContent* c);
// Remove a content from list
void removeContent(JGSessionContent* c);
// Reset the current audio content
// If the content is not re-usable (SRTP with local address),
// add a new identical content and remove the old old one from the session
// Clear the endpoint
void removeCurrentAudioContent(bool removeReq = false);
// This method is used to set the current audio content
// Clear the endpoint if the current content is replaced
// Reset the current content. Try to use the given content
// Else, find the first available content and try to use it
// Send a transport info for the new current content
// Send ringing if requested
// Return false on error
bool resetCurrentAudioContent(bool session, bool earlyMedia,
bool sendTransInfo = true, JGSessionContent* newContent = 0, bool sendRing = true);
// Start RTP for the current content
// For raw udp transports, sends a 'trying' session info
bool startRtp();
// Check a received candidate's parameters
// Return false if some parameter's value is incorrect
bool checkRecvCandidate(JGSessionContent& content, JGRtpCandidate& candidate);
// Check a received content(s). Fill received lists with accepted/rejected content(s)
// The lists don't own their pointers
// Return false on error
bool processContentAdd(const JGEvent& event, ObjList& ok, ObjList& remove);
// Remove contents. Confirm the received event
// Return false if there are no more contents
bool removeContents(JGEvent* event);
// Build a RTP audio content. Add used codecs to the list
// Build and init the candidate(s) if the content is a raw udp one
JGSessionContent* buildAudioContent(JGRtpCandidates::Type type,
JGSessionContent::Senders senders = JGSessionContent::SendBoth,
bool rtcp = false, bool useFormats = true);
// Build a file transfer content
JGSessionContent* buildFileTransferContent(bool send, const char* filename,
NamedList& params);
// Reserve local port for a RTP session content
bool initLocalCandidates(JGSessionContent& content, bool sendTransInfo);
// Match a local content agaist a received one
// Return false if there is no common media
bool matchMedia(JGSessionContent& local, JGSessionContent& recv,
bool& firstChanged, bool& telEvChanged) const;
// Find a session content in a list
JGSessionContent* findContent(JGSessionContent& recv, const ObjList& list) const;
// Set early media to remote
void setEarlyMediaOut(Message& msg);
// Enqueue a call.progress message from the current audio content
// Used for early media
void enqueueCallProgress();
// Init/start file transfer. Try to change host direction on failure
// If host dir succeeds, still return false, but don't terminate transfer
bool setupSocksFileTransfer(bool start);
// Change host sender. Return false on failure
bool changeFTHostDir(bool resetState = true);
// Drop file transfer data. Remove the first host in list
void dropFT(bool removeFirst);
// Drop file transfer hosts
void dropFTHosts(bool local, const char* reason = 0);
// Drop file transfer host
void dropFTHost(JGStreamHost* sh, ObjList* remove, const char* reason = 0);
// Get the RTP direction param from a content
// FIXME: ignore content senders for early media ?
inline const char* rtpDir(const JGSessionContent& c) {
if (c.senders() == JGSessionContent::SendInitiator)
return isOutgoing() ? "send" : "receive";
if (c.senders() == JGSessionContent::SendResponder)
return isOutgoing() ? "receive" : "send";
return "bidir";
}
// Build a RTP candidate
JGRtpCandidate* buildCandidate(bool nonP2P = true, bool rtp = true);
// Get the first file transfer content
inline JGSessionContent* firstFTContent() {
ObjList* o = m_ftContents.skipNull();
return o ? static_cast<JGSessionContent*>(o->get()) : 0;
}
private:
// Handle hold/active/mute actions
// Confirm the received element
void handleAudioInfoEvent(JGEvent* event);
// Check jingle version override from call.execute or resource caps
void overrideJingleVersion(const NamedList& list, bool caps);
// Override session flags
void overrideJingleFlags(const NamedList& list, const char* param);
// Copy chan/session parameters to a destination list
void copySessionParams(NamedList& list, bool redirect = true);
// Check media for a received content
bool checkMedia(const JGEvent& event, JGSessionContent& c);
// Clear and reset data related to a given type: audio ...
void resetEp(const String& what, bool releaseContent = true);
// Hangup and drop the call if failed to setup encryption
void dropNoCrypto();
// Send ringing
void sendRinging(NamedList* params = 0);
Mutex m_mutex; // Lock transport and session
State m_state; // Connection state
JGSession* m_session; // Jingle session attached to this connection
bool m_rtpStarted; // RTP started flag
bool m_acceptRelay; // Accept to replace with a relay candidate
JGSession::Version m_sessVersion; // Jingle session version
int m_sessFlags; // Session flags
int m_ringFlags; // Ring flags
JabberID m_local; // Local user's JID
JabberID m_remote; // Remote user's JID
ObjList m_audioContents; // The list of negotiated audio contents
JGSessionContent* m_audioContent; // The current audio content
JGRtpMediaList m_audioFormats; // Audio formats used by this channel
String m_callerPrompt; // Text to be sent to called before calling it
String m_subject; // Connection subject
String m_line; // Connection line
String m_localip; // Local address
bool m_offerRawTransport; // Offer RAW transport on outgoing session
bool m_offerIceTransport; // Offer ICE transport on outgoing session
bool m_offerP2PTransport; // Offer P2P transport on outgoing session
bool m_offerGRawTransport; // Offer Google raw transport on outgoing session
unsigned int m_redirectCount; // Redirect counter
int m_dtmfMeth; // Used DMTF method
String m_rtpId; // Started RTP id
// Crypto (for contents created by us)
bool m_secure; // The channel is using crypto
bool m_secureRequired; // Crypto is mandatory
// Termination
bool m_hangup; // Hang up flag: True - already hung up
String m_reason; // Hangup reason
// Timeouts
int64_t m_presTimeout; // Maxcall after waiting for presence
// Transfer
bool m_transferring; // The call is already involved in a transfer
String m_transferStanzaId; // Sent transfer stanza id used to track the result
JabberID m_transferTo; // Transfer target
JabberID m_transferFrom; // Transfer source
String m_transferSid; // Session id for attended transfer
XmlElement* m_recvTransferStanza; // Received iq transfer element
// On hold data
int m_dataFlags; // The data status
String m_onHoldOutId; // The id of the hold stanza sent to remote
String m_activeOutId; // The id of the active stanza sent to remote
// File transfer
FileTransferStatus m_ftStatus; // File transfer status
int m_ftHostDirection; // Which endpoint can send file transfer hosts
String m_ftNotifier; // The notifier expected in chan.notify
String m_ftStanzaId;
String m_dstAddrDomain; // SHA1(SID + local + remote) used by SOCKS
ObjList m_ftContents; // The list of negotiated file transfer contents
ObjList m_streamHosts; // The list of negotiated SOCKS stream hosts
bool m_connSocksServer; // Try to build a socks listener if not configured
};
/*
* Transfer thread (route and execute)
*/
class YJGTransfer : public Thread
{
public:
YJGTransfer(YJGConnection* conn, const char* subject = 0);
virtual void run(void);
private:
String m_transferorID; // Transferor channel's id
String m_transferredID; // Transferred channel's id
Driver* m_transferredDrv; // Transferred driver's pointer
JabberID m_to; // Transfer target
JabberID m_from; // Transfer source
String m_sid; // Session id for unattended transfer
Message m_msg;
};
/*
* Module message handlers
*/
class YJGMessageHandler : public MessageHandler
{
public:
enum {
JabberIq = 50, // handleJabberIq()
ChanNotify = -2, // handleChanNotify()
EngineStart = -3, // handleEngineStart()
ResNotify = -4, // handleResNotify()
ResSubscribe = 10, // handleResSubscribe()
UserNotify = -5, // handleUserNotify()
};
YJGMessageHandler(int handler, int prio);
protected:
virtual bool received(Message& msg);
private:
int m_handler;
};
/*
* YJGDriver
*/
class YJGDriver : public Driver
{
public:
// Dtmf type
enum DtmfType {
DtmfUnknown = 0,
DtmfRfc2833, // Send RFC 2833 tones
DtmfInband, // Send inband tones
DtmfJingle, // Use the jingle protocol
DtmfChat // Send chat
};
YJGDriver();
virtual ~YJGDriver();
// Check if a message was sent by us
inline bool isModule(Message& msg) {
String* module = msg.getParam("module");
return module && *module == name();
}
// Build a message to be sent by us
inline Message* message(const char* msg) const {
Message* m = new Message(msg);
m->addParam("module",name());
return m;
}
// Add local ip to a list of parameters
inline bool addLocalIp(NamedList& list) {
Lock lock(this);
if (!m_localAddress)
return false;
list.addParam("localip",m_localAddress);
return true;
}
// Set local ip from a list of parameter or configured address
inline void setLocalIp(String& addr, NamedList& list) {
Lock lock(this);
addr = list.getValue("localip",m_localAddress);
}
// Check if a domain is handled by the module
inline bool handleDomain(const String& domain) {
Lock lock(this);
return m_domains.find(domain) != 0;
}
// Retrieve the default resource
inline void defaultResource(String& buf) {
Lock lock(this);
ObjList* o = m_resources.skipNull();
if (o)
buf = static_cast<String*>(o->get());
}
// Check if a resource can be handled by the module
inline bool handleResource(const String& name) {
if (m_handleAllRes)
return true;
Lock lock(this);
return !m_resources.skipNull() || m_resources.find(name);
}
// Inherited methods
virtual void initialize();
virtual bool hasLine(const String& line) const;
virtual bool msgExecute(Message& msg, String& dest);
// Message handler: Disconnect channels, destroy streams, clear rosters
virtual bool received(Message& msg, int id);
// Handle jabber.iq messages
bool handleJabberIq(Message& msg);
// Handle resource.notify messages
bool handleResNotify(Message& msg);
// Handle resource.subscribe messages
bool handleResSubscribe(Message& msg);
// Handle user.notify messages
bool handleUserNotify(Message& msg);
// Handle chan.notify messages
bool handleChanNotify(Message& msg);
// Handle msg.execute messages. Send chan.text if enabled
bool handleImExecute(Message& msg);
// Handle engine.start message
void handleEngineStart(Message& msg);
// Search a client's roster to get a resource
// (with audio capabilities) for a subscribed user.
// Set noSub to true if false is returned and the client
// is not subscribed to the remote user (or the remote user is not found).
// Return false if user or resource is not found
bool getClientTargetResource(JBClientStream* stream, JabberID& target, bool* noSub = 0);
// Find a channel by id. Return a referenced pointer
inline YJGConnection* findChan(const String& id) {
Lock lock(this);
YJGConnection* ch = static_cast<YJGConnection*>(find(id));
return (ch && ch->ref()) ? ch : 0;
}
// Find a connection by local and remote jid, optionally ignore local
// resource (always ignore if local has no resource)
YJGConnection* findByJid(const JabberID& local, const JabberID& remote,
bool anyResource = false);
// Find a channel by its sid
YJGConnection* findBySid(const String& sid);
// Get a copy of the default file transfer proxy
inline JGStreamHost* defFTProxy() {
Lock lock(this);
return m_ftProxy ? new JGStreamHost(*m_ftProxy) : 0;
}
// Notify presence
void notifyPresence(const JabberID& from, const char* to, bool online);
// Build and dispatch a 'jabber.account' message. Returns it on success
Message* checkAccount(const String& line, bool query = false,
const JabberID* contact = 0) const;
private:
// Update the list of domains
void setDomains(const String& list);
bool m_init;
String m_localAddress; // The local machine's address
String m_anonymousCaller; // Caller username when missing
JGStreamHost* m_ftProxy; // Default file transfer proxy
ObjList m_handlers; // Message handlers list
ObjList m_domains; // Domains handled by the module
bool m_handleAllRes; // Handle all resources (ignore the list)
ObjList m_resources; // Resources handled by the module
XMPPFeatureList m_features; // Domain or resource features to advertise
XmlElement* m_entityCaps; // ntity capabilities element built from features
};
/*
* Local data
*/
static Configuration s_cfg; // The configuration file
static JGRtpMediaList s_knownCodecs(JGRtpMediaList::Audio); // List of all known codecs
static JGRtpMediaList s_usedCodecs(JGRtpMediaList::Audio); // List of used audio codecs
static unsigned int s_pendingTimeout = 10000; // Outgoing call pending timeout
static bool s_requestSubscribe = true; // Request subscribe before making a non client
// call with target without resource
static bool s_autoSubscribe = false; // Automatically respond to (un)subscribe requests
static bool s_imToChanText = false; // Send received IM messages as chan.text if a channel is found
static bool s_singleTone = true; // Send single/batch DTMFs
static bool s_useCrypto = false; // Offer crypto on outgoing calls
static bool s_cryptoMandatory = false; // Offer mandatory crypto on outgoing calls
static bool s_acceptRelay = false;
static bool s_offerRawTransport = true; // Offer RAW UDP transport on outgoing sessions
static bool s_offerIceTransport = true; // Offer ICE UDP transport on outgoing sessions
static bool s_offerP2PTransport = false; // Offer P2P UDP transport on outgoing sessions
static bool s_offerGRawTransport = false; // Offer Google RAW UDP transport on outgoing sessions
static int s_priority = 0; // Resource priority for presence generated by this module
static unsigned int s_redirectCount = 0; // Redirect counter
static int s_dtmfMeth = YJGDriver::DtmfJingle; // Default DTMF method to use
static bool s_clearFilePath = false; // Clear file path when sending a file transfer
static JGSession::Version s_sessVersion = JGSession::VersionUnknown; // Default jingle session version for outgoing calls
static int s_ringFlags = 0; // Default channel ring flags
static String s_capsNode = "http://yate.null.ro/yate/jingle/caps"; // node for entity capabilities
static bool s_serverMode = true; // Server/client mode
static YJGEngine* s_jingle = 0;
static YJGDriver plugin; // The driver
static bool s_ilbcDefault30 = true; // Default ilbc format when ptime is unknown (30 or 20)
// Channel ring flags
const TokenDict YJGConnection::s_ringFlgName[] = {
{"none", RingNone},
{"noearlysession", RingNoEarlySession},
{"sessioncontent", RingWithContent},
{"sessioncontentonly", RingWithContentOnly},
{0,0}
};
// Message handlers installed by the module
static const TokenDict s_msgHandler[] = {
{"jabber.iq", YJGMessageHandler::JabberIq},
{"chan.notify", YJGMessageHandler::ChanNotify},
{"engine.start", YJGMessageHandler::EngineStart},
{"resource.notify", YJGMessageHandler::ResNotify},
{"resource.subscribe", YJGMessageHandler::ResSubscribe},
{"user.notify", YJGMessageHandler::UserNotify},
{0,0}
};
// Error mapping
static TokenDict s_errMap[] = {
{"normal", JGSession::ReasonOk},
{"normal-clearing", JGSession::ReasonOk},
{"hangup", JGSession::ReasonOk},
{"busy", JGSession::ReasonBusy},
{"rejected", JGSession::ReasonDecline},
{"nomedia", JGSession::ReasonMedia},
{"cancelled", JGSession::ReasonCancel},
{"failure", JGSession::ReasonGeneral},
{"noroute", JGSession::ReasonDecline},
{"noconn", JGSession::ReasonDecline},
{"noauth", JGSession::ReasonGeneral},
{"nocall", JGSession::ReasonGeneral},
{"noanswer", JGSession::ReasonGeneral},
{"forbidden", JGSession::ReasonGeneral},
{"congestion", JGSession::ReasonGeneral},
{"looping", JGSession::ReasonGeneral},
{"shutdown", JGSession::ReasonGone},
{"notransport", JGSession::ReasonTransport},
{"offline", JGSession::ReasonGone},
{"gone", JGSession::ReasonGone},
{"shutdown", JGSession::ReasonGone},
{"timeout", JGSession::ReasonExpired},
{"timeout", JGSession::ReasonTimeout},
// Remote termination only
{"failure", JGSession::ReasonConn},
{"failure", JGSession::ReasonTransport},
{"failure", JGSession::ReasonApp},
{"failure", JGSession::ReasonAltSess},
{"failure", JGSession::ReasonConn},
{"failure", JGSession::ReasonFailApp},
{"failure", JGSession::ReasonFailTransport},
{"failure", JGSession::ReasonParams},
{"failure", JGSession::ReasonSecurity},
// Non jingle reasons
{"transferred", JGSession::Transferred},
{"crypto-required", JGSession::CryptoRequired},
{"invalid-crypto", JGSession::InvalidCrypto},
{0,0}
};
// Error mapping
static const TokenDict s_dictDtmfMeth[] = {
{"rfc2833", YJGDriver::DtmfRfc2833},
{"inband", YJGDriver::DtmfInband},
{"jingle", YJGDriver::DtmfJingle},
{"chat", YJGDriver::DtmfChat},
{0,0}
};
// Check if a payload name is telephone event one
static inline bool isTelEvent(const String& name)
{
return (name &= "telephone-event") || (name &= "tone") ||
(name &= "audio/telephone-event");
};
// Add a parameter to a list.
// Optionally add it to a copy params string
static inline void jingleAddParam(NamedList& list, const char* param, const char* value,
String* copy, bool emptyOk = true)
{
if (TelEngine::null(param))
return;
list.addParam(param,value,emptyOk);
if (copy)
copy->append(param,",");
}
// Add secure parameters from crypto
static void addSecure(NamedList& list, JGCrypto* crypto)
{
if (!crypto)
return;
list.addParam("secure",String::boolText(true));
list.addParam("crypto_suite",crypto->m_suite);
list.addParam("crypto_key",crypto->m_keyParams);
// TODO: add session params
}
// Replace 'ilbc' to used ilbc20/30
static void adjustUsedIlbc(String& fmts)
{
if (!fmts)
return;
ObjList* list = fmts.split(',',false);
ObjList* o = list->find("ilbc");
if (o) {
JGRtpMedia* m = 0;
plugin.lock();
for (ObjList* l = s_usedCodecs.skipNull(); l; l = l->skipNext()) {
m = static_cast<JGRtpMedia*>(l->get());
if (m->m_name == "iLBC")
break;
m = 0;
}
if (m)
*(static_cast<String*>(o->get())) = m->m_synonym;
else
o->remove();
plugin.unlock();
fmts.clear();
fmts.append(list,",");
}
TelEngine::destruct(list);
}
#ifdef DEBUG
// Utility function needed for debug: dump a candidate to a string
static void dumpCandidate(String& buf, JGRtpCandidate* c, char sep = ' ')
{
if (!c)
return;
buf << "name=" << *c;
buf << sep << "addr=" << c->m_address;
buf << sep << "port=" << c->m_port;
buf << sep << "component=" << c->m_component;
buf << sep << "generation=" << c->m_generation;
buf << sep << "network=" << c->m_network;
buf << sep << "priority=" << c->m_priority;
buf << sep << "protocol=" << c->m_protocol;
buf << sep << "type=" << c->m_type;
JGRtpCandidateP2P* p2p = YOBJECT(JGRtpCandidateP2P,c);
if (p2p) {
buf << sep << "username=" << p2p->m_username;
buf << sep << "password=" << p2p->m_password;
}
}
#endif
/*
* YJGEngine
*/
// Send a session's stanza (dispatch a jabber.iq message)
bool YJGEngine::sendStanza(JGSession* session, XmlElement*& stanza)
{
if (!(session && stanza)) {
TelEngine::destruct(stanza);
return false;
}
bool iq = stanza->toString() == XMPPUtils::s_tag[XmlTag::Iq];
if (!(iq || stanza->toString() == XMPPUtils::s_tag[XmlTag::Message])) {
TelEngine::destruct(stanza);
return false;
}
DDebug(this,DebugAll,"sendStanza() session=(%p,%s) stanza=(%p,%s)",
session,session->sid().c_str(),stanza,stanza->tag());
Message m(iq ? "jabber.iq" : "msg.execute");
m.addParam("module",plugin.name());
if (session->line())
m.addParam("line",session->line());
if (iq) {
m.addParam("from",session->local().bare());
m.addParam("to",session->remote().bare());
m.addParam("from_instance",session->local().resource());
m.addParam("to_instance",session->remote().resource());
}
else {
m.addParam("caller",session->local().bare());
m.addParam("called",session->remote().bare());
m.addParam("caller_instance",session->local().resource());
m.addParam("called_instance",session->remote().resource());
}
m.addParam(new NamedPointer("xml",stanza));
return Engine::dispatch(m);
}
// Process jingle events
void YJGEngine::processEvent(JGEvent* event)
{
if (!event)
return;
JGSession* session = event->session();
// This should never happen !!!
if (!session) {
DDebug(this,DebugStub,"Received event without session");
delete event;
return;
}
plugin.lock();
YJGConnection* conn = static_cast<YJGConnection*>(session->userData());
if (conn && !conn->ref()) {
plugin.unlock();
delete event;
return;
}
plugin.unlock();
if (conn) {
if (!conn->handleEvent(event) || event->final())
conn->disconnect(event->reason());
TelEngine::destruct(conn);
}
else {
if (event->type() == JGEvent::Jingle &&
event->action() == JGSession::ActInitiate) {
bool ok = plugin.canAccept(true);
if (ok && event->session()->ref()) {
conn = new YJGConnection(event);
conn->initChan();
// Constructor failed ?
if (conn->state() == YJGConnection::Pending)
TelEngine::destruct(conn);
else if (!conn->route()) {
Lock lck(plugin);
event->session()->userData(0);
}
}
else if (!ok) {
Debug(&plugin,DebugWarn,"Refusing new Jingle call, full or exiting");
event->session()->hangup(event->session()->createReason(JGSession::ReasonGeneral));
}
else {
Debug(this,DebugWarn,"Session ref failed for new connection");
event->session()->hangup(event->session()->createReason(JGSession::ReasonGeneral));
}
}
else {
DDebug(this,DebugAll,"Invalid (non initiate) event for new session");
event->confirmElement(XMPPError::Request,"Unknown session");
}
}
delete event;
}
/*
* YJGEngineWorker
*/
void YJGEngineWorker::run()
{
Debug(&plugin,DebugAll,"%s start running",currentName());
while (true) {
if (Thread::check(false) || Engine::exiting())
break;
JGEvent* ev = s_jingle->getEvent(Time::msecNow());
if (ev)
s_jingle->processEvent(ev);
else
Thread::idle(false);
}
Debug(&plugin,DebugAll,"%s stop running",currentName());
}
/*
* YJGConnection
*/
// Outgoing call
YJGConnection::YJGConnection(Message& msg, const char* caller, const char* called,
bool available, const NamedList& caps, const char* file, const char* localip)
: Channel(&plugin,0,true),
m_mutex(true,"YJGConnection"),
m_state(Pending), m_session(0), m_rtpStarted(false), m_acceptRelay(s_acceptRelay),
m_sessVersion(s_sessVersion), m_sessFlags(s_jingle->sessionFlags()),
m_ringFlags(s_ringFlags),
m_local(caller), m_remote(called), m_audioContent(0),
m_audioFormats(JGRtpMediaList::Audio),
m_callerPrompt(msg.getValue("callerprompt")),
m_localip(localip),
m_offerRawTransport(true), m_offerIceTransport(true),
m_offerP2PTransport(false), m_offerGRawTransport(false),
m_redirectCount(s_redirectCount), m_dtmfMeth(s_dtmfMeth),
m_secure(s_useCrypto), m_secureRequired(s_cryptoMandatory),
m_hangup(false), m_presTimeout(-1), m_transferring(false), m_recvTransferStanza(0),
m_dataFlags(0), m_ftStatus(FTNone), m_ftHostDirection(FTHostNone),
m_connSocksServer(msg.getBoolValue("socksserver",true))
{
int redir = msg.getIntValue("redirectcount",m_redirectCount);
m_redirectCount = (redir >= 0) ? redir : 0;
m_dtmfMeth = msg.getIntValue("dtmfmethod",s_dictDtmfMeth,s_dtmfMeth);
m_secure = msg.getBoolValue("secure",m_secure);
m_secureRequired = msg.getBoolValue("secure_required",m_secureRequired);
overrideJingleVersion(msg,false);
if (available)
overrideJingleVersion(caps,true);
overrideJingleFlags(msg,"ojingle_flags");
if (m_sessVersion != JGSession::Version0) {
m_offerRawTransport = msg.getBoolValue("offerrawudp",s_offerRawTransport);
m_offerIceTransport = msg.getBoolValue("offericeudp",s_offerIceTransport);
m_offerP2PTransport = msg.getBoolValue("offerp2p",s_offerP2PTransport);
m_offerGRawTransport = msg.getBoolValue("offergraw",s_offerGRawTransport);
}
else
m_offerRawTransport = false;
m_subject = msg.getValue("subject");
m_line = msg.getValue("line");
String uri = msg.getValue("diverteruri",msg.getValue("diverter"));
// Skip protocol if present
if (uri) {
int pos = uri.find(':');
m_transferFrom.set((pos >= 0) ? uri.substr(pos + 1) : uri);
}
// Get formats. Check if this is a file transfer session
if (null(file)) {
String audio = msg["formats"];
plugin.lock();
if (audio)
adjustUsedIlbc(audio);
else if (!s_usedCodecs.createList(audio,true))
audio = "alaw,mulaw";
m_audioFormats.setMedia(s_usedCodecs,audio);
plugin.unlock();
}
else {
m_secure = false;
m_ftStatus = FTIdle;
m_ftHostDirection = FTHostLocal;
NamedString* oper = msg.getParam("operation");
bool send = (oper && *oper == "send");
m_ftContents.append(buildFileTransferContent(send,file,msg));
// Add default proxy stream host if we have one
JGStreamHost* sh = plugin.defFTProxy();
if (sh)
m_streamHosts.append(sh);
}
Debug(this,DebugCall,"Outgoing%s. caller='%s' called='%s'%s%s [%p]",
m_ftStatus != FTNone ? " file transfer" : "",caller,called,
m_transferFrom ? ". Transferred from=": "",
m_transferFrom.safe(),this);
// Set timeout and maxcall
setMaxcall(msg);
setMaxPDD(msg);
setChanParams(msg);
if (!available) {
u_int64_t timeNow = Time::now();
// Save maxcall for later, set presence retrieval timeout instead
m_presTimeout = maxcall() ? maxcall() - timeNow : 0;
if (s_pendingTimeout)
maxcall(s_pendingTimeout * (u_int64_t)1000 + timeNow);
}
XDebug(this,DebugInfo,"Time: " FMT64 ". Maxcall set to " FMT64 " us. [%p]",
Time::now(),maxcall(),this);
// Startup
Message* m = message("chan.startup",msg);
m->setParam("direction",getStatus());
m_targetid = msg.getValue("id");
m->copyParams(msg,"caller,callername,called,billid,callto,username");
Engine::enqueue(m);
// Make the call
if (available)
presenceChanged(true);
}
// Incoming call
YJGConnection::YJGConnection(JGEvent* event)
: Channel(&plugin,0,false),
m_mutex(true,"YJGConnection"),
m_state(Active), m_session(event->session()), m_rtpStarted(false), m_acceptRelay(s_acceptRelay),
m_sessVersion(event->session()->version()), m_sessFlags(s_jingle->sessionFlags()),
m_ringFlags(s_ringFlags),
m_local(event->session()->local()), m_remote(event->session()->remote()),
m_audioContent(0),
m_audioFormats(JGRtpMediaList::Audio),
m_offerRawTransport(true), m_offerIceTransport(true),
m_offerP2PTransport(false), m_offerGRawTransport(false),
m_redirectCount(0), m_dtmfMeth(s_dtmfMeth),
m_secure(s_useCrypto), m_secureRequired(s_cryptoMandatory),
m_hangup(false), m_presTimeout(-1), m_transferring(false), m_recvTransferStanza(0),
m_dataFlags(0), m_ftStatus(FTNone), m_ftHostDirection(FTHostNone),
m_connSocksServer(false)
{
m_line = m_session->line();
plugin.lock();
m_audioFormats.setMedia(s_usedCodecs);
plugin.unlock();
// Update local ip in non server mode
if (!s_serverMode && m_line) {
Message* m = plugin.checkAccount(m_line);
if (m) {
m_localip = m->getValue("localip");
TelEngine::destruct(m);
}
}
if (event->jingle()) {
// Check if this call is transferred
XmlElement* trans = XMPPUtils::findFirstChild(*event->jingle(),XmlTag::Transfer);
if (trans)
m_transferFrom = trans->getAttribute("from");
// Get subject
m_subject = XMPPUtils::subject(*event->jingle());
}
Debug(this,DebugCall,"Incoming. caller='%s' called='%s'%s%s [%p]",
m_remote.c_str(),m_local.c_str(),
m_transferFrom ? ". Transferred from=" : "",
m_transferFrom.safe(),this);
// Set session
m_session->userData(this);
if (m_sessVersion == JGSession::Version0)
m_offerRawTransport = false;
// Process incoming content(s)
ObjList ok;
ObjList remove;
bool haveAudioSession = false;
bool haveFTSession = false;
if (processContentAdd(*event,ok,remove)) {
for (ObjList* o = ok.skipNull(); o; o = o->skipNext()) {
JGSessionContent* c = static_cast<JGSessionContent*>(o->get());
switch (c->type()) {