1 /**
2  * ysipchan.cpp
3  * This file is part of the YATE Project http://YATE.null.ro
4  *
5  * Yet Another Sip Channel
6  *
7  * Yet Another Telephony Engine - a fully featured software PBX and IVR
8  * Copyright (C) 2004-2014 Null Team
9  *
10  * This software is distributed under multiple licenses;
11  * see the COPYING file in the main directory for licensing
12  * information for this specific distribution.
13  *
14  * This use of this software may be subject to additional restrictions.
15  * See the LEGAL file in the main directory for details.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20  */
21 
22 #include <yatephone.h>
23 #include <yatesip.h>
24 #include <yatesdp.h>
25 
26 #include <string.h>
27 
28 
29 using namespace TelEngine;
30 namespace { // anonymous
31 
32 class YateSIPListener;                   // Base class for listeners (need binding)
33 class YateSIPPartyHolder;                // A SIPParty holder
34 class YateSIPTransport;                  // SIP transport: keeps a socket, read/send data
35 class YateSIPUDPTransport;               // UDP transport
36 class YateSIPTCPTransport;               // TCP/TLS transport
37 class YateSIPTransportWorker;            // A transport worker
38 class YateSIPTCPListener;                // A TCP listener
39 class YateUDPParty;                      // A SIP UDP party
40 class YateTCPParty;                      // A SIP TCP/TLS party
41 class YateSIPEngine;                     // The SIP engine
42 class YateSIPLine;                       // A line
43 class YateSIPEndPoint;                   // Endpoint processor
44 class SIPDriver;
45 
46 #define EXPIRES_MIN 60
47 #define EXPIRES_DEF 600
48 #define EXPIRES_MAX 3600
49 
50 // TCP transport idle values in seconds
51 // Outgoing: interval to send keep alive
52 // Incoming: interval allowed to stay with refcounter=1 and no data received/sent
53 #define TCP_IDLE_MIN 32
54 #define TCP_IDLE_DEF 120
55 #define TCP_IDLE_MAX 600
56 
57 // Maximum allowed value for bind retry interval in milliseconds
58 // 1 minute
59 #define BIND_RETRY_MAX 60000
60 
61 static const TokenDict dict_errors[] = {
62     { "incomplete", 484 },
63     { "noroute", 404 },
64     { "noroute", 604 },
65     { "noconn", 503 },
66     { "noconn", 408 },
67     { "noauth", 401 },
68     { "noautoauth", 401 },
69     { "nomedia", 415 },
70     { "nocall", 481 },
71     { "busy", 486 },
72     { "busy", 600 },
73     { "noanswer", 480 },
74     { "noanswer", 487 },
75     { "rejected", 406 },
76     { "rejected", 606 },
77     { "forbidden", 403 },
78     { "forbidden", 603 },
79     { "offline", 404 },
80     { "congestion", 480 },
81     { "unallocated", 410 },
82     { "moved", 410 },
83     { "failure", 500 },
84     { "pending", 491 },
85     { "looping", 483 },
86     { "timeout", 408 },
87     { "timeout", 504 },
88     { "postdialdelay", 504 },
89     { "service-not-implemented", 501 },
90     { "unimplemented", 501 },
91     { "service-unavailable", 503 },
92     { "unacceptable", 488 },
93     { "noresource", 503 },
94     { "interworking", 500 },
95     { "interworking", 400 },
96     { "invalid-message", 400 },
97     { "protocol-error", 400 },
98     {  0,   0 },
99 };
100 
101 static const char s_dtmfs[] = "0123456789*#ABCDF";
102 
103 static const TokenDict info_signals[] = {
104     { "*", 10 },
105     { "#", 11 },
106     { "A", 12 },
107     { "B", 13 },
108     { "C", 14 },
109     { "D", 15 },
110     {  0,   0 },
111 };
112 
113 class BodyTrace : public String
114 {
115 public:
BodyTrace(const String & body)116     inline BodyTrace(const String& body)
117 	: m_hash(body.hash()), m_length(body.length())
118 	{}
119 
sameBody(const String & body) const120     inline bool sameBody(const String& body) const
121 	{ return body.hash() == m_hash && body.length() == m_length; }
122 
123     unsigned int m_hash;
124     unsigned int m_length;
125 };
126 
127 // Protocol definition
128 class ProtocolHolder
129 {
130 public:
131     enum Protocol {
132 	Unknown = 0,
133 	Udp,
134 	Tcp,
135 	Tls
136     };
ProtocolHolder(int p)137     inline ProtocolHolder(int p)
138 	: m_proto(p)
139 	{}
140     // Retrieve protocol
protocol() const141     inline int protocol() const
142 	{ return m_proto; }
protoName(bool upperCase=true) const143     inline const char* protoName(bool upperCase = true) const
144 	{ return lookupProtoName(protocol(),upperCase); }
lookupProtoName(int proto,bool upperCase=true)145     static inline const char* lookupProtoName(int proto, bool upperCase = true)
146 	{ return lookup(proto,upperCase ? s_protoUC : s_protoLC); }
lookupProto(const char * name,bool upperCase=true,int def=Unknown)147     static inline int lookupProto(const char* name, bool upperCase = true,
148 	int def = Unknown)
149 	{ return lookup(name,upperCase ? s_protoUC : s_protoLC,def); }
lookupProtoAny(const String & name,int def=Unknown)150     static inline int lookupProtoAny(const String& name, int def = Unknown) {
151 	    String tmp = name;
152 	    return lookupProto(tmp.toLower(),false,def);
153 	}
154     static const TokenDict s_protoLC[];  // Lower case proto name
155     static const TokenDict s_protoUC[];  // Upper case proto name
156 protected:
157     int m_proto;
158 private:
ProtocolHolder()159     ProtocolHolder() {}                  // No default
160 };
161 
162 class DtmfMethods
163 {
164 public:
165     enum Method {
166 	Info,
167 	Rfc2833,
168 	Inband,
169 	MethodCount
170     };
DtmfMethods()171     inline DtmfMethods()
172 	{ setDefault();	}
set(int _0=MethodCount,int _1=MethodCount,int _2=MethodCount)173     inline void set(int _0 = MethodCount, int _1 = MethodCount, int _2 = MethodCount) {
174 	    m_methods[0] = _0;
175 	    m_methods[1] = _1;
176 	    m_methods[2] = _2;
177 	}
setDefault()178     inline void setDefault()
179 	{ set(Rfc2833,Info,Inband); }
180     // Replace all methods from comma separated list
181     // If no method is set use other or setDefEmpty (reset to default)
182     // Return false if methods contain unknown methods
183     bool set(const String& methods, const DtmfMethods* other, bool setDefEmpty = true,
184 	bool intersectOther = false);
185     // Intersect with other methods
186     void intersect(const DtmfMethods& other);
187     // Retrieve a method from deperecated parameters
188     // Reset the method if the parameter is false
189     // Display a message anyway if warn is not false
190     // Return true if the parameter was found
191     bool getDeprecatedDtmfMethod(const NamedList& list, const char* param, int method, bool* warn);
192     // Reset a method
193     void reset(int method);
194     // Build a string list from methods
195     void buildMethods(String& buf, const char* sep = ",");
196     bool hasMethod(int method) const;
printMethods(DebugEnabler * enabler,int level,const String & str)197     inline void printMethods(DebugEnabler* enabler, int level, const String& str) {
198 	    String tmp;
199 	    buildMethods(tmp);
200 	    Debug(enabler,level,"Built DTMF methods '%s' from '%s'",tmp.safe(),str.safe());
201 	}
operator [](unsigned int index)202     inline int operator[](unsigned int index) {
203 	    if (index < MethodCount)
204 		return m_methods[index];
205 	    return MethodCount;
206 	}
operator =(const DtmfMethods & other)207     inline DtmfMethods& operator=(const DtmfMethods& other) {
208 	    for (int i = 0; i < MethodCount; i++)
209 		m_methods[i] = other.m_methods[i];
210 	    return *this;
211 	}
212     static const TokenDict s_methodName[];
213 protected:
214     int m_methods[MethodCount];
215 };
216 
217 // A SIP party holder
218 class YateSIPPartyHolder : public ProtocolHolder
219 {
220 public:
YateSIPPartyHolder(DebugEnabler * enabler,Mutex * mutex=0,const String & traceId=String::empty ())221     inline YateSIPPartyHolder(DebugEnabler* enabler, Mutex* mutex = 0, const String& traceId = String::empty())
222 	: ProtocolHolder(Udp),
223 	m_party(0), m_partyMutex(mutex), m_sips(false),	m_transLocalPort(0), m_transRemotePort(0),
224 	m_enabler(enabler), m_traceId(traceId)
225 	{}
~YateSIPPartyHolder()226     virtual ~YateSIPPartyHolder()
227 	{ setParty(); }
228     // Retrieve a referrenced pointer to the held party
party()229     inline SIPParty* party() {
230 	    Lock lock(m_partyMutex);
231 	    return (m_party && m_party->ref()) ? m_party : 0;
232 	}
233     // Retrieve the transport from party
234     YateSIPTransport* transport(bool ref = false);
235     // Check if a transport is used by our party
isTransport(YateSIPTransport * trans)236     inline bool isTransport(YateSIPTransport* trans)
237 	{ return trans == transport(); }
238     // Set the held party. Referrence it before
239     void setParty(SIPParty* party = 0);
240     // Set the held party if remote address changed
241     // Return true if holder party was set to given party
242     bool setPartyChanged(SIPParty* party);
243     // Set the party of a non answer message. Return true on success
244     bool setSipParty(SIPMessage* message, const YateSIPLine* line = 0,
245 	bool useEp = false, const char* host = 0, int port = 0) const;
246     // (Re)Build party. Return true on success
247     bool buildParty(bool force = true, bool isTemp = false);
248     // Change party and its transport if the parameter list contains a transport
249     // Set force to true to try building a party anyway
250     // Return true on success
251     bool setParty(const NamedList& params, bool force,
252 	const String& prefix = String::empty(),
253 	const String& defRemoteAddr = String::empty(), int defRemotePort = 0,
254 	bool isTemp = false);
255     // SIPS URI usage
sips() const256     inline bool sips() const
257 	{ return m_sips; }
sips(bool on)258     inline bool sips(bool on)
259 	{ return change(m_sips,on); }
260     // Transport status changed notification
261     virtual void transportChangedStatus(int stat, const String& reason);
262     // Check if transport config params are present in parameters list
haveTransParams(const NamedList & params,const String & prefix=String::empty ())263     static inline bool haveTransParams(const NamedList& params,
264 	const String& prefix = String::empty()) {
265 	    return params[prefix + "connection_id"] ||
266 		params.getParam(prefix + "ip_transport") ||
267 		params.getBoolValue(prefix + "ip_transport_tcp");
268 	}
269 
270 protected:
271     // Change a parameter, notify descendents
272     bool change(String& dest, const String& src);
273     bool change(int& dest, int src);
274     bool change(bool& dest, bool src);
275     // Changing notification for descendents
276     virtual void changing();
277     // Update transport type. Return true if changed
278     bool updateProto(const NamedList& params, const String& prefix = String::empty());
279     // Update transport remote addr/port. Return true if changed
280     bool updateRemoteAddr(const NamedList& params, const String& prefix = String::empty(),
281 	const String& defRemoteAddr = String::empty(), int defRemotePort = 0);
282     // Update transport local addr/port. Return true if changed
283     bool updateLocalAddr(const NamedList& params, const String& prefix = String::empty());
284     // Update RTP local address
285     void setRtpLocalAddr(String& addr, Message* m = 0);
286 
287     SIPParty* m_party;                   // Held party
288     Mutex* m_partyMutex;                 // Mutex protecting the party pointer
289     bool m_sips;                         // SIPS URI is used
290     // Data used to (re)build the transport
291     String m_transId;
292     String m_transLocalAddr;
293     int m_transLocalPort;
294     String m_transRemoteAddr;
295     int m_transRemotePort;
296     // Failure
297     String m_partyInvalidRemote;
298 
299 private:
300     DebugEnabler* m_enabler;
301     String m_traceId;
302 };
303 
304 // Base class for listeners (need binding)
305 class YateSIPListener
306 {
307 public:
308     YateSIPListener(const char* name, int proto, const String& addr = String::empty(),
309 	int port = 0);
listenerName() const310     inline const String& listenerName() const
311 	{ return m_name; }
lName() const312     inline const char* lName() const
313 	{ return m_name; }
address() const314     inline const String& address() const
315 	{ return m_address; }
port() const316     inline int port() const
317 	{ return m_port; }
ipv6() const318     inline bool ipv6() const
319 	{ return m_ipv6; }
ipv6Support() const320     inline bool ipv6Support() const
321 	{ return m_ipv6Support; }
322     // Check if address would change
addrWouldChange(Mutex * mutex,const String & addr,int port)323     inline bool addrWouldChange(Mutex* mutex, const String& addr, int port) {
324 	    Lock lck(mutex);
325 	    return m_port != port || m_cfgAddr != addr;
326 	}
327 protected:
328     // Check bind now flag
329     bool bindNow(Mutex* mutex);
330     // Set addr/port/IPv6 support. Set bind flag if changed
331     void setAddr(const String& addr, int port, bool ipv6);
332     // Update IPv6 support from global. Set bind flag if changed and we must use IPv6
333     void updateIPv6Support();
334     // Update rtp address. Return true if set rtp addr flag changed
335     bool updateRtpAddr(const NamedList& params, String& buf, Mutex* mutex = 0);
336     // Initialize a socket
337     Socket* initSocket(SocketAddr& addr, Mutex* mutex, int backLogBuffer, bool forceBind,
338 	String& reason);
339 
340     unsigned int m_bindInterval;         // Interval to try binding
341     u_int64_t m_nextBind;                // Next time to bind
342     bool m_bind;                         // Re-bind flag
343     String m_cfgAddr;                    // Configured address
344     String m_address;                    // Address to bind
345     int m_port;                          // Port to bind
346     bool m_ipv6;                         // Listen on IPv6 address(es)
347     bool m_ipv6Support;                  // IPv6 supported
348     bool m_setRtpAddr;                   // Set rtp address from bind address
349     String m_bindRtpLocalAddr;           // Rtp local address set from bind address
350 
351 private:
352     String m_name;                       // Listener name
353     int m_proto;                         // Listener protocol
354 };
355 
356 // SIP transport: keeps a socket, read data from it, send data through it
357 class YateSIPTransport : public Mutex, public RefObject, public ProtocolHolder
358 {
359     YCLASS(YateSIPTransport,RefObject);
360     YNOCOPY(YateSIPTransport);
361     friend class SIPDriver;
362     friend class YateSIPEndPoint;
363     friend class YateSIPTransportWorker;
364 public:
365     enum Status {
366 	Idle = 0,
367 	Connected,
368 	Terminating,
369 	Terminated
370     };
371     // (Re)Initialize the transport
372     bool init(const NamedList& params, const NamedList& defs, bool first,
373 	Thread::Priority prio = Thread::Normal);
374     // Retrieve status
status() const375     inline int status() const
376 	{ return m_status; }
377     // Check if valid (connected)
valid() const378     inline bool valid() const
379 	{ return status() == Connected; }
380     // Check if VIA header should be ignored
ignoreVia() const381     inline bool ignoreVia() const
382 	{ return m_ignoreVia; }
383     // Retrieve local address for this transport
384     // This method is not thread safe for outgoing TCP
local() const385     inline const SocketAddr& local() const
386 	{ return m_local; }
387     // Retrieve remote address for this transport
388     // This method is not thread safe for outgoing TCP
remote() const389     inline const SocketAddr& remote() const
390 	{ return m_remote; }
391     // Safely retrieve RTP local address
rtpAddr(String & buf)392     inline void rtpAddr(String& buf) {
393 	    Lock lock(this);
394 	    buf = m_rtpLocalAddr;
395 	}
396     // Safely retrieve RTP external NAT address, only if set
rtpNatAddr(String & buf)397     inline void rtpNatAddr(String& buf) {
398 	    Lock lock(this);
399 	    if (m_rtpNatAddr)
400 		buf = m_rtpNatAddr;
401 	}
402     // Print sent messages to output
403     void printSendMsg(const SIPMessage* msg, const SocketAddr* addr = 0);
404     // Print received messages to output
405     // For TCP transports the function will assume 'buf' is not null terminated
406     void printRecvMsg(const char* buf, int len, const String& traceId = String::empty());
407     // Add transport data yate message
408     void fillMessage(Message& msg, bool addRoute = false);
409     // Transport descendents
udpTransport()410     virtual YateSIPUDPTransport* udpTransport()
411 	{ return 0; }
tcpTransport()412     virtual YateSIPTCPTransport* tcpTransport()
413 	{ return 0; }
414     // Stop the worker. Change status
415     void terminate(const char* reason = 0);
416     // Process data (read/send).
417     // Return 0 to continue processing, positive to sleep (usec),
418     //  negative to terminate and destroy
419     virtual int process() = 0;
420     // Retrieve the transport id
421     virtual const String& toString() const;
422     // Reset and delete a socket
423     static void resetSocket(Socket*& sock, int linger);
424     // Status names
statusName(int stat,const char * defVal="Unknown")425     static inline const char* statusName(int stat, const char* defVal = "Unknown")
426 	{ return lookup(stat,s_statusName,defVal); }
427     static const TokenDict s_statusName[];
428 protected:
429     YateSIPTransport(int proto, const String& id, Socket* sock, int stat = Connected);
430     virtual void destroyed();
431     // Status changed notification for descendents
statusChanged()432     virtual void statusChanged()
433 	{}
434     // Start the worker thread
435     bool startWorker(Thread::Priority prio);
436     // Change transport status. Notify it
437     void changeStatus(int stat);
438     // Handle received messages, set party, add to engine
439     // Consume the message
440     void receiveMsg(SIPMessage*& msg);
441     // Print socket read error to output
442     void printReadError();
443     // Print socket write error to output
444     void printWriteError(int res, unsigned int len, bool alarm = false);
445     // Set m_protoAddr from local/remote ip/port or reset it
446     void setProtoAddr(bool set);
447 
448     String m_id;                         // Transport id
449     int m_status;                        // Transport status
450     unsigned int m_statusChgTime;        // Last status changed time (seconds)
451     String m_reason;                     // Termination reason
452     Socket* m_sock;                      // The socket
453     unsigned int m_maxpkt;               // Max receive packet length
454     DataBlock m_buffer;                  // Read buffer
455     SocketAddr m_local;                  // Local ip/port
456     SocketAddr m_remote;                 // Remote ip/port
457     String m_rtpLocalAddr;               // RTP local address
458     String m_rtpNatAddr;                 // NAT IP to override RTP local address
459     YateSIPTransportWorker* m_worker;    // Transport worker
460     bool m_initialized;                  // Flag reset when initializing by the module and set in init()
461     String m_protoAddr;                  // Proto + addr: used for debug (send/recv msg)
462     String m_role;
463     bool m_ignoreVia;                    // Ignore VIA header (override from global)
464 private:
YateSIPTransport()465     YateSIPTransport() : ProtocolHolder(Udp) {} // No default constructor
466 };
467 
468 // UDP transport
469 class YateSIPUDPTransport : public YateSIPTransport, public YateSIPListener
470 {
471     YCLASS(YateSIPUDPTransport,YateSIPTransport);
472     friend class YateSIPTransport;
473 public:
474     YateSIPUDPTransport(const String& id);
isDefault() const475     inline bool isDefault() const
476 	{ return m_default; }
udpTransport()477     virtual YateSIPUDPTransport* udpTransport()
478 	{ return this; }
479     // (Re)Initialize the transport
480     bool init(const NamedList& params, const NamedList& defs, bool first,
481 	Thread::Priority prio = Thread::Normal);
482     // Send data
483     bool send(const void* data, unsigned int len, const SocketAddr& addr);
484     // Process data (read)
485     virtual int process();
486 protected:
487     bool m_default;
488     bool m_forceBind;
489     bool m_errored;
490     int m_bufferReq;
491 };
492 
493 // TCP/TLS transport
494 class YateSIPTCPTransport : public YateSIPTransport
495 {
496     YCLASS(YateSIPTCPTransport,YateSIPTransport);
497     friend class YateTCPParty;
498 public:
499     // Build an outgoing transport
500     YateSIPTCPTransport(bool tls, const String& laddr, const String& raddr, int rport);
501     // Build an incoming transport
502     YateSIPTCPTransport(Socket* sock, bool tls);
outgoing() const503     inline bool outgoing() const
504 	{ return m_outgoing; }
tls() const505     inline bool tls() const
506 	{ return protocol() == Tls; }
remoteAddr() const507     inline const String& remoteAddr() const
508 	{ return m_remoteAddr; }
remotePort() const509     inline int remotePort() const
510 	{ return m_remotePort; }
localAddr() const511     inline const String& localAddr() const
512 	{ return m_localAddr; }
513     // Safely return a reference to party
514     YateTCPParty* getParty();
tcpTransport()515     virtual YateSIPTCPTransport* tcpTransport()
516 	{ return this; }
517     // (Re)Initialize the transport
518     bool init(const NamedList& params, bool first, Thread::Priority prio = Thread::Normal);
519     // Set flow timer flag and idle interval (in seconds)
520     // Reset idle timeout
521     void setFlowTimer(bool on, unsigned int interval);
522     // Send an event
523     bool send(SIPEvent* event);
524     // Process data (read/send)
525     virtual int process();
526 protected:
527     virtual void destroyed();
528     // Status changed notification
529     virtual void statusChanged();
530     // Reset transport's party
531     void resetParty(YateTCPParty* party, bool set);
532     // Connect an outgoing transport. Terminate the socket before it
533     // Return: 1: OK, 0: retry connect, -1: stop the transport
534     int connect(u_int64_t connToutUs = 60000000);
535     // Send pending messages or keepalive, return false on failure
536     bool sendPending(const Time& time, bool& sent);
537     // Read data
538     bool readData(const Time& time, bool& read);
539     // Reset socket and connection related data
540     void resetConnection(Socket* sock = 0);
541     // Set transport idle timeout
542     void setIdleTimeout(u_int64_t time = Time::now());
543     // Send keep alive (or response to keep alive)
544     bool sendKeepAlive(bool request);
sendPendingKeepAlive()545     inline bool sendPendingKeepAlive() {
546 	    if (!m_keepAlivePending)
547 		return true;
548 	    m_keepAlivePending = false;
549 	    return sendKeepAlive(false);
550 	}
551 
552     bool m_outgoing;                     // Direction
553     YateTCPParty* m_party;               // Transport party
554     ObjList m_queue;                     // Pending message queue
555     int m_sent;                          // Sent bytes from first message in queue
556                                          // -1 to dequeue a new message and print it
557     unsigned int m_firstKeepalive;       // Outgoing: first keep alive interval
558     bool m_firstKeepaliveSent;           // First keep alive used
559     unsigned int m_idleInterval;         // Incoming: interval allowed to stay with a reference
560                                          //  counter=1 without receiving any data
561                                          // Outgoing: keep alive interval
562     u_int64_t m_idleTimeout;             // Idle timeout: check state or send keep alive
563     bool m_flowTimer;                    // Flow timer flag (RFC5626)
564     bool m_keepAlivePending;             // Pending keep alive response
565     SIPMessage* m_msg;                   // Partially received SIP message (expecting body)
566     DataBlock m_sipBuffer;               // Accumulated read data
567     unsigned int m_sipBufOffs;           // Offset in sip buffer for partial sip message
568     unsigned int m_contentLen;           // Expected content length for partial sip message
569     // Outgoing (re-connect info)
570     String m_remoteAddr;                 // Remote party address
571     int m_remotePort;                    // Remote port
572     String m_localAddr;                  // Optional local address to bind to
573     unsigned int m_connectRetry;         // Number of re-connect
574     u_int64_t m_nextConnect;             // Interval to try ro re-connect
575 };
576 
577 // Transport worker
578 class YateSIPTransportWorker : public Thread
579 {
580     friend class YateSIPTransport;
581 public:
582     YateSIPTransportWorker(YateSIPTransport* trans, Thread::Priority prio);
583     ~YateSIPTransportWorker();
584     virtual void run();
585 private:
586     void cleanupTransport(bool final, bool terminate = false);
587     YateSIPTransport* m_transport;
588 };
589 
590 class YateSIPTCPListener : public Thread, public GenObject, public ProtocolHolder, public YateSIPListener
591 {
592     friend class SIPDriver;
593     friend class YateSIPEndPoint;
594 public:
595     YateSIPTCPListener(int proto, const String& name, const NamedList& params);
596     ~YateSIPTCPListener();
597     void init(const NamedList& params, bool first);
tls() const598     inline bool tls() const
599 	{ return protocol() == Tls; }
listening() const600     inline bool listening() const
601 	{ return m_socket != 0; }
602     // Retrieve local address for this transport
603     // This method is not thread safe
local() const604     inline const SocketAddr& local() const
605 	{ return m_local; }
setReason(const char * reason)606     inline void setReason(const char* reason) {
607 	    if (!reason)
608 		return;
609 	    Lock lck(m_mutex);
610 	    m_reason = reason;
611 	}
612     virtual void run();
toString() const613     virtual const String& toString() const
614 	{ return listenerName(); }
615 private:
616     // Close the socket. Remove from endpoint list
617     void cleanup(bool final);
618     // Reset socket
619     void stopListening(const char* reason = 0, int level = DebugNote);
620 
621     Mutex m_mutex;                       // Mutex protecting transport parameters and bind ip/port
622     String m_reason;                     // Last error (state change) string
623     bool m_sslContextChanged;            // SSL context changed flag
624     bool m_sslContextCheck;              // Check SSL context availability
625     bool m_transParamsChanged;           // Transport parameters changed flag
626     Socket* m_socket;                    // The socket
627     SocketAddr m_local;                  // Local ip/port
628     unsigned int m_backlog;              // Pending connections queue length
629     String m_sslContext;                 // SSL/TLS context
630     NamedList m_transParams;             // Parameters for created transports
631     bool m_initialized;                  // Flag reset when initializing by the module and set in init()
632 };
633 
634 class YateUDPParty : public SIPParty
635 {
636 public:
637     YateUDPParty(YateSIPUDPTransport* trans, const SocketAddr& addr, int* localPort = 0,
638 	const char* localAddr = 0);
639     ~YateUDPParty();
addr() const640     inline const SocketAddr& addr() const
641 	{ return m_addr; }
642     virtual bool transmit(SIPEvent* event);
643     virtual const char* getProtoName() const;
644     virtual bool setParty(const URI& uri);
645     virtual void* getTransport();
646     // Get an object from this one
647     virtual void* getObject(const String& name) const;
648 protected:
649     YateSIPUDPTransport* m_transport;
650     SocketAddr m_addr;
651 };
652 
653 class YateTCPParty : public SIPParty
654 {
655 public:
656     YateTCPParty(YateSIPTCPTransport* trans);
657     ~YateTCPParty();
658     virtual bool transmit(SIPEvent* event);
659     virtual const char* getProtoName() const;
660     virtual bool setParty(const URI& uri);
661     virtual void* getTransport();
662     // Get an object from this one
663     virtual void* getObject(const String& name) const;
664     // Update party local/remote addr/port from transport
665     void updateAddrs();
666 protected:
667     virtual void destroyed();
668     YateSIPTCPTransport* m_transport;
669 };
670 
671 class SipHandler;
672 
673 class YateSIPEngine : public SIPEngine
674 {
675 public:
676     YateSIPEngine(YateSIPEndPoint* ep);
677     // Initialize the engine
678     void initialize(NamedList* params);
679     virtual bool buildParty(SIPMessage* message);
680     virtual void allocTraceId(String& id);
681     virtual void traceMsg(SIPMessage* message, bool incoming = true);
682     virtual bool checkUser(String& username, const String& realm, const String& nonce,
683 	const String& method, const String& uri, const String& response,
684 	const SIPMessage* message, const MimeHeaderLine* authLine, GenObject* userData);
685     virtual SIPTransaction* forkInvite(SIPMessage* answer, SIPTransaction* trans);
686     // Transport status changed notification
687     void transportChangedStatus(YateSIPTransport* trans, int stat, const String& reason);
688     // Check if the engine has an active transaction using a given transport
689     bool hasActiveTransaction(YateSIPTransport* trans);
690     // Check if the engine has pending transactions
691     bool hasInitialTransaction();
692     // Clear transactions
clearTransactions()693     inline void clearTransactions() {
694 	    Lock lck(this);
695 	    m_transList.clear();
696 	}
prack() const697     inline bool prack() const
698 	{ return m_prack; }
info() const699     inline bool info() const
700 	{ return m_info; }
foreignAuth() const701     inline bool foreignAuth() const
702 	{ return m_foreignAuth; }
703 private:
704     static bool copyAuthParams(NamedList* dest, const NamedList& src, bool ok = true);
705     YateSIPEndPoint* m_ep;
706     bool m_prack;
707     bool m_info;
708     bool m_fork;
709     bool m_forkEarly;
710     bool m_foreignAuth;
711     uint64_t m_traceIds;
712 };
713 
714 class YateSIPLine : public String, public Mutex, public CallAccount, public YateSIPPartyHolder
715 {
716     YCLASS(YateSIPLine,String)
717 public:
718     YateSIPLine(const String& name);
719     virtual ~YateSIPLine();
720     bool matchInbound(const String& addr, int port, const String& user) const;
721     void setupAuth(SIPMessage* msg) const;
722     SIPMessage* buildRegister(int expires);
723     void login();
724     void logout(bool sendLogout = true, const char* reason = 0);
725     bool process(SIPEvent* ev);
726     void timer(const Time& when);
727     bool update(const Message& msg);
728     // Transport status changed notification
729     virtual void transportChangedStatus(int stat, const String& reason);
getLocalAddr() const730     inline const String& getLocalAddr() const
731 	{ return m_localAddr; }
getPartyAddr() const732     inline const String& getPartyAddr() const
733 	{ return m_partyAddr ? m_partyAddr : m_transRemoteAddr; }
getLocalPort() const734     inline int getLocalPort() const
735 	{ return m_localPort; }
getPartyPort() const736     inline int getPartyPort() const
737 	{ return m_partyPort ? m_partyPort : m_transRemotePort; }
localDetect() const738     inline bool localDetect() const
739 	{ return m_localDetect; }
getFullName() const740     inline const String& getFullName() const
741 	{ return m_display; }
getUserName() const742     inline const String& getUserName() const
743 	{ return m_username; }
getAuthName() const744     inline const String& getAuthName() const
745 	{ return m_authname ? m_authname : m_username; }
regDomain() const746     inline const String& regDomain() const
747 	{ return m_registrar ? m_registrar : m_transRemoteAddr; }
domain() const748     inline const String& domain() const
749 	{ return m_domain ? m_domain : regDomain(); }
domain(const char * defDomain) const750     inline const char* domain(const char* defDomain) const
751 	{ return m_domain ? m_domain.c_str() :
752 	    (TelEngine::null(defDomain) ? regDomain().c_str() : defDomain); }
valid() const753     inline bool valid() const
754 	{ return m_valid; }
marked() const755     inline bool marked() const
756 	{ return m_marked; }
marked(bool mark)757     inline void marked(bool mark)
758 	{ m_marked = mark; }
759 private:
760     void clearTransaction();
761     void detectLocal(const SIPMessage* msg);
762     void keepalive();
763     void setValid(bool valid, const char* reason = 0, const char* error = 0);
764     virtual void changing();
765 
766     String m_registrar;
767     String m_username;
768     String m_authname;
769     String m_password;
770     String m_domain;
771     String m_display;
772     u_int64_t m_resend;
773     u_int64_t m_keepalive;
774     int m_interval;
775     int m_alive;
776     int m_flags;
777     int m_trans;
778     SIPTransaction* m_tr;
779     RefPointer<SIPSequence> m_seq;
780     bool m_marked;
781     bool m_valid;
782     String m_callid;
783     String m_localAddr;
784     String m_partyAddr;
785     int m_localPort;
786     int m_partyPort;
787     bool m_localDetect;
788     bool m_keepTcpOffline;               // Don't reset party when offline
789     bool m_matchPort;
790     bool m_matchUser;
791     bool m_forceNotify;
792 };
793 
794 class YateSIPEndPoint : public Thread
795 {
796     friend class SIPDriver;
797     friend class YateSIPTCPListener;
798 public:
799     YateSIPEndPoint(Thread::Priority prio = Thread::Normal,
800 	unsigned int partyMutexCount = 5);
801     ~YateSIPEndPoint();
802     bool Init(void);
803     void run(void);
804     bool incoming(SIPEvent* e, SIPTransaction* t);
805     void invite(SIPEvent* e, SIPTransaction* t);
806     void regReq(SIPEvent* e, SIPTransaction* t);
807     void regRun(const SIPMessage* message, SIPTransaction* t);
808     void options(SIPEvent* e, SIPTransaction* t);
809     bool generic(SIPEvent* e, SIPTransaction* t, int defErr = 405, bool async = false);
810     bool generic(const SIPMessage* message, SIPTransaction* t, const String& meth, bool autoAuth, bool isMsg);
811     bool buildParty(SIPMessage* message, const char* host = 0, int port = 0, const YateSIPLine* line = 0);
addTcpTransport(YateSIPTCPTransport * trans)812     inline void addTcpTransport(YateSIPTCPTransport* trans) {
813 	    if (!trans)
814 		return;
815 	    Lock lock(m_mutex);
816 	    m_transports.append(trans)->setDelete(false);
817 	}
818     // Retrieve the default transport. Return a referrenced object
defTransport()819     inline YateSIPUDPTransport* defTransport() {
820 	    Lock lock(m_mutex);
821 	    return (m_defTransport && m_defTransport->ref()) ? m_defTransport : 0;
822 	}
823     // (re)set default UDP transport
824     void updateDefUdpTransport();
825     // Retrieve a transport by name (name can be a prefix).
826     // Return a referrenced object
827     YateSIPTransport* findTransport(const String& name);
828     // Retrieve an UDP transport. Return a referrenced object
829     YateSIPUDPTransport* findUdpTransport(const String& name);
830     // Retrieve an UDP transport by addr/port. Return a referrenced object
831     YateSIPUDPTransport* findUdpTransport(const String& addr, int port);
832     // Build or delete an UDP transport (re-init existing). Start the thread
833     bool setupUdpTransport(const String& name, bool enabled, const NamedList& params,
834 	const NamedList& defs = NamedList::empty(), const char* reason = 0);
835     // Delete an UDP transport
836     bool removeUdpTransport(const String& name, const char* reason);
837     // Remove a transport from list without deleting it. Notify termination.
838     // Return true if found
839     bool removeTransport(YateSIPTransport* trans, bool updDef = true);
840     // Clear all transports
841     void clearUdpTransports(const char* reason);
842     // Transport status changed notification
843     void transportChangedStatus(YateSIPTransport* trans, int stat, const String& reason);
844     // Build or delete a TCP listener. Start the thread
845     bool setupListener(int proto, const String& name, bool enabled, const NamedList& params);
846     // Remove a listener from list without deleting it. Return true if found
847     bool removeListener(YateSIPTCPListener* listener);
848     // Remove a listener from list. Remove all if name is empty. Wait for termination
849     void cancelListener(const String& name = String::empty(), const char* reason = 0);
850     // This method is called by the driver when start/end initializing
851     void initializing(bool start);
852     // Complete transport names
853     void completeTransports(Message& msg, const String& partWord,
854 	bool udp = true, bool tcp = true, bool tls = true);
engine() const855     inline YateSIPEngine* engine() const
856 	{ return m_engine; }
incFailedAuths()857     inline void incFailedAuths()
858 	{ m_failedAuths++; }
failedAuths()859     inline unsigned int failedAuths()
860     {
861 	unsigned int tmp = m_failedAuths;
862 	m_failedAuths = 0;
863 	return tmp;
864     }
timedOutTrs()865     inline unsigned int timedOutTrs()
866     {
867 	unsigned int tmp = m_timedOutTrs;
868 	m_timedOutTrs = 0;
869 	return tmp;
870     }
timedOutByes()871     inline unsigned int timedOutByes()
872     {
873 	unsigned int tmp = m_timedOutByes;
874 	m_timedOutByes = 0;
875 	return tmp;
876     }
877     MutexPool m_partyMutexPool;          // SIPParty mutex pool
878     // Check if data is allowed to be read from socket(s) and processed
879     static bool canRead();
880     static int s_evCount;
881 private:
882     YateSIPEngine *m_engine;
883     Mutex m_mutex;                       // Protect transports and listeners
884     ObjList m_transports;                // All transports (non UDP are not owned)
885     YateSIPUDPTransport* m_defTransport; // Default transport (pointer to object in m_transports)
886     ObjList m_listeners;                 // Listeners list
887 
888     unsigned int m_failedAuths;
889     unsigned int m_timedOutTrs;
890     unsigned int m_timedOutByes;
891 };
892 
893 // Handle transfer requests
894 // Respond to the enclosed transaction
895 class YateSIPRefer : public Thread
896 {
897 public:
898     YateSIPRefer(const String& transferorID, const String& transferredID,
899 	Driver* transferredDrv, Message* msg, SIPMessage* sipNotify,
900 	SIPTransaction* transaction);
901     virtual void run(void);
cleanup(void)902     virtual void cleanup(void)
903 	{ release(true); }
904 private:
905     // Respond the transaction and deref() it
906     void setTrResponse(int code);
907     // Set transaction response. Send the notification message. Notify the
908     // connection and release other objects
909     void release(bool fromCleanup = false);
910 
911     String m_transferorID;           // Transferor channel's id
912     String m_transferredID;          // Transferred channel's id
913     Driver* m_transferredDrv;        // Transferred driver's pointer
914     Message* m_msg;                  // 'call.route' message
915     SIPMessage* m_sipNotify;         // NOTIFY message to send the result
916     int m_notifyCode;                // The result to send with NOTIFY
917     SIPTransaction* m_transaction;   // The transaction to respond to
918     int m_rspCode;                   // The transaction response
919 };
920 
921 class YateSIPRegister : public Thread
922 {
923 public:
YateSIPRegister(YateSIPEndPoint * ep,SIPMessage * message,SIPTransaction * t)924     inline YateSIPRegister(YateSIPEndPoint* ep, SIPMessage* message, SIPTransaction* t)
925 	: Thread("YSIP Register"),
926 	  m_ep(ep), m_msg(message), m_tr(t)
927 	{ }
run()928     virtual void run()
929 	{ m_ep->regRun(m_msg,m_tr); }
930 private:
931     YateSIPEndPoint* m_ep;
932     RefPointer<SIPMessage> m_msg;
933     RefPointer<SIPTransaction> m_tr;
934 };
935 
936 class YateSIPGeneric : public Thread
937 {
938 public:
YateSIPGeneric(YateSIPEndPoint * ep,SIPMessage * message,SIPTransaction * t,const char * method,int defErr,bool autoAuth,bool isMsg)939     inline YateSIPGeneric(YateSIPEndPoint* ep, SIPMessage* message, SIPTransaction* t,
940 	const char* method, int defErr, bool autoAuth, bool isMsg)
941 	: Thread("YSIP Generic"),
942 	  m_ep(ep), m_msg(message), m_tr(t),
943 	  m_method(method), m_error(defErr), m_auth(autoAuth), m_message(isMsg)
944 	{ }
run()945     virtual void run()
946 	{ if (!m_ep->generic(m_msg,m_tr,m_method,m_auth,m_message)) m_tr->setResponse(m_error); }
947 private:
948     YateSIPEndPoint* m_ep;
949     RefPointer<SIPMessage> m_msg;
950     RefPointer<SIPTransaction> m_tr;
951     String m_method;
952     int m_error;
953     bool m_auth;
954     bool m_message;
955 };
956 
957 class YateSIPConnection : public Channel, public SDPSession, public YateSIPPartyHolder
958 {
959     friend class SIPDriver;
960     YCLASS(YateSIPConnection,Channel)
961 public:
962     enum {
963 	Incoming = 0,
964 	Outgoing = 1,
965 	Ringing = 2,
966 	Established = 3,
967 	Cleared = 4,
968     };
969     enum {
970 	ReinviteNone,
971 	ReinvitePending,
972 	ReinviteRequest,
973 	ReinviteReceived,
974     };
975     YateSIPConnection(SIPEvent* ev, SIPTransaction* tr);
976     YateSIPConnection(Message& msg, const String& uri, const char* target = 0);
977     ~YateSIPConnection();
978     virtual void destroyed();
979     virtual void complete(Message& msg, bool minimal=false) const;
980     virtual void disconnected(bool final, const char *reason);
981     virtual bool msgProgress(Message& msg);
982     virtual bool msgRinging(Message& msg);
983     virtual bool msgAnswered(Message& msg);
984     virtual bool msgTone(Message& msg, const char* tone);
985     virtual bool msgText(Message& msg, const char* text);
986     virtual bool msgDrop(Message& msg, const char* reason);
987     virtual bool msgUpdate(Message& msg);
988     virtual bool msgControl(Message& msg);
989     virtual bool callPrerouted(Message& msg, bool handled);
990     virtual bool callRouted(Message& msg);
991     virtual void callAccept(Message& msg);
992     virtual void callRejected(const char* error, const char* reason, const Message* msg);
993     void startRouter();
994     bool process(SIPEvent* ev);
995     bool checkUser(SIPTransaction* t, bool refuse = true);
996     void doBye(SIPTransaction* t);
997     void doCancel(SIPTransaction* t);
998     bool doInfo(SIPTransaction* t);
999     void doRefer(SIPTransaction* t);
1000     void doMessage(SIPTransaction* t);
1001     void reInvite(SIPTransaction* t);
1002     void hangup();
dialog() const1003     inline const SIPDialog& dialog() const
1004 	{ return m_dialog; }
setStatus(const char * stat,int state=-1)1005     inline void setStatus(const char *stat, int state = -1)
1006 	{ status(stat); if (state >= 0) m_state = state; }
setReason(const char * str="Request Terminated",int code=487,Mutex * mtx=0)1007     inline void setReason(const char* str = "Request Terminated", int code = 487,
1008 	Mutex* mtx = 0) {
1009 	    Lock lck(mtx);
1010 	    m_reason = str;
1011 	    m_reasonCode = code;
1012 	}
getTransaction() const1013     inline SIPTransaction* getTransaction() const
1014 	{ return m_tr; }
callid() const1015     inline const String& callid() const
1016 	{ return m_dialog; }
user() const1017     inline const String& user() const
1018 	{ return m_user; }
getPort() const1019     inline int getPort() const
1020 	{ return m_port; }
getLine() const1021     inline const String& getLine() const
1022 	{ return m_line; }
referTerminated()1023     inline void referTerminated()
1024 	{ m_referring = false; }
isDialog(const String & callid,const String & fromTag,const String & toTag) const1025     inline bool isDialog(const String& callid, const String& fromTag,
1026 	const String& toTag) const
1027 	{ return callid == m_dialog &&
1028 	    m_dialog.fromTag(isOutgoing()) == fromTag &&
1029 	    m_dialog.toTag(isOutgoing()) == toTag; }
stopOCall() const1030     inline bool stopOCall() const
1031 	{ return m_stopOCall; }
1032     // Build and add a callid parameter to a list
addCallId(NamedList & nl,const String & dialog,const String & fromTag,const String & toTag)1033     static inline void addCallId(NamedList& nl, const String& dialog,
1034 	const String& fromTag, const String& toTag) {
1035 	    String tmp;
1036 	    tmp << "sip/" << dialog << "/" << fromTag << "/" << toTag;
1037 	    nl.addParam("callid",tmp);
1038 	}
traceId() const1039     const String& traceId() const
1040         { return m_traceId; }
1041 
1042 protected:
1043     virtual Message* buildChanRtp(RefObject* context);
1044     MimeSdpBody* createProvisionalSDP(Message& msg);
1045     virtual void mediaChanged(const SDPMedia& media);
1046     virtual void dispatchingRtp(Message*& msg, SDPMedia* media);
1047     virtual void endDisconnect(const Message& msg, bool handled);
1048 
1049 private:
1050     virtual void statusParams(String& str);
1051     void clearTransaction();
1052     void detachTransaction2();
1053     void startPendingUpdate();
1054     bool processTransaction2(SIPEvent* ev, const SIPMessage* msg, int code);
1055     SIPMessage* createDlgMsg(const char* method, const char* uri = 0);
1056     void updateTarget(const SIPMessage* msg, bool force = false, bool chgParty = true);
1057     void emitUpdate();
1058     bool emitPRACK(const SIPMessage* msg);
1059     bool startClientReInvite(NamedList& msg, bool rtpForward);
1060     bool reInviteForward(SIPTransaction* t, MimeSdpBody* sdp, int invite);
1061     bool reInviteProxy(SIPTransaction* t, MimeSdpBody* sdp, int invite);
1062     // Build the 'call.route' and NOTIFY messages needed by the transfer thread
1063     bool initTransfer(Message*& msg, SIPMessage*& sipNotify, const SIPMessage* sipRefer,
1064 	const MimeHeaderLine* refHdr, const URI& uri, const MimeHeaderLine* replaces);
1065     // Decode an application/isup body into 'msg' if configured to do so
1066     // The message's name and user data are restored before exiting, regardless the result
1067     // Return true if an ISUP message was succesfully decoded
1068     bool decodeIsupBody(Message& msg, MimeBody* body);
1069     // Build the body of a SIP message from an engine message
1070     // Encode an ISUP message from parameters received in msg if enabled to process them
1071     // Build a multipart/mixed body if more then one body is going to be sent
1072     MimeBody* buildSIPBody(Message& msg, MimeSdpBody* sdp = 0, const char* prefixName = 0);
1073     // Build the body of a hangup SIP message
1074     MimeBody* buildSIPBody();
1075     // Update NAT address from params or transport
1076     void updateRtpNatAddress(NamedList* params = 0);
1077     // Process allow list. Get INFO support
1078     bool infoAllowed(const SIPMessage* msg);
1079     // Send tone(s) using method
1080     bool sendTone(Message& msg, const char* tone, int meth, bool& retVal);
setSilent(const char * reason)1081     inline void setSilent(const char* reason) {
1082 	    if (m_silent || (YSTRING("silent") != reason))
1083 		return;
1084 	    m_silent = true;
1085 	    clearTransaction();
1086 	}
1087 
1088     SIPTransaction* m_tr;
1089     SIPTransaction* m_tr2;
1090     // are we already hung up?
1091     bool m_hungup;
1092     // should we send a BYE?
1093     bool m_byebye;
1094     // should we CANCEL?
1095     bool m_cancel;
1096     int m_state;
1097     String m_reason;
1098     int m_reasonCode;
1099     // SIP dialog of this call, used for re-INVITE or BYE
1100     SIPDialog m_dialog;
1101     // remote URI as we send in dialog messages
1102     URI m_uri;
1103     String m_domain;
1104     String m_user;
1105     String m_line;
1106     int m_port;
1107     Message* m_route;
1108     ObjList* m_routes;
1109     bool m_authBye;
1110     bool m_autoChangeParty;              // Auto change party from received message
1111     bool m_checkAllowInfo;               // Check Allow in INVITE and OK for INFO support
1112     bool m_missingAllowInfoDefVal;       // Default INFO support if Allow header is missing
1113     DtmfMethods m_dtmfMethods;
1114     bool m_honorDtmfDetect;
1115     // REFER already running
1116     bool m_referring;
1117     // reINVITE requested or in progress
1118     int m_reInviting;
1119     // sequence number of last transmitted PRACK
1120     int m_lastRseq;
1121     // media parameters before we sent a reINVITE
1122     NamedList m_revert;
1123     bool m_silent;                       // Silently discard SIP dialog
1124     bool m_stopOCall;
1125     String m_traceId;
1126 };
1127 
1128 class YateSIPGenerate : public GenObject
1129 {
1130     YCLASS(YateSIPGenerate,GenObject)
1131 public:
1132     YateSIPGenerate(SIPMessage* m, int tries);
1133     virtual ~YateSIPGenerate();
1134     bool process(SIPEvent* ev);
busy() const1135     inline bool busy() const
1136 	{ return m_tr != 0; }
code() const1137     inline int code() const
1138 	{ return m_code; }
answer() const1139     inline const SIPMessage* answer() const
1140 	{ return m_msg; }
1141 private:
1142     void clearTransaction();
1143     SIPTransaction* m_tr;
1144     RefPointer<SIPMessage> m_msg;
1145     int m_code;
1146 };
1147 
1148 class SIPDriver : public Driver
1149 {
1150 public:
1151     enum Relay {
1152 	Stop = Private,
1153 	Start = Private << 1,
1154     };
1155     SIPDriver();
1156     ~SIPDriver();
1157     virtual void initialize();
1158     virtual bool hasLine(const String& line) const;
1159     virtual bool msgExecute(Message& msg, String& dest);
1160     virtual bool received(Message& msg, int id);
ep() const1161     inline YateSIPEndPoint* ep() const
1162 	{ return m_endpoint; }
parser()1163     inline SDPParser& parser()
1164         { return m_parser; }
traceActive() const1165     inline bool traceActive() const
1166     {
1167 	return s_trace || Engine::sharedVars().exists(YSTRING("trace")) ||
1168 	    Engine::sharedVars().exists(YSTRING("trace_sip"));
1169     }
1170     void epTerminated(YateSIPEndPoint* ep);
1171     YateSIPConnection* findCall(const String& callid, bool incRef = false);
1172     YateSIPConnection* findDialog(const SIPDialog& dialog, bool incRef = false);
1173     YateSIPConnection* findDialog(const String& dialog, const String& fromTag,
1174 	const String& toTag, bool incRef = false);
1175     YateSIPLine* findLine(const String& line) const;
1176     YateSIPLine* findLine(const String& addr, int port, const String& user = String::empty(),
1177 	SIPParty* party = 0);
1178     // Drop channels belonging using a given transport
1179     // Return the number of disconnected channels
1180     unsigned int transportTerminated(YateSIPTransport* trans);
1181     bool validLine(const String& line);
1182     bool commandComplete(Message& msg, const String& partLine, const String& partWord);
1183     virtual bool commandExecute(String& retVal, const String& line);
1184     virtual void msgStatus(Message& msg);
1185     virtual void statusParams(String& str);
1186     // Build and dispatch a socket.ssl message
1187     bool socketSsl(Socket** sock, bool server, const String& context = String::empty());
1188     // Send a SIP method
1189     bool sendMethod(Message& msg, const char* method, bool msgExec = false,
1190 	const char* target = 0);
1191 
1192     static bool s_trace;
1193 
1194 protected:
1195     virtual void genUpdate(Message& msg);
1196     // Setup a listener from config
1197     void setupListener(const String& name, const NamedList& params, bool isGeneral,
1198 	const NamedList& defs = NamedList::empty());
canStopCall() const1199     bool canStopCall() const
1200 	{ return true; }
1201 private:
1202     bool onHelp(Message& msg);
1203     // Add status methods
1204     void msgStatusAccounts(Message& msg);
1205     void msgStatusTransports(Message& msg, bool showUdp, bool showTcp, bool showTls);
1206     void msgStatusListener(Message& msg);
1207     void msgStatusTransport(Message& msg, const String& id);
1208 
1209     SDPParser m_parser;
1210     YateSIPEndPoint *m_endpoint;
1211 };
1212 
1213 static SIPDriver plugin;
1214 
1215 class UserHandler : public MessageHandler
1216 {
1217 public:
UserHandler()1218     UserHandler()
1219 	: MessageHandler("user.login",150,plugin.name())
1220 	{ }
1221     virtual bool received(Message &msg);
1222 };
1223 
1224 class SipHandler : public MessageHandler
1225 {
1226 public:
1227     enum {
1228 	BodyRaw = 0,
1229 	BodyBase64 = 1,
1230 	BodyHex = 2,
1231 	BodyHexS = 3,
1232     };
SipHandler()1233     SipHandler()
1234 	: MessageHandler("xsip.generate",110,plugin.name())
1235 	{ }
1236     virtual bool received(Message &msg);
1237     static const TokenDict s_bodyEnc[];
1238 };
1239 
1240 static ObjList s_lines;
1241 static Configuration s_cfg;
1242 static Mutex s_globalMutex(true,"SIPGlobal"); // Protect globals (don't use the plugin to avoid deadlocks)
1243 static bool s_engineStart = false;       // engine.start received
1244 static unsigned int s_engineStop = 0;    // engine.stop message counter
1245 static bool s_engineHalt = false;        // engine.halt received
1246 static bool s_sslClientAvailable = false;// SSL is available to be used when connecting to remote hosts
1247 static unsigned int s_bindRetryMs = 500; // Listeners bind retry interval
1248 static String s_realm = "Yate";
1249 static int s_floodEvents = 100;
1250 static bool s_floodProtection = true;
1251 static int s_maxForwards = 20;
1252 static int s_congRetry = 30;
1253 static int s_nat_refresh = 25;
1254 static bool s_privacy = false;
1255 static bool s_auto_nat = true;
1256 static bool s_progress = false;
1257 static bool s_start_rtp = false;
1258 static bool s_ack_required = true;
1259 static bool s_1xx_formats = true;
1260 static bool s_sdp_implicit = true;
1261 static bool s_rtp_preserve = false;
1262 static bool s_enable_transfer = false;
1263 static bool s_enable_options = false;
1264 static bool s_enable_message = false;
1265 static bool s_enable_register = false;
1266 static bool s_auth_message = true;
1267 static bool s_auth_register = true;
1268 static bool s_msg_async = true;
1269 static bool s_reg_async = true;
1270 static bool s_gen_async = true;
1271 static bool s_multi_ringing = false;
1272 static bool s_refresh_nosdp = true;
1273 static bool s_update_target = false;
1274 static bool s_update_verify = false;
1275 static bool s_preventive_bye = true;
1276 static bool s_ignoreVia = true;          // Ignore Via headers and send answer back to the source
1277 static bool s_changeParty2xx = false;    // Change party when handling 2xx. Ignored if autochangeparty is disabled
1278 static bool s_warnPacketUDP = true;      // Warn when receiving possible truncated packet
1279 static bool s_initialHeaders = false;    // Put all headers as received in initial message sent to yate
1280 static bool s_sipt_isup = false;         // Control the application/isup body processing
1281 static bool s_printMsg = true;           // Print sent/received SIP messages to output
1282 static ObjList* s_authCopyHeader = 0;    // Copy headers in user.auth
1283 
1284 static bool s_ipv6 = false;              // IPv6 support enabled
1285 static u_int64_t s_waitActiveUdpTrans = 1000000; // Time to wait for active UDP transactions
1286                                                  // to complete when a listener is disabled
1287 static unsigned int s_tcpConnectRetry = 3; // Number of TCP connect attempts
1288 static u_int64_t s_tcpConnectInterval = 1000000; // The interval to attempt tcp connect
1289 static unsigned int s_tcpIdle = TCP_IDLE_DEF; // TCP transport idle interval
1290 static unsigned int s_tcpKeepalive = TCP_IDLE_DEF; // TCP transport keepalive interval
1291 static unsigned int s_tcpKeepaliveFirst = 0; // TCP transport first keepalive interval
1292 static unsigned int s_tcpMaxpkt = 1500;  // Maximum packet to accept on TCP connections
1293 static String s_tcpOutRtpip;             // RTP ip for outgoing tcp/tls transports (protected by plugin mutex)
1294 static bool s_lineKeepTcpOffline = true; // Lines: keep TCP transports when offline
1295 static String s_sslCertFile;             // File containing the SSL client certificate to present if requested by the server
1296 static String s_sslKeyFile;              // File containing the key of the SSL client certificate
1297 
1298 static int s_expires_min = EXPIRES_MIN;
1299 static int s_expires_def = EXPIRES_DEF;
1300 static int s_expires_max = EXPIRES_MAX;
1301 static int s_defEncoding = SipHandler::BodyBase64;
1302 
1303 static const String s_statusCmd = "status";
1304 static const String s_noAutoAuth = "noautoauth";
1305 static const String s_username = "username";
1306 
1307 static u_int64_t s_printFloodTime = 0;
1308 
1309 int YateSIPEndPoint::s_evCount = 0;
1310 bool SIPDriver::s_trace = false;
1311 
1312 // DTMF methods
1313 static bool s_checkAllowInfo = true;         // Check Allow in INVITE and OK for INFO support
1314 static bool s_missingAllowInfoDefVal = true; // Default INFO support if Allow header is missing
1315 static DtmfMethods s_dtmfMethods;
1316 static bool s_honorDtmfDetect = true;
1317 // Deprecated dtmf params warn
1318 static bool s_warnDtmfInfoCfg = true;
1319 static bool s_warnDtmfInbandCfg = true;
1320 static bool s_warnDtmfInfoCallExecute = true;
1321 static bool s_warnDtmfInbandCallExecute = true;
1322 static bool s_warnDtmfMethodChanDtmf = true;
1323 
1324 const TokenDict DtmfMethods::s_methodName[] = {
1325     { "info",     Info},
1326     { "rfc2833",  Rfc2833},
1327     { "inband",   Inband},
1328     { "sip-info", Info},
1329     { 0, 0 },
1330 };
1331 
1332 // Lower case proto name
1333 const TokenDict ProtocolHolder::s_protoLC[] = {
1334     { "udp",  Udp},
1335     { "tcp",  Tcp},
1336     { "tls",  Tls},
1337     { 0, 0 },
1338 };
1339 
1340 // Upper case proto name
1341 const TokenDict ProtocolHolder::s_protoUC[] = {
1342     { "UDP",  Udp},
1343     { "TCP",  Tcp},
1344     { "TLS",  Tls},
1345     { 0, 0 },
1346 };
1347 
1348 // Transport status names
1349 const TokenDict YateSIPTransport::s_statusName[] = {
1350     { "Idle",        Idle},
1351     { "Connected",   Connected},
1352     { "Terminating", Terminating},
1353     { "Terminated",  Terminated},
1354     { 0, 0 },
1355 };
1356 
1357 // Body encodings
1358 const TokenDict SipHandler::s_bodyEnc[] = {
1359     { "raw",    BodyRaw},
1360     { "base64", BodyBase64},
1361     { "hex",    BodyHex},
1362     { "hexs",   BodyHexS},
1363     { 0, 0 },
1364 };
1365 
getGlobal(String & dest,String & src)1366 static inline String& getGlobal(String& dest, String& src)
1367 {
1368     Lock lck(s_globalMutex);
1369     return (dest = src);
1370 }
1371 
1372 // Get an address. Check if enclosed in []
getAddrCheckIPv6(String & dest,const String & src)1373 static inline void getAddrCheckIPv6(String& dest, const String& src)
1374 {
1375     if (!src)
1376 	return;
1377     const char* s = src;
1378     if (!(s[0] == '[' && s[src.length() - 1] == ']'))
1379 	dest = src;
1380     else
1381 	dest.assign(s + 1,src.length() - 2);
1382 }
1383 
1384 // Generate a transport id index when needed
getTransIndex()1385 static inline unsigned int getTransIndex()
1386 {
1387     static unsigned int s_index = 0;
1388     Lock lck(plugin);
1389     if (!++s_index)
1390 	++s_index;
1391     return s_index;
1392 }
1393 
1394 // Add a socket error to a buffer
addSockError(String & buf,Socket & sock,const char * sep=" ")1395 static inline void addSockError(String& buf, Socket& sock, const char* sep = " ")
1396 {
1397     String tmp;
1398     Thread::errorString(tmp,sock.error());
1399     buf << sep << tmp << " (" << sock.error() << ")";
1400 }
1401 
1402 // Build an address from host and interface part of another address
addIfaceAddr(String & buf,const String & host,const String & addr)1403 static inline void addIfaceAddr(String& buf, const String& host, const String& addr)
1404 {
1405     buf << host;
1406     int p = addr.find('%');
1407     if (p >= 0)
1408 	buf.append(addr.c_str() + p,addr.length() - p);
1409 }
1410 
1411 // Return default udp/tcp/tls port
sipPort(bool noTls)1412 static inline int sipPort(bool noTls)
1413 {
1414     return noTls ? 5060 : 5061;
1415 }
1416 
1417 // Return valid tcp idle interval
tcpIdleInterval(int val)1418 static unsigned int tcpIdleInterval(int val)
1419 {
1420     int min = TCP_IDLE_MIN;
1421     // Adjust minimum value to engine INVITE timeout
1422     if (plugin.ep())
1423 	min = (int)(plugin.ep()->engine()->getTimer('B',true) / 1000000) * 3 / 2;
1424     if (val >= min && val <= TCP_IDLE_MAX)
1425 	return val;
1426     return (val < min) ? min : TCP_IDLE_MAX;
1427 }
1428 
1429 // Return a valid maxpkt
getMaxpkt(int val,int defVal)1430 static unsigned int getMaxpkt(int val, int defVal)
1431 {
1432     if (val >= 524 && val <= 65528)
1433 	return val;
1434     if (val <= 0)
1435 	return defVal;
1436     if (val > 65528)
1437 	return 65528;
1438     return 524;
1439 }
1440 
1441 // Skip tabs, spaces, CR and LF from buffer start
1442 // Return true if the buffer changed
skipSpaces(const char * & buf,unsigned int & len,bool crlf=true)1443 static inline bool skipSpaces(const char*& buf, unsigned int& len, bool crlf = true)
1444 {
1445     unsigned int i = 0;
1446     if (crlf) {
1447 	for (; i < len; i++)
1448 	    if (buf[i] != '\r' && buf[i] != '\n' && buf[i] != ' ' && buf[i] != '\t')
1449 		break;
1450     }
1451     else
1452 	for (; i < len; i++)
1453 	    if (buf[i] != ' ' && buf[i] != '\t')
1454 		break;
1455     if (!i)
1456 	return false;
1457     buf += i;
1458     len -= i;
1459     return true;
1460 }
1461 
1462 // Skip spaces at buffer start
1463 // Check for keep alive request
1464 // Return true if keep alive request was found
skipSpacesCheckKeepAlive(const char * & buf,unsigned int & len)1465 static inline bool skipSpacesCheckKeepAlive(const char*& buf, unsigned int& len)
1466 {
1467     static const char* s_keepAlive = "\r\n\r\n";
1468     bool found = false;
1469     while (len) {
1470 	skipSpaces(buf,len,false);
1471 	if (!len)
1472 	    break;
1473 	if (buf[0] != '\r') {
1474 	    if (buf[0] != '\n')
1475 		break;
1476 	    buf++;
1477 	    len--;
1478 	    continue;
1479 	}
1480 	unsigned int i = 1;
1481 	while (i < len && i < 4 && buf[i] == s_keepAlive[i])
1482 	    i++;
1483 	// End of buffer before full keep live: don't advance
1484 	if (i < 4 && i == len)
1485 	    break;
1486 	buf += i;
1487 	len -= i;
1488 	if (i == 4) {
1489 	    found = true;
1490 	    break;
1491 	}
1492     }
1493     if (found)
1494 	skipSpaces(buf,len);
1495     return found;
1496 }
1497 
1498 // Find an empty line in a buffer
1499 // Return the position past it or buffer length + 1 if not found
1500 // NOTE: returned value may be buffer length
getEmptyLine(const char * buf,unsigned int len)1501 static inline unsigned int getEmptyLine(const char* buf, unsigned int len)
1502 {
1503     int count = 0;
1504     unsigned int i = 0;
1505     for (; count < 2 && i < len; i++) {
1506 	if (buf[i] == '\r') {
1507 	    i++;
1508 	    if (i < len && buf[i] == '\n')
1509 		count++;
1510 	    else
1511 		count = 0;
1512 	}
1513 	else if (buf[i] == '\n')
1514 	    count++;
1515 	else
1516 	    count = 0;
1517     }
1518     return (count == 2) ? i : len + 1;
1519 }
1520 
1521 // Fill a buffer with message method/code for debug purposes
getMsgLine(String & buf,const SIPMessage * msg)1522 static inline void getMsgLine(String& buf, const SIPMessage* msg)
1523 {
1524     if (!msg)
1525 	return;
1526     if (msg->isAnswer())
1527 	buf << "code " << msg->code;
1528     else
1529 	buf << "'" << msg->method << " " << msg->uri << "'";
1530 }
1531 
1532 enum {
1533     START,
1534     CHECK_TO,
1535     HAS_TO,
1536     CHECK_TAG,
1537     HAS_TAG,
1538 };
1539 
msgIsAllowed(const char * buf,int len)1540 static bool msgIsAllowed(const char* buf, int len)
1541 {
1542     if (!(buf && len))
1543 	return false;
1544 
1545 
1546     int pos = 0;
1547     // check REGISTER
1548     while (pos < len) {
1549 	if (buf[pos] == ' ' || buf[pos] == '\n' || buf[pos] == '\r' || buf[pos] == '\t') {
1550 	    pos++;
1551 	    continue;
1552 	}
1553 	if ((pos <= len - 8) && (buf[pos] == 'O' || buf[pos] == 'o') &&
1554 	    (buf[pos + 1] == 'P' || buf[pos + 1] == 'p') && (buf[pos + 2] == 'T' || buf[pos + 2] == 't') &&
1555 	    (buf[pos + 3] == 'I' || buf[pos + 3] == 'i') && (buf[pos + 4] == 'O' || buf[pos + 4] == 'o') &&
1556 	    (buf[pos + 5] == 'N' || buf[pos + 5] == 'n') && (buf[pos + 6] == 'S' || buf[pos + 6] == 's') &&
1557 	    (buf[pos + 7] == ' ' || buf[pos + 7] == '\t'))
1558 	    return false;
1559 	if ((pos <= len - 9) && (buf[pos] == 'R' || buf[pos] == 'r') &&
1560 	    (buf[pos + 1] == 'E' || buf[pos + 1] == 'e') && (buf[pos + 2] == 'G' || buf[pos + 2] == 'g') &&
1561 	    (buf[pos + 3] == 'I' || buf[pos + 3] == 'i') && (buf[pos + 4] == 'S' || buf[pos + 4] == 's') &&
1562 	    (buf[pos + 5] == 'T' || buf[pos + 5] == 't') && (buf[pos + 6] == 'E' || buf[pos + 6] == 'e') &&
1563 	    (buf[pos + 7] == 'R' || buf[pos + 7] == 'r') && (buf[pos + 8] == ' ' || buf[pos + 8] == '\t'))
1564 	    return false;
1565 	else if ((pos <= len - 10) && (buf[pos] == 'S' || buf[pos] == 's') &&
1566 	    (buf[pos + 1] == 'U' || buf[pos + 1] == 'u') && (buf[pos + 2] == 'B' || buf[pos + 2] == 'b') &&
1567 	    (buf[pos + 3] == 'S' || buf[pos + 3] == 's') && (buf[pos + 4] == 'C' || buf[pos + 4] == 'c') &&
1568 	    (buf[pos + 5] == 'R' || buf[pos + 5] == 'r') && (buf[pos + 6] == 'I' || buf[pos + 6] == 'i') &&
1569 	    (buf[pos + 7] == 'B' || buf[pos + 7] == 'b') && (buf[pos + 8] == 'E' || buf[pos + 8] == 'e') &&
1570 	    (buf[pos + 9] == ' ' || buf[pos + 9] == '\t'))
1571 	    return false;
1572 	else if ((pos <= len - 7) && ((buf[pos] == 'I' || buf[pos] == 'i') && ++pos) &&
1573 	    ((buf[pos] == 'N' || buf[pos] == 'n') && pos++) && ((buf[pos] == 'V' || buf[pos] == 'v') && pos++) &&
1574 	    ((buf[pos] == 'I' || buf[pos] == 'i') && pos++) && ((buf[pos] == 'T' || buf[pos] == 't') && pos++) &&
1575 	    ((buf[pos] == 'E' || buf[pos] == 'e') && pos++) && ((buf[pos] == ' ' || buf[pos] == '\t') && pos++))
1576 	    break;
1577 	else
1578 	    return true;
1579     }
1580 
1581     /**
1582      * START = begin of line
1583      * CHECK_TO = T/t[o/O] has been found
1584      * HAS_TO = T/t[o/O]: has been found
1585      * CHECK_TAG = T/t[o/O]:...; has been found
1586      * HAS_TAG = T/t[o/O]:...;tag has been found - expecting =
1587      */
1588     while (pos < len - 1) {
1589 	// go to new line
1590 	while (pos < len && buf[pos] != '\r' && buf[pos] != '\n') pos++;
1591 	int status = START;
1592 	bool breakLoop = false;
1593 	while (pos < len) {
1594 
1595 	    switch (buf[pos]) {
1596 		case ' ':
1597 		case '\t':
1598 		    if (status == START)
1599 			breakLoop = true;
1600 		    break;
1601 		case '\n':
1602 		case '\r':
1603 		    if (status != START) {
1604 			// new line found before finding a tag, return false
1605 			if (status == HAS_TO)
1606 			    return false;
1607 			// try the next line
1608 			breakLoop = true;
1609 		    }
1610 		    break;
1611 		case 'T':
1612 		case 't':
1613 		    if (status == START) {
1614 			if (pos < len - 1)
1615 			    if (buf[pos + 1] == 'o' || buf[pos + 1] == 'O') pos++;
1616 			status = CHECK_TO;
1617 		    }
1618 		    else if (status == CHECK_TO)
1619 			// something like Tot is at the start of the line, try next line
1620 			breakLoop = true;
1621 		    // 	 if status is HAS_TO, skip over
1622 		    else if (status == CHECK_TAG) {
1623 			if (pos < len - 2) {
1624 			    if ((buf[pos + 1] == 'a' || buf[pos + 1] == 'A') && (buf[pos + 2] == 'g' || buf[pos + 2] == 'G')) {
1625 				pos += 2;
1626 				status = HAS_TAG;
1627 			    }
1628 			    else
1629 				// might be another tag, return to HAS_TO
1630 				status = HAS_TO;
1631 			}
1632 			else
1633 			    // we're at the end of the string and we don't have enough chars to check for tag
1634 			    breakLoop = true;
1635 		    }
1636 		    else if (status == HAS_TAG)
1637 			// might be another tag, return to HAS_TO
1638 			status = HAS_TO;
1639 		    break;
1640 		case ':':
1641 		    if (status == CHECK_TO)
1642 			status = HAS_TO;
1643 		    else if (status == START)
1644 			// : at start of line, unnacceptable, try next line
1645 			breakLoop = true;
1646 		    // if status is HAS_TO, skip over
1647 		    else if (status == CHECK_TAG || status == HAS_TAG)
1648 			// skip over : while looking for 'tag', return to HAS_TO
1649 			status = HAS_TO;
1650 		    break;
1651 		case ';':
1652 		    if (status == HAS_TO)
1653 			status = CHECK_TAG;
1654 		    else if (status == START || status == CHECK_TO)
1655 			// ; at start of line or after 'to' unnacceptable, try next line
1656 			breakLoop = true;
1657 		    // if status is HAS_TO/CHECK_TAG, skip over
1658 		    else if (status == HAS_TAG)
1659 			// skip over : while looking for 'tag', return to HAS_TO
1660 			status = HAS_TO;
1661 		    break;
1662 		case '=':
1663 		    if (status == HAS_TAG)
1664 			// found ';tag=', is reINVITE
1665 			return true;
1666 		    else if (status == START || status == CHECK_TO)
1667 			// ; at start of line or after 'to' unnacceptable, try next line
1668 			breakLoop = true;
1669 		    // if status is HAS_TO, skip over
1670 		    else if (status == CHECK_TAG)
1671 			// ignore, return to HAS_TO
1672 			status = HAS_TO;
1673 		    break;
1674 		default:
1675 		    if (status == CHECK_TAG || status == HAS_TAG)
1676 			status = HAS_TO;
1677 		    else if (status == START || status == CHECK_TO)
1678 			breakLoop = true;
1679 		    // if status is HAS_TO, skip over
1680 		    break;
1681 	    }
1682 	    if (breakLoop)
1683 		break;
1684 	    pos++;
1685 	}
1686     }
1687     return false;
1688 }
1689 
1690 // Reset transport timeout from expires
resetTransportIdle(const SIPMessage * msg,int interval)1691 static void resetTransportIdle(const SIPMessage* msg, int interval)
1692 {
1693     if (!msg || interval <= 0)
1694 	return;
1695     YateSIPTCPTransport* tcp = YOBJECT(YateSIPTCPTransport,msg->getParty());
1696     if (!tcp)
1697 	return;
1698     const MimeHeaderLine* hl = msg->getHeader("Flow-Timer");
1699     int val = hl ? hl->toInteger() : 0;
1700     bool on = (val > 0 && val < interval);
1701     if (on) {
1702 	// Wait extra time for incoming transports
1703 	interval = tcp->outgoing() ? val : val + 20;
1704     }
1705     tcp->setFlowTimer(on,interval);
1706 }
1707 
1708 // Check if an IPv4 address belongs to one of the non-routable blocks
isPrivateAddr(const String & host)1709 static bool isPrivateAddr(const String& host)
1710 {
1711     if (host.startsWith("192.168.") || host.startsWith("169.254.") || host.startsWith("10."))
1712 	return true;
1713     String s(host);
1714     if (!s.startSkip("172.",false))
1715 	return false;
1716     int i = 0;
1717     s >> i;
1718     return (i >= 16) && (i <= 31) && s.startsWith(".");
1719 }
1720 
1721 // Check if there may be a NAT between an address embedded in the protocol
1722 //  and an address obtained from the network layer
isNatBetween(const String & embAddr,const String & netAddr)1723 static bool isNatBetween(const String& embAddr, const String& netAddr)
1724 {
1725     if (embAddr == netAddr)
1726 	return false;
1727     int embFamily = SocketAddr::family(embAddr);
1728     if (embFamily != SocketAddr::IPv4)
1729 	return false;
1730     int netFamily = SocketAddr::family(netAddr);
1731     if (embFamily != netFamily)
1732 	return false;
1733     return isPrivateAddr(embAddr) && !isPrivateAddr(netAddr);
1734 }
1735 
1736 // List of headers we may not want to handle generically
1737 static const char* s_filterHeaders[] = {
1738     "from",
1739     "to",
1740     0
1741 };
1742 
1743 // List of critical headers we surely don't want to handle generically
1744 static const char* s_rejectHeaders[] = {
1745     "via",
1746     "route",
1747     "record-route",
1748     "call-id",
1749     "cseq",
1750     "max-forwards",
1751     "content-length",
1752     0
1753 };
1754 
1755 // List of authentication headers we normally don't handle generically
1756 static const char* s_authHeaders[] = {
1757     "www-authenticate",
1758     "proxy-authenticate",
1759     "authorization",
1760     "proxy-authorization",
1761     0
1762 };
1763 
1764 // Check if a string matches one member of a static list
matchAny(const String & name,const char ** strs)1765 static bool matchAny(const String& name, const char** strs)
1766 {
1767     for (; *strs; strs++)
1768 	if (name == *strs)
1769 	    return true;
1770     return false;
1771 }
1772 
1773 // Copy headers from SIP message to Yate message
copySipHeaders(NamedList & msg,const SIPMessage & sip,bool filter=true,bool auth=false,bool all=false)1774 static void copySipHeaders(NamedList& msg, const SIPMessage& sip, bool filter = true, bool auth = false,
1775     bool all = false)
1776 {
1777     const ObjList* l = sip.header.skipNull();
1778     for (; l; l = l->skipNext()) {
1779 	const MimeHeaderLine* t = static_cast<const MimeHeaderLine*>(l->get());
1780 	String name(t->name());
1781 	name.toLower();
1782 	// Filtered headers (from/to) are added explicitly
1783 	if (filter && matchAny(name,s_filterHeaders))
1784 	    continue;
1785 	const char* prefix = "sip_";
1786 	if (matchAny(name,s_rejectHeaders) || (!auth && matchAny(name,s_authHeaders))) {
1787 	    if (!all)
1788 		continue;
1789 	    prefix = "sipheader_";
1790 	}
1791 	NamedString* ns = new NamedString(prefix + name);
1792 	t->buildLine(*ns,false);
1793 	msg.addParam(ns);
1794     }
1795 }
1796 
1797 // Copy headers from Yate message to SIP message
copySipHeaders(SIPMessage & sip,const NamedList & msg,const char * prefix="osip_")1798 static void copySipHeaders(SIPMessage& sip, const NamedList& msg, const char* prefix = "osip_")
1799 {
1800     prefix = msg.getValue(YSTRING("osip-prefix"),prefix);
1801     if (!prefix)
1802 	return;
1803     unsigned int n = msg.length();
1804     for (unsigned int i = 0; i < n; i++) {
1805 	NamedString* str = msg.getParam(i);
1806 	if (!str)
1807 	    continue;
1808 	String name(str->name());
1809 	if (!name.startSkip(prefix,false))
1810 	    continue;
1811 	if (name.trimBlanks().null())
1812 	    continue;
1813 	sip.addHeader(name,*str);
1814     }
1815 }
1816 
1817 // Copy privacy related information from SIP message to Yate message
copyPrivacy(NamedList & msg,const SIPMessage & sip)1818 static void copyPrivacy(NamedList& msg, const SIPMessage& sip)
1819 {
1820     bool anonip = (sip.getHeaderValue("Anonymity") &= "ipaddr");
1821     const MimeHeaderLine* hl = sip.getHeader("Remote-Party-ID");
1822     const MimeHeaderLine* ai = sip.getHeader("P-Asserted-Identity");
1823     const MimeHeaderLine* pr = sip.getHeader("Privacy");
1824     if (ai) {
1825 	URI uri(*ai);
1826 	const char* tmp = uri.getDescription();
1827 	if (tmp)
1828 	    msg.setParam("asserted_callername",tmp);
1829 	tmp = uri.getUser();
1830 	if (tmp)
1831 	    msg.setParam("asserted_caller",tmp);
1832 	tmp = uri.getHost();
1833 	if (tmp)
1834 	    msg.setParam("asserted_domain",tmp);
1835 	tmp = uri.getExtra();
1836 	if (tmp)
1837 	    msg.setParam("asserted_params",tmp);
1838     }
1839     if (!(anonip || hl || ai || pr))
1840 	return;
1841     const NamedString* p = hl ? hl->getParam("screen") : 0;
1842     if (p)
1843 	msg.setParam("screened",*p);
1844     if (pr && (*pr &= "none")) {
1845 	msg.setParam("privacy",String::boolText(false));
1846 	return;
1847     }
1848     bool privname = false;
1849     bool privuri = false;
1850     String priv;
1851     if (anonip)
1852 	priv.append("addr",",");
1853     p = hl ? hl->getParam("privacy") : 0;
1854     if (p) {
1855 	if ((*p &= "full") || (*p &= "full-network"))
1856 	    privname = privuri = true;
1857 	else if ((*p &= "name") || (*p &= "name-network"))
1858 	    privname = true;
1859 	else if ((*p &= "uri") || (*p &= "uri-network"))
1860 	    privuri = true;
1861     }
1862     if (pr) {
1863 	if ((*pr &= "user") || pr->getParam("user"))
1864 	    privname = true;
1865 	if ((*pr &= "header") || pr->getParam("header"))
1866 	    privuri = true;
1867     }
1868     if (privname)
1869 	priv.append("name",",");
1870     if (privuri)
1871 	priv.append("uri",",");
1872     if (pr) {
1873 	if ((*pr &= "session") || pr->getParam("session"))
1874 	    priv.append("session",",");
1875 	if ((*pr &= "critical") || pr->getParam("critical"))
1876 	    priv.append("critical",",");
1877 	if ((*pr &= "id") || pr->getParam("id"))
1878 	    priv.append("id",",");
1879     }
1880     if (priv)
1881 	msg.setParam("privacy",priv);
1882     if (hl) {
1883 	URI uri(*hl);
1884 	const char* tmp = uri.getDescription();
1885 	if (tmp)
1886 	    msg.setParam("privacy_callername",tmp);
1887 	tmp = uri.getUser();
1888 	if (tmp)
1889 	    msg.setParam("privacy_caller",tmp);
1890 	tmp = uri.getHost();
1891 	if (tmp)
1892 	    msg.setParam("privacy_domain",tmp);
1893 	const String* str = hl->getParam("party");
1894 	if (!TelEngine::null(str))
1895 	    msg.setParam("remote_party",*str);
1896 	str = hl->getParam("id-type");
1897 	if (!TelEngine::null(str))
1898 	    msg.setParam("remote_id_type",*str);
1899     }
1900 }
1901 
1902 // Copy privacy related information from Yate message to SIP message
copyPrivacy(SIPMessage & sip,const NamedList & msg)1903 static void copyPrivacy(SIPMessage& sip, const NamedList& msg)
1904 {
1905     const String& screened = msg[YSTRING("screened")];
1906     const String& privacy = msg[YSTRING("privacy")];
1907     if (screened.null() && privacy.null())
1908 	return;
1909     bool screen = screened.toBoolean();
1910     bool anonip = (privacy.find("addr") >= 0);
1911     bool privname = (privacy.find("name") >= 0);
1912     bool privuri = (privacy.find("uri") >= 0);
1913     bool privid = (privacy.find("id") >= 0);
1914     bool nopriv = !privacy.toBoolean(true);
1915     String rfc3323;
1916     // allow for a simple "privacy=yes" or similar
1917     if (privacy.toBoolean(false) || (privacy == YSTRING("full")))
1918 	privname = privuri = true;
1919     // "privacy=no" is translated to RFC 3323 "none"
1920     else if (nopriv)
1921 	rfc3323 = "none";
1922     if (anonip)
1923 	sip.setHeader("Anonymity","ipaddr");
1924     if (screen || privname || privuri) {
1925 	const char* caller = msg.getValue(YSTRING("privacy_caller"),msg.getValue(YSTRING("caller")));
1926 	if (!caller)
1927 	    caller = "anonymous";
1928 	const char* domain = msg.getValue(YSTRING("privacy_domain"),msg.getValue(YSTRING("domain")));
1929 	if (!domain)
1930 	    domain = "domain";
1931 	String tmp = msg.getValue(YSTRING("privacy_callername"),msg.getValue(YSTRING("callername")));
1932 	if (tmp) {
1933 	    MimeHeaderLine::addQuotes(tmp);
1934 	    tmp += " ";
1935 	}
1936 	tmp << "<sip:" << caller << "@" << domain << ">";
1937 	MimeHeaderLine* hl = new MimeHeaderLine("Remote-Party-ID",tmp);
1938 	if (screen)
1939 	    hl->setParam("screen","yes");
1940 	if (privname && privuri)
1941 	    hl->setParam("privacy","full");
1942 	else if (privname)
1943 	    hl->setParam("privacy","name");
1944 	else if (privuri)
1945 	    hl->setParam("privacy","uri");
1946 	else
1947 	    hl->setParam("privacy","none");
1948 	const char* str = msg.getValue(YSTRING("remote_party"));
1949 	if (str)
1950 	    hl->setParam("party",str);
1951 	str = msg.getValue(YSTRING("remote_id_type"));
1952 	if (str)
1953 	    hl->setParam("id-type",str);
1954 	sip.addHeader(hl);
1955     }
1956     if (privid || nopriv) {
1957 	const char* caller = msg.getValue(YSTRING("asserted_caller"),msg.getValue(YSTRING("caller")));
1958 	if (caller) {
1959 	    const char* domain = msg.getValue(YSTRING("asserted_domain"),msg.getValue(YSTRING("domain")));
1960 	    const char* extra = msg.getValue(YSTRING("asserted_params"));
1961 	    String tmp;
1962 	    if (domain)
1963 		tmp << "<sip:" << caller << "@" << domain << extra << ">";
1964 	    else if (isE164(caller))
1965 		tmp << "<tel:" << caller << extra << ">";
1966 	    if (tmp) {
1967 		String desc = msg.getValue(YSTRING("asserted_callername"),msg.getValue(YSTRING("callername")));
1968 		if (desc) {
1969 		    MimeHeaderLine::addQuotes(desc);
1970 		    tmp = desc + " " + tmp;
1971 		}
1972 		sip.addHeader(new MimeHeaderLine("P-Asserted-Identity",tmp));
1973 		if (privid) {
1974 		    MimeHeaderLine* hl = const_cast<MimeHeaderLine*>(sip.getHeader("From"));
1975 		    if (hl) {
1976 			URI uri(*hl);
1977 			if (uri.getHost() &&
1978 			    (uri.getProtocol() == YSTRING("sip") || uri.getProtocol() == YSTRING("sips"))) {
1979 			    String tmp = "<" + uri.getProtocol() + ":Anonymous@";
1980 			    if (uri.getPort())
1981 				SocketAddr::appendTo(tmp,uri.getHost(),uri.getPort());
1982 			    else
1983 				SocketAddr::appendAddr(tmp,uri.getHost());
1984 			    *hl = tmp + uri.getExtra() + ">";
1985 			}
1986 			else if (domain)
1987 			    *hl = "<sip:Anonymous@" + String(domain) + ">";
1988 			else
1989 			    *hl = "<sip:Anonymous@anonymous.invalid>";
1990 		    }
1991 		}
1992 	    }
1993 	}
1994     }
1995     if (rfc3323.null()) {
1996 	if (privname)
1997 	    rfc3323.append("user",";");
1998 	if (privuri)
1999 	    rfc3323.append("header",";");
2000 	if (privid)
2001 	    rfc3323.append("id",";");
2002 	if (privacy.find("session") >= 0)
2003 	    rfc3323.append("session",";");
2004 	if (rfc3323 && (privacy.find("critical") >= 0))
2005 	    rfc3323.append("critical",";");
2006     }
2007     if (rfc3323)
2008 	sip.addHeader("Privacy",rfc3323);
2009 }
2010 
2011 // Check if a SDP body is accepted by UAC
sdpAccept(const SIPMessage * sip,bool def)2012 static bool sdpAccept(const SIPMessage* sip, bool def)
2013 {
2014     static const Regexp r("\\(^\\|,\\) *application/sdp *\\($\\|[,;]\\)",false,true);
2015     const MimeHeaderLine* hl = sip ? sip->getHeader("Accept") : 0;
2016     return hl ? r.matches(*hl) : def;
2017 }
2018 
2019 // Copy message body to yate message
copySipBody(NamedList & msg,const MimeBody * body,bool text=false,unsigned int idx=0)2020 static bool copySipBody(NamedList& msg, const MimeBody* body, bool text = false, unsigned int idx = 0)
2021 {
2022     if (!body)
2023 	return false;
2024     if (body->isMultipart()) {
2025 	idx = 0;
2026 	for (const ObjList* l = static_cast<const MimeMultipartBody*>(body)->bodies().skipNull();
2027 		l; l = l->skipNext()) {
2028 	    if (copySipBody(msg,static_cast<const MimeBody*>(l->get()),text,idx))
2029 		idx++;
2030 	}
2031 	return idx > 0;
2032     }
2033 
2034     if (body->isSDP())
2035 	return false;
2036     String suffix;
2037     if (idx)
2038 	suffix << "." << idx;
2039     // add the body if it's a string one
2040     MimeStringBody* strBody = YOBJECT(MimeStringBody,body);
2041     if (strBody) {
2042 	msg.addParam("xsip_type" + suffix,strBody->getType());
2043 	msg.addParam("xsip_body" + suffix,strBody->text());
2044 	if (text)
2045 	    msg.addParam("text" + suffix,strBody->text());
2046     }
2047     else {
2048 	MimeLinesBody* txtBody = YOBJECT(MimeLinesBody,body);
2049 	if (txtBody) {
2050 	    String bodyText((const char*)txtBody->getBody().data(),txtBody->getBody().length());
2051 	    msg.addParam("xsip_type" + suffix,txtBody->getType());
2052 	    msg.addParam("xsip_body" + suffix,bodyText);
2053 	}
2054 	else if (s_sipt_isup && (body->getType() == YSTRING("application/isup")))
2055 	    return false;
2056 	else {
2057 	    const DataBlock& binBody = body->getBody();
2058 	    String bodyText;
2059 	    int enc = s_defEncoding;
2060 	    switch (enc) {
2061 		case SipHandler::BodyRaw:
2062 		    bodyText.assign((const char*)binBody.data(),binBody.length());
2063 		    break;
2064 		case SipHandler::BodyHex:
2065 		    bodyText.hexify(binBody.data(),binBody.length());
2066 		    break;
2067 		case SipHandler::BodyHexS:
2068 		    bodyText.hexify(binBody.data(),binBody.length(),' ');
2069 		    break;
2070 		default:
2071 		    enc = SipHandler::BodyBase64;
2072 		    {
2073 			Base64 b64(binBody.data(),binBody.length(),false);
2074 			b64.encode(bodyText);
2075 			b64.clear(false);
2076 		    }
2077 	    }
2078 	    msg.addParam("xsip_type" + suffix,body->getType());
2079 	    msg.addParam("xsip_body_encoding" + suffix,lookup(enc,SipHandler::s_bodyEnc));
2080 	    msg.addParam("xsip_body" + suffix,bodyText);
2081 	}
2082     }
2083     const ObjList* o = body->headers().skipNull();
2084     if (o) {
2085 	String hdrPrefix = "xsip_body" + suffix + ".header_";
2086 	for (; o; o = o->skipNext()) {
2087 	    const MimeHeaderLine* hdr = static_cast<const MimeHeaderLine*>(o->get());
2088 	    String val;
2089 	    hdr->buildLine(val,false);
2090 	    msg.addParam(hdrPrefix + hdr->name(),val);
2091 	}
2092     }
2093     return true;
2094 }
2095 
2096 // Copy body from SIP message to Yate message
copySipBody(NamedList & msg,const SIPMessage & sip,bool text=false)2097 static bool copySipBody(NamedList& msg, const SIPMessage& sip, bool text = false)
2098 {
2099     return copySipBody(msg,sip.body,text);
2100 }
2101 
2102 // Create a custom body from Yate message
createSipBody(const NamedList & msg,MimeBody * b1=0,MimeBody * b2=0,const ObjList * bodyTrace=0)2103 static MimeBody* createSipBody(const NamedList& msg, MimeBody* b1 = 0, MimeBody* b2 = 0,
2104     const ObjList* bodyTrace = 0)
2105 {
2106     ObjList extra;
2107     for (int i = 0; ; i++) {
2108 	String suffix;
2109 	if (i)
2110 	    suffix << "." << i;
2111 	String pName = "xsip_body" + suffix;
2112 	const String& body = msg[pName];
2113 	if (!body)
2114 	    break;
2115 	if (bodyTrace) {
2116 	    BodyTrace* bt = static_cast<BodyTrace*>(bodyTrace->get());
2117 	    bodyTrace = bodyTrace->skipNext();
2118 	    if (bt && bt->sameBody(body))
2119 		break;
2120 	}
2121 	const String& type = msg["xsip_type" + suffix];
2122 	if (!type)
2123 	    continue;
2124 	const String& bodyEnc = msg["xsip_body_encoding" + suffix];
2125 	MimeBody* bExtra = 0;
2126 	if (bodyEnc.null())
2127 	    bExtra = new MimeStringBody(type,body.c_str(),body.length());
2128 	else {
2129 	    DataBlock binBody;
2130 	    bool ok = false;
2131 	    switch (bodyEnc.toInteger(SipHandler::s_bodyEnc)) {
2132 		case SipHandler::BodyRaw:
2133 		    binBody.append(body);
2134 		    ok = true;
2135 		    break;
2136 		case SipHandler::BodyHex:
2137 		case SipHandler::BodyHexS:
2138 		    ok = binBody.unHexify(body);
2139 		    break;
2140 		case SipHandler::BodyBase64:
2141 		    {
2142 			Base64 b64;
2143 			b64 << body;
2144 			ok = b64.decode(binBody);
2145 		    }
2146 		    break;
2147 	    }
2148 	    if (!ok) {
2149 		Debug(&plugin,DebugWarn,"Invalid xsip_body_encoding%s '%s'",suffix.safe(),bodyEnc.c_str());
2150 		continue;
2151 	    }
2152 	    bExtra = new MimeBinaryBody(type,(const char*)binBody.data(),binBody.length());
2153 	}
2154 	String hdr;
2155 	hdr << pName << ".header_";
2156 	for (const ObjList* o = msg.paramList()->skipNull(); o; o = o->skipNext()) {
2157 	    const NamedString* ns = static_cast<const NamedString*>(o->get());
2158 	    if (ns->name().startsWith(hdr)) {
2159 		String name = ns->name().substr(hdr.length());
2160 		if (name)
2161 		    bExtra->appendHdr(new MimeHeaderLine(name,*ns));
2162 	    }
2163 	}
2164 	extra.append(bExtra);
2165     }
2166 
2167     unsigned int n = 0;
2168     if (b1)
2169 	n++;
2170     if (b2)
2171 	n++;
2172     MimeBody* bExtra = static_cast<MimeBody*>(extra.remove(false));
2173     if (bExtra) {
2174 	n++;
2175 	if (extra.skipNull())
2176 	    n++;
2177     }
2178     if (n < 2)
2179 	return b1 ? b1 : (b2 ? b2 : bExtra);
2180 
2181     MimeMultipartBody* multi = new MimeMultipartBody;
2182     if (b1)
2183 	multi->appendBody(b1);
2184     if (b2)
2185 	multi->appendBody(b2);
2186     while (bExtra) {
2187 	multi->appendBody(bExtra);
2188 	bExtra = static_cast<MimeBody*>(extra.remove(false));
2189     }
2190     return multi;
2191 }
2192 
2193 // Copy body from Yate message to SIP message
copySipBody(SIPMessage & sip,const NamedList & msg,const ObjList * bodyTrace=0)2194 static bool copySipBody(SIPMessage& sip, const NamedList& msg, const ObjList* bodyTrace = 0)
2195 {
2196     MimeBody* body = createSipBody(msg,0,0,bodyTrace);
2197     if (!body)
2198 	return false;
2199     sip.setBody(body);
2200     return true;
2201 }
2202 
2203 // Check if the given body have the given type
2204 // Find the given type inside multiparts
getOneBody(MimeBody * body,const char * type)2205 static inline MimeBody* getOneBody(MimeBody* body, const char* type)
2206 {
2207     return body ? body->getFirst(type) : 0;
2208 }
2209 
2210 // Check if the given body is a SDP one or find an enclosed SDP body
2211 //  if it is a multipart
getSdpBody(MimeBody * body)2212 static inline MimeSdpBody* getSdpBody(MimeBody* body)
2213 {
2214     if (!body)
2215 	return 0;
2216     return static_cast<MimeSdpBody*>(body->isSDP() ? body : body->getFirst("application/sdp"));
2217 }
2218 
2219 // Add a mime body parameter to a list of parameters
2220 // Remove quotes, trim blanks and convert to lower case before adding
2221 // Return false if the parameter wasn't added
addBodyParam(NamedList & nl,const char * param,MimeBody * body,const char * bodyParam)2222 inline bool addBodyParam(NamedList& nl, const char* param, MimeBody* body, const char* bodyParam)
2223 {
2224     const NamedString* ns = body ? body->getParam(bodyParam) : 0;
2225     if (!ns)
2226 	return false;
2227     String p = *ns;
2228     MimeHeaderLine::delQuotes(p);
2229     p.trimBlanks();
2230     if (p.null())
2231 	return false;
2232     p.toLower();
2233     nl.addParam(param,p);
2234     return true;
2235 }
2236 
2237 // Decode an application/isup body into 'msg' if configured to do so
2238 // The message's name and user data are restored before exiting, regardless the result
2239 // Return true if an ISUP message was succesfully decoded
doDecodeIsupBody(const DebugEnabler * debug,Message & msg,MimeBody * body)2240 static bool doDecodeIsupBody(const DebugEnabler* debug, Message& msg, MimeBody* body)
2241 {
2242     if (!s_sipt_isup)
2243 	return false;
2244     // Get a valid application/isup body
2245     MimeBinaryBody* isup = static_cast<MimeBinaryBody*>(getOneBody(body,"application/isup"));
2246     if (!isup)
2247 	return false;
2248     // Remember the message's name and user data and fill parameters
2249     String name = msg;
2250     RefObject* userdata = msg.userData();
2251     if (userdata)
2252 	userdata->ref();
2253     msg = "isup.decode";
2254     msg.addParam("message-prefix","isup.");
2255     addBodyParam(msg,"isup.protocol-type",isup,"version");
2256     addBodyParam(msg,"isup.protocol-basetype",isup,"base");
2257     msg.addParam(new NamedPointer("rawdata",new DataBlock(isup->body())));
2258     bool ok = Engine::dispatch(msg);
2259     // Clear added params and restore message
2260     if (!ok) {
2261 	Debug(debug,DebugMild,"%s failed error='%s'",
2262 	    msg.c_str(),msg.getValue(YSTRING("error")));
2263 	msg.clearParam(YSTRING("error"));
2264     }
2265     msg.clearParam(YSTRING("rawdata"));
2266     msg = name;
2267     msg.userData(userdata);
2268     TelEngine::destruct(userdata);
2269     return ok;
2270 }
2271 
2272 // Build the body of a SIP message from an engine message
2273 // Encode an ISUP message from parameters received in msg if enabled to process them
2274 // Build a multipart/mixed body if more then one body is going to be sent
doBuildSIPBody(const DebugEnabler * debug,Message & msg,MimeSdpBody * sdp,const char * prefixName=0)2275 static MimeBody* doBuildSIPBody(const DebugEnabler* debug, Message& msg,
2276     MimeSdpBody* sdp, const char* prefixName = 0)
2277 {
2278     MimeBinaryBody* isup = 0;
2279 
2280     // Build isup
2281     while (s_sipt_isup) {
2282 	static const String s_stdPrefix("message-prefix");
2283 	String prefix = msg.getValue(prefixName ? prefixName : s_stdPrefix.c_str());
2284 	if (!msg.getParam(prefix + "message-type"))
2285 	    break;
2286 
2287 	// Remember the message's name, prefix and user data
2288 	String pre;
2289 	String name = msg;
2290 	RefObject* userdata = msg.userData();
2291 	if (userdata)
2292 	    userdata->ref();
2293 
2294 	DataBlock* data = 0;
2295 	msg = "isup.encode";
2296 	if (prefixName) {
2297 	    pre = msg.getValue(s_stdPrefix);
2298 	    msg.setParam(s_stdPrefix,prefix);
2299 	}
2300 	if (Engine::dispatch(msg)) {
2301 	    NamedString* ns = msg.getParam(YATOM("rawdata"));
2302 	    if (ns) {
2303 		NamedPointer* np = static_cast<NamedPointer*>(ns->getObject(YATOM("NamedPointer")));
2304 		if (np)
2305 		    data = static_cast<DataBlock*>(np->userObject(YATOM("DataBlock")));
2306 	    }
2307 	}
2308 	if (data && data->length()) {
2309 	    isup = new MimeBinaryBody("application/isup",(const char*)data->data(),data->length());
2310 	    isup->setParam("version",msg.getValue(prefix + "protocol-type"));
2311 	    const char* s = msg.getValue(prefix + "protocol-basetype");
2312 	    if (s)
2313 		isup->setParam("base",s);
2314 	    MimeHeaderLine* line = new MimeHeaderLine("Content-Disposition","signal");
2315 	    line->setParam("handling","optional");
2316 	    isup->appendHdr(line);
2317 	}
2318 	else {
2319 	    Debug(debug,DebugMild,"%s failed error='%s'",
2320 		msg.c_str(),msg.getValue(YSTRING("error")));
2321 	    msg.clearParam(YSTRING("error"));
2322 	}
2323 
2324 	// Restore message
2325 	msg = name;
2326 	if (prefixName) {
2327 	    if (pre)
2328 		msg.setParam(s_stdPrefix,pre);
2329 	    else
2330 		msg.clearParam(s_stdPrefix);
2331 	}
2332 	msg.userData(userdata);
2333 	TelEngine::destruct(userdata);
2334 	break;
2335     }
2336 
2337     return createSipBody(msg,sdp,isup);
2338 }
2339 
2340 // Find an URI parameter separator. Accept '?' or '&'
findURIParamSep(const String & str,int start)2341 static inline int findURIParamSep(const String& str, int start)
2342 {
2343     if (start < 0)
2344 	return -1;
2345     for (int i = start; i < (int)str.length(); i++)
2346 	if (str[i] == '?' || str[i] == '&')
2347 	    return i;
2348     return -1;
2349 }
2350 
2351 // Set a transaction response from an authentication error
setAuthError(SIPTransaction * trans,const NamedList & params,bool stale,const String & domain=String::empty ())2352 static void setAuthError(SIPTransaction* trans, const NamedList& params,
2353     bool stale, const String& domain = String::empty())
2354 {
2355     const String& error = params[YSTRING("error")];
2356     while (error) {
2357 	int code = error.toInteger(dict_errors,401);
2358 	if (code < 400 || code > 699)
2359 	    break;
2360 	if ((code == 401) && (s_noAutoAuth != error))
2361 	    break;
2362 	SIPMessage* m = new SIPMessage(trans->initialMessage(),code,params.getValue(YSTRING("reason")));
2363 	copySipHeaders(*m,params);
2364 	trans->setResponse(m);
2365 	m->deref();
2366 	return;
2367     }
2368     String r;
2369     trans->requestAuth(getGlobal(r,s_realm),domain,stale);
2370 }
2371 
2372 
2373 // Replace all methods from comma separated list
2374 // If no method is set use other or setDefEmpty (reset to default)
set(const String & methods,const DtmfMethods * other,bool setDefEmpty,bool intersectOther)2375 bool DtmfMethods::set(const String& methods, const DtmfMethods* other, bool setDefEmpty,
2376     bool intersectOther)
2377 {
2378     set();
2379     bool found = false;
2380     bool ok = true;
2381     ObjList* m = methods.split(',');
2382     int i = 0;
2383     for (ObjList* o = m->skipNull(); o && i < MethodCount; o = o->skipNext()) {
2384 	String* s = static_cast<String*>(o->get());
2385 	int meth = lookup(s->trimBlanks(),s_methodName,MethodCount);
2386 	if (meth != MethodCount) {
2387 	    m_methods[i++] = meth;
2388 	    found = true;
2389 	}
2390 	else if (*s)
2391 	    ok = false;
2392     }
2393     TelEngine::destruct(m);
2394     if (!found) {
2395 	if (other) {
2396 	    *this = *other;
2397 	    intersectOther = false;
2398 	}
2399 	else if (setDefEmpty)
2400 	    setDefault();
2401     }
2402     if (intersectOther && other)
2403 	intersect(*other);
2404     return ok;
2405 }
2406 
2407 // Intersect with other methods
intersect(const DtmfMethods & other)2408 void DtmfMethods::intersect(const DtmfMethods& other)
2409 {
2410     for (int i = 0; i < MethodCount; i++)
2411 	if (m_methods[i] != MethodCount && !other.hasMethod(m_methods[i]))
2412 	    m_methods[i] = MethodCount;
2413 }
2414 
2415 // Retrieve a method from deperecated parameters
2416 // Reset the method if the parameter is false
2417 // Display a message anyway if warn is not false
getDeprecatedDtmfMethod(const NamedList & list,const char * param,int method,bool * warn)2418 bool DtmfMethods::getDeprecatedDtmfMethod(const NamedList& list, const char* param,
2419     int method, bool* warn)
2420 {
2421     String* p = list.getParam(param);
2422     if (!p)
2423 	return false;
2424     if (!p->toBoolean())
2425 	reset(method);
2426     if (warn && *warn) {
2427 	*warn = false;
2428 	Debug(&plugin,DebugConf,"Deprecated '%s' in '%s'. Use 'dtmfmethods' instead!",param,list.c_str());
2429     }
2430     return true;
2431 }
2432 
2433 // Reset a method
reset(int method)2434 void DtmfMethods::reset(int method)
2435 {
2436     for (int i = 0; i < MethodCount; i++)
2437 	if (m_methods[i] == method) {
2438 	    m_methods[i] = MethodCount;
2439 	    break;
2440 	}
2441 }
2442 
2443 // Build a string list from methods
buildMethods(String & buf,const char * sep)2444 void DtmfMethods::buildMethods(String& buf, const char* sep)
2445 {
2446     for (int i = 0; i < MethodCount; i++)
2447 	buf.append(lookup(m_methods[i],s_methodName),sep);
2448 }
2449 
hasMethod(int method) const2450 bool DtmfMethods::hasMethod(int method) const
2451 {
2452     for (int i = 0; i < MethodCount; i++)
2453 	if (m_methods[i] == method)
2454 	    return true;
2455     return false;
2456 }
2457 
2458 
change(String & dest,const String & src)2459 bool YateSIPPartyHolder::change(String& dest, const String& src)
2460 {
2461     if (dest == src)
2462 	return false;
2463     changing();
2464     dest = src;
2465     return true;
2466 }
2467 
change(int & dest,int src)2468 bool YateSIPPartyHolder::change(int& dest, int src)
2469 {
2470     if (dest == src)
2471 	return false;
2472     changing();
2473     dest = src;
2474     return true;
2475 }
2476 
change(bool & dest,bool src)2477 bool YateSIPPartyHolder::change(bool& dest, bool src)
2478 {
2479     if (dest == src)
2480 	return false;
2481     changing();
2482     dest = src;
2483     return true;
2484 }
2485 
changing()2486 void YateSIPPartyHolder::changing()
2487 {
2488 }
2489 
2490 // Check if a transport is used by our party
transport(bool ref)2491 YateSIPTransport* YateSIPPartyHolder::transport(bool ref)
2492 {
2493     Lock lock(m_partyMutex);
2494     YateSIPTransport* trans = 0;
2495     if (m_party)
2496 	trans = static_cast<YateSIPTransport*>(m_party->getTransport());
2497     return (trans && (!ref || trans->ref())) ? trans : 0;
2498 }
2499 
2500 // Set the held party. Referrence it before
setParty(SIPParty * party)2501 void YateSIPPartyHolder::setParty(SIPParty* party)
2502 {
2503     Lock lck(m_partyMutex);
2504     if (party == m_party)
2505 	return;
2506     if (party && !party->ref())
2507 	party = 0;
2508 #ifdef DEBUG
2509     if (party != m_party) {
2510 	String extra;
2511 	if (party) {
2512 	    String local, remote;
2513 	    extra += " local=";
2514 	    party->appendAddr(extra,true);
2515 	    extra += " remote=";
2516 	    party->appendAddr(extra,false);
2517 	}
2518 	TraceDebug(m_traceId,m_enabler,DebugAll,"YateSIPPartyHolder set party (%p)%s trans=(%p) [%p]",
2519 	    party,extra.safe(),party ? party->getTransport() : 0,this);
2520     }
2521 #endif
2522     SIPParty* tmp = m_party;
2523     m_party = party;
2524     lck.drop();
2525     TelEngine::destruct(tmp);
2526 }
2527 
2528 // Set the held party if remote address changed
setPartyChanged(SIPParty * party)2529 bool YateSIPPartyHolder::setPartyChanged(SIPParty* party)
2530 {
2531     if (!(party && m_party))
2532 	return false;
2533     if (party == m_party)
2534 	return true;
2535     Lock lck(m_partyMutex);
2536     if (!m_party)
2537 	return false;
2538     if (party == m_party)
2539 	return true;
2540     RefPointer<SIPParty> crt = m_party;
2541     if (!crt)
2542 	return false;
2543     lck.drop();
2544     String partyAddr, crtAddr;
2545     int partyPort, crtPort;
2546     party->getAddr(partyAddr,partyPort,false);
2547     crt->getAddr(crtAddr,crtPort,false);
2548     crt = 0;
2549     bool changed = partyPort != crtPort || partyAddr != crtAddr;
2550     if (changed) {
2551 	String crt;
2552 	String p;
2553 	SocketAddr::appendTo(crt,crtAddr,crtPort);
2554 	SocketAddr::appendTo(p,partyAddr,partyPort);
2555 	TraceDebug(m_traceId,m_enabler,DebugInfo,"YateSIPPartyHolder party addr changed '%s' -> '%s' [%p]",
2556 	    crt.c_str(),p.c_str(),this);
2557 	setParty(party);
2558     }
2559     return changed;
2560 }
2561 
2562 // Set the party of a non answer message
setSipParty(SIPMessage * message,const YateSIPLine * line,bool useEp,const char * host,int port) const2563 bool YateSIPPartyHolder::setSipParty(SIPMessage* message, const YateSIPLine* line,
2564     bool useEp, const char* host, int port) const
2565 {
2566     if (!message || message->isAnswer())
2567 	return false;
2568     Lock lck(m_partyMutex);
2569     if (!m_party) {
2570 	lck.drop();
2571 	if (useEp && plugin.ep())
2572 	    plugin.ep()->buildParty(message,host,port,line);
2573 	return 0 != message->getParty();
2574     }
2575     message->setParty(m_party);
2576     lck.drop();
2577     if (line)
2578 	line->setupAuth(message);
2579     return true;
2580 }
2581 
2582 // Change party and its transport. Return true on success
buildParty(bool force,bool isTemp)2583 bool YateSIPPartyHolder::buildParty(bool force, bool isTemp)
2584 {
2585     XDebug(m_enabler,DebugAll,"YateSIPPartyHolder::buildParty(%s,%s,%d,%s,%d) force=%u [%p]",
2586 	protoName(),m_transLocalAddr.c_str(),m_transLocalPort,
2587 	m_transRemoteAddr.c_str(),m_transRemotePort,force,this);
2588     m_partyInvalidRemote.clear();
2589     if (!force) {
2590 	Lock lock(m_partyMutex);
2591 	if (m_party)
2592 	    return true;
2593     }
2594     YateSIPTCPTransport* tcpTrans = 0;
2595     YateSIPUDPTransport* udpTrans = 0;
2596     bool initTcp = false;
2597     bool addrValid = true;
2598     if (m_transId) {
2599 	YateSIPTransport* trans = 0;
2600 	if (plugin.ep())
2601 	    trans = plugin.ep()->findTransport(m_transId);
2602 	if (trans) {
2603 	    tcpTrans = trans->tcpTransport();
2604 	    if (!tcpTrans) {
2605 		udpTrans = trans->udpTransport();
2606 		if (!udpTrans)
2607 		    TelEngine::destruct(trans);
2608 	    }
2609 	}
2610     }
2611     if (!(tcpTrans || udpTrans)) {
2612 	if (protocol() == Udp) {
2613 	    if (plugin.ep()) {
2614 		if (!m_transLocalAddr)
2615 		    udpTrans = plugin.ep()->defTransport();
2616 		else {
2617 		    SocketAddr addr(s_ipv6 ? SocketAddr::Unknown : SocketAddr::IPv4);
2618 		    addr.host(m_transLocalAddr);
2619 		    udpTrans = plugin.ep()->findUdpTransport(addr.host(),m_transLocalPort);
2620 		}
2621 	    }
2622 	}
2623 	else {
2624 	    initTcp = true;
2625 	    bool tls = (protocol() == Tls);
2626 	    if (tls || protocol() == Tcp) {
2627 		addrValid = m_transRemoteAddr && m_transRemotePort > 0;
2628 		if (addrValid)
2629 		    tcpTrans = new YateSIPTCPTransport(tls,m_transLocalAddr,
2630 			m_transRemoteAddr,m_transRemotePort);
2631 	    }
2632 	    else
2633 		TraceDebug(m_traceId,DebugStub,"YateSIPPartyHolder::buildParty() transport %s not implemented",
2634 		    protoName());
2635 	}
2636     }
2637     SIPParty* p = 0;
2638     if (udpTrans) {
2639 	SocketAddr addr(s_ipv6 ? SocketAddr::Unknown : SocketAddr::IPv4);
2640 	addr.host(m_transRemoteAddr);
2641 	addr.port(m_transRemotePort);
2642 	addrValid = addr.host() && addr.port() > 0;
2643 	if (addrValid)
2644 	    p = new YateUDPParty(udpTrans,addr);
2645     }
2646     else if (tcpTrans) {
2647 	p = tcpTrans->getParty();
2648 	if (!p)
2649 	    p = new YateTCPParty(tcpTrans);
2650     }
2651     setParty(p);
2652     TelEngine::destruct(p);
2653     if (!addrValid) {
2654 	m_partyInvalidRemote = "";
2655 	SocketAddr::appendTo(m_partyInvalidRemote,m_transRemoteAddr,m_transRemotePort);
2656 	DDebug(m_enabler,DebugNote,"Failed to build %s transport with invalid remote addr=%s",
2657 	    protoName(),m_partyInvalidRemote.c_str());
2658     }
2659     if (tcpTrans && initTcp) {
2660 	// TODO: handle other params: maxpkt, thread prio
2661 	tcpTrans->init(NamedList::empty(),true);
2662     }
2663     if (!isTemp || m_party)
2664 	TraceDebug(m_traceId,m_enabler,m_party ? DebugAll : DebugNote,
2665 	    "%s party trans_name=%s proto=%s local=%s remote=%s [%p]",
2666 	    m_party ? "Set" : "Failed to set",m_transId.c_str(),protoName(),
2667 	    SocketAddr::appendTo(m_transLocalAddr,m_transLocalPort).c_str(),
2668 	    SocketAddr::appendTo(m_transRemoteAddr,m_transRemotePort).c_str(),m_enabler);
2669     TelEngine::destruct(udpTrans);
2670     TelEngine::destruct(tcpTrans);
2671     return m_party != 0;
2672 }
2673 
2674 // Transport status changed notification
transportChangedStatus(int stat,const String & reason)2675 void YateSIPPartyHolder::transportChangedStatus(int stat, const String& reason)
2676 {
2677     if (stat != YateSIPTransport::Connected)
2678 	return;
2679     Lock lck(m_partyMutex);
2680     RefPointer<SIPParty> p = m_party;
2681     if (!p)
2682 	return;
2683     YateSIPTransport* trans = static_cast<YateSIPTransport*>(p->getTransport());
2684     if (!(trans && trans->udpTransport()))
2685 	return;
2686     // No need to lock transport to get its addr: this method is called from
2687     //  transport itself just after connected
2688     String tLocalAddr = trans->local().host();
2689     int tLocalPort = trans->local().port();
2690     lck.drop();
2691     String pLocalAddr;
2692     int pLocalPort = 0;
2693     p->getAddr(pLocalAddr,pLocalPort,true);
2694     if (pLocalPort != tLocalPort || tLocalAddr != pLocalAddr) {
2695 	p->setAddr(tLocalAddr,tLocalPort,true);
2696 	DDebug(m_enabler,DebugInfo,"YateSIPPartyHolder party local addr changed '%s' -> '%s' [%p]",
2697 	    SocketAddr::appendTo(pLocalAddr,pLocalPort).c_str(),
2698 	    SocketAddr::appendTo(tLocalAddr,tLocalPort).c_str(),m_enabler);
2699     }
2700 }
2701 
2702 // Change party and its transport. Return true on success
setParty(const NamedList & params,bool force,const String & prefix,const String & defRemoteAddr,int defRemotePort,bool isTemp)2703 bool YateSIPPartyHolder::setParty(const NamedList& params, bool force, const String& prefix,
2704     const String& defRemoteAddr, int defRemotePort, bool isTemp)
2705 {
2706     if (!(force || haveTransParams(params,prefix))) {
2707 	setParty();
2708 	return false;
2709     }
2710     const String& transId = params[prefix + "connection_id"];
2711     if (change(m_transId,transId))
2712 	TraceDebug(m_traceId,m_enabler,DebugAll,
2713 	    "YateSIPPartyHolder transport id changed to '%s' [%p]",
2714 	    m_transId.c_str(),this);
2715     updateProto(params,prefix);
2716     updateRemoteAddr(params,prefix,defRemoteAddr,defRemotePort);
2717     updateLocalAddr(params,prefix);
2718     return buildParty(true,isTemp);
2719 }
2720 
2721 // Update transport type. Return true if changed
updateProto(const NamedList & params,const String & prefix)2722 bool YateSIPPartyHolder::updateProto(const NamedList& params, const String& prefix)
2723 {
2724     int proto = lookupProtoAny(params[prefix + "ip_transport"]);
2725     if (proto == Unknown) {
2726 	if (!params.getBoolValue(prefix + "ip_transport_tcp")) {
2727 	    if (m_transId) {
2728 		// Check transport id prefix
2729 		if (m_transId.startsWith("tcp:",false))
2730 		    proto = Tcp;
2731 		else if (m_transId.startsWith("tls:",false))
2732 		    proto = Tls;
2733 		else
2734 		    proto = Udp;
2735 	    }
2736 	    else
2737 		proto = sips() ? Tls : Udp;
2738 	}
2739 	else if (!params.getBoolValue(prefix + "ip_transport_tls"))
2740 	    proto = Tcp;
2741 	else
2742 	    proto = Tls;
2743     }
2744     bool chg = change(m_proto,proto);
2745     if (chg)
2746 	TraceDebug(m_traceId,m_enabler,DebugAll,"YateSIPPartyHolder transport proto changed to '%s' [%p]",
2747 	    protoName(),this);
2748     return chg;
2749 }
2750 
2751 // Update transport remote addr/port. Return true if changed
updateRemoteAddr(const NamedList & params,const String & prefix,const String & defRemoteAddr,int defRemotePort)2752 bool YateSIPPartyHolder::updateRemoteAddr(const NamedList& params, const String& prefix,
2753     const String& defRemoteAddr, int defRemotePort)
2754 {
2755     const char* addr = params.getValue(prefix + "ip_transport_remoteip",defRemoteAddr);
2756     int port = params.getIntValue(prefix + "ip_transport_remoteport",defRemotePort);
2757     if (port <= 0)
2758 	port = sipPort(protocol() != Tls);
2759     bool chg = change(m_transRemoteAddr,addr);
2760     chg = change(m_transRemotePort,port) || chg;
2761     if (chg && plugin.debugAt(DebugAll)) {
2762 	String s;
2763 	SocketAddr::appendTo(s,m_transRemoteAddr,m_transRemotePort);
2764 	TraceDebug(m_traceId,m_enabler,DebugAll,"YateSIPPartyHolder remote addr changed to '%s' [%p]",
2765 	    s.c_str(),this);
2766     }
2767     return chg;
2768 }
2769 
2770 // Update transport local addr/port. Return true if changed
updateLocalAddr(const NamedList & params,const String & prefix)2771 bool YateSIPPartyHolder::updateLocalAddr(const NamedList& params, const String& prefix)
2772 {
2773     bool chg = change(m_transLocalAddr,params[prefix + "ip_transport_localip"]);
2774     int port = params.getIntValue(prefix + "ip_transport_localport");
2775     chg = change(m_transLocalPort,port) || chg;
2776     if (chg && plugin.debugAt(DebugAll)) {
2777 	String s;
2778 	SocketAddr::appendTo(s,m_transLocalAddr,m_transLocalPort);
2779 	TraceDebug(m_traceId,m_enabler,DebugAll,"YateSIPPartyHolder local addr changed to '%s' [%p]",
2780 	    s.c_str(),this);
2781     }
2782     return chg;
2783 }
2784 
2785 // Update RTP local address
setRtpLocalAddr(String & addr,Message * m)2786 void YateSIPPartyHolder::setRtpLocalAddr(String& addr, Message* m)
2787 {
2788     addr.clear();
2789     if (m)
2790 	addr = m->getValue(YSTRING("rtp_localip"));
2791     if (!addr && m_party) {
2792 	Lock lock(m_partyMutex);
2793 	YateSIPTransport* t = YOBJECT(YateSIPTransport,m_party);
2794 	if (t && !t->ref())
2795 	    t = 0;
2796 	lock.drop();
2797 	if (t)
2798 	    t->rtpAddr(addr);
2799 	TelEngine::destruct(t);
2800     }
2801     DDebug(m_enabler,DebugAll,"YateSIPPartyHolder rtp local addr is '%s' [%p]",
2802 	addr.c_str(),this);
2803 }
2804 
2805 
YateSIPListener(const char * name,int proto,const String & addr,int port)2806 YateSIPListener::YateSIPListener(const char* name, int proto, const String& addr, int port)
2807     : m_bindInterval(0), m_nextBind(0),
2808     m_bind(true), m_address(addr), m_port(port),
2809     m_ipv6(false), m_ipv6Support(false), m_setRtpAddr(false),
2810     m_name(name), m_proto(proto)
2811 {
2812 }
2813 
2814 // Check bind now flag
bindNow(Mutex * mutex)2815 bool YateSIPListener::bindNow(Mutex* mutex)
2816 {
2817     if (!m_bind)
2818 	return false;
2819     Lock lck(mutex);
2820     bool old = m_bind;
2821     m_bind = false;
2822     return old;
2823 }
2824 
2825 // Set addr/port and bind flag. Return the bind flag
setAddr(const String & addr,int port,bool ipv6)2826 void YateSIPListener::setAddr(const String& addr, int port, bool ipv6)
2827 {
2828     if (m_cfgAddr != addr) {
2829 	m_bind = true;
2830 	SocketAddr::splitIface(addr,m_address);
2831 	m_cfgAddr = addr;
2832     }
2833     if (m_port != port) {
2834 	m_bind = true;
2835 	m_port = port;
2836     }
2837     if (m_ipv6 != ipv6) {
2838 	m_bind = true;
2839 	m_ipv6 = ipv6;
2840     }
2841 }
2842 
2843 // Update IPv6 support from global
updateIPv6Support()2844 void YateSIPListener::updateIPv6Support()
2845 {
2846     if (m_ipv6Support == s_ipv6)
2847 	return;
2848     m_ipv6Support = s_ipv6;
2849     // Force re-bind if we are using IPv6
2850     if (m_ipv6 && !m_bind) {
2851 	Debug(&plugin,DebugAll,"Listener(%s,'%s') IPv6 support changed. Forcing re-bind",
2852 	    ProtocolHolder::lookupProtoName(m_proto),lName());
2853 	m_bind = true;
2854     }
2855 }
2856 
2857 // Update rtp address
updateRtpAddr(const NamedList & params,String & buf,Mutex * mutex)2858 bool YateSIPListener::updateRtpAddr(const NamedList& params, String& buf, Mutex* mutex)
2859 {
2860     Lock lck(mutex);
2861     NamedString* ns = params.getParam(YSTRING("rtp_localip"));
2862     if (ns)
2863 	buf = *ns;
2864     else
2865 	buf.clear();
2866     bool val = false;
2867     if (m_proto == ProtocolHolder::Udp && params == YSTRING("general"))
2868 	val = false;
2869     else if (ns && ns->null())
2870 	val = false;
2871     else
2872 	val = buf.null();
2873     // We should set rtp addr from bind address and we already have one
2874     if (val && m_bindRtpLocalAddr) {
2875 	buf = m_bindRtpLocalAddr;
2876 	m_setRtpAddr = false;
2877 	return false;
2878     }
2879     if (val == m_setRtpAddr)
2880 	return false;
2881     m_setRtpAddr = val;
2882     return true;
2883 }
2884 
2885 // Initialize a socket
initSocket(SocketAddr & lAddr,Mutex * mutex,int backLogBuffer,bool forceBind,String & reason)2886 Socket* YateSIPListener::initSocket(SocketAddr& lAddr, Mutex* mutex,
2887     int backLogBuffer, bool forceBind, String& reason)
2888 {
2889     reason = "";
2890     Lock lck(mutex);
2891     String addr = m_cfgAddr;
2892     int port = m_port;
2893     bool ipv6 = m_ipv6;
2894     bool ipv6Support = m_ipv6Support;
2895     lck.drop();
2896     bool udp = (m_proto == ProtocolHolder::Udp);
2897     const char* type = ProtocolHolder::lookupProtoName(m_proto);
2898     Debug(&plugin,DebugAll,
2899 	"Listener(%s,'%s') initializing socket addr='%s' port=%d",
2900 	type,lName(),addr.c_str(),port);
2901     Socket* sock = 0;
2902     // Use a while() to break to the end
2903     while (true) {
2904 	if (!ipv6)
2905 	    lAddr.assign(SocketAddr::IPv4);
2906 	else {
2907 	    if (!ipv6Support) {
2908 		reason << "IPv6 support not enabled";
2909 		break;
2910 	    }
2911 	    if (!lAddr.assign(SocketAddr::IPv6)) {
2912 		reason << "IPv6 not available";
2913 		break;
2914 	    }
2915 	}
2916 	if (addr && !lAddr.host(addr)) {
2917 	    reason << "Invalid address";
2918 	    break;
2919 	}
2920 	lAddr.port(port);
2921 	if (udp)
2922 	    sock = new Socket(lAddr.family(),SOCK_DGRAM,IPPROTO_UDP);
2923 	else
2924 	    sock = new Socket(lAddr.family(),SOCK_STREAM);
2925 	if (!sock->valid()) {
2926 	    reason = "Create socket failed";
2927 	    break;
2928 	}
2929 	if (ipv6 && !sock->setIpv6OnlyOption(true)) {
2930 	    reason << "Failed to set option IPv6 only";
2931 	    break;
2932 	}
2933 	if (!udp)
2934 	    sock->setReuse();
2935 #ifdef SO_RCVBUF
2936 	// Set UDP buffer size
2937 	if (udp && backLogBuffer > 0) {
2938 	    int buflen = backLogBuffer;
2939 	    if (buflen < 4096)
2940 		buflen = 4096;
2941 	    if (sock->setOption(SOL_SOCKET,SO_RCVBUF,&buflen,sizeof(buflen))) {
2942 		buflen = 0;
2943 		socklen_t sz = sizeof(buflen);
2944 		if (sock->getOption(SOL_SOCKET,SO_RCVBUF,&buflen,&sz))
2945 		    Debug(&plugin,DebugNote,"Listener(%s,'%s') buffer size is %d (requested %d)",
2946 			type,lName(),buflen,backLogBuffer);
2947 		else
2948 		    Debug(&plugin,DebugWarn,
2949 			"Listener(%s,'%s') could not get UDP buffer size (requested %d)",
2950 			type,lName(),backLogBuffer);
2951 	    }
2952 	    else
2953 		Debug(&plugin,DebugWarn,"Listener(%s,'%s') could not set buffer size %d",
2954 		    type,lName(),buflen);
2955 	}
2956 #endif
2957 	// Bind the socket
2958 	bool ok = sock->bind(lAddr);
2959 	if (!ok && forceBind) {
2960 	    String error;
2961 	    Thread::errorString(error,sock->error());
2962 	    Debug(&plugin,DebugWarn,
2963 		"Listener(%s,'%s') unable to bind on %s - trying a random port. %d '%s'",
2964 		type,lName(),lAddr.addr().c_str(),sock->error(),error.c_str());
2965 	    lAddr.port(0);
2966 	    ok = sock->bind(lAddr);
2967 	    if (ok && !sock->getSockName(lAddr)) {
2968 		reason = "Failed to retrieve bind address";
2969 		break;
2970 	    }
2971 	}
2972 	if (!ok) {
2973 	    reason = "Bind failed";
2974 	    break;
2975 	}
2976 	if (!sock->setBlocking(false)) {
2977 	    reason = "Set non blocking mode failed";
2978 	    break;
2979 	}
2980 	if (!udp && !sock->listen(backLogBuffer)) {
2981 	    reason = "Listen failed";
2982 	    break;
2983 	}
2984 	break;
2985     }
2986     if (!reason) {
2987 	Debug(&plugin,DebugInfo,"Listener(%s,'%s') started on '%s' (%s)",
2988 	    type,lName(),lAddr.addr().c_str(),lAddr.familyName());
2989 	m_nextBind = 0;
2990 	m_bindInterval = 0;
2991 	return sock;
2992     }
2993     String s;
2994     if (sock) {
2995 	String tmp;
2996 	Thread::errorString(tmp,sock->error());
2997 	s << " (" << sock->error() << " '" << tmp << "')";
2998     }
2999     Alarm(&plugin,"socket",DebugWarn,
3000 	"Listener(%s,'%s') failed to start on addr='%s' port=%d ipv6=%s: %s%s",
3001 	type,lName(),addr.safe(),port,String::boolText(ipv6),
3002 	reason.c_str(),s.safe());
3003     if (!m_bindInterval)
3004 	m_bindInterval = s_bindRetryMs;
3005     else if (m_bindInterval < BIND_RETRY_MAX)
3006 	m_bindInterval *= 2;
3007     m_nextBind = Time::now() + m_bindInterval * 1000;
3008     YateSIPTransport::resetSocket(sock,0);
3009     return 0;
3010 }
3011 
3012 
YateSIPTransport(int proto,const String & id,Socket * sock,int stat)3013 YateSIPTransport::YateSIPTransport(int proto, const String& id, Socket* sock, int stat)
3014     : Mutex(true,"YateSIPTransport"),
3015     ProtocolHolder(proto),
3016     m_id(id), m_status(stat), m_statusChgTime(Time::secNow()),
3017     m_sock(sock), m_maxpkt(1500),
3018     m_worker(0), m_initialized(false),
3019     m_ignoreVia(s_ignoreVia)
3020 {
3021 }
3022 
3023 // Initialize transport
init(const NamedList & params,const NamedList & defs,bool first,Thread::Priority prio)3024 bool YateSIPTransport::init(const NamedList& params, const NamedList& defs,
3025     bool first, Thread::Priority prio)
3026 {
3027     static String s_maxPkt = "maxpkt";
3028     lock();
3029     m_initialized = true;
3030     m_ignoreVia = s_ignoreVia;
3031     if (udpTransport()) {
3032 	int v = params.getIntValue(s_maxPkt,defs.getIntValue(s_maxPkt,m_maxpkt));
3033 	m_maxpkt = getMaxpkt(v,1500);
3034 	m_ignoreVia = params.getBoolValue(YSTRING("ignorevia"),m_ignoreVia);
3035     }
3036     else {
3037 	m_rtpLocalAddr = params.getValue(YSTRING("rtp_localip"));
3038 	m_maxpkt = getMaxpkt(params.getIntValue(YSTRING("tcp_maxpkt"),m_maxpkt),m_maxpkt);
3039 	// Set rtp ip for tcp outgoing
3040 	if (!m_rtpLocalAddr && tcpTransport() && tcpTransport()->outgoing()) {
3041 	    Lock lck(s_globalMutex);
3042 	    m_rtpLocalAddr = s_tcpOutRtpip;
3043 	}
3044     }
3045     m_rtpNatAddr = params.getValue(YSTRING("nat_address"));
3046     m_role = params[YSTRING("role")];
3047     unlock();
3048     // Done if not first
3049     if (!first)
3050 	return true;
3051     if (m_sock) {
3052 	m_sock->getSockName(m_local);
3053 	m_sock->getPeerName(m_remote);
3054     }
3055     return true;
3056 }
3057 
printSendMsg(const SIPMessage * msg,const SocketAddr * addr)3058 void YateSIPTransport::printSendMsg(const SIPMessage* msg, const SocketAddr* addr)
3059 {
3060     if (!msg)
3061 	return;
3062     if (!plugin.debugAt(DebugInfo))
3063 	return;
3064     if (!plugin.filterDebug(addr ? addr->addr() : m_remote.addr()))
3065 	return;
3066     String tmp;
3067     getMsgLine(tmp,msg);
3068     String raddr;
3069     if (addr)
3070 	raddr = " to " + addr->addr();
3071     String buf((char*)msg->getBuffer().data(),msg->getBuffer().length());
3072     TraceDebug(msg->traceId(),&plugin,DebugInfo,"'%s' sending %s %p%s [%p]\r\n------\r\n%s------",
3073 	m_protoAddr.c_str(),tmp.c_str(),msg,raddr.safe(),this,buf.c_str());
3074 }
3075 
3076 // Print received messages to output
printRecvMsg(const char * buf,int len,const String & traceId)3077 void YateSIPTransport::printRecvMsg(const char* buf, int len,const String& traceId)
3078 {
3079     if (!buf)
3080 	return;
3081     if (!plugin.debugAt(DebugInfo))
3082 	return;
3083     if (!plugin.filterDebug(m_remote.addr()))
3084 	return;
3085     String tmp;
3086     String raddr;
3087     if (udpTransport())
3088 	raddr = " from " + m_remote.addr();
3089     else {
3090 	tmp.assign(buf,len);
3091 	buf = tmp;
3092     }
3093     TraceDebug(traceId,&plugin,DebugInfo,
3094 	"'%s' received %d bytes SIP message%s [%p]\r\n------\r\n%s------",
3095 	m_protoAddr.c_str(),len,raddr.safe(),this,buf);
3096 }
3097 
3098 // Add transport data yate message
fillMessage(Message & msg,bool addRoute)3099 void YateSIPTransport::fillMessage(Message& msg, bool addRoute)
3100 {
3101     msg.setParam("connection_id",toString());
3102     msg.setParam("connection_reliable",String::boolText(0 != tcpTransport()));
3103     if (m_role) {
3104 	Lock lck(this);
3105 	msg.setParam("role",m_role);
3106     }
3107     if (addRoute) {
3108 	msg.setParam("route_params","oconnection_id");
3109 	msg.setParam("oconnection_id",toString());
3110     }
3111 }
3112 
3113 // Stop the worker. Remove from global list
terminate(const char * reason)3114 void YateSIPTransport::terminate(const char* reason)
3115 {
3116     XDebug(&plugin,DebugInfo,"YateSIPTransport::terminate(%s) [%p]",reason,this);
3117     changeStatus(Terminating);
3118     if (m_worker) {
3119 	bool wait = false;
3120 	lock();
3121 	if (m_worker) {
3122 	    if (Thread::current() != m_worker)
3123 		wait = true;
3124 	    else
3125 		m_worker->m_transport = 0;
3126 	    m_worker->cancel();
3127 	}
3128 	unlock();
3129 	if (wait) {
3130 	    unsigned int n = 500;
3131 	    while (m_worker && n--)
3132 		Thread::idle();
3133 	    if (m_worker)
3134 		Debug(&plugin,DebugFail,"Transport(%s) terminating with worker running [%p]",
3135 		    m_id.c_str(),this);
3136 	}
3137     }
3138     if (!TelEngine::null(reason)) {
3139 	Lock lock(this);
3140 	if (!m_reason)
3141 	    m_reason = reason;
3142     }
3143     changeStatus(Terminated);
3144 }
3145 
toString() const3146 const String& YateSIPTransport::toString() const
3147 {
3148     return m_id;
3149 }
3150 
3151 // Reset and delete a socket
resetSocket(Socket * & sock,int linger)3152 void YateSIPTransport::resetSocket(Socket*& sock, int linger)
3153 {
3154     if (!sock)
3155 	return;
3156     sock->setLinger(linger);
3157     delete sock;
3158     sock = 0;
3159 }
3160 
destroyed()3161 void YateSIPTransport::destroyed()
3162 {
3163     terminate("Destroyed");
3164     resetSocket(m_sock,-1);
3165     Debug(&plugin,DebugAll,"Transport(%s) destroyed [%p]",m_id.c_str(),this);
3166     RefObject::destroyed();
3167 }
3168 
3169 // Start the worker thread
startWorker(Thread::Priority prio)3170 bool YateSIPTransport::startWorker(Thread::Priority prio)
3171 {
3172     Lock lck(this);
3173     if (m_worker)
3174 	return true;
3175     m_worker = new YateSIPTransportWorker(this,prio);
3176     if (m_worker->startup())
3177 	return true;
3178     Debug(&plugin,DebugWarn,"Transport(%s) failed to start worker thread [%p]",m_id.c_str(),this);
3179     m_reason = "Failed to start worker";
3180     m_worker = 0;
3181     return false;
3182 }
3183 
3184 // Change transport status. Notify it
changeStatus(int stat)3185 void YateSIPTransport::changeStatus(int stat)
3186 {
3187     Lock lock(this);
3188     if (stat == m_status || m_status == Terminated)
3189 	return;
3190     unsigned int t = Time::secNow();
3191     DDebug(&plugin,DebugAll,"Transport(%s) changed status old=%s new=%s statustime=%u [%p]",
3192 	m_id.c_str(),statusName(m_status),statusName(stat),t - m_statusChgTime,this);
3193     m_statusChgTime = t;
3194     m_status = stat;
3195     String reason;
3196     if (m_status == Terminated) {
3197 	reason = m_reason;
3198 	m_reason.clear();
3199     }
3200     lock.drop();
3201     statusChanged();
3202     if (plugin.ep())
3203 	plugin.ep()->transportChangedStatus(this,m_status,reason);
3204 }
3205 
3206 // Handle received messages, set party, add to engine
receiveMsg(SIPMessage * & msg)3207 void YateSIPTransport::receiveMsg(SIPMessage*& msg)
3208 {
3209     if (!msg)
3210 	return;
3211     YateSIPEngine* engine = plugin.ep() ? plugin.ep()->engine() : 0;
3212     if (!engine) {
3213 	TelEngine::destruct(msg);
3214 	return;
3215     }
3216     if (!msg->isAnswer() || engine->autoChangeParty()) {
3217 	SIPParty* party = 0;
3218 	YateSIPUDPTransport* udp = udpTransport();
3219 	YateSIPTCPTransport* tcp = tcpTransport();
3220 	if (udp) {
3221 	    URI uri(msg->uri);
3222 	    YateSIPLine* line = plugin.findLine(m_remote.host(),m_remote.port(),uri.getUser());
3223 	    const char* host = 0;
3224 	    int port = -1;
3225 	    if (line && line->getLocalPort()) {
3226 		host = line->getLocalAddr();
3227 		port = line->getLocalPort();
3228 	    }
3229 	    if (!host)
3230 		host = m_local.host();
3231 	    if (port <= 0)
3232 		port = m_local.port();
3233 	    party = new YateUDPParty(udp,m_remote,&port,host);
3234 	}
3235 	else if (tcp) {
3236 	    party = tcp->getParty();
3237 	    if (!party) {
3238 		party = new YateTCPParty(tcp);
3239 		DDebug(&plugin,DebugAll,
3240 		    "Transport(%s) built tcp party (%p) for received message (%p) [%p]",
3241 		    m_id.c_str(),party,msg,this);
3242 	    }
3243 	}
3244 	if (party) {
3245 	    msg->setParty(party);
3246 	    TelEngine::destruct(party);
3247 	}
3248     }
3249     engine->addMessage(msg);
3250     TelEngine::destruct(msg);
3251 }
3252 
3253 // Print socket read error to output
printReadError()3254 void YateSIPTransport::printReadError()
3255 {
3256     if (m_sock->canRetry())
3257 	return;
3258     m_reason = "Socket read error:";
3259     addSockError(m_reason,*m_sock);
3260     Debug(&plugin,DebugWarn,"Transport(%s) %s [%p]",m_id.c_str(),m_reason.c_str(),this);
3261 }
3262 
3263 // Print socket write error to output
printWriteError(int res,unsigned int len,bool alarm)3264 void YateSIPTransport::printWriteError(int res, unsigned int len, bool alarm)
3265 {
3266     if (res == (int)len) {
3267 	XDebug(&plugin,DebugAll,"Transport(%s) sent %u bytes [%p]",
3268 	    m_id.c_str(),len,this);
3269 	return;
3270     }
3271     if (res >= 0) {
3272 	Debug(&plugin,DebugAll,"Transport(%s) sent %d/%u [%p]",m_id.c_str(),res,len,this);
3273 	return;
3274     }
3275     if (m_sock->canRetry())
3276         return;
3277     m_reason = "Socket send error:";
3278     addSockError(m_reason,*m_sock);
3279     if (alarm)
3280 	Alarm(&plugin,"socket",DebugWarn,"Transport(%s) %s [%p]",m_id.c_str(),m_reason.c_str(),this);
3281     else
3282 	Debug(&plugin,DebugWarn,"Transport(%s) %s [%p]",m_id.c_str(),m_reason.c_str(),this);
3283 }
3284 
3285 // Set m_protoAddr from local/remote ip/port or reset it
setProtoAddr(bool set)3286 void YateSIPTransport::setProtoAddr(bool set)
3287 {
3288     Lock lck(this);
3289     if (!set) {
3290 	m_protoAddr = "";
3291 	return;
3292     }
3293     m_protoAddr << protoName(false) << ":" << m_local.addr();
3294     if (!udpTransport())
3295 	m_protoAddr << "-" << m_remote.addr();
3296 }
3297 
3298 
YateSIPUDPTransport(const String & id)3299 YateSIPUDPTransport::YateSIPUDPTransport(const String& id)
3300     : YateSIPTransport(Udp,id,0,Idle), YateSIPListener(id,Udp),
3301     m_default(false), m_forceBind(true), m_errored(false), m_bufferReq(0)
3302 {
3303     Debug(&plugin,DebugAll,"Transport(%s) created [%p]",m_id.c_str(),this);
3304 }
3305 
3306 // (Re)Initialize the transport
init(const NamedList & params,const NamedList & defs,bool first,Thread::Priority prio)3307 bool YateSIPUDPTransport::init(const NamedList& params, const NamedList& defs, bool first,
3308     Thread::Priority prio)
3309 {
3310     updateRtpAddr(params,m_rtpLocalAddr,this);
3311     m_default = params.getBoolValue("default",toString() == YSTRING("general"));
3312     m_forceBind = params.getBoolValue("udp_force_bind",true);
3313     m_bufferReq = params.getIntValue("buffer",defs.getIntValue("buffer"));
3314     if (first) {
3315 	const String& addr = params["addr"];
3316 	setAddr(addr,params.getIntValue("port",5060),
3317 	    params.getBoolValue("ipv6",(addr.find(':') >= 0)));
3318 	m_ipv6Support = s_ipv6;
3319     }
3320     bool ok = YateSIPTransport::init(params,defs,first,prio);
3321     if (plugin.debugAt(DebugAll)) {
3322 	Lock lck(this);
3323 	String s;
3324 	SocketAddr::appendTo(s,m_address,m_port);
3325 	Debug(&plugin,DebugAll,
3326 	    "Listener(%s,'%s') initialized addr='%s' default=%s maxpkt=%u rtp_localip=%s nat_address=%s [%p]",
3327 	    protoName(),lName(),s.c_str(),String::boolText(m_default),m_maxpkt,
3328 	    m_rtpLocalAddr.c_str(),m_rtpNatAddr.c_str(),this);
3329     }
3330     if (ok && first)
3331 	ok = startWorker(prio);
3332     return ok;
3333 }
3334 
3335 // Send data
send(const void * data,unsigned int len,const SocketAddr & addr)3336 bool YateSIPUDPTransport::send(const void* data, unsigned int len, const SocketAddr& addr)
3337 {
3338     if (!m_sock)
3339 	return false;
3340     Lock lck(this);
3341     if (!m_sock)
3342 	return false;
3343     int sent = m_sock->sendTo(data,len,addr);
3344     bool err = (sent < 0);
3345     printWriteError(sent,len,err && !m_errored);
3346     if (m_errored && !err)
3347 	Alarm(&plugin,"socket",DebugNote,"Transport(%s) error cleared [%p]",m_id.c_str(),this);
3348     m_errored = err;
3349     return !err || m_sock->canRetry();
3350 }
3351 
3352 // Process data (read/send).
3353 // Return 0 to continue processing, positive to sleep (usec),
3354 //  negative to terminate and destroy
process()3355 int YateSIPUDPTransport::process()
3356 {
3357     bool force = bindNow(this);
3358     if (force || !m_sock) {
3359 	if (m_sock) {
3360 	    changeStatus(Idle);
3361 	    Lock lck(this);
3362 	    YateSIPTransport::resetSocket(m_sock,-1);
3363 	    m_local.clear();
3364 	    m_bindRtpLocalAddr.clear();
3365 	    setProtoAddr(false);
3366 	}
3367 	if (!force && m_nextBind > Time::now())
3368 	    return Thread::idleUsec();
3369 	String reason;
3370 	SocketAddr addr;
3371 	Socket* sock = initSocket(addr,this,m_bufferReq,m_forceBind,reason);
3372 	if (!sock) {
3373 	    changeStatus(Idle);
3374 	    Lock lck(this);
3375 	    m_reason = reason;
3376 	    return Thread::idleUsec();
3377 	}
3378 	lock();
3379 	m_sock = sock;
3380 	m_local = addr;
3381 	m_reason.clear();
3382 	unlock();
3383 	setProtoAddr(true);
3384 	changeStatus(Connected);
3385     }
3386     else if (m_ipv6 && !m_ipv6Support) {
3387 	Lock lck(this);
3388 	if (m_ipv6 && !m_ipv6Support) {
3389 	    // Force re-bind
3390 	    Debug(&plugin,DebugInfo,
3391 		"Listener(%s,'%s') IPv6 support changed. Forcing re-bind [%p]",
3392 		protoName(),lName(),this);
3393 	    m_bind = true;
3394 	    return Thread::idleUsec();
3395 	}
3396     }
3397     // Set RTP addr from bind address
3398     if (m_setRtpAddr) {
3399 	Lock lck(this);
3400 	if (m_setRtpAddr) {
3401 	    m_rtpLocalAddr.clear();
3402 	    if (!m_local.isNullAddr()) {
3403 		addIfaceAddr(m_rtpLocalAddr,m_local.host(),m_cfgAddr);
3404 		if (m_rtpLocalAddr)
3405 		    Debug(&plugin,DebugAll,"Listener(%s,'%s') set rtp_localip='%s' [%p]",
3406 			protoName(),lName(),m_rtpLocalAddr.c_str(),this);
3407 	    }
3408 	    m_bindRtpLocalAddr = m_rtpLocalAddr;
3409 	    m_setRtpAddr = false;
3410 	}
3411     }
3412     int& evc = YateSIPEndPoint::s_evCount;
3413     // Do nothing if the endpoint is flooded with events or terminating
3414     if (!(YateSIPEndPoint::canRead() || ((evc & 3) == 0)))
3415 	return Thread::idleUsec();
3416     int retVal = 0;
3417     // Check if we can read (select is available)
3418     // Wait up to the platform idle time if we had no events in last run
3419     if (m_sock->canSelect()) {
3420 	bool ok = false;
3421 	if (m_sock->select(&ok,0,0,Thread::idleUsec())) {
3422 	    if (!ok)
3423 		return 0;
3424 	}
3425 	else {
3426 	    // Select failed
3427 	    if (m_sock->canRetry())
3428 		return Thread::idleUsec();
3429 	    String tmp;
3430 	    Thread::errorString(tmp,m_sock->error());
3431 	    Debug(&plugin,DebugWarn,"Transport(%s) select failed: %d '%s' [%p]",
3432 		m_id.c_str(),m_sock->error(),tmp.c_str(),this);
3433 	    return Thread::idleUsec();
3434 	}
3435     }
3436     else
3437 	retVal = Thread::idleUsec();
3438     // We can read the data
3439     m_buffer.resize(m_maxpkt + 1);
3440     int res = m_sock->recvFrom((void*)m_buffer.data(),m_buffer.length() - 1,m_remote);
3441     if (res <= 0) {
3442 	printReadError();
3443 	return retVal;
3444     }
3445     if (res < 72) {
3446 	DDebug(&plugin,DebugInfo,
3447 	    "Transport(%s) received short SIP message of %d bytes from %s [%p]",
3448 	    m_id.c_str(),res,m_remote.addr().c_str(),this);
3449 	return 0;
3450     }
3451     if (res == (int)m_maxpkt && s_warnPacketUDP) {
3452 	s_warnPacketUDP = false;
3453 	Alarm(&plugin,"config",DebugConf,
3454 	    "Transport(%s) received likely truncated packet with length %d, try to increase maxpkt [%p]",
3455 	    m_id.c_str(),res,this);
3456     }
3457     char* b = (char*)m_buffer.data();
3458     b[res] = 0;
3459     bool print = true;
3460     if (s_printMsg && !plugin.traceActive()) {
3461 	print = false;
3462 	printRecvMsg(b,res);
3463     }
3464 
3465     if (s_floodProtection && s_floodEvents && evc >= s_floodEvents) {
3466 	if (!s_printFloodTime)
3467 	    Alarm(&plugin,"performance",DebugWarn,
3468 		"Flood detected, dropping INVITE/REGISTER/SUBSCRIBE/OPTIONS, allowing reINVITES");
3469 	s_printFloodTime = Time::now() + 10000000;
3470 	if (!msgIsAllowed(b,res)) {
3471 	    if (s_printMsg && print)
3472 		printRecvMsg(b,res);
3473 	    return 0;
3474 	}
3475     }
3476     else if (s_printFloodTime && s_printFloodTime < Time::now()) {
3477 	s_printFloodTime = 0;
3478 	Alarm(&plugin,"performance",DebugNote,"Flood drop cleared, resumed normal message processing");
3479     }
3480 
3481     SIPMessage* msg = SIPMessage::fromParsing(0,b,res);
3482     if (msg) {
3483 	msg->msgPrint = print;
3484 	receiveMsg(msg);
3485     }
3486     return 0;
3487 }
3488 
3489 
3490 // Outgoing
YateSIPTCPTransport(bool tls,const String & laddr,const String & raddr,int rport)3491 YateSIPTCPTransport::YateSIPTCPTransport(bool tls, const String& laddr, const String& raddr,
3492     int rport)
3493     : YateSIPTransport(tls ? Tls : Tcp,String::empty(),0,Idle),
3494     m_outgoing(true), m_party(0), m_sent(-1),
3495     m_firstKeepalive(0), m_firstKeepaliveSent(false),
3496     m_idleInterval(TCP_IDLE_DEF), m_idleTimeout(0),
3497     m_flowTimer(false), m_keepAlivePending(false),
3498     m_msg(0), m_sipBufOffs(0), m_contentLen(0),
3499     m_remoteAddr(raddr), m_remotePort(rport), m_localAddr(laddr),
3500     m_connectRetry(s_tcpConnectRetry), m_nextConnect(0)
3501 {
3502     m_maxpkt = s_tcpMaxpkt;
3503     if (m_remotePort <= 0)
3504 	m_remotePort = sipPort(protocol() != Tls);
3505     m_id << (tls ? "tls:" : "tcp:") << getTransIndex() << "-";
3506     SocketAddr::appendTo(m_id,raddr,m_remotePort);
3507     Debug(&plugin,DebugAll,"Transport(%s) created [%p]",m_id.c_str(),this);
3508     if (plugin.ep())
3509 	plugin.ep()->addTcpTransport(this);
3510 }
3511 
3512 // Incoming
YateSIPTCPTransport(Socket * sock,bool tls)3513 YateSIPTCPTransport::YateSIPTCPTransport(Socket* sock, bool tls)
3514     : YateSIPTransport(tls ? Tls : Tcp,String::empty(),sock,sock ? Connected : Idle),
3515     m_outgoing(false), m_party(0), m_sent(-1),
3516     m_firstKeepalive(0), m_firstKeepaliveSent(false),
3517     m_idleInterval(TCP_IDLE_DEF), m_idleTimeout(0),
3518     m_flowTimer(false), m_keepAlivePending(false),
3519     m_msg(0), m_sipBufOffs(0), m_contentLen(0),
3520     m_remotePort(0), m_connectRetry(0), m_nextConnect(0)
3521 {
3522     m_maxpkt = s_tcpMaxpkt;
3523     m_id << (tls ? "tls:" : "tcp:");
3524     if (m_sock) {
3525     	m_sock->getSockName(m_local);
3526 	m_sock->getPeerName(m_remote);
3527 	m_id << m_local.addr() << "-" << m_remote.addr();
3528 	setProtoAddr(true);
3529     }
3530     else
3531 	m_id << getTransIndex();
3532     Debug(&plugin,DebugAll,"Transport(%s) created [%p]",m_id.c_str(),this);
3533     if (plugin.ep())
3534 	plugin.ep()->addTcpTransport(this);
3535 }
3536 
getParty()3537 YateTCPParty* YateSIPTCPTransport::getParty()
3538 {
3539     Lock lock(this);
3540     return (m_party && m_party->ref()) ? m_party : 0;
3541 }
3542 
3543 // (Re)Initialize the transport
init(const NamedList & params,bool first,Thread::Priority prio)3544 bool YateSIPTCPTransport::init(const NamedList& params, bool first, Thread::Priority prio)
3545 {
3546     bool ok = YateSIPTransport::init(params,NamedList::empty(),first,prio);
3547     String extra;
3548     if (outgoing()) {
3549 	m_idleInterval = params.getIntValue(YSTRING("tcp_keepalive"),s_tcpKeepalive,0);
3550 	m_firstKeepalive = params.getIntValue(YSTRING("tcp_keepalive_first"),
3551 	    s_tcpKeepaliveFirst,0);
3552 	if (m_firstKeepalive && m_idleInterval && m_firstKeepalive >= m_idleInterval)
3553 	    m_firstKeepalive = 0;
3554 	extra << " (first=" << m_firstKeepalive << ")";
3555     }
3556     else
3557 	m_idleInterval = tcpIdleInterval(params.getIntValue(YSTRING("tcp_idle"),s_tcpIdle));
3558     setIdleTimeout();
3559     Debug(&plugin,DebugAll,
3560 	"Transport(%s) initialized maxpkt=%u rtp_localip=%s nat_address=%s tcp_%s=%usec%s [%p]",
3561 	m_id.c_str(),m_maxpkt,m_rtpLocalAddr.c_str(),m_rtpNatAddr.c_str(),
3562 	(outgoing() ? "keepalive" : "idle"),m_idleInterval,extra.safe(),this);
3563     if (ok && first)
3564 	ok = startWorker(prio);
3565     return ok;
3566 }
3567 
3568 // Set flow timer flag and idle interval (in seconds)
3569 // Reset idle timeout
setFlowTimer(bool on,unsigned int interval)3570 void YateSIPTCPTransport::setFlowTimer(bool on, unsigned int interval)
3571 {
3572     Lock lock(this);
3573     m_flowTimer = on;
3574     if (m_flowTimer || m_outgoing || (!m_outgoing && m_idleInterval < interval))
3575 	m_idleInterval = interval;
3576     Debug(&plugin,DebugInfo,"Transport(%s) flow timer is '%s' idle interval is %u seconds [%p]",
3577 	m_id.c_str(),String::boolText(m_flowTimer),m_idleInterval,this);
3578     setIdleTimeout();
3579 }
3580 
3581 // Send data
send(SIPEvent * event)3582 bool YateSIPTCPTransport::send(SIPEvent* event)
3583 {
3584     SIPMessage* msg = event->getMessage();
3585     if (!msg)
3586 	return true;
3587     if (s_engineHalt)
3588 	return false;
3589     Lock lock(this);
3590     if (m_status == Terminated)
3591 	return false;
3592     if (m_queue.find(msg))
3593 	return true;
3594     if (!msg->ref())
3595 	return false;
3596     m_queue.append(msg);
3597 #ifdef XDEBUG
3598     String tmp;
3599     getMsgLine(tmp,msg);
3600     Debug(&plugin,DebugAll,"Transport(%s) enqueued (%p,%s) [%p]",
3601 	m_id.c_str(),msg,tmp.c_str(),this);
3602 #endif
3603     return true;
3604 }
3605 
3606 // Process data (read/send)
process()3607 int YateSIPTCPTransport::process()
3608 {
3609     if (s_engineHalt) {
3610 	// Stop processing
3611 	Lock lck(this);
3612 	// Last chance to send pending data
3613 	ObjList* first = m_queue.skipNull();
3614 	if (first && m_sock && m_sock->valid()) {
3615 	    DataBlock buf;
3616 	    for (ObjList* o = first; o && buf.length() < 4096; o = o->skipNext()) {
3617 		SIPMessage* msg = static_cast<SIPMessage*>(o->get());
3618 		if (s_printMsg && (o != first || m_sent < 0))
3619 		    printSendMsg(msg);
3620 		if (!msg->dontSend()) {
3621 		    if (o != first || m_sent <= 0)
3622 			buf += msg->getBuffer();
3623 		    else {
3624 			int remaining = msg->getBuffer().length() - m_sent;
3625 			if (remaining > 0)
3626 			    buf.assign(((char*)msg->getBuffer().data()) + m_sent,remaining);
3627 		    }
3628 		}
3629 	    }
3630 	    if (buf.length()) {
3631 		DDebug(&plugin,DebugAll,"Transport(%s) sending last %u bytes [%p]",
3632 		    m_id.c_str(),buf.length(),this);
3633 		m_sock->writeData(buf.data(),buf.length());
3634 	    }
3635 	}
3636 	m_queue.clear();
3637 	// Terminate now incoming with no reference
3638 	// Remember: the worker is referencing us
3639 	if (!m_outgoing && refcount() == 2)
3640 	    return -1;
3641 	return 2000;
3642     }
3643     if (!(m_sock && m_sock->valid())) {
3644 	if (!m_outgoing)
3645 	    return -1;
3646 	if (tls() && !s_sslClientAvailable) {
3647 	    Debug(&plugin,DebugNote,"Transport(%s) SSL not available locally [%p]",
3648 		toString().c_str(),this);
3649 	    return -1;
3650 	}
3651 	if (!m_connectRetry || s_engineStop)
3652 	    return -1;
3653 	if (m_nextConnect > Time::now())
3654 	    return Thread::idleUsec();
3655 	m_connectRetry--;
3656 	int conn = connect();
3657 	m_firstKeepaliveSent = false;
3658 	if (conn > 0)
3659 	    setIdleTimeout();
3660 	else if (conn < 0)
3661 	    m_connectRetry = 0;
3662 	if (conn > 0 || m_connectRetry) {
3663 	    m_nextConnect = Time::now() + s_tcpConnectInterval;
3664 	    return Thread::idleUsec();
3665 	}
3666 	return -1;
3667     }
3668     Time time;
3669     bool sent = false;
3670     // Send pending data/keepalive
3671     if (!sendPending(time,sent)) {
3672 	resetConnection();
3673 	return m_outgoing ? 0 : -1;
3674     }
3675     // Read data
3676     bool read = false;
3677     if (!readData(time,read)) {
3678 	resetConnection();
3679 	return m_outgoing ? 0 : -1;
3680     }
3681     // Outgoing received data: reset reconnect
3682     if (m_outgoing && read && m_nextConnect) {
3683 	DDebug(&plugin,DebugAll,"Transport(%s) resetting re-connect [%p]",
3684 	    m_id.c_str(),this);
3685 	m_connectRetry = s_tcpConnectRetry;
3686 	m_nextConnect = 0;
3687     }
3688     // Idle incoming with refcount=2 (the worker is referencing us): terminate
3689     if (!m_outgoing && m_idleTimeout < time) {
3690 	if (refcount() == 2) {
3691 	    m_reason = "Connection idle timeout";
3692 	    Debug(&plugin,DebugInfo,"Transport(%s) idle [%p]",m_id.c_str(),this);
3693 	    return -1;
3694 	}
3695 	setIdleTimeout(time);
3696     }
3697     return read ? 0 : Thread::idleUsec();
3698 }
3699 
destroyed()3700 void YateSIPTCPTransport::destroyed()
3701 {
3702     TelEngine::destruct(m_msg);
3703     YateSIPTransport::destroyed();
3704 }
3705 
3706 // Status changed notification for descendents
statusChanged()3707 void YateSIPTCPTransport::statusChanged()
3708 {
3709     Lock lock(this);
3710     if (m_status == Terminated) {
3711 	// Remove messages now: they keep a party who is keeping a reference to us
3712 	m_queue.clear();
3713 	m_sent = -1;
3714     }
3715 }
3716 
3717 // Reset transport's party
resetParty(YateTCPParty * party,bool set)3718 void YateSIPTCPTransport::resetParty(YateTCPParty* party, bool set)
3719 {
3720     if (!party)
3721 	return;
3722     Lock lock(this);
3723     if (!m_party) {
3724 	if (!set) {
3725 	    Debug(&plugin,DebugNote,
3726 		"Transport(%s) party (%p) trying to reset empty [%p]",
3727 		m_id.c_str(),party,this);
3728 	    return;
3729 	}
3730     }
3731     else if (set || m_party != party) {
3732 	int level = DebugNote;
3733 #ifdef DEBUG
3734 	if (set && m_party != party)
3735 	    level = DebugFail;
3736 #endif
3737 	Debug(&plugin,level,"Transport(%s) party (%p) trying to %sset (%p) [%p]",
3738 	    m_id.c_str(),party,set ? "" : "re",m_party,this);
3739 	return;
3740     }
3741     m_party = set ? party : 0;
3742     DDebug(&plugin,DebugAll,"Transport(%s) party changed to (%p) [%p]",
3743 	m_id.c_str(),m_party,this);
3744 }
3745 
3746 // Connect an outgoing transport. Terminate the socket before it
connect(u_int64_t connToutUs)3747 int YateSIPTCPTransport::connect(u_int64_t connToutUs)
3748 {
3749     resetConnection();
3750     Socket* sock = 0;
3751     int retVal = -1;
3752     m_reason.clear();
3753     // Use a while() to break to the end
3754     while (true) {
3755 	if (!m_remoteAddr) {
3756 	    m_reason = "Empty remote address";
3757 	    break;
3758 	}
3759 	// Allow connect retry
3760 	retVal = 0;
3761 	SocketAddr a(s_ipv6 ? SocketAddr::Unknown : SocketAddr::IPv4);
3762 	if (!a.host(m_remoteAddr)) {
3763 	    m_reason << "Failed to resolve '" << m_remoteAddr << "'";
3764 	    break;
3765 	}
3766 	a.port(m_remotePort);
3767 	sock = new Socket(a.family(),SOCK_STREAM);
3768 	if (!sock->valid()) {
3769 	    m_reason << "Failed to create socket";
3770 	    break;
3771 	}
3772 	// Bind to local ip
3773 	SocketAddr lip(s_ipv6 ? SocketAddr::Unknown : SocketAddr::IPv4);
3774 	if (m_localAddr) {
3775 	    if (!lip.host(m_localAddr)) {
3776 		m_reason << "Invalid local address '" << m_localAddr << "'";
3777 		// Don't allow connect retry
3778 		retVal = -1;
3779 		break;
3780 	    }
3781 	    if (!sock->bind(lip)) {
3782 		m_reason << "Failed to bind on '" << lip.host() << "' (" << m_localAddr << "). ";
3783 		addSockError(m_reason,*sock);
3784 		// Don't allow connect retry
3785 		retVal = -1;
3786 		break;
3787 	    }
3788 	}
3789 	// Use async connect
3790 	if (connToutUs && !(sock->canSelect() && sock->setBlocking(false))) {
3791 	    connToutUs = 0;
3792 	    if (sock->canSelect()) {
3793 		String tmp;
3794 		addSockError(tmp,*sock);
3795 		Debug(&plugin,DebugInfo,
3796 		    "Transport(%s) using sync connect (async set failed).%s [%p]",
3797 		    m_id.c_str(),tmp.c_str(),this);
3798 	    }
3799 	    else
3800 		Debug(&plugin,DebugInfo,
3801 		    "Transport(%s) using sync connect (select() not available) [%p]",
3802 		    m_id.c_str(),this);
3803 	}
3804 	u_int64_t start = connToutUs ? Time::now() : 0;
3805 	unsigned int intervals = 0;
3806 	if (start) {
3807 	    intervals = (unsigned int)(connToutUs / Thread::idleUsec());
3808 	    // Make sure we wait for at least 1 timeout interval
3809 	    if (!intervals)
3810 		intervals = 1;
3811 	}
3812 	if (plugin.debugAt(DebugAll)) {
3813 	    String s;
3814 	    s << "'" << a.addr() << "'";
3815 	    if (a.host() != m_remoteAddr)
3816 		s << " (" << m_remoteAddr << ")";
3817 	    if (m_localAddr)
3818 		s << " localip=" << lip.addr();
3819 	    Debug(&plugin,DebugAll,"Transport(%s) attempt to connect to %s [%p]",
3820 		m_id.c_str(),s.safe(),this);
3821 	}
3822 	bool ok = sock->connect(a);
3823 	bool timeout = false;
3824 	bool stop = false;
3825 	// Async connect in progress
3826 	if (!ok && sock->inProgress()) {
3827 	    bool done = false;
3828 	    bool event = false;
3829 	    while (intervals && !(done || event || stop)) {
3830 		if (!sock->select(0,&done,&event,Thread::idleUsec()))
3831 		    break;
3832 	        intervals--;
3833 		stop = Thread::check(false) || Engine::exiting();
3834 	    }
3835 	    timeout = !intervals && !(done || event);
3836 	    if (!stop && sock && !sock->error() && (done || event) && sock->updateError())
3837 		ok = !sock->error();
3838 	}
3839 	if (ok) {
3840 	    // TLS?
3841 	    if (tls() && !plugin.socketSsl(&sock,false)) {
3842 		m_reason = "SSL not available locally";
3843 		retVal = -1;
3844 		ok = false;
3845 	    }
3846 	    if (ok) {
3847 		if (!Thread::check(false))
3848 		    retVal = 1;
3849 		else {
3850 		    m_reason = "Cancelled";
3851 		    retVal = -1;
3852 		}
3853 	    }
3854 	}
3855 	else if (!stop) {
3856 	    m_reason << "Failed to connect to '" << a.addr() << "'";
3857 	    if (a.host() != m_remoteAddr)
3858 		m_reason << " (" << m_remoteAddr << ")";
3859 	    if (timeout)
3860 		m_reason << " . Connect timeout";
3861 	    else
3862 		addSockError(m_reason,*sock);
3863 	}
3864 	break;
3865     }
3866     if (retVal > 0)
3867 	resetConnection(sock);
3868     else {
3869 	int level = DebugWarn;
3870 	if (!m_reason) {
3871 	    if (Thread::check(false) || Engine::exiting()) {
3872 		level = DebugInfo;
3873 		m_reason = "Connect cancelled";
3874 	    }
3875 	    else
3876 		m_reason = "Connect failed";
3877 	}
3878 	Debug(&plugin,level,"Transport(%s) %s (remaining %u connect attempts) [%p]",
3879 	    m_id.c_str(),m_reason.c_str(),!retVal ? m_connectRetry : 0,this);
3880 	resetSocket(sock,0);
3881     }
3882     return retVal;
3883 }
3884 
3885 // Send pending messages, return false on failure
sendPending(const Time & time,bool & sent)3886 bool YateSIPTCPTransport::sendPending(const Time& time, bool& sent)
3887 {
3888     sent = false;
3889     if (!m_sock)
3890 	return false;
3891     int attempts = 3;
3892     while (attempts--) {
3893 	Lock lock(this);
3894 	ObjList* o = m_queue.skipNull();
3895 	SIPMessage* msg = o ? static_cast<SIPMessage*>(o->get()) : 0;
3896 	if (msg && m_sent < 0) {
3897 	    m_sent = 0;
3898 	    if (!sendPendingKeepAlive())
3899 		return false;
3900 	    XDebug(&plugin,DebugAll,"Transport(%s) dequeued (%p) [%p]",
3901 		m_id.c_str(),msg,this);
3902 	    if (s_printMsg)
3903 		printSendMsg(msg);
3904 	}
3905 	else if (!msg) {
3906 	    m_sent = -1;
3907 	    if (!sendPendingKeepAlive())
3908 		return false;
3909 	    break;
3910 	}
3911 	if (msg->dontSend())
3912 	    break;
3913 	const DataBlock& buf = msg->getBuffer();
3914 	sent = !msg->dontSend();
3915 	int len = buf.length();
3916 	if (sent && len > m_sent) {
3917 	    char* b = (char*)(buf.data());
3918 	    len -= m_sent;
3919 	    int wr = m_sock->writeData(b + m_sent,len);
3920 	    printWriteError(wr,len);
3921 	    if (wr > 0) {
3922 		m_sent += wr;
3923 		// Outgoing: reset keep alive timer
3924 		if (m_outgoing)
3925 		    setIdleTimeout(time);
3926 	    }
3927 	    else if (wr && !m_sock->canRetry())
3928 		return false;
3929 	}
3930 	if (m_sent >= (int)buf.length()) {
3931 #ifdef DEBUG
3932 	    String tmp;
3933 	    getMsgLine(tmp,msg);
3934 	    Debug(&plugin,DebugAll,"Transport(%s) sent (%p,%s) [%p]",
3935 		m_id.c_str(),msg,tmp.c_str(),this);
3936 #endif
3937 	    o->remove();
3938 	    m_sent = -1;
3939 	    continue;
3940 	}
3941 	break;
3942     }
3943     // Keep alive?
3944     if (m_outgoing && !sent && m_idleTimeout <= time) {
3945 	if (sendKeepAlive(true)) {
3946 	    sent = true;
3947 	    setIdleTimeout(time);
3948 	}
3949 	else
3950 	    return false;
3951     }
3952     return true;
3953 }
3954 
3955 // Read data
readData(const Time & time,bool & read)3956 bool YateSIPTCPTransport::readData(const Time& time, bool& read)
3957 {
3958     read = false;
3959     m_buffer.resize(m_maxpkt + 1);
3960     int res = m_sock->readData((void*)m_buffer.data(),m_buffer.length() - 1);
3961     if (res < 0) {
3962 	printReadError();
3963 	return m_sock->canRetry();
3964     }
3965     if (!res) {
3966 	m_reason = "Network down";
3967 	Debug(&plugin,DebugNote,"Transport(%s) %s [%p]",m_id.c_str(),m_reason.c_str(),this);
3968 	return false;
3969     }
3970     read = true;
3971 #ifdef XDEBUG
3972 #if 0
3973     String nb((const char*)m_buffer.data(),res);
3974     String ob((const char*)m_sipBuffer.data(),m_sipBuffer.length());
3975 #else
3976     String nb, ob;
3977     nb.hexify(m_buffer.data(),res,' ');
3978     ob.hexify(m_sipBuffer.data(),m_sipBuffer.length(),' ');
3979 #endif
3980     Debug(&plugin,DebugAll,"%s current buffer %u '%s' read %d '%s' [%p]",
3981 	m_id.c_str(),m_sipBuffer.length(),ob.safe(),res,nb.safe(),this);
3982 #endif
3983     const char* data = (const char*)m_buffer.data();
3984     unsigned int len = res;
3985     if (m_sipBuffer.length()) {
3986 	m_sipBuffer.append(m_buffer.data(),len);
3987 	len = m_sipBuffer.length();
3988 	data = (const char*)m_sipBuffer.data();
3989     }
3990     bool ok = true;
3991     unsigned int over = 0;
3992     bool respond = false;
3993     while (len > 3) {
3994 	ok = false;
3995 	if (!m_msg) {
3996 	    m_sipBufOffs = 0;
3997 	    m_contentLen = 0;
3998 	    // Skip spaces, check for keep alive
3999 	    if (m_outgoing || respond)
4000 		skipSpaces(data,len);
4001 	    else
4002 		respond = skipSpacesCheckKeepAlive(data,len);
4003 	    if (len < 72) {
4004 		ok = true;
4005 		break;
4006 	    }
4007 	    // Find an empty line
4008 	    m_sipBufOffs = getEmptyLine(data,len);
4009 	    if (m_sipBufOffs > len) {
4010 		m_sipBufOffs = 0;
4011 		if (len <= m_maxpkt)
4012 		    ok = true;
4013 		else
4014 		    over = len;
4015 		break;
4016 	    }
4017 	    if (m_sipBufOffs > m_maxpkt) {
4018 		over = m_sipBufOffs;
4019 		break;
4020 	    }
4021 	    // Parse the message headers
4022 	    m_msg = SIPMessage::fromParsing(0,data,m_sipBufOffs,&m_contentLen);
4023 	    if (!m_msg) {
4024 		m_reason = "Received invalid message";
4025 		String tmp(data,m_sipBufOffs);
4026 		Debug(&plugin,DebugNote,
4027 		    "'%s' got invalid message [%p]\r\n------\r\n%s\r\n------",
4028 		    m_id.c_str(),this,tmp.c_str());
4029 		break;
4030 	    }
4031 	    // Check now if expected message length exceeds maxpkt
4032 	    unsigned int expected = m_sipBufOffs + m_contentLen;
4033 	    if (expected > m_maxpkt) {
4034 		over = expected;
4035 		break;
4036 	    }
4037 	}
4038 	ok = true;
4039 	// Expecting message body ?
4040 	if (m_contentLen) {
4041 	    if (m_sipBufOffs + m_contentLen > len)
4042 		break;
4043 	    m_msg->buildBody(data + m_sipBufOffs,m_contentLen);
4044 	    m_sipBufOffs += m_contentLen;
4045 	    m_contentLen = 0;
4046 	}
4047 	bool print = true;
4048 	if (s_printMsg && !plugin.traceActive()) {
4049 	    print = false;
4050 	    printRecvMsg(data,m_sipBufOffs);
4051 	}
4052 	SIPMessage* msg = m_msg;
4053 	msg->msgPrint = print;
4054 	m_msg = 0;
4055 	receiveMsg(msg);
4056 	data += m_sipBufOffs;
4057 	len -= m_sipBufOffs;
4058 	m_sipBufOffs = 0;
4059     }
4060     if (!len)
4061 	m_sipBuffer.clear();
4062     else
4063 	m_sipBuffer.assign((void*)data,len);
4064     if (!ok) {
4065 	if (over) {
4066 	    m_reason = "Buffer overflow (message too long)";
4067 	    Debug(&plugin,DebugNote,"'%s' %s len=%u maxpkt=%u [%p]",
4068 		m_id.c_str(),m_reason.c_str(),over,m_maxpkt,this);
4069 	}
4070 	return false;
4071     }
4072     if (respond) {
4073 	// RFC5626: send CR/LF in response
4074 	Lock lck(this);
4075 	m_keepAlivePending = true;
4076     }
4077     // Got data: reset timeout for incoming and connection check for all
4078     if (!m_outgoing)
4079 	setIdleTimeout(time);
4080     return true;
4081 }
4082 
4083 // Reset socket and status
resetConnection(Socket * sock)4084 void YateSIPTCPTransport::resetConnection(Socket* sock)
4085 {
4086     Lock lck(this);
4087     DDebug(&plugin,DebugAll,"Transport(%s) resetting connection sock=%p [%p]",
4088 	m_id.c_str(),sock,this);
4089     // Reset send/recv data
4090     TelEngine::destruct(m_msg);
4091     m_sent = -1;
4092     m_sipBuffer.clear();
4093     m_sipBufOffs = 0;
4094     m_contentLen = 0;
4095     m_keepAlivePending = false;
4096     m_flowTimer = false;
4097     setProtoAddr(false);
4098     // Reset socket and addresses
4099     if (m_sock) {
4100 	resetSocket(m_sock,-1);
4101 	m_local.clear();
4102 	m_remote.clear();
4103     }
4104     m_sock = sock;
4105     if (m_sock) {
4106 	m_sock->getSockName(m_local);
4107 	m_sock->getPeerName(m_remote);
4108 	setProtoAddr(true);
4109 	Debug(&plugin,DebugAll,"Transport(%s) connected local=%s remote=%s [%p]",
4110 	    m_id.c_str(),m_local.addr().c_str(),m_remote.addr().c_str(),this);
4111     }
4112     // Update party local/remote ip/port
4113     if (m_party)
4114 	m_party->updateAddrs();
4115     lck.drop();
4116     changeStatus(m_sock ? Connected : Idle);
4117 }
4118 
setIdleTimeout(u_int64_t time)4119 void YateSIPTCPTransport::setIdleTimeout(u_int64_t time)
4120 {
4121     unsigned int i = m_idleInterval;
4122     if (outgoing() && !m_firstKeepaliveSent) {
4123 	m_firstKeepaliveSent = true;
4124 	if (m_firstKeepalive)
4125 	    i = m_firstKeepalive;
4126     }
4127     m_idleTimeout = time + (u_int64_t)i * 1000000;
4128     XDebug(&plugin,DebugAll,"Transport(%s) set idle timeout to %u (interval=%u) [%p]",
4129 	m_id.c_str(),(unsigned int)(m_idleTimeout / 1000000),i,this);
4130 }
4131 
sendKeepAlive(bool request)4132 bool YateSIPTCPTransport::sendKeepAlive(bool request)
4133 {
4134     XDebug(&plugin,DebugAll,"Transport(%s) sending keep alive%s [%p]",
4135 	m_id.c_str(),request ? "" : " response",this);
4136     unsigned int len = request ? 4 : 2;
4137     int wr = m_sock->writeData("\r\n\r\n",len);
4138     printWriteError(wr,len);
4139     return wr >= 0 || m_sock->canRetry();
4140 }
4141 
4142 
YateSIPTransportWorker(YateSIPTransport * trans,Thread::Priority prio)4143 YateSIPTransportWorker::YateSIPTransportWorker(YateSIPTransport* trans,
4144     Thread::Priority prio)
4145     : Thread("YSIP Worker",prio), m_transport(trans)
4146 {
4147     XDebug(&plugin,DebugAll,"YateSIPTransportWorker(%p,%s) [%p]",
4148 	trans,trans ? trans->toString().c_str() : "",this);
4149 }
4150 
~YateSIPTransportWorker()4151 YateSIPTransportWorker::~YateSIPTransportWorker()
4152 {
4153     cleanupTransport(true);
4154 }
4155 
run()4156 void YateSIPTransportWorker::run()
4157 {
4158     if (!m_transport)
4159 	return;
4160     DDebug(&plugin,DebugAll,"YateSIPTransportWorker (%p) '%s' started [%p]",
4161 	m_transport,m_transport->toString().c_str(),this);
4162     while (true) {
4163 	if (Thread::check(false))
4164 	    break;
4165 	// Keep the transport alive while calling its method
4166 	RefPointer<YateSIPTransport> trans = m_transport;
4167 	int n = trans ? trans->process() : -1;
4168 	trans = 0;
4169 	if (n > 0)
4170 	    Thread::usleep(n);
4171 	else if (n < 0)
4172 	    break;
4173     }
4174     DDebug(&plugin,DebugAll,"YateSIPTransportWorker terminated [%p]",this);
4175     cleanupTransport(false,!Thread::check(false));
4176 }
4177 
cleanupTransport(bool final,bool terminate)4178 void YateSIPTransportWorker::cleanupTransport(bool final, bool terminate)
4179 {
4180     // Reset now transport data: the thread might be cancelled from
4181     // YateSIPTransport::destroyed()
4182     if (m_transport) {
4183 	Lock lock(m_transport);
4184 	m_transport->m_worker = 0;
4185     }
4186     RefPointer<YateSIPTransport> trans = m_transport;
4187     m_transport = 0;
4188 #ifdef XDEBUG
4189     Debugger debug(DebugAll,"YateSIPTransportWorker::cleanupTransport()",
4190 	" final=%u terminate=%u transport=%p [%p]",
4191 	final,terminate,(YateSIPTransport*)trans,this);
4192 #endif
4193     if (!trans)
4194 	return;
4195     if (final)
4196 	Debug(DebugWarn,"YateSIPTransportWorker abnormally terminated! [%p]",this);
4197     YateSIPTCPTransport* tcp = trans->tcpTransport();
4198     if (tcp && tcp->outgoing())
4199 	tcp = 0;
4200     if (terminate)
4201 	trans->terminate();
4202     // Deref incoming TCP
4203     if (tcp)
4204 	tcp->deref();
4205     trans = 0;
4206 }
4207 
4208 
YateSIPTCPListener(int proto,const String & name,const NamedList & params)4209 YateSIPTCPListener::YateSIPTCPListener(int proto, const String& name, const NamedList& params)
4210     : Thread("YSIP Listener",Thread::priority(params.getValue("thread"))),
4211     ProtocolHolder(proto),
4212     YateSIPListener(name,proto),
4213     m_mutex(true,"YSIPListener"),
4214     m_sslContextChanged(true), m_sslContextCheck(true), m_transParamsChanged(true),
4215     m_socket(0), m_backlog(5), m_transParams(params), m_initialized(false)
4216 {
4217     init(params,true);
4218 }
4219 
~YateSIPTCPListener()4220 YateSIPTCPListener::~YateSIPTCPListener()
4221 {
4222     cleanup(true);
4223 }
4224 
4225 // Init data
init(const NamedList & params,bool first)4226 void YateSIPTCPListener::init(const NamedList& params, bool first)
4227 {
4228     m_initialized = true;
4229     const String& addr = params["addr"];
4230     int port = params.getIntValue("port");
4231     if (port <= 0)
4232 	port = sipPort(!tls());
4233     String sslContext;
4234     m_mutex.lock();
4235     if (tls()) {
4236 	sslContext = params.getValue("sslcontext");
4237 	m_sslContextChanged = first || m_sslContextChanged || (sslContext != m_sslContext);
4238 	m_sslContext = sslContext;
4239 	if (!m_sslContext)
4240 	    Alarm(&plugin,"config",DebugConf,"Listener(%s,'%s') ssl context is empty [%p]",
4241 		protoName(),lName(),this);
4242 	// Always set check flag on re-init
4243 	m_sslContextCheck = true;
4244     }
4245     m_backlog = params.getIntValue("backlog",5,0);
4246     setAddr(addr,port,params.getBoolValue("ipv6",(addr.find(':') >= 0)));
4247     if (first)
4248 	m_bind = true;
4249     updateIPv6Support();
4250     m_transParamsChanged = m_transParamsChanged || first;
4251     const String& role = params[YSTRING("role")];
4252     if (role != m_transParams[YSTRING("role")]) {
4253 	m_transParamsChanged = true;
4254 	m_transParams.setParam("role",role);
4255     }
4256     String rtp;
4257     bool setRtpAddrChg = updateRtpAddr(params,rtp);
4258     if (rtp != m_transParams["rtp_localip"]) {
4259 	m_transParamsChanged = true;
4260 	m_transParams.setParam("rtp_localip",rtp);
4261     }
4262     else if (setRtpAddrChg)
4263 	m_transParamsChanged = true;
4264     Debug(&plugin,DebugAll,
4265 	"Listener(%s,'%s') initialized addr='%s' port=%d sslcontext='%s' rtp_localip='%s' [%p]",
4266 	protoName(),lName(),addr.c_str(),port,sslContext.safe(),rtp.c_str(),this);
4267     m_mutex.unlock();
4268 }
4269 
run()4270 void YateSIPTCPListener::run()
4271 {
4272     DDebug(&plugin,DebugAll,"Listener(%s,'%s') start running [%p]",
4273 	protoName(),lName(),this);
4274     SocketAddr lAddr;
4275     NamedList transParams("");
4276     String sslContext;
4277     bool showWaitStart = true;
4278     bool sslAvailable = false;
4279     while (true) {
4280 	if (Thread::check(false))
4281 	    break;
4282 	bool setRtpAddr = false;
4283 	if (m_sslContextChanged || m_transParamsChanged) {
4284 	    Lock lock(m_mutex);
4285 	    if (m_sslContextChanged) {
4286 		if (sslContext != m_sslContext) {
4287 		    sslAvailable = false;
4288 		    sslContext = m_sslContext;
4289 		}
4290 		if (tls() && !sslContext)
4291 		    m_reason = "Empty SSL context";
4292 	    }
4293 	    if (m_transParamsChanged) {
4294 		transParams = m_transParams;
4295 		setRtpAddr = m_setRtpAddr;
4296 	    }
4297 	    m_sslContextChanged = false;
4298 	    m_transParamsChanged = false;
4299 	}
4300 	if (tls()) {
4301 	    if (!sslContext) {
4302 		stopListening();
4303 		Thread::msleep(3 * Thread::idleMsec());
4304 		continue;
4305 	    }
4306 	    if (m_sslContextCheck) {
4307 		if (!s_engineStart) {
4308 		    if (showWaitStart) {
4309 			Debug(&plugin,DebugAll,
4310 			    "Listener(%s,'%s') waiting for engine start to check SSL context [%p]",
4311 			    protoName(),lName(),this);
4312 			showWaitStart = false;
4313 		    }
4314 		    Thread::idle();
4315 		    continue;
4316 		}
4317 		sslAvailable = plugin.socketSsl(0,true,sslContext);
4318 		Lock lck(m_mutex);
4319 		m_sslContextCheck = false;
4320 		if (!sslAvailable)
4321 		    m_reason = "SSL context not available";
4322 		lck.drop();
4323 		if (!sslAvailable) {
4324 		    Alarm(&plugin,"config",DebugConf,
4325 			"Listener(%s,'%s') SSL context '%s' not available [%p]",
4326 			protoName(),lName(),sslContext.c_str(),this);
4327 		    stopListening();
4328 		}
4329 	    }
4330 	    if (!sslAvailable) {
4331 		Thread::msleep(3 * Thread::idleMsec());
4332 		continue;
4333 	    }
4334 	}
4335 	bool force = bindNow(&m_mutex);
4336 	if (force || !m_socket) {
4337 	    if (m_socket) {
4338 		stopListening("Address changed",DebugInfo);
4339 		Lock lck(m_mutex);
4340 		m_bindRtpLocalAddr.clear();
4341 	    }
4342 	    if (!force && m_nextBind > Time::now()) {
4343 		Thread::idle();
4344 		continue;
4345 	    }
4346 	    String reason;
4347 	    Socket* sock = initSocket(lAddr,&m_mutex,m_backlog,false,reason);
4348 	    Lock lck(m_mutex);
4349 	    m_socket = sock;
4350 	    m_reason = reason;
4351 	    if (!m_socket)
4352 		continue;
4353 	    m_local = lAddr;
4354 	    setRtpAddr = m_setRtpAddr;
4355 	}
4356 	else if (m_ipv6 && !m_ipv6Support) {
4357 	    // Check if we should drop and re-bind
4358 	    Lock lck(m_mutex);
4359 	    bool disable = m_ipv6 && !m_ipv6Support;
4360 	    lck.drop();
4361 	    if (disable) {
4362 		stopListening("IPv6 support changed",DebugInfo);
4363 		Thread::idle();
4364 		continue;
4365 	    }
4366 	}
4367 	if (setRtpAddr) {
4368 	    // Set RTP addr from bind address
4369 	    String rtp;
4370 	    String old = transParams["rtp_localip"];
4371 	    if (!lAddr.isNullAddr())
4372 		addIfaceAddr(rtp,lAddr.host(),m_cfgAddr);
4373 	    if (rtp)
4374 		transParams.setParam("rtp_localip",rtp);
4375 	    else
4376 		transParams.clearParam("rtp_localip");
4377 	    if (rtp != old)
4378 		Debug(&plugin,DebugAll,"Listener(%s,'%s') set rtp_localip='%s' [%p]",
4379 		    protoName(),lName(),rtp.c_str(),this);
4380 	    m_bindRtpLocalAddr = rtp;
4381 	}
4382 	SocketAddr addr;
4383 	Socket* sock = m_socket->accept(addr);
4384 	if (!sock) {
4385 	    Thread::idle();
4386 	    continue;
4387 	}
4388 	Debug(&plugin,DebugAll,"Listener(%s,'%s') '%s' got conn from '%s' [%p]",
4389 	    protoName(),lName(),lAddr.addr().c_str(),addr.addr().c_str(),this);
4390 	if (!sock->setBlocking(false)) {
4391 	    String tmp;
4392 	    Thread::errorString(tmp,sock->error());
4393 	    Debug(&plugin,DebugAll,
4394 		"Listener(%s,'%s') '%s' failed to set non-blocking mode for '%s'. %d '%s' [%p]",
4395 		protoName(),lName(),lAddr.addr().c_str(),addr.addr().c_str(),
4396 		sock->error(),tmp.c_str(),this);
4397 	    delete sock;
4398 	    Thread::idle();
4399 	    continue;
4400 	}
4401 	if (!tls() || plugin.socketSsl(&sock,true,sslContext)) {
4402 	    YateSIPTCPTransport* trans = new YateSIPTCPTransport(sock,tls());
4403 	    if (!trans->init(transParams,true))
4404 		TelEngine::destruct(trans);
4405 	}
4406 	else {
4407 	    Debug(&plugin,DebugWarn,"Listener(%s,'%s') failed to start SSL [%p]",
4408 		protoName(),lName(),this);
4409 	    delete sock;
4410 	}
4411     }
4412     cleanup(false);
4413 }
4414 
4415 // Close the socket. Remove from endpoint list
cleanup(bool final)4416 void YateSIPTCPListener::cleanup(bool final)
4417 {
4418     if (plugin.ep())
4419 	plugin.ep()->removeListener(this);
4420     if (final) {
4421 	if (!m_socket)
4422 	    DDebug(&plugin,DebugInfo,"Listener(%s,'%s') terminated [%p]",
4423 		protoName(),lName(),this);
4424 	else
4425 	    Alarm(&plugin,"system",DebugWarn,"Listener(%s,'%s') abnormally terminated [%p]",
4426 		protoName(),lName(),this);
4427     }
4428     m_mutex.lock();
4429     const char* reason = 0;
4430     if (!m_reason)
4431 	reason = "Terminated";
4432     m_mutex.unlock();
4433     stopListening(reason,DebugInfo);
4434 }
4435 
4436 // Reset socket
stopListening(const char * reason,int level)4437 void YateSIPTCPListener::stopListening(const char* reason, int level)
4438 {
4439     if (!m_socket)
4440 	return;
4441     Lock lck(m_mutex);
4442     m_local.clear();
4443     if (!m_socket)
4444 	return;
4445     if (!reason)
4446 	reason = m_reason;
4447     Debug(&plugin,level,"Listener(%s,'%s') stop listening reason='%s' [%p]",
4448 	protoName(),lName(),reason,this);
4449     YateSIPTransport::resetSocket(m_socket,0);
4450 }
4451 
4452 
YateUDPParty(YateSIPUDPTransport * trans,const SocketAddr & addr,int * localPort,const char * localAddr)4453 YateUDPParty::YateUDPParty(YateSIPUDPTransport* trans, const SocketAddr& addr,
4454     int* localPort, const char* localAddr)
4455     : m_transport(0), m_addr(addr)
4456 {
4457     if (plugin.ep())
4458 	m_mutex = plugin.ep()->m_partyMutexPool.mutex(this);
4459     if (trans && trans->ref())
4460 	m_transport = trans;
4461     if (!localPort) {
4462 	if (m_transport) {
4463 	    m_localPort = m_transport->local().port();
4464 	    m_local = m_transport->local().host();
4465 	}
4466     }
4467     else {
4468 	m_localPort = *localPort;
4469 	m_local = localAddr;
4470     }
4471     m_party = m_addr.host();
4472     m_partyPort = m_addr.port();
4473     if (SocketAddr::isNullAddr(m_local)) {
4474 	SocketAddr laddr(s_ipv6 ? SocketAddr::Unknown : SocketAddr::IPv4);
4475 	if (laddr.local(addr))
4476 	    m_local = laddr.host();
4477 	else
4478 	    m_local = "localhost";
4479 	if (!m_localPort)
4480 	    m_localPort = 5060;
4481     }
4482     DDebug(&plugin,DebugAll,"YateUDPParty local '%s' party '%s' transport=%p [%p]",
4483 	SocketAddr::appendTo(m_local,m_localPort).c_str(),m_addr.addr().c_str(),
4484 	m_transport,this);
4485 }
4486 
~YateUDPParty()4487 YateUDPParty::~YateUDPParty()
4488 {
4489     DDebug(&plugin,DebugAll,"YateUDPParty::~YateUDPParty() transport=%p [%p]",
4490 	m_transport,this);
4491     TelEngine::destruct(m_transport);
4492 }
4493 
transmit(SIPEvent * event)4494 bool YateUDPParty::transmit(SIPEvent* event)
4495 {
4496     const SIPMessage* msg = event->getMessage();
4497     if (!msg)
4498 	return false;
4499     if (m_transport) {
4500 	Lock lck(m_transport);
4501 	if (s_printMsg)
4502 	    m_transport->printSendMsg(msg,&m_addr);
4503 	if (msg->dontSend()) {
4504 	    if (event->getTransaction())
4505 		event->getTransaction()->setSilent();
4506 	    return true;
4507 	}
4508 	return m_transport->send(msg->getBuffer().data(),msg->getBuffer().length(),m_addr);
4509     }
4510     String tmp;
4511     getMsgLine(tmp,msg);
4512     Debug(&plugin,DebugWarn,"No transport to send %s to %s:%d",
4513 	tmp.c_str(),m_addr.host().c_str(),m_addr.port());
4514     return false;
4515 }
4516 
getProtoName() const4517 const char* YateUDPParty::getProtoName() const
4518 {
4519     return "UDP";
4520 }
4521 
setParty(const URI & uri)4522 bool YateUDPParty::setParty(const URI& uri)
4523 {
4524     Lock lock(m_mutex);
4525     if (m_partyPort && m_party) {
4526 	if (m_transport) {
4527 	    if (m_transport->ignoreVia())
4528 		return true;
4529 	}
4530 	else if (s_ignoreVia)
4531 	    return true;
4532     }
4533     if (uri.getHost().null())
4534 	return false;
4535     int port = uri.getPort();
4536     if (port <= 0)
4537 	port = 5060;
4538     if (!m_addr.host(uri.getHost())) {
4539 	Debug(&plugin,DebugWarn,"Could not resolve UDP party name '%s' [%p]",
4540 	    uri.getHost().safe(),this);
4541 	return false;
4542     }
4543     m_addr.port(port);
4544     m_party = uri.getHost();
4545     m_partyPort = port;
4546     DDebug(&plugin,DebugInfo,"New UDP party is %s (%s) [%p]",
4547 	SocketAddr::appendTo(m_party,m_partyPort).c_str(),m_addr.addr().c_str(),this);
4548     return true;
4549 }
4550 
getTransport()4551 void* YateUDPParty::getTransport()
4552 {
4553     return m_transport;
4554 }
4555 
4556 // Get an object from this one
getObject(const String & name) const4557 void* YateUDPParty::getObject(const String& name) const
4558 {
4559     if (name == YATOM("YateUDPParty"))
4560 	return (void*)this;
4561     if (name == YATOM("YateSIPUDPTransport") || name == YATOM("YateSIPTransport"))
4562 	return m_transport;
4563     return SIPParty::getObject(name);
4564 }
4565 
4566 
YateTCPParty(YateSIPTCPTransport * trans)4567 YateTCPParty::YateTCPParty(YateSIPTCPTransport* trans)
4568     : SIPParty(true),
4569     m_transport(0)
4570 {
4571     if (plugin.ep())
4572 	m_mutex = plugin.ep()->m_partyMutexPool.mutex(this);
4573     if (trans && trans->ref()) {
4574 	m_transport = trans;
4575 	trans->resetParty(this,true);
4576     }
4577     updateAddrs();
4578     DDebug(&plugin,DebugAll,"YateTCPParty local %s party %s transport=%p [%p]",
4579 	SocketAddr::appendTo(m_local,m_localPort).c_str(),
4580 	SocketAddr::appendTo(m_party,m_partyPort).c_str(),m_transport,this);
4581 }
4582 
~YateTCPParty()4583 YateTCPParty::~YateTCPParty()
4584 {
4585     XDebug(&plugin,DebugAll,"YateTCPParty::~YateTCPParty() transport=%p [%p]",
4586 	m_transport,this);
4587     TelEngine::destruct(m_transport);
4588 }
4589 
transmit(SIPEvent * event)4590 bool YateTCPParty::transmit(SIPEvent* event)
4591 {
4592     const SIPMessage* msg = event->getMessage();
4593     if (!msg)
4594 	return false;
4595     if (m_transport) {
4596 	bool ok = m_transport->send(event);
4597 	if (msg->dontSend() && event->getTransaction())
4598 	    event->getTransaction()->setSilent();
4599 	return ok;
4600     }
4601     String tmp;
4602     getMsgLine(tmp,msg);
4603     Debug(&plugin,DebugWarn,"YateTCPParty no transport to send %s [%p]",
4604 	tmp.c_str(),this);
4605     return false;
4606 }
4607 
getProtoName() const4608 const char* YateTCPParty::getProtoName() const
4609 {
4610     if (m_transport)
4611 	return m_transport->protoName();
4612     return "TCP";
4613 }
4614 
setParty(const URI & uri)4615 bool YateTCPParty::setParty(const URI& uri)
4616 {
4617     Lock lock(m_mutex);
4618     if (m_partyPort && m_party && s_ignoreVia)
4619 	return true;
4620     Debug(&plugin,DebugWarn,"YateTCPParty::setParty(%s) not implemented [%p]",
4621 	uri.safe(),this);
4622     return false;
4623 }
4624 
getTransport()4625 void* YateTCPParty::getTransport()
4626 {
4627     return m_transport;
4628 }
4629 
4630 // Get an object from this one
getObject(const String & name) const4631 void* YateTCPParty::getObject(const String& name) const
4632 {
4633     if (name == YATOM("YateTCPParty"))
4634 	return (void*)this;
4635     if (name == YATOM("YateSIPTCPTransport") || name == YATOM("YateSIPTransport"))
4636 	return m_transport;
4637     return SIPParty::getObject(name);
4638 }
4639 
updateAddrs()4640 void YateTCPParty::updateAddrs()
4641 {
4642     if (!m_transport)
4643 	return;
4644     m_transport->lock();
4645     String laddr = m_transport->local().host();
4646     int lport = m_transport->local().port();
4647     String raddr = m_transport->remote().host();
4648     int rport = m_transport->remote().port();
4649     String transLocalAddr = m_transport->localAddr();
4650     SocketAddr remote;
4651     if (raddr)
4652 	remote = m_transport->remote();
4653     else {
4654 	if (!s_ipv6)
4655 	    remote.assign(AF_INET);
4656 	remote.host(m_transport->remoteAddr());
4657 	remote.port(m_transport->remotePort());
4658 	raddr = remote.host();
4659 	rport = remote.port();
4660     }
4661     m_transport->unlock();
4662     if (!laddr) {
4663 	SocketAddr addr;
4664 	if (transLocalAddr && addr.host(transLocalAddr))
4665 	    laddr = addr.host();
4666 	if (!laddr) {
4667 	    addr.clear();
4668 	    if (addr.local(remote))
4669 		laddr = addr.host();
4670 	    else
4671 		laddr = "localhost";
4672 	}
4673     }
4674     if (lport <= 0)
4675 	lport = sipPort(!m_transport->tls());
4676     setAddr(laddr,lport,true);
4677     setAddr(raddr,rport,false);
4678 }
4679 
destroyed()4680 void YateTCPParty::destroyed()
4681 {
4682     DDebug(&plugin,DebugAll,"YateTCPParty::destroyed() transport=%p [%p]",
4683 	m_transport,this);
4684     if (m_transport) {
4685 	m_transport->resetParty(this,false);
4686 	TelEngine::destruct(m_transport);
4687     }
4688     SIPParty::destroyed();
4689 }
4690 
4691 
YateSIPEngine(YateSIPEndPoint * ep)4692 YateSIPEngine::YateSIPEngine(YateSIPEndPoint* ep)
4693     : SIPEngine(s_cfg.getValue("general","useragent")),
4694       m_ep(ep), m_prack(false), m_info(false), m_foreignAuth(false),
4695       m_traceIds(0)
4696 {
4697     addAllowed("INVITE");
4698     addAllowed("BYE");
4699     addAllowed("CANCEL");
4700     if (s_enable_message)
4701 	addAllowed("MESSAGE");
4702     if (s_enable_register)
4703 	addAllowed("REGISTER");
4704     if (s_enable_transfer)
4705 	addAllowed("REFER");
4706     if (s_enable_options)
4707 	addAllowed("OPTIONS");
4708     m_prack = s_cfg.getBoolValue("general","prack");
4709     if (m_prack)
4710 	addAllowed("PRACK");
4711     m_info = s_cfg.getBoolValue("general","info",true);
4712     if (m_info)
4713 	addAllowed("INFO");
4714     NamedList *l = s_cfg.getSection("methods");
4715     if (l) {
4716 	unsigned int len = l->length();
4717 	for (unsigned int i=0; i<len; i++) {
4718 	    NamedString *n = l->getParam(i);
4719 	    if (!n)
4720 		continue;
4721 	    String meth(n->name());
4722 	    meth.toUpper();
4723 	    addAllowed(meth);
4724 	}
4725     }
4726     initialize(s_cfg.getSection("general"));
4727 }
4728 
4729 // Initialize the engine
initialize(NamedList * params)4730 void YateSIPEngine::initialize(NamedList* params)
4731 {
4732     NamedList dummy("");
4733     if (!params)
4734 	params = &dummy;
4735     lazyTrying(params->getBoolValue("lazy100",false));
4736     m_fork = params->getBoolValue("fork",true);
4737     m_forkEarly = params->getBoolValue("fork_early",false);
4738     m_flags = params->getIntValue("flags",m_flags);
4739     m_foreignAuth = params->getBoolValue("auth_foreign",false);
4740     m_reqTransCount = params->getIntValue("sip_req_trans_count",4,2,10,false);
4741     m_rspTransCount = params->getIntValue("sip_rsp_trans_count",5,2,10,false);
4742     m_autoChangeParty = params->getBoolValue("autochangeparty");
4743     int64_t t1 = params->getIntValue("t1",500,100,5000,false);
4744     int64_t t2 = params->getIntValue("t4",5000,1000,25000,false);
4745     if (t2 < 3 * t1)
4746 	t2 = 3 * t1;
4747     m_t1 = 1000 * t1;
4748     m_t4 = 1000 * t2;
4749     DDebug(this,DebugAll,"Initialized sip_req_trans_count=%d sip_rsp_trans_count=%d",
4750 	m_reqTransCount,m_rspTransCount);
4751 }
4752 
forkInvite(SIPMessage * answer,SIPTransaction * trans)4753 SIPTransaction* YateSIPEngine::forkInvite(SIPMessage* answer, SIPTransaction* trans)
4754 {
4755     if (m_fork && (answer->code > 100) && trans->isActive()) {
4756 	switch (answer->code / 100) {
4757 	    case 1:
4758 		if (!m_forkEarly)
4759 		    break;
4760 		// fall through
4761 	    case 2:
4762 		Debug(this,DebugNote,"Changing early dialog tag because of forked %d",answer->code);
4763 		trans->setDialogTag(answer->getParamValue("To","tag"));
4764 		trans->processMessage(answer);
4765 		return trans;
4766 	}
4767     }
4768     return SIPEngine::forkInvite(answer,trans);
4769 }
4770 
4771 // Transport status changed notification
transportChangedStatus(YateSIPTransport * trans,int stat,const String & reason)4772 void YateSIPEngine::transportChangedStatus(YateSIPTransport* trans, int stat, const String& reason)
4773 {
4774     if (!(trans && stat == YateSIPTransport::Terminated))
4775 	return;
4776     // Clear transactions
4777     Lock lock(this);
4778     for (ObjList* l = m_transList.skipNull(); l; l = l->skipNext()) {
4779 	SIPTransaction* t = static_cast<SIPTransaction*>(l->get());
4780 	if (t->initialMessage() && t->initialMessage()->getParty() &&
4781 	    trans == t->initialMessage()->getParty()->getTransport()) {
4782 	    bool active = t->isActive();
4783 	    Debug(this,active ? DebugInfo : DebugAll,
4784 		"Clearing %stransaction (%p) transport terminated reason=%s",
4785 		active ? "active " : "",t,reason.c_str());
4786 	    t->setCleared();
4787 	}
4788     }
4789 }
4790 
4791 // Check if the engine has an active transaction using a given transport
hasActiveTransaction(YateSIPTransport * trans)4792 bool YateSIPEngine::hasActiveTransaction(YateSIPTransport* trans)
4793 {
4794     if (!trans)
4795 	return false;
4796     Lock lock(this);
4797     for (ObjList* l = m_transList.skipNull(); l; l = l->skipNext()) {
4798 	SIPTransaction* t = static_cast<SIPTransaction*>(l->get());
4799 	if (t->isActive() && t->initialMessage() && t->initialMessage()->getParty() &&
4800 	    trans == t->initialMessage()->getParty()->getTransport())
4801 	    return true;
4802     }
4803     return false;
4804 }
4805 
4806 // Check if the engine has pending transactions
hasInitialTransaction()4807 bool YateSIPEngine::hasInitialTransaction()
4808 {
4809     Lock lock(this);
4810     for (ObjList* l = m_transList.skipNull(); l; l = l->skipNext()) {
4811 	SIPTransaction* t = static_cast<SIPTransaction*>(l->get());
4812 	if (t->getState() == SIPTransaction::Initial)
4813 	    return true;
4814     }
4815     return false;
4816 }
4817 
buildParty(SIPMessage * message)4818 bool YateSIPEngine::buildParty(SIPMessage* message)
4819 {
4820     return m_ep->buildParty(message);
4821 }
4822 
allocTraceId(String & id)4823 void YateSIPEngine::allocTraceId(String& id)
4824 {
4825     if (!plugin.traceActive())
4826       return;
4827     id << "sip-";
4828     Lock l(this);
4829     id << m_traceIds++;
4830 }
4831 
traceMsg(SIPMessage * message,bool incoming)4832 void YateSIPEngine::traceMsg(SIPMessage* message, bool incoming)
4833 {
4834     if (!(message && message->msgPrint && s_printMsg && message->getParty()))
4835 	return;
4836     YateSIPTransport* trans = static_cast<YateSIPTransport*>(message->getParty()->getTransport());
4837     if (!trans)
4838 	return;
4839     if (incoming) {
4840 	DataBlock d(message->getBuffer().data(),message->getBuffer().length(),false,1);
4841 	*((uint8_t*)d.data() + (d.length() - 1)) = 0;
4842 	trans->printRecvMsg ((const char*)d.data(),
4843 		    d.length(),message->traceId());
4844 	d.clear(false);
4845       }
4846     else
4847 	trans->printSendMsg(message);
4848 }
4849 
copyAuthParams(NamedList * dest,const NamedList & src,bool ok)4850 bool YateSIPEngine::copyAuthParams(NamedList* dest, const NamedList& src, bool ok)
4851 {
4852     // we added those and we want to exclude them from copy
4853     static TokenDict exclude[] = {
4854 	{ "protocol", 1 },
4855 	// purposely copy the username and realm
4856 	{ "nonce", 1 },
4857 	{ "method", 1 },
4858 	{ "uri", 1 },
4859 	{ "response", 1 },
4860 	{ "ip_host", 1 },
4861 	{ "ip_port", 1 },
4862 	{ "address", 1 },
4863 	{ "id", 1 },
4864 	{ "billid", 1 },
4865 	{ "handlers", 1 },
4866 	{  0,   0 },
4867     };
4868     if (!dest)
4869 	return ok;
4870     unsigned int n = src.length();
4871     for (unsigned int i = 0; i < n; i++) {
4872 	NamedString* s = src.getParam(i);
4873 	if (!s)
4874 	    continue;
4875 	// Don't copy added SIP headers: on success they will be added again
4876 	if (s->name().startsWith("sip_"))
4877 	    continue;
4878 	String name = s->name();
4879 	if (name.startSkip("authfail_",false) == ok)
4880 	    continue;
4881 	if (name.toInteger(exclude,0))
4882 	    continue;
4883 	dest->setParam(name,*s);
4884     }
4885     return ok;
4886 }
4887 
checkUser(String & username,const String & realm,const String & nonce,const String & method,const String & uri,const String & response,const SIPMessage * message,const MimeHeaderLine * authLine,GenObject * userData)4888 bool YateSIPEngine::checkUser(String& username, const String& realm, const String& nonce,
4889     const String& method, const String& uri, const String& response,
4890     const SIPMessage* message, const MimeHeaderLine* authLine, GenObject* userData)
4891 {
4892     NamedList* params = YOBJECT(NamedList,userData);
4893 
4894     Message m("user.auth");
4895     m.addParam("protocol","sip");
4896     if (username) {
4897 	m.addParam(s_username,username);
4898 	m.addParam("realm",realm);
4899 	m.addParam("nonce",nonce);
4900 	m.addParam("response",response);
4901     }
4902     m.addParam("method",method);
4903     m.addParam("uri",uri);
4904     if (message) {
4905 	String raddr;
4906 	int rport = 0;
4907 	message->getParty()->getAddr(raddr,rport,false);
4908 	String port(rport);
4909 	m.addParam("ip_host",raddr);
4910 	m.addParam("ip_port",port);
4911 	m.addParam("ip_transport",message->getParty()->getProtoName());
4912 	YateSIPTransport* trans = YOBJECT(YateSIPTransport,message->getParty());
4913 	if (trans)
4914 	    trans->fillMessage(m);
4915 	if (raddr)
4916 	    m.addParam("address",SocketAddr::appendTo(raddr,rport));
4917 	// a dialogless INVITE could create a new call
4918 	m.addParam("newcall",String::boolText((message->method == YSTRING("INVITE")) && !message->getParam("To","tag")));
4919 	URI domain;
4920 	const MimeHeaderLine* hl = message->getHeader("From");
4921 	if (hl)
4922 	    domain = *hl;
4923 	if (!domain.getHost())
4924 	    domain = uri;
4925 	m.addParam("domain",domain.getHost(),false);
4926 	hl = message->getHeader("User-Agent");
4927 	if (hl)
4928 	    m.addParam("device",*hl);
4929 	m.addParam("trace_id",message->traceId());
4930 	s_globalMutex.lock();
4931 	for (const ObjList* l = message->header.skipNull(); l; l = l->skipNext()) {
4932 	    hl = static_cast<const MimeHeaderLine*>(l->get());
4933 	    String name(hl->name());
4934 	    name.toLower();
4935 	    if (!(name.startsWith("security-") ||
4936 		(s_authCopyHeader && s_authCopyHeader->find(name))))
4937 		continue;
4938 	    String tmp;
4939 	    hl->buildLine(tmp,false);
4940 	    m.addParam("sip_" + name,tmp);
4941 	}
4942 	s_globalMutex.unlock();
4943     }
4944 
4945     if (params) {
4946 	m.copyParam(*params,"id");
4947 	m.copyParam(*params,"number");
4948 	m.copyParam(*params,"caller");
4949 	m.copyParam(*params,"called");
4950 	m.copyParam(*params,"billid");
4951 	m.copyParam(*params,"expires");
4952 	m.copyParam(*params,"trace_id");
4953     }
4954     if (authLine && m_foreignAuth) {
4955 	m.addParam("auth",*authLine);
4956 	for (const ObjList* l = authLine->params().skipNull(); l; l = l->skipNext()) {
4957 	    const NamedString* p = static_cast<const NamedString*>(l->get());
4958 	    m.setParam("auth_" + p->name(),*p);
4959 	}
4960     }
4961     else
4962 	authLine = 0;
4963 
4964     if (!Engine::dispatch(m))
4965 	return copyAuthParams(params,m,false);
4966 
4967     // empty password returned means authentication succeeded
4968     if (m.retValue().null()) {
4969 	if (username.null()) {
4970 	    if (authLine) {
4971 		username = authLine->getParam(s_username);
4972 		MimeHeaderLine::delQuotes(username);
4973 	    }
4974 	    if (username.null())
4975 		username = m.getValue(s_username);
4976 	}
4977 	return copyAuthParams(params,m);
4978     }
4979     // check for refusals
4980     if (m.retValue() == "-") {
4981 	if (params) {
4982 	    const char* err = m.getValue(YSTRING("error"));
4983 	    if (err)
4984 		params->setParam("error",err);
4985 	    err = m.getValue(YSTRING("reason"));
4986 	    if (err)
4987 		params->setParam("reason",err);
4988 	}
4989 	return copyAuthParams(params,m,false);
4990     }
4991     // password works only with username
4992     if (!username)
4993 	return copyAuthParams(params,m,false);
4994 
4995     String res;
4996     buildAuth(username,realm,m.retValue(),nonce,method,uri,res);
4997     if (res == response)
4998 	return copyAuthParams(params,m);
4999     // if the URI included some parameters retry after stripping them off
5000     int sc = uri.find(';');
5001     bool ok = false;
5002     if (sc >= 0) {
5003 	buildAuth(username,realm,m.retValue(),nonce,method,uri.substr(0,sc),res);
5004 	ok = (res == response) && copyAuthParams(params,m);
5005     }
5006 
5007     if (!ok && !response.null()) {
5008 	DDebug(&plugin,DebugNote,"Failed authentication for username='%s'",username.c_str());
5009 	m_ep->incFailedAuths();
5010 	plugin.changed();
5011 	Message* fail = new Message(m);
5012 	*fail = "user.authfail";
5013 	fail->retValue().clear();
5014 	Engine::enqueue(fail);
5015     }
5016     return ok || copyAuthParams(params,m,false);
5017 }
5018 
5019 
YateSIPEndPoint(Thread::Priority prio,unsigned int partyMutexCount)5020 YateSIPEndPoint::YateSIPEndPoint(Thread::Priority prio, unsigned int partyMutexCount)
5021     : Thread("YSIP EndPoint",prio),
5022       m_partyMutexPool(partyMutexCount,true,"SIPParty"),
5023       m_engine(0), m_mutex(true,"YateSIPEndPoint"), m_defTransport(0),
5024       m_failedAuths(0),m_timedOutTrs(0), m_timedOutByes(0)
5025 {
5026     Debug(&plugin,DebugAll,"YateSIPEndPoint::YateSIPEndPoint(%s) [%p]",
5027 	Thread::priority(prio),this);
5028 }
5029 
~YateSIPEndPoint()5030 YateSIPEndPoint::~YateSIPEndPoint()
5031 {
5032     Debug(&plugin,DebugAll,"YateSIPEndPoint::~YateSIPEndPoint() [%p]",this);
5033     plugin.channels().clear();
5034     s_lines.clear();
5035     if (m_engine) {
5036 	// send any pending events
5037 	while (m_engine->process())
5038 	    ;
5039 	delete m_engine;
5040 	m_engine = 0;
5041     }
5042     m_defTransport = 0;
5043     plugin.epTerminated(this);
5044 }
5045 
buildParty(SIPMessage * message,const char * host,int port,const YateSIPLine * line)5046 bool YateSIPEndPoint::buildParty(SIPMessage* message, const char* host, int port, const YateSIPLine* line)
5047 {
5048     if (message->isAnswer())
5049 	return false;
5050     Debug(&plugin,DebugAll,"YateSIPEndPoint::buildParty(%p,'%s',%d,%p)",
5051 	message,host,port,line);
5052     if (line && line->setSipParty(message,line))
5053 	return true;
5054     // Find transport
5055     YateSIPUDPTransport* trans = defTransport();
5056     if (!trans && line && line->getLocalAddr())
5057 	trans = findUdpTransport(line->getLocalAddr(),line->getLocalPort());
5058     if (!trans)
5059 	return false;
5060     // Build an udp party
5061     URI uri(message->uri);
5062     if (line) {
5063 	if (!host)
5064 	    host = line->getPartyAddr();
5065 	if (port <= 0)
5066 	    port = line->getPartyPort();
5067 	line->setupAuth(message);
5068     }
5069     if (!host) {
5070 	host = uri.getHost().safe();
5071 	if (port <= 0)
5072 	    port = uri.getPort();
5073     }
5074     if (port <= 0)
5075 	port = 5060;
5076     trans->lock();
5077     int f = trans->local().family();
5078     trans->unlock();
5079     SocketAddr addr(f);
5080     if (!addr.host(host)) {
5081 	TelEngine::destruct(trans);
5082 	Debug(&plugin,DebugWarn,"Error resolving name '%s' (address family '%s')",
5083 	    host,SocketAddr::lookupFamily(f));
5084 	return false;
5085     }
5086     addr.port(port);
5087     DDebug(&plugin,DebugAll,"built addr: %s",addr.addr().c_str());
5088     YateUDPParty* party = new YateUDPParty(trans,addr);
5089     TelEngine::destruct(trans);
5090     message->setParty(party);
5091     TelEngine::destruct(party);
5092     return true;
5093 }
5094 
5095 // (re)set default UDP transport
updateDefUdpTransport()5096 void YateSIPEndPoint::updateDefUdpTransport()
5097 {
5098     static const String s_general("general");
5099     Lock lock(m_mutex);
5100     m_defTransport = 0;
5101     // Find a non-general default transport
5102     for (ObjList* o = m_transports.skipNull(); o; o = o->skipNext()) {
5103 	YateSIPTransport* t = static_cast<YateSIPTransport*>(o->get());
5104 	m_defTransport = t->udpTransport();
5105 	if (m_defTransport && m_defTransport->toString() != s_general &&
5106 	    m_defTransport->isDefault())
5107 	    break;
5108 	m_defTransport = 0;
5109     }
5110     if (!m_defTransport) {
5111 	m_defTransport = findUdpTransport(s_general);
5112 	if (m_defTransport)
5113 	    m_defTransport->deref();
5114     }
5115     if (m_defTransport)
5116 	Debug(&plugin,DebugInfo,"Default UDP transport is '%s'",
5117 	    m_defTransport->toString().c_str());
5118     else if (!Engine::exiting())
5119 	Debug(&plugin,DebugNote,"Default UDP transport not set");
5120 }
5121 
5122 // Retrieve a transport by name. Return referrenced object
findTransport(const String & name)5123 YateSIPTransport* YateSIPEndPoint::findTransport(const String& name)
5124 {
5125     if (!name)
5126 	return 0;
5127     Lock lock(m_mutex);
5128     ObjList* o = m_transports.find(name);
5129     YateSIPTransport* t = o ? static_cast<YateSIPTransport*>(o->get()) : 0;
5130     return (t && t->ref()) ? t : 0;
5131 }
5132 
5133 // Retrieve an UDP transport by name. Return referrenced object
findUdpTransport(const String & name)5134 YateSIPUDPTransport* YateSIPEndPoint::findUdpTransport(const String& name)
5135 {
5136     YateSIPTransport* t = findTransport(name);
5137     YateSIPUDPTransport* trans = t ? t->udpTransport() : 0;
5138     if (!trans)
5139 	TelEngine::destruct(t);
5140     return trans;
5141 }
5142 
5143 // Retrieve an UDP transport by addr/port. Return referrenced object
findUdpTransport(const String & addr,int port)5144 YateSIPUDPTransport* YateSIPEndPoint::findUdpTransport(const String& addr, int port)
5145 {
5146     Lock lock(m_mutex);
5147     for (ObjList* o = m_transports.skipNull(); o; o = o->skipNext()) {
5148 	YateSIPTransport* t = static_cast<YateSIPTransport*>(o->get());
5149 	if (!t->udpTransport())
5150 	    continue;
5151 	Lock lck(t);
5152 	if (t->local().port() == port && t->local().host() == addr)
5153 	    return t->ref() ? static_cast<YateSIPUDPTransport*>(t) : 0;
5154     }
5155     return 0;
5156 }
5157 
5158 // Build an UDP transport (re-init existing). Start the thread
setupUdpTransport(const String & name,bool enabled,const NamedList & params,const NamedList & defs,const char * reason)5159 bool YateSIPEndPoint::setupUdpTransport(const String& name, bool enabled,
5160     const NamedList& params, const NamedList& defs, const char* reason)
5161 {
5162     if (!name)
5163 	return false;
5164     YateSIPUDPTransport* rd = findUdpTransport(name);
5165     if (rd) {
5166 	if (enabled) {
5167 	    reason = 0;
5168 	    const String& addr = params["addr"];
5169 	    bool ipv6 = params.getBoolValue("ipv6",(addr.find(':') >= 0));
5170 	    if (rd->ipv6() == ipv6 && (!rd->ipv6() || rd->ipv6Support() == s_ipv6)) {
5171 		int port = params.getIntValue("port",5060);
5172 		if (rd->addrWouldChange(rd,addr,port))
5173 		    reason = "Address changed";
5174 	    }
5175 	    else if (rd->ipv6() == ipv6)
5176 		reason = "IPv6 support changed";
5177 	    else
5178 		reason = "Address family changed";
5179 	}
5180 	else if (!reason)
5181 	    reason = "Disabled";
5182 	if (!reason)
5183 	    rd->init(params,defs,false);
5184 	else
5185 	    removeUdpTransport(name,reason);
5186 	TelEngine::destruct(rd);
5187 	if (!(enabled && reason))
5188 	    return true;
5189     }
5190     if (!enabled)
5191 	return true;
5192     Lock lock(m_mutex);
5193     const char* s = params.getValue("thread",defs.getValue("thread"));
5194     rd = new YateSIPUDPTransport(name);
5195     rd->init(params,defs,true,Thread::priority(s));
5196     m_transports.append(rd);
5197     return true;
5198 }
5199 
5200 // Delete an UDP transport
removeUdpTransport(const String & name,const char * reason)5201 bool YateSIPEndPoint::removeUdpTransport(const String& name, const char* reason)
5202 {
5203     XDebug(&plugin,DebugAll,"YateSIPEndPoint::removeUdpTransport(%s,%s)",name.c_str(),reason);
5204     if (!name)
5205 	return false;
5206     YateSIPUDPTransport* rd = findUdpTransport(name);
5207     if (!rd)
5208 	return false;
5209     Debug(&plugin,DebugInfo,"Listener(%s,'%s') stop listening reason='%s' [%p]",
5210 	rd->protoName(),rd->lName(),reason,rd);
5211     removeTransport(rd,false);
5212     // Terminate channels, disconnect lines
5213     plugin.transportTerminated(rd);
5214     // Notify lines
5215     for (ObjList* ol = s_lines.skipNull(); ol; ol = ol->skipNext()) {
5216 	YateSIPLine* line = static_cast<YateSIPLine*>(ol->get());
5217 	if (line->isTransport(rd))
5218 	    line->transportChangedStatus(YateSIPTransport::Terminated,reason);
5219     }
5220     // Wait for active transactions to terminate
5221     if (!Engine::exiting()) {
5222 	unsigned int intervals = (unsigned int)(s_waitActiveUdpTrans / Thread::idleUsec());
5223 	if (!intervals)
5224 	    intervals = 1;
5225 	while (intervals > 0 && !Engine::exiting() &&
5226 	    m_engine->hasActiveTransaction(rd)) {
5227 	    Thread::idle();
5228 	    intervals--;
5229 	}
5230 	if (!intervals)
5231 	    Debug(&plugin,DebugNote,
5232 		"Removing udp transport '%s' with active transactions using it",
5233 		name.c_str());
5234     }
5235     rd->terminate(reason);
5236     rd->deref();
5237     TelEngine::destruct(rd);
5238     return true;
5239 }
5240 
5241 // Remove a transport from list
removeTransport(YateSIPTransport * trans,bool updDef)5242 bool YateSIPEndPoint::removeTransport(YateSIPTransport* trans, bool updDef)
5243 {
5244     if (!trans)
5245 	return false;
5246     Lock lock(m_mutex);
5247     if (!m_transports.remove(trans,false))
5248 	return false;
5249     Debug(&plugin,DebugAll,"Removed transport (%p,'%s')",trans,trans->toString().c_str());
5250     if (trans == m_defTransport) {
5251 	Debug(&plugin,DebugInfo,"Reset default UDP transport");
5252 	m_defTransport = 0;
5253 	if (updDef)
5254 	    updateDefUdpTransport();
5255     }
5256     return true;
5257 }
5258 
5259 // Remove all transports
clearUdpTransports(const char * reason)5260 void YateSIPEndPoint::clearUdpTransports(const char* reason)
5261 {
5262 #ifdef DEBUG
5263     Debugger debug(DebugAll,"YateSIPEndPoint::clearUdpTransports()");
5264 #else
5265     Debug(&plugin,DebugAll,"Clearing udp transports reason=%s",reason);
5266 #endif
5267     while (true) {
5268 	Lock lock(m_mutex);
5269 	RefPointer<YateSIPUDPTransport> trans;
5270 	for (ObjList* o = m_transports.skipNull(); o; o = o->skipNext()) {
5271 	    trans = YOBJECT(YateSIPUDPTransport,o->get());
5272 	    if (trans)
5273 		break;
5274 	}
5275 	if (!trans)
5276 	    break;
5277 	lock.drop();
5278 	Debug(&plugin,DebugInfo,"Listener(%s,'%s') stop listening reason='%s' [%p]",
5279 	    trans->protoName(),trans->lName(),reason,(YateSIPUDPTransport*)trans);
5280 	removeTransport(trans);
5281 	trans->terminate(reason);
5282 	trans->deref();
5283 	trans = 0;
5284     }
5285 }
5286 
5287 // TCP transport status changed notification
transportChangedStatus(YateSIPTransport * trans,int stat,const String & reason)5288 void YateSIPEndPoint::transportChangedStatus(YateSIPTransport* trans, int stat, const String& reason)
5289 {
5290     if (!trans)
5291 	return;
5292     DDebug(&plugin,DebugAll,"YateSIPEndPoint::transportChangedStatus(%p,%s,%s)",
5293 	trans,YateSIPTransport::statusName(stat),reason.c_str());
5294     // Remove from list
5295     if (stat == YateSIPTCPTransport::Terminated)
5296 	removeTransport(trans);
5297     // Notify lines
5298     for (ObjList* ol = s_lines.skipNull(); ol; ol = ol->skipNext()) {
5299 	YateSIPLine* line = static_cast<YateSIPLine*>(ol->get());
5300 	if (line->isTransport(trans))
5301 	    line->transportChangedStatus(stat,reason);
5302 	else if (line->valid() && stat == YateSIPTransport::Connected
5303 	    && trans->protocol() == ProtocolHolder::Udp && line->protocol() == ProtocolHolder::Udp
5304 	    && !line->transport()) {
5305 	    // Line is configured to be online without registering to server
5306 	    //  has no transport but has configured UDP transport
5307 	    // Try to re-build the party
5308 	    line->buildParty();
5309 	}
5310     }
5311     // Notify transactions in engine
5312     if (m_engine)
5313 	m_engine->transportChangedStatus(trans,stat,reason);
5314     if (stat != YateSIPTCPTransport::Terminated)
5315 	return;
5316     // Notify unregister
5317     if (!Engine::exiting()) {
5318 	Message* m = new Message("user.unregister");
5319 	m->addParam("connection_id",trans->toString());
5320 	Engine::enqueue(m);
5321     }
5322     // Notify channels
5323     plugin.transportTerminated(trans);
5324 }
5325 
5326 // Build or delete a TCP listener. Start the thread
setupListener(int proto,const String & name,bool enabled,const NamedList & params)5327 bool YateSIPEndPoint::setupListener(int proto, const String& name, bool enabled, const NamedList& params)
5328 {
5329     if (!name)
5330 	return false;
5331     Lock lock(m_mutex);
5332     ObjList* o = m_listeners.find(name);
5333     if (o) {
5334 	YateSIPTCPListener* l = static_cast<YateSIPTCPListener*>(o->get());
5335 	if (enabled) {
5336 	    if (l->protocol() == proto)
5337 		l->init(params,false);
5338 	    else {
5339 		lock.drop();
5340 		cancelListener(name,"Type changed");
5341 		return setupListener(proto,name,enabled,params);
5342 	    }
5343 	}
5344 	else {
5345 	    lock.drop();
5346 	    cancelListener(name,"Disabled");
5347 	}
5348 	return true;
5349     }
5350     if (!enabled)
5351 	return true;
5352     // Build it
5353     YateSIPTCPListener* listener = new YateSIPTCPListener(proto,name,params);
5354     if (listener->startup()) {
5355 	m_listeners.append(listener);
5356 	DDebug(&plugin,DebugAll,"Added listener %p '%s'",listener,listener->toString().c_str());
5357 	return true;
5358     }
5359     Alarm(&plugin,"config",DebugWarn,"Failed to start listener thread type=%s name='%s'",
5360 	ProtocolHolder::lookupProtoName(proto),name.c_str());
5361     return false;
5362 }
5363 
5364 // Remove a listener from list without deleting it. Return true if found
removeListener(YateSIPTCPListener * listener)5365 bool YateSIPEndPoint::removeListener(YateSIPTCPListener* listener)
5366 {
5367     if (!listener)
5368 	return false;
5369     Lock lock(m_mutex);
5370     if (!m_listeners.remove(listener,false))
5371 	return false;
5372     DDebug(&plugin,DebugAll,"Removed listener (%p,'%s')",listener,listener->toString().c_str());
5373     return true;
5374 }
5375 
5376 // Remove a listener from list. Remove all if name is empty. Wait for termination
cancelListener(const String & name,const char * reason)5377 void YateSIPEndPoint::cancelListener(const String& name, const char* reason)
5378 {
5379     m_mutex.lock();
5380     bool wait = false;
5381     for (ObjList* o = m_listeners.skipNull(); o; o = o->skipNext()) {
5382 	YateSIPTCPListener* l = static_cast<YateSIPTCPListener*>(o->get());
5383 	if (name && name != l->toString())
5384 	    continue;
5385 	wait = true;
5386 	Debug(&plugin,DebugAll,"Stopping listener (%p,'%s') reason=%s",
5387 	    l,l->toString().c_str(),reason);
5388 	l->setReason(reason);
5389 	l->cancel();
5390 	if (name)
5391 	    break;
5392     }
5393     m_mutex.unlock();
5394     if (!wait)
5395 	return;
5396     while (true) {
5397 	Thread::idle();
5398 	Lock lck(m_mutex);
5399 	ObjList* o = !name ? m_listeners.skipNull() : m_listeners.find(name);
5400 	if (!o)
5401 	    break;
5402     }
5403     if (!name)
5404     	Debug(&plugin,DebugAll,"Stopped all listeners");
5405     else
5406     	Debug(&plugin,DebugAll,"Stopped listener '%s'",name.c_str());
5407 }
5408 
5409 // This method is called by the driver when start/end initializing
5410 // start==true: Reset initialized flag for listeners and UDP transports
5411 // start==false: Terminate not initialized listeners and UDP transports
initializing(bool start)5412 void YateSIPEndPoint::initializing(bool start)
5413 {
5414     ObjList rmListener;
5415     ObjList rmUdpTrans;
5416     m_mutex.lock();
5417     for (ObjList* o = m_listeners.skipNull(); o; o = o->skipNext()) {
5418 	YateSIPTCPListener* l = static_cast<YateSIPTCPListener*>(o->get());
5419 	if (start)
5420 	    l->m_initialized = false;
5421 	else if (!l->m_initialized)
5422 	    rmListener.append(new String(l->toString()));
5423     }
5424     for (ObjList* o = m_transports.skipNull(); o; o = o->skipNext()) {
5425 	YateSIPTCPTransport* t = static_cast<YateSIPTCPTransport*>(o->get());
5426 	if (start)
5427 	    t->m_initialized = false;
5428 	else if (!t->m_initialized && t->udpTransport())
5429 	    rmUdpTrans.append(new String(t->toString()));
5430     }
5431     m_mutex.unlock();
5432     if (start)
5433 	return;
5434     for (ObjList* o = rmListener.skipNull(); o; o = o->skipNext()) {
5435 	String* name = static_cast<String*>(o->get());
5436 	Debug(&plugin,DebugNote,"Stopping deleted listener '%s'",name->c_str());
5437 	cancelListener(*name,"Deleted");
5438     }
5439     for (ObjList* o = rmUdpTrans.skipNull(); o; o = o->skipNext())
5440 	removeUdpTransport(o->get()->toString(),"Deleted");
5441 }
5442 
5443 // Complete transport names
completeTransports(Message & msg,const String & partWord,bool udp,bool tcp,bool tls)5444 void YateSIPEndPoint::completeTransports(Message& msg, const String& partWord,
5445     bool udp, bool tcp, bool tls)
5446 {
5447     Lock lock(m_mutex);
5448     for (ObjList* o = m_transports.skipNull(); o; o = o->skipNext()) {
5449 	YateSIPTransport* t = static_cast<YateSIPTransport*>(o->get());
5450 	switch (t->protocol()) {
5451 	    case ProtocolHolder::Udp:
5452 		if (!udp)
5453 		    continue;
5454 		break;
5455 	    case ProtocolHolder::Tcp:
5456 		if (!tcp)
5457 		    continue;
5458 		break;
5459 	    case ProtocolHolder::Tls:
5460 		if (!tls)
5461 		    continue;
5462 		break;
5463 	}
5464 	Module::itemComplete(msg.retValue(),t->toString(),partWord);
5465     }
5466 }
5467 
Init()5468 bool YateSIPEndPoint::Init()
5469 {
5470     m_engine = new YateSIPEngine(this);
5471     m_engine->debugChain(&plugin);
5472     return true;
5473 }
5474 
5475 // Check if data is allowed to be read from socket(s) and processed
canRead()5476 bool YateSIPEndPoint::canRead()
5477 {
5478     return s_floodEvents <= 1 || (s_evCount < s_floodEvents) || Engine::exiting();
5479 }
5480 
run()5481 void YateSIPEndPoint::run()
5482 {
5483     for (;;)
5484     {
5485 	if (!canRead()) {
5486 	    if (s_evCount == s_floodEvents)
5487 	        Debug(&plugin,DebugMild,"Flood detected: %d handled events",s_evCount);
5488 	    else if ((s_evCount % s_floodEvents) == 0)
5489 	        Debug(&plugin,DebugWarn,"Severe flood detected: %d events",s_evCount);
5490 	}
5491 	SIPEvent* e = m_engine->getEvent();
5492 	if (e)
5493 	    s_evCount++;
5494 	else
5495 	    s_evCount = 0;
5496 	// hack: use a loop so we can use break and continue
5497 	for (; e; m_engine->processEvent(e),e = 0) {
5498 	    SIPTransaction* t = e->getTransaction();
5499 	    if (!t)
5500 		continue;
5501 	    plugin.lock();
5502 
5503 	    if (t->isOutgoing() && t->getResponseCode() == 408) {
5504 	    	if (t->getMethod() == YSTRING("BYE")) {
5505 		    DDebug(&plugin,DebugInfo,"BYE for transaction %p has timed out",t);
5506 		    m_timedOutByes++;
5507 		    plugin.changed();
5508 		}
5509 		if (e->getState() == SIPTransaction::Cleared && e->getUserData()) {
5510 		    DDebug(&plugin,DebugInfo,"Transaction %p has timed out",t);
5511 		    m_timedOutTrs++;
5512 		    plugin.changed();
5513 		}
5514 	    }
5515 
5516 	    GenObject* obj = static_cast<GenObject*>(t->getUserData());
5517 	    RefPointer<YateSIPConnection> conn = YOBJECT(YateSIPConnection,obj);
5518 	    YateSIPLine* line = YOBJECT(YateSIPLine,obj);
5519 	    YateSIPGenerate* gen = YOBJECT(YateSIPGenerate,obj);
5520 	    plugin.unlock();
5521 	    if (conn) {
5522 		if (conn->process(e)) {
5523 		    delete e;
5524 		    break;
5525 		}
5526 		else
5527 		    continue;
5528 	    }
5529 	    if (line) {
5530 		if (line->process(e)) {
5531 		    delete e;
5532 		    break;
5533 		}
5534 		else
5535 		    continue;
5536 	    }
5537 	    if (gen) {
5538 		if (gen->process(e)) {
5539 		    delete e;
5540 		    break;
5541 		}
5542 		else
5543 		    continue;
5544 	    }
5545 	    if ((e->getState() == SIPTransaction::Trying) &&
5546 		!e->isOutgoing() && incoming(e,e->getTransaction())) {
5547 		delete e;
5548 		break;
5549 	    }
5550 	}
5551 	if (s_evCount || s_engineHalt) {
5552 	    if (Thread::check(false))
5553 		break;
5554 	}
5555 	else
5556 	    Thread::usleep(Thread::idleUsec());
5557     }
5558     plugin.epTerminated(this);
5559 }
5560 
incoming(SIPEvent * e,SIPTransaction * t)5561 bool YateSIPEndPoint::incoming(SIPEvent* e, SIPTransaction* t)
5562 {
5563     if (t->isInvite())
5564 	invite(e,t);
5565     else if (t->getMethod() == YSTRING("BYE")) {
5566 	YateSIPConnection* conn = plugin.findCall(t->getCallID(),true);
5567 	if (conn) {
5568 	    conn->doBye(t);
5569 	    conn->deref();
5570 	}
5571 	else
5572 	    t->setResponse(481);
5573     }
5574     else if (t->getMethod() == YSTRING("CANCEL")) {
5575 	YateSIPConnection* conn = plugin.findCall(t->getCallID(),true);
5576 	if (conn) {
5577 	    conn->doCancel(t);
5578 	    conn->deref();
5579 	}
5580 	else
5581 	    t->setResponse(481);
5582     }
5583     else if (t->getMethod() == YSTRING("INFO")) {
5584 	YateSIPConnection* conn = plugin.findCall(t->getCallID(),true);
5585 	bool done = false;
5586 	if (conn) {
5587 	    done = conn->doInfo(t);
5588 	    conn->deref();
5589 	    if (!done)
5590 		done = generic(e,t,415);
5591 	}
5592 	else if (t->getDialogTag()) {
5593 	    done = true;
5594 	    t->setResponse(481);
5595 	}
5596 	else
5597 	    done = generic(e,t,415);
5598 	if (!done)
5599 	    t->setResponse(415);
5600     }
5601     else if (s_enable_register && t->getMethod() == YSTRING("REGISTER"))
5602 	regReq(e,t);
5603     else if (s_enable_options && t->getMethod() == YSTRING("OPTIONS"))
5604 	options(e,t);
5605     else if (s_enable_transfer && t->getMethod() == YSTRING("REFER")) {
5606 	YateSIPConnection* conn = plugin.findCall(t->getCallID(),true);
5607 	if (conn) {
5608 	    conn->doRefer(t);
5609 	    conn->deref();
5610 	}
5611 	else
5612 	    t->setResponse(481);
5613     }
5614     else if (s_enable_message && t->getMethod() == YSTRING("MESSAGE")) {
5615 	YateSIPConnection* conn = plugin.findCall(t->getCallID(),true);
5616 	if (conn) {
5617 	    conn->doMessage(t);
5618 	    conn->deref();
5619 	}
5620 	else
5621 	    return generic(e,t);
5622     }
5623     else
5624 	return generic(e,t);
5625     return true;
5626 }
5627 
invite(SIPEvent * e,SIPTransaction * t)5628 void YateSIPEndPoint::invite(SIPEvent* e, SIPTransaction* t)
5629 {
5630     if (e->getMessage()->getParam("To","tag")) {
5631 	SIPDialog dlg(*e->getMessage());
5632 	YateSIPConnection* conn = plugin.findDialog(dlg,true);
5633 	if (conn) {
5634 	    conn->reInvite(t);
5635 	    conn->deref();
5636 	}
5637 	else {
5638 	    Debug(&plugin,DebugWarn,"Got re-INVITE for missing dialog");
5639 	    t->setResponse(481);
5640 	}
5641 	return;
5642     }
5643 
5644     if (!plugin.canAccept()) {
5645 	Debug(&plugin,DebugWarn,"Refusing new SIP call, full or exiting");
5646 	t->setResponse(480);
5647 	return;
5648     }
5649 
5650     YateSIPConnection* conn = new YateSIPConnection(e,t);
5651     conn->initChan();
5652     conn->startRouter();
5653 
5654 }
5655 
regReq(SIPEvent * e,SIPTransaction * t)5656 void YateSIPEndPoint::regReq(SIPEvent* e, SIPTransaction* t)
5657 {
5658     if (Engine::exiting()) {
5659 	Debug(&plugin,DebugWarn,"Dropping request, engine is exiting");
5660 	t->setResponse(500, "Server Shutting Down");
5661 	return;
5662     }
5663     if (s_reg_async) {
5664 	YateSIPRegister* reg = new YateSIPRegister(this,e->getMessage(),t);
5665 	if (reg->startup())
5666 	    return;
5667 	Debug(&plugin,DebugWarn,"Failed to start register thread");
5668 	delete reg;
5669     }
5670     regRun(e->getMessage(),t);
5671 }
5672 
regRun(const SIPMessage * message,SIPTransaction * t)5673 void YateSIPEndPoint::regRun(const SIPMessage* message, SIPTransaction* t)
5674 {
5675     const MimeHeaderLine* hl = message->getHeader("Contact");
5676     if (!hl) {
5677 	t->setResponse(400);
5678 	return;
5679     }
5680 
5681     String tmp(message->getHeader("Expires"));
5682     if (tmp.null())
5683 	tmp = hl->getParam("expires");
5684     int expires = tmp.toInteger(-1);
5685     if (expires < 0)
5686 	expires = s_expires_def;
5687     if (expires > s_expires_max)
5688 	expires = s_expires_max;
5689     if (expires && (expires < s_expires_min) && (*hl != "*")) {
5690 	tmp = s_expires_min;
5691 	SIPMessage* r = new SIPMessage(t->initialMessage(),423);
5692 	r->addHeader("Min-Expires",tmp);
5693 	t->setResponse(r);
5694 	r->deref();
5695 	return;
5696     }
5697 
5698     URI addr(*hl);
5699     String num = addr.getUser();
5700     if (!num) {
5701 	const MimeHeaderLine* to = message->getHeader("To");
5702 	if (to) {
5703 	    URI toUri(*to);
5704 	    num = toUri.getUser();
5705 	}
5706     }
5707     Message msg("user.register");
5708     msg.addParam("number",num,false);
5709     msg.addParam("sip_uri",t->getURI());
5710     msg.addParam("sip_callid",t->getCallID());
5711     tmp = expires;
5712     msg.setParam("expires",tmp);
5713     String user;
5714     int age = t->authUser(user,false,&msg);
5715     DDebug(&plugin,DebugAll,"User '%s' age %d",user.c_str(),age);
5716     if (((age < 0) || (age > 10)) && s_auth_register) {
5717 	setAuthError(t,msg,age >= 0);
5718 	return;
5719     }
5720 
5721     // TODO: track registrations, allow deregistering all
5722     if (*hl == "*") {
5723 	t->setResponse(200);
5724 	return;
5725     }
5726 
5727     if (user.null())
5728 	user = num;
5729     msg.setParam(s_username,user);
5730     msg.setParam("driver","sip");
5731     String data(addr);
5732     String raddr;
5733     int rport = 0;
5734     message->getParty()->getAddr(raddr,rport,false);
5735     bool nat = false;
5736     if (addr.getProtocol().startsWith("sip")) {
5737 	nat = isNatBetween(addr.getHost(),raddr);
5738 	if (!nat && YOBJECT(YateUDPParty,message->getParty())) {
5739 	    int port = addr.getPort();
5740 	    if (!port)
5741 		port = 5060;
5742 	    nat = (rport != port) && msg.getBoolValue(YSTRING("nat_port_support"),true);
5743 	}
5744     }
5745     bool natChanged = false;
5746     if (msg.getBoolValue(YSTRING("nat_support"),s_auto_nat && nat)) {
5747 	String tmp;
5748 	if (addr.getPort())
5749 	    SocketAddr::appendTo(tmp,addr.getHost(),addr.getPort());
5750 	else
5751 	    tmp = addr.getHost();
5752 	String r;
5753 	SocketAddr::appendTo(r,raddr,rport);
5754 	Debug(&plugin,DebugInfo,"Registration NAT detected: private '%s' public '%s'",
5755 	    tmp.c_str(),r.c_str());
5756 	msg.addParam("reg_nat_addr",tmp);
5757 	int pos = data.find(tmp);
5758 	if (pos >= 0) {
5759 	    int len = tmp.length();
5760 	    tmp.clear();
5761 	    tmp << data.substr(0,pos) << r << data.substr(pos + len);
5762 	    data = tmp;
5763 	    natChanged = true;
5764 	}
5765     }
5766     msg.setParam("data","sip/" + data);
5767     msg.setParam("ip_host",raddr);
5768     msg.setParam("ip_port",String(rport));
5769     msg.setParam("ip_transport",message->getParty()->getProtoName());
5770 
5771     bool dereg = false;
5772     if (!expires) {
5773 	msg = "user.unregister";
5774 	dereg = true;
5775     }
5776     else
5777 	msg.setParam("sip_to",addr);
5778     hl = message->getHeader("User-Agent");
5779     if (hl)
5780 	msg.setParam("device",*hl);
5781     // Add transport and also route if registering
5782     if (message->getParty()) {
5783 	YateSIPTransport* trans = static_cast<YateSIPTransport*>(message->getParty()->getTransport());
5784 	if (trans)
5785 	    trans->fillMessage(msg,(0 != expires));
5786     }
5787     copySipHeaders(msg,*message,true,
5788 	static_cast<const YateSIPEngine*>(t->getEngine())->foreignAuth(),s_initialHeaders);
5789     SIPMessage* r = 0;
5790     bool ok = Engine::dispatch(msg);
5791     t->setTransCount(msg.getIntValue(YSTRING("xsip_trans_count"),-1));
5792     // Always OK deregistration attempts
5793     if (ok || dereg) {
5794 	if (dereg) {
5795 	    r = new SIPMessage(t->initialMessage(),200);
5796 	    Debug(&plugin,DebugNote,"Unregistered user '%s'",user.c_str());
5797 	}
5798 	else {
5799 	    tmp = msg.getValue(YSTRING("expires"),tmp);
5800 	    if (tmp.null())
5801 		tmp = expires;
5802 	    r = new SIPMessage(t->initialMessage(),200);
5803 	    r->addHeader("Expires",tmp);
5804 	    MimeHeaderLine* contact = new MimeHeaderLine("Contact","<" + addr + ">");
5805 	    contact->setParam("expires",tmp);
5806 	    r->addHeader(contact);
5807 	    if (natChanged) {
5808 		if (s_nat_refresh > 0)
5809 		    r->addHeader("P-NAT-Refresh",String(s_nat_refresh));
5810 		r->addHeader("X-Real-Contact",data);
5811 	    }
5812 	    if (t->initialMessage() && t->initialMessage()->getParty() &&
5813 		t->initialMessage()->getParty()->isReliable()) {
5814 		const String& ftValue = msg[YSTRING("xsip_flow-timer")];
5815 		int flowTimer = ftValue.toInteger();
5816 		if (flowTimer > 10 && flowTimer <= 120)
5817 		    r->addHeader(new MimeHeaderLine("Flow-Timer",ftValue));
5818 	    }
5819 	    // Reset transport timeout
5820 	    resetTransportIdle(r,tmp.toInteger());
5821 	    TraceDebugObj(r,&plugin,DebugNote,"Registered user '%s' expires in %s s%s",
5822 		user.c_str(),tmp.c_str(),natChanged ? " (NAT)" : "");
5823 	}
5824     }
5825     else {
5826 	int code = msg.getIntValue(YSTRING("code"),msg.getIntValue(YSTRING("reason"),dict_errors,404));
5827 	if (code < 300 || code > 699)
5828 	    code = 404;
5829 	r = new SIPMessage(t->initialMessage(),code);
5830     }
5831     copySipHeaders(*r,msg);
5832     t->setResponse(r);
5833     TelEngine::destruct(r);
5834 }
5835 
options(SIPEvent * e,SIPTransaction * t)5836 void YateSIPEndPoint::options(SIPEvent* e, SIPTransaction* t)
5837 {
5838     if (!sdpAccept(e->getMessage(),true)) {
5839 	t->setResponse(415);
5840 	return;
5841     }
5842     switch (Engine::accept()) {
5843 	case Engine::Congestion:
5844 	    if (t->setResponse()) {
5845 		SIPMessage* m = new SIPMessage(e->getMessage(),503);
5846 		m->addHeader("Retry-After",String(s_congRetry));
5847 		t->setResponse(m);
5848 		TelEngine::destruct(m);
5849 	    }
5850 	    break;
5851 	case Engine::Reject:
5852 	    t->setResponse(503);
5853 	    break;
5854 	default:
5855 	    t->setResponse(Engine::exiting() ? 503 : 200);
5856     }
5857 }
5858 
generic(SIPEvent * e,SIPTransaction * t,int defErr,bool async)5859 bool YateSIPEndPoint::generic(SIPEvent* e, SIPTransaction* t, int defErr, bool async)
5860 {
5861     String meth(t->getMethod());
5862     meth.toLower();
5863     bool autoAuth = false;
5864     bool isMsg = false;
5865     if (s_enable_message && meth == YSTRING("message")) {
5866 	isMsg = true;
5867 	autoAuth = s_auth_message;
5868 	if (s_msg_async)
5869 	    async = true;
5870     }
5871     if (!isMsg) {
5872 	Lock mylock(s_globalMutex);
5873 	const String* auth = s_cfg.getKey("methods",meth);
5874 	if (!auth)
5875 	    return false;
5876 	autoAuth = auth->toBoolean(true);
5877 	if (s_gen_async)
5878 	    async = true;
5879     }
5880     if (async) {
5881 	YateSIPGeneric* gen = new YateSIPGeneric(this,e->getMessage(),t,meth,defErr,autoAuth,isMsg);
5882 	if (gen->startup())
5883 	    return true;
5884 	Debug(&plugin,DebugWarn,"Failed to start generic thread");
5885 	delete gen;
5886     }
5887     return generic(e->getMessage(),t,meth,autoAuth,isMsg);
5888 }
5889 
generic(const SIPMessage * message,SIPTransaction * t,const String & meth,bool autoAuth,bool isMsg)5890 bool YateSIPEndPoint::generic(const SIPMessage* message, SIPTransaction* t, const String& meth, bool autoAuth, bool isMsg)
5891 {
5892     if (!(message && t))
5893 	return false;
5894     Message m(isMsg ? "call.route" : ("sip." + meth).c_str());
5895     if (isMsg) {
5896 	m.addParam("module",plugin.name());
5897 	m.addParam("route_type","msg");
5898     }
5899     YateSIPConnection* conn = 0;
5900     if (message->getParam("To","tag")) {
5901 	SIPDialog dlg(*message);
5902 	conn = plugin.findDialog(dlg,true);
5903 	if (conn)
5904 	    m.addParam("id",conn->id());
5905     }
5906     String host;
5907     int portNum = 0;
5908     message->getParty()->getAddr(host,portNum,false);
5909     URI uri(message->uri);
5910     String user;
5911     YateSIPLine* line = plugin.findLine(host,portNum,uri.getUser(),message->getParty());
5912     m.addParam("called",uri.getUser(),false);
5913     uri = message->getHeader("From");
5914     uri.parse();
5915     m.addParam("caller",uri.getUser(),false);
5916     m.addParam("callername",uri.getDescription(),false);
5917     if (line) {
5918 	// message comes from line we have registered to
5919 	if (user.null())
5920 	    user = line->getUserName();
5921 	m.addParam("domain",line->domain());
5922 	m.addParam("in_line",*line);
5923     }
5924     else if (autoAuth) {
5925 	int age = t->authUser(user,false,&m);
5926 	DDebug(&plugin,DebugAll,"User '%s' age %d",user.c_str(),age);
5927 	if ((age < 0) || (age > 10)) {
5928 	    setAuthError(t,m,age >= 0);
5929 	    TelEngine::destruct(conn);
5930 	    return true;
5931 	}
5932     }
5933     // Add transport info
5934     YateSIPTransport* trans = YOBJECT(YateSIPTransport,message->getParty());
5935     if (trans)
5936 	trans->fillMessage(m);
5937     if (conn) {
5938 	m.userData(conn);
5939 	conn->complete(m);
5940 	TelEngine::destruct(conn);
5941     }
5942     m.addParam(s_username,user,false);
5943 
5944     String tmp(message->getHeaderValue("Max-Forwards"));
5945     int maxf = tmp.toInteger(s_maxForwards);
5946     if (maxf > s_maxForwards)
5947 	maxf = s_maxForwards;
5948     tmp = maxf-1;
5949     m.addParam("antiloop",tmp);
5950 
5951     m.addParam("address",SocketAddr::appendTo(host,portNum));
5952     m.addParam("ip_host",host);
5953     m.addParam("ip_port",String(portNum));
5954     m.addParam("ip_transport",message->getParty()->getProtoName());
5955     m.addParam("sip_uri",t->getURI());
5956     m.addParam("sip_callid",t->getCallID());
5957     // establish the dialog here so user code will have the dialog tag handy
5958     t->setDialogTag();
5959     m.addParam("xsip_dlgtag",t->getDialogTag());
5960     copySipHeaders(m,*message,false,
5961 	static_cast<const YateSIPEngine*>(t->getEngine())->foreignAuth(),s_initialHeaders);
5962 
5963     doDecodeIsupBody(&plugin,m,message->body);
5964     copySipBody(m,*message);
5965     // attempt to find out if the handler modified the body
5966     ObjList bodies;
5967     const String* body = m.getParam(YSTRING("xsip_body"));
5968     if (body) {
5969 	bodies.append(new BodyTrace(*body));
5970 	for (int i = 1; ; i++) {
5971 	    body = m.getParam("xsip_body." + String(i));
5972 	    if (!body)
5973 		break;
5974 	    bodies.append(new BodyTrace(*body));
5975 	}
5976     }
5977 
5978     int code = 0;
5979     bool ok = Engine::dispatch(m);
5980     t->setTransCount(m.getIntValue(YSTRING("xsip_trans_count"),-1));
5981     while (isMsg && ok) {
5982 	ok = m.retValue() && m.retValue() != YSTRING("-") &&
5983 	    m.retValue() != YSTRING("error");
5984 	if (!ok)
5985 	    break;
5986 	ok = (m.getIntValue(YSTRING("antiloop"),1) > 0);
5987 	if (!ok) {
5988 	    code = 483;
5989 	    break;
5990 	}
5991 	m = "msg.execute";
5992 	m.setParam("callto",m.retValue());
5993 	m.clearParam(YSTRING("error"));
5994 	m.clearParam(YSTRING("reason"));
5995 	m.retValue().clear();
5996 	ok = Engine::dispatch(m);
5997 	break;
5998     }
5999     if (ok) {
6000 	const String* ret = m.getParam(YSTRING("code"));
6001 	if (!ret)
6002 	    ret = &m.retValue();
6003 	code = ret->toInteger(m.getIntValue(YSTRING("reason"),dict_errors,200));
6004     }
6005     else {
6006 	int reason = m.getIntValue(YSTRING("reason"),dict_errors,code);
6007 	code = m.getIntValue(YSTRING("code"),reason);
6008 	// msg.execute: other modules migth not set code
6009 	// Check error if code is 0 and reason was 0
6010 	// (reason!=0 and code==0 means code was explicitly set to 0 in the message)
6011 	if (isMsg && !code && !reason)
6012 	    code = m.getIntValue(YSTRING("error"));
6013 	if (code < 300)
6014 	    code = 0;
6015     }
6016     if ((code >= 200) && (code < 700)) {
6017 	SIPMessage* resp = new SIPMessage(message,code);
6018 	copySipHeaders(*resp,m);
6019 	copySipBody(*resp,m,bodies.skipNull());
6020 	t->setResponse(resp);
6021 	resp->deref();
6022 	return true;
6023     }
6024     return false;
6025 }
6026 
6027 
6028 // Build the transfer thread
6029 // transferorID: Channel id of the sip connection that received the REFER request
6030 // transferredID: Channel id of the transferor's peer
6031 // transferredDrv: Channel driver of the transferor's peer
6032 // msg: already populated 'call.route'
6033 // sipNotify: already populated SIPMessage("NOTIFY")
YateSIPRefer(const String & transferorID,const String & transferredID,Driver * transferredDrv,Message * msg,SIPMessage * sipNotify,SIPTransaction * transaction)6034 YateSIPRefer::YateSIPRefer(const String& transferorID, const String& transferredID,
6035     Driver* transferredDrv, Message* msg, SIPMessage* sipNotify,
6036     SIPTransaction* transaction)
6037     : Thread("YSIP Transfer"),
6038     m_transferorID(transferorID), m_transferredID(transferredID),
6039     m_transferredDrv(transferredDrv), m_msg(msg), m_sipNotify(sipNotify),
6040     m_notifyCode(200), m_transaction(0), m_rspCode(500)
6041 {
6042     if (transaction && transaction->ref())
6043 	m_transaction = transaction;
6044 }
6045 
run()6046 void YateSIPRefer::run()
6047 {
6048     String* attended = m_msg->getParam(YSTRING("transfer_callid"));
6049 #ifdef DEBUG
6050     if (attended)
6051 	Debug(&plugin,DebugAll,"%s(%s) running callid=%s fromtag=%s totag=%s [%p]",
6052 	    name(),m_transferorID.c_str(),attended->c_str(),
6053 	    m_msg->getValue(YSTRING("transfer_fromtag")),
6054 	    m_msg->getValue(YSTRING("transfer_totag")),this);
6055     else
6056 	Debug(&plugin,DebugAll,"%s(%s) running [%p]",name(),m_transferorID.c_str(),this);
6057 #endif
6058 
6059     // Use a while() to break to the end
6060     while (m_transferredDrv && m_msg) {
6061 	// Attended transfer: check if the requested channel is owned by our plugin
6062 	// NOTE: Remove the whole 'if' when a routing module will be able to route
6063 	//  attended transfer requests
6064 	if (attended) {
6065 	    String* from = m_msg->getParam(YSTRING("transfer_fromtag"));
6066 	    String* to = m_msg->getParam(YSTRING("transfer_totag"));
6067 	    if (null(from) || null(to)) {
6068 		m_rspCode = m_notifyCode = 487;     // Request Terminated
6069 		break;
6070 	    }
6071 	    YateSIPConnection* conn = plugin.findDialog(*attended,*from,*to,true);
6072 	    if (conn) {
6073 		m_transferredDrv->lock();
6074 		RefPointer<Channel> chan = m_transferredDrv->find(m_transferredID);
6075 		m_transferredDrv->unlock();
6076 		if (chan && conn->getPeer() &&
6077 		    chan->connect(conn->getPeer(),m_msg->getValue(YSTRING("reason")))) {
6078 		    m_rspCode = 202;
6079 		    m_notifyCode = 200;
6080 		}
6081 		else
6082 		    m_rspCode = m_notifyCode = 487;     // Request Terminated
6083 		TelEngine::destruct(conn);
6084 		break;
6085 	    }
6086 	    // Not ours
6087 	    m_msg->clearParam("called");
6088 	    YateSIPConnection::addCallId(*m_msg,*attended,*from,*to);
6089 	}
6090 
6091 	// Route the call
6092 	bool ok = Engine::dispatch(m_msg);
6093 	m_transferredDrv->lock();
6094 	RefPointer<Channel> chan = m_transferredDrv->find(m_transferredID);
6095 	m_transferredDrv->unlock();
6096 	if (!(ok && chan)) {
6097 #ifdef DEBUG
6098 	    if (ok)
6099 		Debug(&plugin,DebugAll,"%s(%s). Connection vanished while routing! [%p]",
6100 		    name(),m_transferorID.c_str(),this);
6101 	    else
6102 		Debug(&plugin,DebugAll,"%s(%s). 'call.route' failed [%p]",
6103 		    name(),m_transferorID.c_str(),this);
6104 #endif
6105 	    m_rspCode = m_notifyCode = (ok ? 487 : 481);
6106 	    break;
6107 	}
6108 	m_msg->userData(chan);
6109 	if ((m_msg->retValue() == "-") || (m_msg->retValue() == YSTRING("error")))
6110 	    m_rspCode = m_notifyCode = 603; // Decline
6111 	else if (m_msg->getIntValue(YSTRING("antiloop"),1) <= 0)
6112 	    m_rspCode = m_notifyCode = 482; // Loop Detected
6113 	else {
6114 	    DDebug(&plugin,DebugAll,"%s(%s). Call succesfully routed [%p]",
6115 		name(),m_transferorID.c_str(),this);
6116 	    *m_msg = "call.execute";
6117 	    m_msg->setParam("callto",m_msg->retValue());
6118 	    m_msg->clearParam(YSTRING("error"));
6119 	    m_msg->retValue().clear();
6120 	    if (Engine::dispatch(m_msg)) {
6121 		DDebug(&plugin,DebugAll,"%s(%s). 'call.execute' succeeded [%p]",
6122 		    name(),m_transferorID.c_str(),this);
6123 		m_rspCode = 202;
6124 		m_notifyCode = 200;
6125 	    }
6126 	    else {
6127 		DDebug(&plugin,DebugAll,"%s(%s). 'call.execute' failed [%p]",
6128 		    name(),m_transferorID.c_str(),this);
6129 		m_rspCode = m_notifyCode = 603; // Decline
6130 	    }
6131 	}
6132 	break;
6133     }
6134     release();
6135 }
6136 
6137 // Respond the transaction and deref() it
setTrResponse(int code)6138 void YateSIPRefer::setTrResponse(int code)
6139 {
6140     if (!m_transaction)
6141 	return;
6142     SIPTransaction* t = m_transaction;
6143     m_transaction = 0;
6144     m_rspCode = code;
6145     t->setResponse(m_rspCode);
6146     TelEngine::destruct(t);
6147 }
6148 
6149 // Set transaction response. Send the notification message. Notify the
6150 // connection and release other objects
release(bool fromCleanup)6151 void YateSIPRefer::release(bool fromCleanup)
6152 {
6153     setTrResponse(m_rspCode);
6154     TelEngine::destruct(m_msg);
6155     // Set NOTIFY response and send it (only if the transaction was accepted)
6156     if (m_sipNotify) {
6157 	if (m_rspCode < 300 && plugin.ep() && plugin.ep()->engine()) {
6158 	    String s;
6159 	    s << "SIP/2.0 " << m_notifyCode << " " << lookup(m_notifyCode,SIPResponses) << "\r\n";
6160 	    m_sipNotify->setBody(new MimeStringBody("message/sipfrag;version=2.0",s));
6161 	    plugin.ep()->engine()->addMessage(m_sipNotify);
6162 	}
6163 	TelEngine::destruct(m_sipNotify);
6164 	// If we still have a NOTIFY message in cleanup() the thread
6165 	//  was cancelled in the hard way
6166 	if (fromCleanup)
6167 	    Debug(&plugin,DebugWarn,"YateSIPRefer(%s) thread terminated abnormally [%p]",
6168 		m_transferorID.c_str(),this);
6169     }
6170     // Notify transferor on termination
6171     if (m_transferorID) {
6172 	plugin.lock();
6173 	YateSIPConnection* conn = static_cast<YateSIPConnection*>(plugin.find(m_transferorID));
6174 	if (conn)
6175 	    conn->referTerminated();
6176 	plugin.unlock();
6177 	m_transferorID = "";
6178     }
6179 }
6180 
6181 
6182 // Incoming call constructor - just before starting the routing thread
YateSIPConnection(SIPEvent * ev,SIPTransaction * tr)6183 YateSIPConnection::YateSIPConnection(SIPEvent* ev, SIPTransaction* tr)
6184     : Channel(plugin,0,false),
6185       SDPSession(&plugin.parser()),
6186       YateSIPPartyHolder(this,driver(),tr->traceId()),
6187       m_tr(tr), m_tr2(0), m_hungup(false), m_byebye(true), m_cancel(false),
6188       m_state(Incoming), m_port(0), m_route(0), m_routes(0),
6189       m_authBye(true), m_autoChangeParty(tr->getEngine()->autoChangeParty()),
6190       m_checkAllowInfo(s_checkAllowInfo), m_missingAllowInfoDefVal(s_missingAllowInfoDefVal),
6191       m_honorDtmfDetect(s_honorDtmfDetect),
6192       m_referring(false), m_reInviting(ReinviteNone), m_lastRseq(0),
6193       m_revert(""), m_silent(false), m_stopOCall(false), m_traceId(tr->traceId())
6194 {
6195     m_ipv6 = s_ipv6;
6196     setSdpDebug(this,this,m_traceId);
6197     TraceDebug(m_traceId,this,DebugAll,"YateSIPConnection::YateSIPConnection(%p,%p) [%p]",ev,tr,this);
6198     setReason();
6199     m_tr->ref();
6200     m_routes = m_tr->initialMessage()->getRoutes();
6201     m_dialog = *m_tr->initialMessage();
6202     m_tr->initialMessage()->getParty()->getAddr(m_host,m_port,false);
6203     SocketAddr::appendTo(m_address,m_host,m_port);
6204     filterDebug(m_address);
6205     m_uri = m_tr->initialMessage()->getHeader("From");
6206     m_uri.parse();
6207     m_tr->setUserData(this);
6208     // Set channel SIP party
6209     setParty(m_tr->initialMessage()->getParty());
6210     updateRtpNatAddress();
6211     // Get dtmf methods
6212     s_globalMutex.lock();
6213     m_dtmfMethods = s_dtmfMethods;
6214     s_globalMutex.unlock();
6215 
6216     URI uri(m_tr->getURI());
6217     YateSIPLine* line = plugin.findLine(m_host,m_port,uri.getUser(),m_party);
6218     Message *m = message("call.preroute");
6219     decodeIsupBody(*m,m_tr->initialMessage()->body);
6220     copySipBody(*m,m_tr->initialMessage()->body);
6221     if (m_traceId)
6222 	m->setParam("trace_id",m_traceId);
6223     m->addParam("caller",m_uri.getUser());
6224     m->addParam("called",uri.getUser());
6225     if (m_uri.getDescription())
6226 	m->addParam("callername",m_uri.getDescription());
6227     const MimeHeaderLine* hl = m_tr->initialMessage()->getHeader("Call-Info");
6228     if (hl) {
6229 	const NamedString* type = hl->getParam("purpose");
6230 	if (!type || *type == YSTRING("info"))
6231 	    m->addParam("caller_info_uri",*hl);
6232 	else if (*type == YSTRING("icon"))
6233 	    m->addParam("caller_icon_uri",*hl);
6234 	else if (*type == YSTRING("card"))
6235 	    m->addParam("caller_card_uri",*hl);
6236     }
6237 
6238     if (s_privacy)
6239 	copyPrivacy(*m,*ev->getMessage());
6240 
6241     String tmp(ev->getMessage()->getHeaderValue("Max-Forwards"));
6242     int maxf = tmp.toInteger(s_maxForwards);
6243     if (maxf > s_maxForwards)
6244 	maxf = s_maxForwards;
6245     tmp = maxf-1;
6246     m->addParam("antiloop",tmp);
6247     m->addParam("ip_host",m_host);
6248     m->addParam("ip_port",String(m_port));
6249     m->addParam("ip_transport",m_tr->initialMessage()->getParty()->getProtoName());
6250     YateSIPTransport* trans = YOBJECT(YateSIPTransport,m_tr->initialMessage()->getParty());
6251     if (trans)
6252 	trans->fillMessage(*m);
6253     m->addParam("sip_uri",uri);
6254     m->addParam("sip_from",m_uri);
6255     m->addParam("sip_to",ev->getMessage()->getHeaderValue("To"));
6256     m->addParam("sip_callid",callid(),false);
6257     m->addParam("device",ev->getMessage()->getHeaderValue("User-Agent"));
6258     copySipHeaders(*m,*ev->getMessage(),true,
6259 	static_cast<const YateSIPEngine*>(tr->getEngine())->foreignAuth(),s_initialHeaders);
6260 
6261     const char* reason = 0;
6262     hl = m_tr->initialMessage()->getHeader("Referred-By");
6263     if (hl)
6264 	reason = "transfer";
6265     else {
6266 	hl = m_tr->initialMessage()->getHeader("Diversion");
6267 	if (hl) {
6268 	    reason = "divert";
6269 	    const String* par = hl->getParam("reason");
6270 	    if (par) {
6271 		tmp = par->c_str();
6272 		MimeHeaderLine::delQuotes(tmp);
6273 		if (tmp.trimBlanks())
6274 		    m->addParam("divert_reason",tmp);
6275 	    }
6276 	    par = hl->getParam("privacy");
6277 	    if (par) {
6278 		tmp = par->c_str();
6279 		MimeHeaderLine::delQuotes(tmp);
6280 		if (tmp.trimBlanks())
6281 		    m->addParam("divert_privacy",tmp);
6282 	    }
6283 	    par = hl->getParam("screen");
6284 	    if (par) {
6285 		tmp = par->c_str();
6286 		MimeHeaderLine::delQuotes(tmp);
6287 		if (tmp.trimBlanks())
6288 		    m->addParam("divert_screen",tmp);
6289 	    }
6290 	    par = hl->getParam("counter");
6291 	    if (par) {
6292 		tmp = par->c_str();
6293 		MimeHeaderLine::delQuotes(tmp);
6294 		if (tmp.trimBlanks())
6295 		    m->addParam("divert_counter",tmp);
6296 	    }
6297 	}
6298     }
6299 
6300     if (hl) {
6301 	URI div(*hl);
6302 	m->addParam("diverter",div.getUser());
6303 	if (div.getDescription())
6304 	    m->addParam("divertername",div.getDescription());
6305 	m->addParam("diverteruri",div);
6306     }
6307     if (line) {
6308 	// call comes from line we have registered to - trust it...
6309 	m_user = line->getUserName();
6310 	m_externalAddr = line->getLocalAddr();
6311 	m_line = *line;
6312 	m_domain = line->domain();
6313 	m->addParam(s_username,m_user);
6314 	m->addParam("domain",m_domain);
6315 	m->addParam("in_line",m_line);
6316     }
6317     else {
6318 	String user;
6319 	int age = tr->authUser(user,false,m);
6320 	DDebug(this,DebugAll,"User '%s' age %d",user.c_str(),age);
6321 	if (age >= 0) {
6322 	    if (age < 10) {
6323 		m_user = user;
6324 		m->setParam(s_username,m_user);
6325 	    }
6326 	    else
6327 		m->setParam("expired_user",user);
6328 	    m->setParam("xsip_nonce_age",String(age));
6329 	}
6330 	m_domain = m->getValue(YSTRING("domain"));
6331 	setChanParams(*m,true);
6332     }
6333 
6334     setRtpLocalAddr(m_rtpLocalAddr);
6335     MimeSdpBody* sdp = getSdpBody(ev->getMessage()->body);
6336     if (sdp) {
6337 	setMedia(plugin.parser().parse(sdp,m_rtpAddr,m_rtpMedia));
6338 	if (m_rtpMedia) {
6339 	    m_rtpForward = true;
6340 	    // guess if the call comes from behind a NAT
6341 	    bool nat = isNatBetween(m_rtpAddr,m_host);
6342 	    if (m->getBoolValue(YSTRING("nat_support"),s_auto_nat && nat)) {
6343 		TraceDebug(m_traceId,this,DebugInfo,"RTP NAT detected: private '%s' public '%s'",
6344 		    m_rtpAddr.c_str(),m_host.c_str());
6345 		m->addParam("rtp_nat_addr",m_rtpAddr);
6346 		m_rtpAddr = m_host;
6347 	    }
6348 	    m->addParam("rtp_addr",m_rtpAddr);
6349 	    putMedia(*m);
6350 	}
6351 	if (m_sdpForward) {
6352 	    const DataBlock& raw = sdp->getBody();
6353 	    String tmp((const char*)raw.data(),raw.length());
6354 	    m->addParam("sdp_raw",tmp);
6355 	    m_rtpForward = true;
6356 	}
6357 	if (m_rtpForward)
6358 	    m->addParam("rtp_forward","possible");
6359     }
6360     else if (ev->getMessage()->body)
6361 	m->addParam("media",String::boolText(false));
6362     else if (sdpAccept(ev->getMessage(),s_sdp_implicit)) {
6363 	tr->autoAck(false);
6364 	m_rtpForward = true;
6365 	m->addParam("rtp_forward","missing");
6366     }
6367     DDebug(this,DebugAll,"RTP addr '%s' [%p]",m_rtpAddr.c_str(),this);
6368     if (reason)
6369 	m->addParam("reason",reason);
6370     if (line)
6371 	line->setInboundParams(*m);
6372     m_route = m;
6373     Message* s = message("chan.startup");
6374     s->addParam("caller",m_uri.getUser());
6375     s->addParam("called",uri.getUser());
6376     if (m_user)
6377 	s->addParam(s_username,m_user);
6378     s->copyParam(*m,YSTRING("connection_id"));
6379     s->copyParam(*m,YSTRING("trace_id"));
6380     Engine::enqueue(s);
6381 }
6382 
6383 // Outgoing call constructor - in call.execute handler
YateSIPConnection(Message & msg,const String & uri,const char * target)6384 YateSIPConnection::YateSIPConnection(Message& msg, const String& uri, const char* target)
6385     : Channel(plugin,0,true),
6386       SDPSession(&plugin.parser()),
6387       YateSIPPartyHolder(this,driver(),msg.getValue(YSTRING("trace_id"))),
6388       m_tr(0), m_tr2(0), m_hungup(false), m_byebye(true), m_cancel(true),
6389       m_state(Outgoing), m_port(0), m_route(0), m_routes(0),
6390       m_authBye(false), m_autoChangeParty(true),
6391       m_checkAllowInfo(s_checkAllowInfo), m_missingAllowInfoDefVal(s_missingAllowInfoDefVal),
6392       m_honorDtmfDetect(s_honorDtmfDetect),
6393       m_referring(false), m_reInviting(ReinviteNone), m_lastRseq(0),
6394       m_revert(""), m_silent(false), m_stopOCall(msg.getBoolValue(YSTRING("stop_call"))),
6395       m_traceId(msg.getValue(YSTRING("trace_id")))
6396 {
6397     TraceDebug(m_traceId,this,DebugAll,"YateSIPConnection::YateSIPConnection(%p,'%s') [%p]",
6398 	&msg,uri.c_str(),this);
6399     setChanParams(msg);
6400     m_autoChangeParty = msg.getBoolValue(YSTRING("oautochangeparty"),
6401 	plugin.ep()->engine()->autoChangeParty());
6402     m_line = msg.getValue(YSTRING("line"));
6403     YateSIPLine* line = 0;
6404     if (m_line) {
6405 	line = plugin.findLine(m_line);
6406 	if (line)
6407 	    line->setOutboundParams(msg);
6408     }
6409     m_ipv6 = msg.getBoolValue(YSTRING("ipv6_support"),s_ipv6);
6410     setSdpDebug(this,this,m_traceId);
6411     setFormatsExtra(msg,true);
6412     m_targetid = target;
6413     setReason();
6414     m_checkAllowInfo = msg.getBoolValue(YSTRING("ocheck_allow_info"),m_checkAllowInfo);
6415     m_missingAllowInfoDefVal = msg.getBoolValue(YSTRING("omissing_allow_info"),m_missingAllowInfoDefVal);
6416     String* meths = msg.getParam("odtmfmethods");
6417     s_globalMutex.lock();
6418     if (meths)
6419 	m_dtmfMethods.set(*meths,&s_dtmfMethods);
6420     else {
6421 	m_dtmfMethods = s_dtmfMethods;
6422 	m_dtmfMethods.getDeprecatedDtmfMethod(msg,"dtmfinfo",DtmfMethods::Info,&s_warnDtmfInfoCallExecute);
6423 	m_dtmfMethods.getDeprecatedDtmfMethod(msg,"dtmfinband",DtmfMethods::Inband,&s_warnDtmfInbandCallExecute);
6424     }
6425     s_globalMutex.unlock();
6426     m_honorDtmfDetect = msg.getBoolValue(YSTRING("ohonor_dtmf_detect"),m_honorDtmfDetect);
6427     m_secure = msg.getBoolValue(YSTRING("secure"),plugin.parser().secure());
6428     setRfc2833(msg.getParam(YSTRING("rfc2833")));
6429     m_rtpForward = msg.getBoolValue(YSTRING("rtp_forward"));
6430     m_sdpForward = msg.getBoolValue(YSTRING("forward_sdp"),m_sdpForward);
6431     m_user = msg.getValue(YSTRING("user"));
6432     String tmp;
6433     bool genSips = sips(msg.getBoolValue(YSTRING("sips"),line && line->sips()));
6434     if (line) {
6435 	if (uri.find('@') < 0 && !uri.startsWith("tel:")) {
6436 	    if (!(uri.startsWith("sip:") || uri.startsWith("sips:")))
6437 		tmp = genSips ? "sips:" : "sip:";
6438 	    tmp << uri << "@";
6439 	    SocketAddr::appendAddr(tmp,line->domain());
6440 	}
6441 	m_externalAddr = line->getLocalAddr();
6442     }
6443     if (tmp.null()) {
6444 	if (!(uri.startsWith("tel:") || uri.startsWith("sip:") || uri.startsWith("sips:"))) {
6445 	    int sep = uri.find(':');
6446 	    if ((sep < 0) || ((sep > 0) && (uri.substr(sep+1).toInteger(-1) > 0)))
6447 		tmp = genSips ? "sips:" : "sip:";
6448 	}
6449 	tmp << uri;
6450     }
6451     m_uri = tmp;
6452     m_uri.parse();
6453     sips(m_uri.getProtocol() == YSTRING("sips"));
6454     if (!setParty(msg,false,"o",m_uri.getHost(),m_uri.getPort(),true) && line) {
6455 	SIPParty* party = line->party();
6456 	setParty(party);
6457 	TelEngine::destruct(party);
6458     }
6459     // No party for SIPS and we don't have transport related params
6460     // Force party creation: this will force used protocol to TLS
6461     if (!m_party && sips() && !haveTransParams(msg,"o"))
6462 	setParty(msg,true,"o",m_uri.getHost(),m_uri.getPort(),true);
6463     SIPMessage* m = new SIPMessage("INVITE",m_uri);
6464     m->dontSend(m_stopOCall);
6465     m->msgTraceId = m_traceId;
6466     setSipParty(m,line,true,msg.getValue("host"),msg.getIntValue("port"));
6467     if (!m->getParty()) {
6468 	String tmp;
6469 	if (m_partyInvalidRemote)
6470 	    tmp << ": invalid remote addr '" << m_partyInvalidRemote << "'";
6471 	TraceDebug(m_traceId,this,DebugWarn,"Could not create party for '%s'%s [%p]",m_uri.c_str(),tmp.safe(),this);
6472 	TelEngine::destruct(m);
6473 	setReason("Failed to create party",500);
6474 	msg.setParam("reason",m_reason);
6475 	msg.setParam("error","notransport");
6476 	return;
6477     }
6478     setParty(m->getParty());
6479     String connId;
6480     YateSIPTransport* trans = YOBJECT(YateSIPTransport,m->getParty());
6481     if (trans)
6482 	connId = trans->toString();
6483     updateRtpNatAddress(&msg);
6484     int maxf = msg.getIntValue(YSTRING("antiloop"),s_maxForwards);
6485     m->addHeader("Max-Forwards",String(maxf));
6486     copySipHeaders(*m,msg);
6487     m_domain = msg.getValue(YSTRING("domain"));
6488     const String* callerId = msg.getParam(YSTRING("caller"));
6489     String caller;
6490     if (callerId)
6491 	caller = *callerId;
6492     else if (line) {
6493 	caller = line->getUserName();
6494 	callerId = &caller;
6495 	m_domain = line->domain(m_domain);
6496     }
6497     String display = msg.getValue(YSTRING("callername"),(line ? line->getFullName().c_str() : (const char*)0));
6498     m_dialog.setCSeq(plugin.ep()->engine()->getSequence()->getNextCSeq() - 1);
6499     m->setSequence(m_dialog.getSequence());
6500     m->complete(plugin.ep()->engine(),
6501 	callerId ? (callerId->null() ? "anonymous" : callerId->c_str()) : (const char*)0,
6502 	m_domain,
6503 	0,
6504 	msg.getIntValue(YSTRING("xsip_flags"),-1));
6505     if (display) {
6506 	MimeHeaderLine* hl = const_cast<MimeHeaderLine*>(m->getHeader("From"));
6507 	if (hl) {
6508 	    MimeHeaderLine::addQuotes(display);
6509 	    *hl = display + " " + *hl;
6510 	}
6511     }
6512     if (msg.getParam(YSTRING("calledname"))) {
6513 	display = msg.getValue(YSTRING("calledname"));
6514 	MimeHeaderLine* hl = const_cast<MimeHeaderLine*>(m->getHeader("To"));
6515 	if (hl) {
6516 	    MimeHeaderLine::addQuotes(display);
6517 	    *hl = display + " " + *hl;
6518 	}
6519     }
6520     if (plugin.ep()->engine()->prack())
6521 	m->addHeader("Supported","100rel");
6522     m->getParty()->getAddr(m_host,m_port,false);
6523     SocketAddr::appendTo(m_address,m_host,m_port);
6524     filterDebug(m_address);
6525     m_dialog = *m;
6526     m_dialog.remoteCSeq = msg.getIntValue("remote_cseq",-1);
6527     if (s_privacy)
6528 	copyPrivacy(*m,msg);
6529 
6530     // Check if this is a transferred call
6531     String* diverter = msg.getParam(YSTRING("diverter"));
6532     if (!null(diverter)) {
6533 	const MimeHeaderLine* from = m->getHeader("From");
6534 	if (from) {
6535 	    URI fr(*from);
6536 	    URI d(fr.getProtocol(),*diverter,fr.getHost(),fr.getPort(),
6537 		msg.getValue(YSTRING("divertername"),""));
6538 	    String* reason = msg.getParam(YSTRING("divert_reason"));
6539 	    String* privacy = msg.getParam(YSTRING("divert_privacy"));
6540 	    String* screen = msg.getParam(YSTRING("divert_screen"));
6541 	    int counter = msg.getIntValue(YSTRING("divert_counter"));
6542 	    bool divert = !(TelEngine::null(reason) && TelEngine::null(privacy) && TelEngine::null(screen));
6543 	    divert = msg.getBoolValue(YSTRING("diversion"),divert);
6544 	    MimeHeaderLine* hl = new MimeHeaderLine(divert ? "Diversion" : "Referred-By",d);
6545 	    if (divert) {
6546 		if (!TelEngine::null(reason))
6547 		    hl->setParam("reason",MimeHeaderLine::quote(*reason));
6548 		if (!TelEngine::null(privacy))
6549 		    hl->setParam("privacy",MimeHeaderLine::quote(*privacy));
6550 		if (!TelEngine::null(screen))
6551 		    hl->setParam("screen",MimeHeaderLine::quote(*screen));
6552 		if ((counter > 0) && (counter < 100))
6553 		    hl->setParam("counter",String(counter));
6554 	    }
6555 	    m->addHeader(hl);
6556 	}
6557     }
6558 
6559     // add some Call-Info headers
6560     const char* info = msg.getValue(YSTRING("caller_info_uri"));
6561     if (info) {
6562 	MimeHeaderLine* hl = new MimeHeaderLine("Call-Info",info);
6563 	hl->setParam("purpose","info");
6564 	m->addHeader(hl);
6565     }
6566     info = msg.getValue(YSTRING("caller_icon_uri"));
6567     if (info) {
6568 	MimeHeaderLine* hl = new MimeHeaderLine("Call-Info",info);
6569 	hl->setParam("purpose","icon");
6570 	m->addHeader(hl);
6571     }
6572     info = msg.getValue(YSTRING("caller_card_uri"));
6573     if (info) {
6574 	MimeHeaderLine* hl = new MimeHeaderLine("Call-Info",info);
6575 	hl->setParam("purpose","card");
6576 	m->addHeader(hl);
6577     }
6578 
6579     setRtpLocalAddr(m_rtpLocalAddr,&msg);
6580     bool fwd = m_rtpForward;
6581     MimeSdpBody* sdp = createPasstroughSDP(msg);
6582     if (msg.getBoolValue(YSTRING("sdp_ack"))) {
6583 	if (sdp) {
6584 	    TelEngine::destruct(sdp);
6585 	    m_rtpLocalAddr = msg.getValue("rtp_addr");
6586 	}
6587 	m->addHeader(new MimeHeaderLine("Accept","application/sdp"));
6588     }
6589     else if (!sdp)
6590 	sdp = createRtpSDP(m_host,msg);
6591     m->setBody(buildSIPBody(msg,sdp));
6592     int tries = msg.getIntValue(YSTRING("xsip_trans_count"),-1);
6593     m_tr = plugin.ep()->engine()->addMessage(m,&m_autoChangeParty);
6594     if (m_tr) {
6595 	m_tr->ref();
6596 	m_tr->setUserData(this);
6597 	m_tr->setTransCount(tries);
6598 	if (!sdp && msg.getBoolValue(YSTRING("sdp_ack"),fwd)) {
6599 	    m_tr->autoAck(false);
6600 	    msg.setParam("sdp_ack",String::boolText(true));
6601 	    if (fwd)
6602 		msg.setParam("rtp_forward","accepted");
6603 	}
6604     }
6605     m->deref();
6606     setMaxcall(msg);
6607     setMaxPDD(msg);
6608     Message* s = message("chan.startup",msg);
6609     s->setParam("caller",caller);
6610     s->copyParams(msg,"callername,called,billid,callto,username");
6611     s->setParam("calledfull",m_uri.getUser());
6612     if (callid())
6613 	s->setParam("sip_callid",callid());
6614     s->addParam("connection_id",connId);
6615     Engine::enqueue(s);
6616 }
6617 
~YateSIPConnection()6618 YateSIPConnection::~YateSIPConnection()
6619 {
6620     TraceDebug(m_traceId,this,DebugAll,"YateSIPConnection::~YateSIPConnection() [%p]",this);
6621 }
6622 
destroyed()6623 void YateSIPConnection::destroyed()
6624 {
6625     DDebug(this,DebugAll,"YateSIPConnection::destroyed() [%p]",this);
6626     hangup();
6627     clearTransaction();
6628     TelEngine::destruct(m_route);
6629     TelEngine::destruct(m_routes);
6630     Channel::destroyed();
6631 }
6632 
startRouter()6633 void YateSIPConnection::startRouter()
6634 {
6635     Message* m = m_route;
6636     m_route = 0;
6637     Channel::startRouter(m);
6638 }
6639 
clearTransaction()6640 void YateSIPConnection::clearTransaction()
6641 {
6642     if (!(m_tr || m_tr2))
6643 	return;
6644     Lock lock(driver());
6645     if (m_tr) {
6646 	m_tr->setUserData(0);
6647 	if (m_silent)
6648 	    m_tr->setSilent();
6649 	else if (m_tr->setResponse()) {
6650 	    SIPMessage* m = new SIPMessage(m_tr->initialMessage(),m_reasonCode,
6651 		m_reason.safe("Request Terminated"));
6652 	    paramMutex().lock();
6653 	    copySipHeaders(*m,parameters(),0);
6654 	    paramMutex().unlock();
6655 	    m->setBody(buildSIPBody());
6656 	    m_tr->setResponse(m);
6657 	    TelEngine::destruct(m);
6658 	    m_byebye = false;
6659 	}
6660 	else if (m_hungup && m_tr->isIncoming() && m_dialog.localTag.null())
6661 	    m_dialog.localTag = m_tr->getDialogTag();
6662 	m_tr->deref();
6663 	m_tr = 0;
6664     }
6665     // cancel any pending reINVITE
6666     if (m_tr2) {
6667 	m_tr2->setUserData(0);
6668 	if (m_silent)
6669 	    m_tr2->setSilent();
6670 	else {
6671 	    m_tr2->autoAck(true);
6672 	    if (m_tr2->isIncoming())
6673 		m_tr2->setResponse(487);
6674 	}
6675 	m_tr2->deref();
6676 	m_tr2 = 0;
6677     }
6678 }
6679 
detachTransaction2()6680 void YateSIPConnection::detachTransaction2()
6681 {
6682     Lock lock(driver());
6683     if (m_tr2) {
6684 	DDebug(this,DebugAll,"Detaching secondary transaction %p [%p]",m_tr2,this);
6685 	m_tr2->setUserData(0);
6686 	m_tr2->deref();
6687 	m_tr2 = 0;
6688 	if (m_reInviting != ReinvitePending)
6689 	    m_reInviting = ReinviteNone;
6690     }
6691     startPendingUpdate();
6692 }
6693 
hangup()6694 void YateSIPConnection::hangup()
6695 {
6696     if (m_hungup)
6697 	return;
6698     Lock mylock(driver());
6699     if (m_hungup)
6700 	return;
6701     m_hungup = true;
6702     const char* error = lookup(m_reasonCode,dict_errors);
6703     TraceDebug(m_traceId,this,DebugAll,"YateSIPConnection::hangup() state=%d trans=%p error='%s' code=%d reason='%s' [%p]",
6704 	m_state,m_tr,error,m_reasonCode,m_reason.c_str(),this);
6705     setMedia(0);
6706     String res = m_reason;
6707     mylock.drop();
6708     Message* m = message("chan.hangup");
6709     if (res)
6710 	m->setParam("reason",res);
6711     Engine::enqueue(m);
6712     if (!error)
6713 	error = res.c_str();
6714     bool sendBye = !m_silent;
6715     switch (m_state) {
6716 	case Cleared:
6717 	    clearTransaction();
6718 	    disconnect(error,parameters());
6719 	    return;
6720 	case Incoming:
6721 	    if (m_tr) {
6722 		clearTransaction();
6723 		disconnect(error,parameters());
6724 		return;
6725 	    }
6726 	    break;
6727 	case Outgoing:
6728 	case Ringing:
6729 	    if (!m_silent && !m_stopOCall && m_cancel && m_tr) {
6730 		SIPMessage* m = new SIPMessage("CANCEL",m_uri);
6731 		setSipParty(m,plugin.findLine(m_line),true,m_host,m_port);
6732 		if (!m->getParty())
6733 		    TraceDebug(m_traceId,this,DebugWarn,"Could not create party for '%s' [%p]",
6734 			SocketAddr::appendTo(m_host,m_port).c_str(),this);
6735 		else {
6736 		    const SIPMessage* i = m_tr->initialMessage();
6737 		    m->copyHeader(i,"Via");
6738 		    m->copyHeader(i,"From");
6739 		    m->copyHeader(i,"To");
6740 		    m->copyHeader(i,"Call-ID");
6741 		    m->setCSeq(i->getCSeq());
6742 		    if (res == YSTRING("pickup")) {
6743 			MimeHeaderLine* hl = new MimeHeaderLine("Reason","SIP");
6744 			hl->setParam("cause","200");
6745 			hl->setParam("text","\"Call completed elsewhere\"");
6746 			m->addHeader(hl);
6747 		    }
6748 		    m->setBody(buildSIPBody());
6749 		    if (plugin.ep()->engine()->addMessage(m,&m_autoChangeParty) && !s_preventive_bye)
6750 			sendBye = false;
6751 		}
6752 		m->deref();
6753 	    }
6754 	    break;
6755     }
6756     clearTransaction();
6757     m_state = Cleared;
6758 
6759     if (sendBye && m_byebye && m_dialog.localTag && m_dialog.remoteTag) {
6760 	SIPMessage* m = createDlgMsg("BYE");
6761 	if (m) {
6762 	    if (res) {
6763 		// FIXME: add SIP and Q.850 cause codes, set the proper reason
6764 		MimeHeaderLine* hl = new MimeHeaderLine("Reason","SIP");
6765 		if ((m_reasonCode >= 300) && (m_reasonCode <= 699) && (m_reasonCode != 487))
6766 		    hl->setParam("cause",String(m_reasonCode));
6767 		hl->setParam("text",MimeHeaderLine::quote(res));
6768 		m->addHeader(hl);
6769 	    }
6770 	    paramMutex().lock();
6771 	    const char* stats = parameters().getValue(YSTRING("rtp_stats"));
6772 	    if (stats)
6773 		m->addHeader("P-RTP-Stat",stats);
6774 	    copySipHeaders(*m,parameters(),0);
6775 	    copySipBody(*m,parameters());
6776 	    paramMutex().unlock();
6777 	    m->setBody(buildSIPBody());
6778 	    plugin.ep()->engine()->addMessage(m,&m_autoChangeParty);
6779 	    m->deref();
6780 	}
6781     }
6782     m_byebye = false;
6783     disconnect(error,parameters());
6784 }
6785 
6786 // Creates a new message in an existing dialog
createDlgMsg(const char * method,const char * uri)6787 SIPMessage* YateSIPConnection::createDlgMsg(const char* method, const char* uri)
6788 {
6789     if (!uri)
6790 	uri = m_uri;
6791     SIPMessage* m = new SIPMessage(method,uri);
6792     m->addRoutes(m_routes);
6793     setSipParty(m,plugin.findLine(m_line),true,m_host,m_port);
6794     if (!m->getParty()) {
6795 	TraceDebug(m_traceId,this,DebugWarn,"Could not create party for '%s' [%p]",
6796 	    SocketAddr::appendTo(m_host,m_port).c_str(),this);
6797 	m->destruct();
6798 	return 0;
6799     }
6800     if (m_dialog.getLastCSeq() < 0)
6801 	m_dialog.setCSeq(plugin.ep()->engine()->getNextCSeq() - 1);
6802     m->setSequence(m_dialog.getSequence());
6803     m->addHeader("Call-ID",callid());
6804     String tmp;
6805     tmp << "<" << m_dialog.localURI << ">";
6806     MimeHeaderLine* hl = new MimeHeaderLine("From",tmp);
6807     tmp = m_dialog.localTag;
6808     if (tmp.null() && m_tr)
6809 	tmp = m_tr->getDialogTag();
6810     if (tmp)
6811 	hl->setParam("tag",tmp);
6812     m->addHeader(hl);
6813     tmp.clear();
6814     tmp << "<" << m_dialog.remoteURI << ">";
6815     hl = new MimeHeaderLine("To",tmp);
6816     tmp = m_dialog.remoteTag;
6817     if (tmp.null() && m_tr)
6818 	tmp = m_tr->getDialogTag();
6819     if (tmp)
6820 	hl->setParam("tag",tmp);
6821     m->addHeader(hl);
6822     return m;
6823 }
6824 
6825 // Update the dialog from received target refresh message
updateTarget(const SIPMessage * msg,bool force,bool chgParty)6826 void YateSIPConnection::updateTarget(const SIPMessage* msg, bool force, bool chgParty)
6827 {
6828     if (!(s_update_target || force))
6829 	return;
6830     if (!msg)
6831 	return;
6832     const MimeHeaderLine* co = msg->getHeader("Contact");
6833     if (co) {
6834 	String old = m_uri;
6835 	m_uri = *co;
6836 	m_uri.parse();
6837 	m_dialog.remoteURI = m_uri;
6838 	if (old != m_uri)
6839 	    TraceDebug(m_traceId,this,DebugInfo,"Dialog URI changed '%s' -> '%s' [%p]",old.c_str(),m_uri.c_str(),this);
6840     }
6841     if (!(m_autoChangeParty && chgParty))
6842 	return;
6843     SIPParty* party = msg->getParty();
6844     if (party) {
6845 	party->getAddr(m_host,m_port,false);
6846 	setParty(party);
6847 	m_address.clear();
6848 	SocketAddr::appendTo(m_address,m_host,m_port);
6849     }
6850 }
6851 
6852 // Emit a call.update to notify cdrbuild of callid dialog tags change
emitUpdate()6853 void YateSIPConnection::emitUpdate()
6854 {
6855     Message* m = message("call.update");
6856     m->addParam("operation","cdrbuild");
6857     Engine::enqueue(m);
6858 }
6859 
6860 // Emit a PRovisional ACK if enabled in the engine, return true to handle them
emitPRACK(const SIPMessage * msg)6861 bool YateSIPConnection::emitPRACK(const SIPMessage* msg)
6862 {
6863     if (!(msg && msg->isAnswer() && (msg->code > 100) && (msg->code < 200)))
6864 	return false;
6865     if (!plugin.ep()->engine()->prack())
6866 	return true;
6867     const MimeHeaderLine* rs = msg->getHeader("RSeq");
6868     const MimeHeaderLine* cs = msg->getHeader("CSeq");
6869     if (!(rs && cs))
6870 	return true;
6871     int seq = rs->toInteger(0,10);
6872     // return false only if we already seen this provisional response
6873     if (seq == m_lastRseq)
6874 	return false;
6875     if (seq < m_lastRseq) {
6876 	TraceDebug(m_traceId,this,DebugMild,"Not sending PRACK for RSeq %d < %d [%p]",
6877 	    seq,m_lastRseq,this);
6878 	return false;
6879     }
6880     String tmp;
6881     const MimeHeaderLine* co = msg->getHeader("Contact");
6882     if (co) {
6883 	tmp = *co;
6884 	static const Regexp r("^[^<]*<\\([^>]*\\)>.*$");
6885 	if (tmp.matches(r))
6886 	    tmp = tmp.matchString(1);
6887     }
6888     SIPMessage* m = createDlgMsg("PRACK",tmp);
6889     if (!m)
6890 	return true;
6891     m_lastRseq = seq;
6892     tmp = *rs;
6893     tmp << " " << *cs;
6894     m->addHeader("RAck",tmp);
6895     plugin.ep()->engine()->addMessage(m,&m_autoChangeParty);
6896     m->deref();
6897     return true;
6898 }
6899 
6900 // Creates a SDP for provisional (1xx) messages
createProvisionalSDP(Message & msg)6901 MimeSdpBody* YateSIPConnection::createProvisionalSDP(Message& msg)
6902 {
6903     // check if we are forwarding RTP or our peer can source at least audio data
6904     if (!msg.getBoolValue(YSTRING("earlymedia"),m_rtpForward
6905 	    || (getPeer() && getPeer()->getSource())))
6906 	return 0;
6907     if (m_rtpForward)
6908 	return createPasstroughSDP(msg);
6909     if (m_rtpAddr.null())
6910 	return 0;
6911     if (s_1xx_formats)
6912 	updateFormats(msg);
6913     return createRtpSDP(true);
6914 }
6915 
6916 // Build and populate a chan.rtp message
buildChanRtp(RefObject * context)6917 Message* YateSIPConnection::buildChanRtp(RefObject* context)
6918 {
6919     Message* m = new Message("chan.rtp");
6920     if (context)
6921 	m->userData(context);
6922     else {
6923 	complete(*m,true);
6924 	m->addParam("call_direction",direction());
6925 	m->addParam("call_address",address());
6926 	putStatus(*m,"call_status");
6927 	m->addParam("call_billid",billid());
6928 	m->userData(static_cast<CallEndpoint*>(this));
6929     }
6930     return m;
6931 }
6932 
6933 // Media changed notification, reimplemented from SDPSession
mediaChanged(const SDPMedia & media)6934 void YateSIPConnection::mediaChanged(const SDPMedia& media)
6935 {
6936     SDPSession::mediaChanged(media);
6937     if (media.id() && media.transport()) {
6938 	Message m("chan.rtp");
6939 	m.addParam("rtpid",media.id());
6940 	m.addParam("media",media);
6941 	m.addParam("transport",media.transport());
6942 	m.addParam("terminate",String::boolText(true));
6943 	m.addParam("call_direction",direction());
6944 	m.addParam("call_address",address());
6945 	putStatus(m,"call_status");
6946 	m.addParam("call_billid",billid());
6947 	if (m_traceId)
6948 	  m.addParam("trace_id",m_traceId);
6949 	Engine::dispatch(m);
6950 	const char* stats = m.getValue(YSTRING("stats"));
6951 	if (stats) {
6952 	    paramMutex().lock();
6953 	    parameters().setParam("rtp_stats"+media.suffix(),stats);
6954 	    paramMutex().unlock();
6955 	}
6956     }
6957     // Clear the data endpoint, will be rebuilt later if required
6958     clearEndpoint(media);
6959 }
6960 
dispatchingRtp(Message * & msg,SDPMedia * media)6961 void YateSIPConnection::dispatchingRtp(Message*& msg, SDPMedia* media)
6962 {
6963     if (!(msg && media))
6964 	return;
6965     if (media->formats() || !(media->isAudio() || media->isVideo()))
6966 	return;
6967     TraceDebug(m_traceId,this,DebugInfo,"Not sending %s for empty media %s [%p]",
6968 	msg->c_str(),media->c_str(),this);
6969     TelEngine::destruct(msg);
6970 }
6971 
6972 // Process SIP events belonging to this connection
process(SIPEvent * ev)6973 bool YateSIPConnection::process(SIPEvent* ev)
6974 {
6975     const SIPMessage* msg = ev->getMessage();
6976     SIPTransaction* tr = ev->getTransaction();
6977     int code = tr->getResponseCode();
6978     DDebug(this,DebugInfo,"YateSIPConnection::process(%p) %s %s code=%d [%p]",
6979 	ev,ev->isActive() ? "active" : "inactive",
6980 	SIPTransaction::stateName(ev->getState()),code,this);
6981 #ifdef XDEBUG
6982     if (msg)
6983 	TraceDebug(m_traceId,this,DebugInfo,"Message %p '%s' %s %s code=%d body=%p",
6984 	    msg,msg->method.c_str(),
6985 	    msg->isOutgoing() ? "outgoing" : "incoming",
6986 	    msg->isAnswer() ? "answer" : "request",
6987 	    msg->code,msg->body);
6988 #endif
6989 
6990     // Change party
6991     if (m_autoChangeParty && ev->isActive() && msg && !msg->isOutgoing())
6992 	setPartyChanged(msg->getParty());
6993 
6994     Lock mylock(driver());
6995     if (tr == m_tr2) {
6996 	mylock.drop();
6997 	return processTransaction2(ev,msg,code);
6998     }
6999 
7000     bool updateTags = true;
7001     SIPDialog oldDlg(m_dialog);
7002     m_dialog = *tr->recentMessage();
7003     mylock.drop();
7004 
7005     if (msg && !msg->isOutgoing() && msg->isAnswer() && (code >= 300) && (code <= 699)) {
7006 	updateTags = false;
7007 	m_cancel = false;
7008 	m_byebye = false;
7009 	setReason(msg->reason,code,driver());
7010 	paramMutex().lock();
7011 	parameters().clearParams();
7012 	parameters().addParam("cause_sip",String(code));
7013 	parameters().addParam("reason_sip",msg->reason);
7014 	if (msg->body) {
7015 	    paramMutex().unlock();
7016 	    Message tmp("isup.decode");
7017 	    bool ok = decodeIsupBody(tmp,msg->body);
7018 	    ok = copySipBody(tmp,msg->body) || ok;
7019 	    paramMutex().lock();
7020 	    if (ok)
7021 		parameters().copyParams(tmp);
7022 	}
7023 	copySipHeaders(parameters(),*msg,true,static_cast<const YateSIPEngine*>(tr->getEngine())->foreignAuth());
7024 	if (code < 400) {
7025 	    // this is a redirect, it should provide a Contact and possibly a Diversion
7026 	    const MimeHeaderLine* hl = msg->getHeader("Contact");
7027 	    if (hl) {
7028 		parameters().addParam("redirect",String::boolText(true));
7029 		URI uri(*hl);
7030 		parameters().addParam("called",uri.getUser());
7031 		if (uri.getDescription())
7032 		    parameters().addParam("calledname",uri.getDescription());
7033 		parameters().addParam("calleduri",uri);
7034 		hl = msg->getHeader("Diversion");
7035 		if (hl) {
7036 		    uri = *hl;
7037 		    parameters().addParam("diverter",uri.getUser());
7038 		    if (uri.getDescription())
7039 			parameters().addParam("divertername",uri.getDescription());
7040 		    parameters().addParam("diverteruri",uri);
7041 		    String tmp = hl->getParam("reason");
7042 		    MimeHeaderLine::delQuotes(tmp);
7043 		    if (tmp.trimBlanks())
7044 			parameters().addParam("divert_reason",tmp);
7045 		    tmp = hl->getParam("privacy");
7046 		    MimeHeaderLine::delQuotes(tmp);
7047 		    if (tmp.trimBlanks())
7048 			parameters().addParam("divert_privacy",tmp);
7049 		    tmp = hl->getParam("screen");
7050 		    MimeHeaderLine::delQuotes(tmp);
7051 		    if (tmp.trimBlanks())
7052 			parameters().addParam("divert_screen",tmp);
7053 		    tmp = hl->getParam("counter");
7054 		    MimeHeaderLine::delQuotes(tmp);
7055 		    if (tmp.trimBlanks())
7056 			parameters().addParam("divert_counter",tmp);
7057 		}
7058 	    }
7059 	    else if (code != 387)
7060 		TraceDebug(m_traceId,this,DebugMild,"Received %d redirect without Contact [%p]",code,this);
7061 	}
7062 	paramMutex().unlock();
7063 	hangup();
7064     }
7065     else if (code == 408) {
7066 	// Proxy timeout does not provide an answer message
7067 	updateTags = false;
7068 	if (m_dialog.remoteTag.null())
7069 	    m_byebye = false;
7070 	paramMutex().lock();
7071 	parameters().setParam("cause_sip","408");
7072 	parameters().clearParam("reason_sip");
7073 	paramMutex().unlock();
7074 	setReason("Request Timeout",code,driver());
7075 	hangup();
7076     }
7077     else if (!m_hungup && code >= 100) {
7078 	Lock lck(paramMutex());
7079 	parameters().setParam("cause_sip",String(code));
7080 	if (msg && msg->reason)
7081 	    parameters().setParam("reason_sip",msg->reason);
7082 	else
7083 	    parameters().clearParam("reason_sip");
7084     }
7085 
7086     // Only update channels' callid if dialog tags change
7087     if (updateTags) {
7088 	Lock lock(driver());
7089 	updateTags = (oldDlg |= m_dialog);
7090     }
7091 
7092     if (!ev->isActive()) {
7093 	Lock lock(driver());
7094 	if (m_tr) {
7095 	    DDebug(this,DebugInfo,"YateSIPConnection clearing transaction %p [%p]",
7096 		m_tr,this);
7097 	    m_tr->setUserData(0);
7098 	    m_tr->deref();
7099 	    m_tr = 0;
7100 	}
7101 	if (m_state != Established) {
7102 	    lock.drop();
7103 	    hangup();
7104 	}
7105 	else if (s_ack_required && (code == 408)) {
7106 	    // call was established but we didn't got the ACK
7107 	    setReason("Not received ACK",code);
7108 	    lock.drop();
7109 	    hangup();
7110 	}
7111 	else {
7112 	    if (updateTags)
7113 		emitUpdate();
7114 	    startPendingUpdate();
7115 	}
7116 	return false;
7117     }
7118     if (!msg || msg->isOutgoing()) {
7119 	if (updateTags)
7120 	    emitUpdate();
7121 	return false;
7122     }
7123     String natAddr;
7124     MimeSdpBody* sdp = getSdpBody(msg->body);
7125     if (sdp) {
7126 	DDebug(this,DebugInfo,"YateSIPConnection got SDP [%p]",this);
7127 	setMedia(plugin.parser().parse(sdp,m_rtpAddr,m_rtpMedia));
7128 	// guess if the call comes from behind a NAT
7129 	if (s_auto_nat && isNatBetween(m_rtpAddr,m_host)) {
7130 	    TraceDebug(m_traceId,this,DebugInfo,"RTP NAT detected: private '%s' public '%s'",
7131 		m_rtpAddr.c_str(),m_host.c_str());
7132 	    natAddr = m_rtpAddr;
7133 	    m_rtpAddr = m_host;
7134 	}
7135 	DDebug(this,DebugAll,"RTP addr '%s' [%p]",m_rtpAddr.c_str(),this);
7136 	if (m_rtpForward && plugin.parser().sdpForward() && !(msg->isACK() || tr->autoAck()))
7137 	    m_sdpForward = true;
7138     }
7139     if ((!m_routes) && msg->isAnswer() && (msg->code > 100) && (msg->code < 300))
7140 	m_routes = msg->getRoutes();
7141 
7142     if (msg->isAnswer() && m_externalAddr.null() && m_line) {
7143 	// see if we should detect our external address
7144 	const YateSIPLine* line = plugin.findLine(m_line);
7145 	if (line && line->localDetect()) {
7146 	    const MimeHeaderLine* hl = msg->getHeader("Via");
7147 	    if (hl) {
7148 		const NamedString* par = hl->getParam("received");
7149 		if (par && *par) {
7150 		    getAddrCheckIPv6(m_externalAddr,*par);
7151 		    TraceDebug(m_traceId,this,DebugInfo,"Detected local address '%s' [%p]",
7152 			m_externalAddr.c_str(),this);
7153 		}
7154 	    }
7155 	}
7156     }
7157 
7158     if (msg->isAnswer() && ((msg->code / 100) == 2)) {
7159 	if (m_checkAllowInfo) {
7160 	    if (m_dtmfMethods.hasMethod(DtmfMethods::Info) && !infoAllowed(msg))
7161 		m_dtmfMethods.reset(DtmfMethods::Info);
7162 	}
7163 	updateTags = false;
7164 	m_cancel = false;
7165 	Lock lock(driver());
7166 	updateTarget(msg,true,s_changeParty2xx);
7167 	const SIPMessage* ack = m_tr ? m_tr->latestMessage() : 0;
7168 	if (ack && ack->isACK()) {
7169 	    DDebug(this,DebugInfo,"YateSIPConnection clearing answered transaction %p [%p]",
7170 		m_tr,this);
7171 	    m_tr->setUserData(0);
7172 	    m_tr->deref();
7173 	    m_tr = 0;
7174 	}
7175 	setReason("",0);
7176 	lock.drop();
7177 	setStatus("answered",Established);
7178 	Message *m = message("call.answered");
7179 	copySipHeaders(*m,*msg);
7180 	decodeIsupBody(*m,msg->body);
7181 	copySipBody(*m,msg->body);
7182 	addRtpParams(*m,natAddr,msg->body,false,m_sdpForward);
7183 	Engine::enqueue(m);
7184 	if (tr->autoAck())
7185 	    startPendingUpdate();
7186 	else if (!m_rtpForward) {
7187 	    MimeSdpBody* sdp = m_rtpMedia ? createRtpSDP(true) : 0;
7188 	    TraceDebug(m_traceId,this,DebugNote,"Sending ACK %s SDP now since RTP is not forwarded [%p]",
7189 		(sdp ? "with" : "without"),this);
7190 	    tr->setAcknowledge(sdp);
7191 	    startPendingUpdate();
7192 	}
7193     }
7194     if (emitPRACK(msg)) {
7195 	if (s_multi_ringing || (m_state < Ringing)) {
7196 	    const char* name = "call.progress";
7197 	    const char* reason = 0;
7198 	    switch (msg->code) {
7199 		case 180:
7200 		    updateTags = false;
7201 		    name = "call.ringing";
7202 		    setStatus("ringing",Ringing);
7203 		    break;
7204 		case 181:
7205 		    reason = "forwarded";
7206 		    setStatus("progressing");
7207 		    break;
7208 		case 182:
7209 		    reason = "queued";
7210 		    setStatus("progressing");
7211 		    break;
7212 		case 183:
7213 		    setStatus("progressing");
7214 		    break;
7215 		// for all others emit a call.progress but don't change status
7216 	    }
7217 	    if (name) {
7218 		Message* m = message(name);
7219 		copySipHeaders(*m,*msg);
7220 		decodeIsupBody(*m,msg->body);
7221 		copySipBody(*m,msg->body);
7222 		if (reason)
7223 		    m->addParam("reason",reason);
7224 		addRtpParams(*m,natAddr,msg->body,false,m_sdpForward);
7225 		if (m_rtpAddr.null())
7226 		    m->addParam("earlymedia","false");
7227 		Engine::enqueue(m);
7228 	    }
7229 	}
7230     }
7231     if (updateTags)
7232 	emitUpdate();
7233     if (msg->isACK()) {
7234 	DDebug(this,DebugInfo,"YateSIPConnection got ACK [%p]",this);
7235 	if (!tr->autoAck()) {
7236 	    Message* m = message("call.update");
7237 	    m->addParam("operation","notify");
7238 	    if (sdp)
7239 		addRtpParams(*m,natAddr,sdp,false,m_sdpForward);
7240 	    else
7241 		m->addParam("rtp_forward",String::boolText(m_rtpForward));
7242 	    Engine::enqueue(m);
7243 	    startPendingUpdate();
7244 	}
7245 	startRtp();
7246     }
7247     return false;
7248 }
7249 
7250 // Process secondary transaction (reINVITE)  belonging to this connection
processTransaction2(SIPEvent * ev,const SIPMessage * msg,int code)7251 bool YateSIPConnection::processTransaction2(SIPEvent* ev, const SIPMessage* msg, int code)
7252 {
7253     Lock mylock(driver());
7254     if (ev->getState() == SIPTransaction::Cleared) {
7255 	bool fatal = (m_reInviting == ReinviteRequest);
7256 	detachTransaction2();
7257 	if (fatal) {
7258 	    setReason("Request Timeout",408);
7259 	    mylock.drop();
7260 	    hangup();
7261 	    mylock.acquire(driver());
7262 	}
7263 	else {
7264 	    Message* m = message("call.update");
7265 	    m->addParam("operation","reject");
7266 	    m->addParam("error","timeout");
7267 	    Engine::enqueue(m);
7268 	}
7269 	m_revert.clearParams();
7270 	return false;
7271     }
7272     if (!msg || msg->isOutgoing())
7273 	return false;
7274 
7275     if ((m_reInviting == ReinviteReceived) && msg->isACK() && m_tr2 && !m_tr2->autoAck()) {
7276 	String natAddr;
7277 	MimeSdpBody* sdp = getSdpBody(msg->body);
7278 	DDebug(this,DebugInfo,"YateSIPConnection got reINVITE ACK %s SDP [%p]",
7279 	    (sdp ? "with" : "without"), this);
7280 	if (sdp) {
7281 	    setMedia(plugin.parser().parse(sdp,m_rtpAddr,m_rtpMedia));
7282 	    // guess if the call comes from behind a NAT
7283 	    if (s_auto_nat && isNatBetween(m_rtpAddr,m_host)) {
7284 		TraceDebug(m_traceId,this,DebugInfo,"RTP NAT detected: private '%s' public '%s'",
7285 		    m_rtpAddr.c_str(),m_host.c_str());
7286 		natAddr = m_rtpAddr;
7287 		m_rtpAddr = m_host;
7288 	    }
7289 	    DDebug(this,DebugAll,"RTP addr '%s' [%p]",m_rtpAddr.c_str(),this);
7290 	}
7291 	detachTransaction2();
7292 
7293 	Message* m = message("call.update");
7294 	m->addParam("operation","notify");
7295 	if (sdp)
7296 	    addRtpParams(*m,natAddr,sdp,false,m_sdpForward);
7297 	else
7298 	    m->addParam("rtp_forward",String::boolText(m_rtpForward));
7299 	Engine::enqueue(m);
7300     }
7301 
7302     if ((code < 200) || !msg->isAnswer())
7303 	return false;
7304 
7305     if (m_reInviting == ReinviteRequest) {
7306 	detachTransaction2();
7307 	// we emitted a client reINVITE, now we are forced to deal with it
7308 	if (code < 300) {
7309 	    MimeSdpBody* sdp = getSdpBody(msg->body);
7310 	    while (sdp) {
7311 		String addr;
7312 		ObjList* lst = plugin.parser().parse(sdp,addr,0,String::empty(),m_rtpForward);
7313 		if (!lst)
7314 		    break;
7315 		if ((addr == m_rtpAddr) || isNatBetween(addr,m_host)) {
7316 		    ObjList* l = m_rtpMedia;
7317 		    for (; l; l = l->next()) {
7318 			SDPMedia* m = static_cast<SDPMedia*>(l->get());
7319 			if (!m)
7320 			    continue;
7321 			SDPMedia* m2 = static_cast<SDPMedia*>((*lst)[*m]);
7322 			if (!m2)
7323 			    continue;
7324 			// both old and new media exist, compare ports
7325 			if (m->remotePort() != m2->remotePort()) {
7326 			    DDebug(this,DebugWarn,"Port for '%s' changed: '%s' -> '%s' [%p]",
7327 				m->c_str(),m->remotePort().c_str(),
7328 				m2->remotePort().c_str(),this);
7329 			    TelEngine::destruct(lst);
7330 			    break;
7331 			}
7332 		    }
7333 		    if (lst) {
7334 			setMedia(lst);
7335 			return false;
7336 		    }
7337 		}
7338 		TelEngine::destruct(lst);
7339 		setReason("Media information changed during reINVITE",415);
7340 		mylock.drop();
7341 		hangup();
7342 		return false;
7343 	    }
7344 	    setReason("Missing media information",415);
7345 	}
7346 	else
7347 	    setReason(msg->reason,code);
7348 	mylock.drop();
7349 	hangup();
7350 	return false;
7351     }
7352 
7353     Message* m = message("call.update");
7354     decodeIsupBody(*m,msg->body);
7355     copySipBody(*m,msg->body);
7356     copySipHeaders(*m,*msg);
7357     if (code < 300) {
7358 	m->addParam("operation","notify");
7359 	String natAddr;
7360 	MimeSdpBody* sdp = getSdpBody(msg->body);
7361 	if (sdp) {
7362 	    DDebug(this,DebugInfo,"YateSIPConnection got reINVITE SDP [%p]",this);
7363 	    setMedia(plugin.parser().parse(sdp,m_rtpAddr,m_rtpMedia,String::empty(),
7364 		m_rtpForward));
7365 	    // guess if the call comes from behind a NAT
7366 	    if (s_auto_nat && isNatBetween(m_rtpAddr,m_host)) {
7367 		TraceDebug(m_traceId,this,DebugInfo,"RTP NAT detected: private '%s' public '%s'",
7368 		    m_rtpAddr.c_str(),m_host.c_str());
7369 		natAddr = m_rtpAddr;
7370 		m_rtpAddr = m_host;
7371 	    }
7372 	    DDebug(this,DebugAll,"RTP addr '%s' [%p]",m_rtpAddr.c_str(),this);
7373 	    if (m_rtpForward) {
7374 		// drop any local RTP we might have before
7375 		m_mediaStatus = m_rtpAddr.null() ? MediaMuted : MediaMissing;
7376 		m_rtpLocalAddr.clear();
7377 		clearEndpoint();
7378 	    }
7379 	}
7380 	bool added = false;
7381 	if (!m_rtpForward || m_rtpAddr)
7382 	    added = addRtpParams(*m,natAddr,sdp);
7383 	else
7384 	    added = addRtpParams(*m,natAddr,sdp,false,true);
7385 	if (!added)
7386 	    addSdpParams(*m,sdp);
7387     }
7388     else {
7389 	m->addParam("operation","reject");
7390 	m->addParam("error",lookup(code,dict_errors,"failure"));
7391 	m->addParam("reason",msg->reason);
7392 	if (ReinviteNone == m_reInviting && !m_rtpForward && m_revert.count()) {
7393 	    // we already changed our media so try to revert
7394 	    detachTransaction2();
7395 	    if (startClientReInvite(m_revert,false)) {
7396 		m_revert.clearParams();
7397 		Engine::enqueue(m);
7398 		return false;
7399 	    }
7400 	}
7401     }
7402     if (!m_tr2 || m_tr2->autoAck())
7403 	detachTransaction2();
7404     m_revert.clearParams();
7405     mylock.drop();
7406     Engine::enqueue(m);
7407     return false;
7408 }
7409 
reInvite(SIPTransaction * t)7410 void YateSIPConnection::reInvite(SIPTransaction* t)
7411 {
7412     if (!checkUser(t))
7413 	return;
7414     DDebug(this,DebugAll,"YateSIPConnection::reInvite(%p) [%p]",t,this);
7415     Lock mylock(driver());
7416     int invite = m_reInviting;
7417     if (m_tr || m_tr2 || (invite == ReinviteRequest) || (invite == ReinviteReceived)) {
7418 	// another request pending - refuse this one
7419 	t->setResponse(491);
7420 	return;
7421     }
7422     if (m_hungup) {
7423 	t->setResponse(481);
7424 	return;
7425     }
7426     m_reInviting = ReinviteReceived;
7427     mylock.drop();
7428     m_dialog.adjustCSeq(t->initialMessage());
7429     // Change party
7430     if (m_autoChangeParty && t->initialMessage() && !t->initialMessage()->isOutgoing())
7431 	setPartyChanged(t->initialMessage()->getParty());
7432 
7433     MimeSdpBody* sdp = getSdpBody(t->initialMessage()->body);
7434     if (sdp || (m_rtpForward && sdpAccept(t->initialMessage(),true))) {
7435 	if (m_rtpForward ? reInviteForward(t,sdp,invite) : reInviteProxy(t,sdp,invite))
7436 	    return;
7437     }
7438     m_reInviting = invite;
7439     if (s_refresh_nosdp && !sdp) {
7440 	// be permissive, accept session refresh with no SDP
7441 	updateTarget(t->initialMessage());
7442 	SIPMessage* m = new SIPMessage(t->initialMessage(),200);
7443 	// if required provide our own media offer
7444 	if (!m_rtpForward)
7445 	    m->setBody(createSDP());
7446 	t->setResponse(m);
7447 	m->deref();
7448 	return;
7449     }
7450     t->setResponse(488);
7451 }
7452 
reInviteForward(SIPTransaction * t,MimeSdpBody * sdp,int invite)7453 bool YateSIPConnection::reInviteForward(SIPTransaction* t, MimeSdpBody* sdp, int invite)
7454 {
7455     String addr;
7456     String natAddr;
7457     ObjList* lst = 0;
7458     if (sdp) {
7459 	lst = plugin.parser().parse(sdp,addr,0,String::empty(),true);
7460 	if (!lst)
7461 	    return false;
7462 	// guess if the call comes from behind a NAT
7463 	if (s_auto_nat && isNatBetween(addr,m_host)) {
7464 	    TraceDebug(m_traceId,this,DebugInfo,"RTP NAT detected: private '%s' public '%s'",
7465 		addr.c_str(),m_host.c_str());
7466 	    natAddr = addr;
7467 	    addr = m_host;
7468 	}
7469 	TraceDebug(m_traceId,this,DebugAll,"reINVITE RTP addr '%s'",addr.c_str());
7470     }
7471 
7472     // for pass-trough RTP we need support from our peer
7473     Message msg("call.update");
7474     complete(msg);
7475     if (s_update_target) {
7476 	bool addrChg = false;
7477 	SIPParty* party = t->initialMessage()->getParty();
7478 	if (party) {
7479 	    String addr;
7480 	    party->appendAddr(addr,false);
7481 	    if (addr != m_address) {
7482 		msg.setParam("address",addr);
7483 		msg.addParam("address_old",m_address);
7484 		addrChg = true;
7485 	    }
7486 	}
7487 	msg.addParam("address_changed",String::boolText(addrChg));
7488 	bool contactChg = false;
7489 	const MimeHeaderLine* co = t->initialMessage()->getHeader("Contact");
7490 	if (co) {
7491 	    URI uri(*co);
7492 	    uri.parse();
7493 	    if (uri != m_uri) {
7494 		msg.addParam("contact",uri);
7495 		msg.addParam("contact_old",m_uri);
7496 		contactChg = true;
7497 	    }
7498 	}
7499 	msg.addParam("contact_changed",String::boolText(contactChg));
7500     }
7501     msg.addParam("operation","request");
7502     copySipHeaders(msg,*t->initialMessage());
7503     msg.addParam("rtp_forward","yes");
7504     msg.addParam("rtp_addr",addr);
7505     if (natAddr)
7506 	msg.addParam("rtp_nat_addr",natAddr);
7507     putMedia(msg,lst);
7508     TelEngine::destruct(lst);
7509     if (sdp)
7510 	addSdpParams(msg,sdp);
7511     else {
7512 	t->autoAck(false);
7513 	msg.addParam("sdp_ack",String::boolText(true));
7514     }
7515     bool ok = Engine::dispatch(msg) && (msg.retValue() != YSTRING("error")) && (msg.retValue() != "-");
7516     Lock mylock(driver());
7517     // if peer doesn't support updates fail the reINVITE
7518     if (!ok) {
7519 	t->setResponse(msg.getIntValue(YSTRING("error"),dict_errors,488),msg.getValue(YSTRING("reason")));
7520 	m_reInviting = invite;
7521     }
7522     else if (m_tr2) {
7523 	// ouch! this shouldn't have happened!
7524 	t->setResponse(491);
7525 	// media is uncertain now so drop the call
7526 	setReason("Internal Server Error",500);
7527 	mylock.drop();
7528 	hangup();
7529     }
7530     else {
7531 	// we remember the request and leave it pending
7532 	t->ref();
7533 	t->setUserData(this);
7534 	m_tr2 = t;
7535     }
7536     return true;
7537 }
7538 
reInviteProxy(SIPTransaction * t,MimeSdpBody * sdp,int invite)7539 bool YateSIPConnection::reInviteProxy(SIPTransaction* t, MimeSdpBody* sdp, int invite)
7540 {
7541     // refuse request if we had no media at all before
7542     if (m_mediaStatus == MediaMissing)
7543 	return false;
7544     String addr;
7545     String natAddr;
7546     ObjList* lst = plugin.parser().parse(sdp,addr);
7547     if (!lst)
7548 	return false;
7549     // guess if the call comes from behind a NAT
7550     if (s_auto_nat && isNatBetween(addr,m_host)) {
7551 	TraceDebug(m_traceId,this,DebugInfo,"RTP NAT detected: private '%s' public '%s'",
7552 	    addr.c_str(),m_host.c_str());
7553 	natAddr = addr;
7554 	addr = m_host;
7555     }
7556     bool audioChg = (getMedia(YSTRING("audio")) != 0);
7557     audioChg ^= ((*lst)[YSTRING("audio")] != 0);
7558 
7559     bool keepExisting = true;
7560     Message ver("call.update");
7561     if (s_update_verify) {
7562 	complete(ver);
7563 	ver.addParam("operation","verify");
7564 	ver.addParam("method",t->initialMessage()->method);
7565 	copySipHeaders(ver,*t->initialMessage());
7566 	ver.addParam("rtp_addr",addr);
7567 	if (natAddr)
7568 	    ver.addParam("rtp_nat_addr",natAddr);
7569 	ver.addParam("audio_changed",String::boolText(audioChg));
7570 	putMedia(ver,lst);
7571 	addSdpParams(ver,sdp);
7572 	if (!Engine::dispatch(ver) || (ver.retValue() == YSTRING("error")) || (ver.retValue() == "-")) {
7573 	    TelEngine::destruct(lst);
7574 
7575 	    SIPMessage* m = new SIPMessage(t->initialMessage(),
7576 		ver.getIntValue(YSTRING("error"),dict_errors,488),ver.getValue(YSTRING("reason")));
7577 	    copySipHeaders(*m,ver);
7578 	    t->setResponse(m);
7579 	    m->deref();
7580 	    m_reInviting = invite;
7581 	    return true;
7582 	}
7583 	keepExisting = ver.getBoolValue(YSTRING("keep_media"),keepExisting);
7584     }
7585 
7586     if (m_rtpAddr != addr) {
7587 	m_rtpAddr = addr;
7588 	TraceDebug(m_traceId,this,DebugAll,"New RTP addr '%s'",m_rtpAddr.c_str());
7589 	// clear all data endpoints - createRtpSDP will build new ones
7590 	if (!s_rtp_preserve)
7591 	    setMedia(0);
7592     }
7593     setMedia(lst,keepExisting);
7594 
7595     m_mediaStatus = MediaMissing;
7596     // let RTP guess again the local interface or use the enforced address
7597     setRtpLocalAddr(m_rtpLocalAddr);
7598     addr = m_address;
7599     String uri = m_uri;
7600     updateTarget(t->initialMessage());
7601     bool addrChg = (addr != m_address);
7602     bool contactChg = (uri != m_uri);
7603 
7604     SIPMessage* m = new SIPMessage(t->initialMessage(), 200);
7605     copySipHeaders(*m,ver);
7606     MimeSdpBody* sdpNew = createRtpSDP(true);
7607     m->setBody(sdpNew);
7608     t->setResponse(m);
7609     m->deref();
7610 
7611     // notify peer about the changes
7612     Message* msg = message("call.update");
7613     msg->addParam("operation","notify");
7614     msg->addParam("mandatory","false");
7615     if (addrChg)
7616 	msg->addParam("address_old",addr);
7617     msg->addParam("address_changed",String::boolText(addrChg));
7618     if (contactChg) {
7619 	msg->addParam("contact",m_uri);
7620 	msg->addParam("contact_old",uri);
7621     }
7622     msg->addParam("contact_changed",String::boolText(contactChg));
7623     msg->addParam("audio_changed",String::boolText(audioChg));
7624     msg->addParam("mute",String::boolText(MediaStarted != m_mediaStatus));
7625     putMedia(*msg);
7626     Engine::enqueue(msg);
7627     m_reInviting = invite;
7628     return true;
7629 }
7630 
checkUser(SIPTransaction * t,bool refuse)7631 bool YateSIPConnection::checkUser(SIPTransaction* t, bool refuse)
7632 {
7633     // don't try to authenticate requests from server
7634     if (m_user.null() || m_line)
7635 	return true;
7636     NamedList params("");
7637     params.addParam("id",id());
7638     params.addParam("billid",billid(),false);
7639     int age = t->authUser(m_user,false,&params);
7640     if ((age >= 0) && (age <= 10))
7641 	return true;
7642     DDebug(this,DebugAll,"YateSIPConnection::checkUser(%p) failed, age %d [%p]",t,age,this);
7643     if (refuse)
7644 	setAuthError(t,params,age >= 0,m_domain);
7645     return false;
7646 }
7647 
doBye(SIPTransaction * t)7648 void YateSIPConnection::doBye(SIPTransaction* t)
7649 {
7650     if (m_authBye && !checkUser(t))
7651 	return;
7652     DDebug(this,DebugAll,"YateSIPConnection::doBye(%p) [%p]",t,this);
7653     const SIPMessage* msg = t->initialMessage();
7654     m_dialog.adjustCSeq(msg);
7655     // Change party
7656     if (m_autoChangeParty && t->initialMessage() && !t->initialMessage()->isOutgoing())
7657 	setPartyChanged(t->initialMessage()->getParty());
7658     if (msg->body) {
7659 	Message tmp("isup.decode");
7660 	bool ok = decodeIsupBody(tmp,msg->body);
7661 	ok = copySipBody(tmp,msg->body) || ok;
7662 	if (ok) {
7663 	    paramMutex().lock();
7664 	    parameters().copyParams(tmp);
7665 	    paramMutex().unlock();
7666 	}
7667     }
7668     Lock mylock(driver());
7669     setMedia(0);
7670     mylock.drop();
7671     SIPMessage* m = new SIPMessage(t->initialMessage(),200);
7672     paramMutex().lock();
7673     copySipHeaders(parameters(),*msg);
7674     const char* stats = parameters().getValue(YSTRING("rtp_stats"));
7675     if (stats)
7676 	m->addHeader("P-RTP-Stat",stats);
7677     paramMutex().unlock();
7678     const MimeHeaderLine* hl = msg->getHeader("Reason");
7679     if (hl) {
7680 	const NamedString* text = hl->getParam("text");
7681 	if (text)
7682 	    setReason(MimeHeaderLine::unquote(*text),m_reasonCode,driver());
7683 	// FIXME: add SIP and Q.850 cause codes
7684     }
7685     t->setResponse(m);
7686     m->deref();
7687     m_byebye = false;
7688     hangup();
7689 }
7690 
doCancel(SIPTransaction * t)7691 void YateSIPConnection::doCancel(SIPTransaction* t)
7692 {
7693 #ifdef DEBUG
7694     // CANCEL cannot be challenged but it may (should?) be authenticated with
7695     //  an old nonce from the transaction that is being cancelled
7696     if (m_user && (t->authUser(m_user) < 0))
7697 	TraceDebug(m_traceId,&plugin,DebugMild,"User authentication failed for user '%s' but CANCELing anyway [%p]",
7698 	    m_user.c_str(),this);
7699 #endif
7700     DDebug(this,DebugAll,"YateSIPConnection::doCancel(%p) [%p]",t,this);
7701     // Change party
7702     if (m_autoChangeParty && t->initialMessage() && !t->initialMessage()->isOutgoing())
7703 	setPartyChanged(t->initialMessage()->getParty());
7704     if (m_tr) {
7705 	t->setResponse(200);
7706 	m_byebye = false;
7707 	clearTransaction();
7708 	disconnect("Cancelled");
7709 	hangup();
7710     }
7711     else
7712 	t->setResponse(481);
7713 }
7714 
doInfo(SIPTransaction * t)7715 bool YateSIPConnection::doInfo(SIPTransaction* t)
7716 {
7717     if (m_authBye && !checkUser(t))
7718 	return true;
7719     DDebug(this,DebugAll,"YateSIPConnection::doInfo(%p) [%p]",t,this);
7720     m_dialog.adjustCSeq(t->initialMessage());
7721     // Change party
7722     if (m_autoChangeParty && t->initialMessage() && !t->initialMessage()->isOutgoing())
7723 	setPartyChanged(t->initialMessage()->getParty());
7724     if (m_hungup) {
7725 	t->setResponse(481);
7726 	return true;
7727     }
7728     int sig = -1;
7729     const MimeLinesBody* lb = YOBJECT(MimeLinesBody,getOneBody(t->initialMessage()->body,"application/dtmf-relay"));
7730     const MimeStringBody* sb = YOBJECT(MimeStringBody,getOneBody(t->initialMessage()->body,"application/dtmf"));
7731     if (lb) {
7732 	const ObjList* l = lb->lines().skipNull();
7733 	for (; l; l = l->skipNext()) {
7734 	    String tmp = static_cast<String*>(l->get());
7735 	    tmp.toUpper();
7736 	    if (tmp.startSkip("SIGNAL=",false)) {
7737 		sig = tmp.trimBlanks().toInteger(info_signals,-1);
7738 		break;
7739 	    }
7740 	}
7741     }
7742     else if (sb) {
7743 	String tmp = sb->text();
7744 	tmp.trimSpaces();
7745 	sig = tmp.toInteger(info_signals,-1);
7746     }
7747     else
7748 	return false;
7749     t->setResponse(200);
7750     if ((sig >= 0) && (sig <= 16)) {
7751 	char tmp[2];
7752 	tmp[0] = s_dtmfs[sig];
7753 	tmp[1] = '\0';
7754 	Message* msg = message("chan.dtmf");
7755 	copySipHeaders(*msg,*t->initialMessage());
7756 	msg->addParam("text",tmp);
7757 	msg->addParam("detected","sip-info");
7758 	dtmfEnqueue(msg);
7759     }
7760     return true;
7761 }
7762 
doRefer(SIPTransaction * t)7763 void YateSIPConnection::doRefer(SIPTransaction* t)
7764 {
7765     if (m_authBye && !checkUser(t))
7766 	return;
7767     DDebug(this,DebugAll,"doRefer(%p) [%p]",t,this);
7768     m_dialog.adjustCSeq(t->initialMessage());
7769     // Change party
7770     if (m_autoChangeParty && t->initialMessage() && !t->initialMessage()->isOutgoing())
7771 	setPartyChanged(t->initialMessage()->getParty());
7772     if (m_hungup) {
7773 	t->setResponse(481);
7774 	return;
7775     }
7776     if (m_referring) {
7777 	DDebug(this,DebugAll,"doRefer(%p). Already referring [%p]",t,this);
7778 	t->setResponse(491);           // Request Pending
7779 	return;
7780     }
7781     m_referring = true;
7782     const MimeHeaderLine* refHdr = t->initialMessage()->getHeader("Refer-To");
7783     if (!(refHdr && refHdr->length())) {
7784 	DDebug(this,DebugAll,"doRefer(%p). Empty or missing 'Refer-To' header [%p]",t,this);
7785 	t->setResponse(400);           // Bad request
7786 	m_referring = false;
7787 	return;
7788     }
7789 
7790     // Get 'Refer-To' URI and its parameters
7791     URI uri(*refHdr);
7792     ObjList params;
7793     // Find the first parameter separator. Ignore everything before it
7794     int start = findURIParamSep(uri.getExtra(),0);
7795     if (start >= 0)
7796 	start++;
7797     else
7798 	start = uri.getExtra().length();
7799     while (start < (int)uri.getExtra().length()) {
7800 	int end = findURIParamSep(uri.getExtra(),start);
7801 	// Check if this is the last parameter or an empty one
7802 	if (end < 0)
7803 	    end = uri.getExtra().length();
7804 	else if (end == start) {
7805 	    start++;
7806 	    continue;
7807 	}
7808 	String param;
7809 	param = uri.getExtra().substr(start,end - start);
7810 	start = end + 1;
7811 	if (!param)
7812 	    continue;
7813 	param = param.uriUnescape();
7814 	int eq = param.find("=");
7815 	if (eq < 0) {
7816 	    DDebug(this,DebugInfo,"doRefer(%p). Skipping 'Refer-To' URI param '%s' [%p]",
7817 		t,param.c_str(),this);
7818 	    continue;
7819 	}
7820 	String name = param.substr(0,eq).trimBlanks();
7821 	String value = param.substr(eq + 1);
7822 	DDebug(this,DebugAll,"doRefer(%p). Found 'Refer-To' URI param %s=%s [%p]",
7823 	    t,name.c_str(),value.c_str(),this);
7824 	if (name)
7825 	    params.append(new MimeHeaderLine(name,value));
7826     }
7827     // Check attended transfer request parameters
7828     ObjList* repl = params.find("Replaces");
7829     const MimeHeaderLine* replaces = repl ? static_cast<MimeHeaderLine*>(repl->get()) : 0;
7830     if (replaces) {
7831 	const String* fromTag = replaces->getParam("from-tag");
7832 	const String* toTag = replaces->getParam("to-tag");
7833 	if (null(replaces) || null(fromTag) || null(toTag)) {
7834 	    DDebug(this,DebugAll,
7835 		"doRefer(%p). Invalid 'Replaces' '%s' from-tag=%s to-tag=%s [%p]",
7836 		t,replaces->safe(),c_safe(fromTag),c_safe(toTag),this);
7837 	    t->setResponse(501);           // Not implemented
7838 	    m_referring = false;
7839 	    return;
7840 	}
7841 	// Avoid replacing the same connection
7842 	if (isDialog(*replaces,*fromTag,*toTag)) {
7843 	    DDebug(this,DebugAll,
7844 		"doRefer(%p). Attended transfer request for the same dialog [%p]",
7845 		t,this);
7846 	    t->setResponse(400,"Can't replace the same dialog");           // Bad request
7847 	    m_referring = false;
7848 	    return;
7849 	}
7850     }
7851 
7852     Message* msg = 0;
7853     SIPMessage* sipNotify = 0;
7854     Channel* ch = YOBJECT(Channel,getPeer());
7855     if (ch && ch->driver() &&
7856 	initTransfer(msg,sipNotify,t->initialMessage(),refHdr,uri,replaces)) {
7857 	(new YateSIPRefer(id(),ch->id(),ch->driver(),msg,sipNotify,t))->startup();
7858 	return;
7859     }
7860     DDebug(this,DebugAll,"doRefer(%p). No peer or peer has no driver [%p]",t,this);
7861     t->setResponse(503);       // Service Unavailable
7862     m_referring = false;
7863 }
7864 
doMessage(SIPTransaction * t)7865 void YateSIPConnection::doMessage(SIPTransaction* t)
7866 {
7867     DDebug(this,DebugAll,"doMessage(%p) [%p]",t,this);
7868     const SIPMessage* sip = t ? t->initialMessage() : 0;
7869     if (!sip)
7870 	return;
7871     if (m_authBye && !checkUser(t))
7872 	return;
7873     m_dialog.adjustCSeq(sip);
7874     // Change party
7875     if (m_autoChangeParty && t->initialMessage() && !t->initialMessage()->isOutgoing())
7876 	setPartyChanged(t->initialMessage()->getParty());
7877     if (m_hungup) {
7878 	t->setResponse(481);
7879 	return;
7880     }
7881     t->setResponse(200);
7882     Message* m = message("chan.text");
7883     copySipHeaders(*m,*sip);
7884     copySipBody(*m,*sip,true);
7885     Engine::enqueue(m);
7886 }
7887 
complete(Message & msg,bool minimal) const7888 void YateSIPConnection::complete(Message& msg, bool minimal) const
7889 {
7890     Channel::complete(msg,minimal);
7891     if (minimal)
7892 	return;
7893     Lock mylock(driver());
7894     if (m_domain)
7895 	msg.setParam("domain",m_domain);
7896     addCallId(msg,m_dialog,m_dialog.fromTag(isOutgoing()),m_dialog.toTag(isOutgoing()));
7897 }
7898 
disconnected(bool final,const char * reason)7899 void YateSIPConnection::disconnected(bool final, const char *reason)
7900 {
7901     TraceDebug(m_traceId,this,DebugAll,"YateSIPConnection::disconnected() '%s' [%p]",reason,this);
7902     setSilent(reason);
7903     if (reason) {
7904 	int code = lookup(reason,dict_errors);
7905 	if (code >= 300 && code <= 699)
7906 	    setReason(lookup(code,SIPResponses,reason),code,driver());
7907 	else
7908 	    setReason(reason,487,driver());
7909     }
7910     Channel::disconnected(final,reason);
7911 }
7912 
msgProgress(Message & msg)7913 bool YateSIPConnection::msgProgress(Message& msg)
7914 {
7915     Channel::msgProgress(msg);
7916     int code = 183;
7917     const NamedString* reason = msg.getParam(YSTRING("reason"));
7918     if (reason) {
7919 	// handle the special progress types that have provisional codes
7920 	if (*reason == YSTRING("forwarded"))
7921 	    code = 181;
7922 	else if (*reason == YSTRING("queued"))
7923 	    code = 182;
7924     }
7925     Lock lock(driver());
7926     if (m_hungup)
7927 	return false;
7928     if (m_tr && (m_tr->getState() == SIPTransaction::Process)) {
7929 	SIPMessage* m = new SIPMessage(m_tr->initialMessage(), code);
7930 	copySipHeaders(*m,msg);
7931 	m->setBody(buildSIPBody(msg,createProvisionalSDP(msg)));
7932 	m_tr->setResponse(m);
7933 	m->deref();
7934     }
7935     setStatus("progressing");
7936     return true;
7937 }
7938 
msgRinging(Message & msg)7939 bool YateSIPConnection::msgRinging(Message& msg)
7940 {
7941     Channel::msgRinging(msg);
7942     Lock lock(driver());
7943     if (m_hungup)
7944 	return false;
7945     if (m_tr && (m_tr->getState() == SIPTransaction::Process)) {
7946 	SIPMessage* m = new SIPMessage(m_tr->initialMessage(), 180);
7947 	copySipHeaders(*m,msg);
7948 	m->setBody(buildSIPBody(msg,createProvisionalSDP(msg)));
7949 	m_tr->setResponse(m);
7950 	m->deref();
7951     }
7952     setStatus("ringing");
7953     return true;
7954 }
7955 
msgAnswered(Message & msg)7956 bool YateSIPConnection::msgAnswered(Message& msg)
7957 {
7958     Channel::msgAnswered(msg);
7959     Lock lock(driver());
7960     if (m_hungup)
7961 	return false;
7962     if (m_tr && (m_tr->getState() == SIPTransaction::Process)) {
7963 	updateFormats(msg,true);
7964 	SIPMessage* m = new SIPMessage(m_tr->initialMessage(), 200);
7965 	copySipHeaders(*m,msg);
7966 	MimeSdpBody* sdp = createPasstroughSDP(msg);
7967 	if (!sdp) {
7968 	    m_rtpForward = false;
7969 	    bool startNow = false;
7970 	    if (m_rtpMedia)
7971 		startNow = msg.getBoolValue(YSTRING("rtp_start"),s_start_rtp);
7972 	    else {
7973 		// early RTP start but media list yet unknown - build best guess
7974 		String fmts;
7975 		plugin.parser().getAudioFormats(fmts);
7976 		ObjList* lst = new ObjList;
7977 		lst->append(new SDPMedia("audio","RTP/AVP",msg.getValue(YSTRING("formats"),fmts)));
7978 		setMedia(lst);
7979 		m_rtpAddr = m_host;
7980 	    }
7981 	    // normally don't start RTP yet, only when we get the ACK
7982 	    sdp = createRtpSDP(startNow);
7983 	}
7984 	m->setBody(buildSIPBody(msg,sdp));
7985 
7986 	const MimeHeaderLine* co = m_tr->initialMessage()->getHeader("Contact");
7987 	if (co) {
7988 	    // INVITE had a Contact: header - time to change remote URI
7989 	    m_uri = *co;
7990 	    m_uri.parse();
7991 	}
7992 
7993 	// and finally send the answer, transaction will finish soon afterwards
7994 	m_tr->setResponse(m);
7995 	m->deref();
7996     }
7997     setReason("",0);
7998     setStatus("answered",Established);
7999     return true;
8000 }
8001 
msgTone(Message & msg,const char * tone)8002 bool YateSIPConnection::msgTone(Message& msg, const char* tone)
8003 {
8004     if (m_hungup)
8005 	return false;
8006     if (TelEngine::null(tone))
8007 	return true;
8008     DtmfMethods methods = m_dtmfMethods;
8009     const String* param = msg.getParam(YSTRING("methods"));
8010     if (param) {
8011 	bool intersect = !msg.getBoolValue(YSTRING("methods_override"));
8012 	methods.set(*param,&m_dtmfMethods,true,intersect);
8013     }
8014     else {
8015 	const String* method = msg.getParam(YSTRING("method"));
8016 	if (method) {
8017 	    if (s_warnDtmfMethodChanDtmf) {
8018 		s_warnDtmfMethodChanDtmf = false;
8019 		TraceDebug(m_traceId,this,DebugConf,"Deprecated 'method' parameter in '%s'. Use 'methods' instead!",msg.c_str());
8020 	    }
8021 	    int meth = lookup(*method,DtmfMethods::s_methodName,DtmfMethods::MethodCount);
8022 	    if (meth != DtmfMethods::MethodCount)
8023 		methods.set(meth);
8024 	}
8025     }
8026     bool retVal = false;
8027     bool ok = false;
8028     if (msg.getBoolValue(YSTRING("honor_dtmf_detect"),m_honorDtmfDetect)) {
8029 	const String& detected = msg[YSTRING("detected")];
8030 	int meth = lookup(detected,DtmfMethods::s_methodName,DtmfMethods::MethodCount);
8031 	if (meth != DtmfMethods::MethodCount && methods.hasMethod(meth)) {
8032 	    ok = sendTone(msg,tone,meth,retVal);
8033 	    methods.reset(meth);
8034 	}
8035     }
8036     for (int i = 0; !ok && i < DtmfMethods::MethodCount; i++) {
8037 	int meth = methods[i];
8038 	if (meth != DtmfMethods::MethodCount)
8039 	    ok = sendTone(msg,tone,meth,retVal);
8040     }
8041     if (!ok && debugAt(DebugNote)) {
8042 	String tmp;
8043 	methods.buildMethods(tmp);
8044 	TraceDebug(m_traceId,this,DebugNote,"Failed to send tones '%s' methods=%s [%p]",tone,tmp.c_str(),this);
8045     }
8046     return retVal;
8047 }
8048 
msgText(Message & msg,const char * text)8049 bool YateSIPConnection::msgText(Message& msg, const char* text)
8050 {
8051     if (m_hungup)
8052 	return false;
8053     DDebug(this,DebugAll,"msgText(%s) [%p]",text,this);
8054     SIPMessage* m = createDlgMsg("MESSAGE");
8055     if (m) {
8056 	if (!copySipBody(*m,msg)) {
8057 	    if (TelEngine::null(text)) {
8058 		TelEngine::destruct(m);
8059 		return false;
8060 	    }
8061 	    m->setBody(new MimeStringBody("text/plain",text));
8062 	}
8063 	copySipHeaders(*m,msg);
8064 	plugin.ep()->engine()->addMessage(m,&m_autoChangeParty);
8065 	m->deref();
8066 	return true;
8067     }
8068     return false;
8069 }
8070 
msgDrop(Message & msg,const char * reason)8071 bool YateSIPConnection::msgDrop(Message& msg, const char* reason)
8072 {
8073     if (!Channel::msgDrop(msg,reason))
8074 	return false;
8075     setSilent(reason);
8076     int code = lookup(reason,dict_errors);
8077     if (code >= 300 && code <= 699)
8078 	setReason(lookup(code,SIPResponses,reason),code,driver());
8079     return true;
8080 }
8081 
msgUpdate(Message & msg)8082 bool YateSIPConnection::msgUpdate(Message& msg)
8083 {
8084     String* oper = msg.getParam(YSTRING("operation"));
8085     if (!oper || oper->null())
8086 	return false;
8087     Lock lock(driver());
8088     if (m_hungup)
8089 	return false;
8090     if (*oper == YSTRING("request")) {
8091 	if (m_tr || m_tr2) {
8092 	    DDebug(this,DebugWarn,"Update request rejected, pending:%s%s [%p]",
8093 		m_tr ? " invite" : "",m_tr2 ? " reinvite" : "",this);
8094 	    msg.setParam("error","pending");
8095 	    msg.setParam("reason","Another INVITE Pending");
8096 	    return false;
8097 	}
8098 	return startClientReInvite(msg,true);
8099     }
8100     if (*oper == YSTRING("initiate")) {
8101 	if (m_reInviting != ReinviteNone) {
8102 	    msg.setParam("error","pending");
8103 	    msg.setParam("reason","Another INVITE Pending");
8104 	    return false;
8105 	}
8106 	m_reInviting = ReinvitePending;
8107 	startPendingUpdate();
8108 	return true;
8109     }
8110     if (!m_tr2) {
8111 	if (*oper == YSTRING("notify")) {
8112 	    if (m_tr && m_tr->isOutgoing() && !m_tr->autoAck()) {
8113 		// generate ACK explicitly and put the SDP in it
8114 		MimeSdpBody* sdp = createPasstroughSDP(msg);
8115 		if (m_rtpMedia && !sdp) {
8116 		    if (m_rtpForward && m_rtpLocalAddr)
8117 			sdp = createSDP(m_rtpLocalAddr,m_rtpMedia);
8118 		    if (!sdp)
8119 			sdp = createRtpSDP(true);
8120 		}
8121 		m_tr->setAcknowledge(sdp);
8122 		return true;
8123 	    }
8124 	    switch (m_reInviting) {
8125 		case ReinviteNone:
8126 		    if (!msg.getBoolValue(YSTRING("audio_changed")))
8127 			break;
8128 		    // if any side is forwarding RTP we shouldn't reach here
8129 		    if (m_rtpForward || msg.getBoolValue(YSTRING("rtp_forward")))
8130 			break;
8131 		    // reINVITE for mute not supported yet
8132 		    if (msg.getBoolValue(YSTRING("mute"),false))
8133 			break;
8134 		    // save current RTP parameters so we can try to revert later
8135 		    m_revert.clearParams();
8136 		    addRtpParams(m_revert);
8137 		    // fall through
8138 		case ReinviteRequest:
8139 		    if (startClientReInvite(msg,(ReinviteRequest == m_reInviting)))
8140 			return true;
8141 		    TraceDebug(m_traceId,this,DebugMild,"Failed to start reINVITE, %s: %s [%p]",
8142 			msg.getValue(YSTRING("error"),"unknown"),
8143 			msg.getValue(YSTRING("reason"),"No reason"),this);
8144 		    return false;
8145 	    }
8146 	}
8147 	msg.setParam("error","nocall");
8148 	return false;
8149     }
8150 
8151     if (m_rtpForward && m_tr2->isOutgoing() && !m_tr2->autoAck() && (m_tr2->getState() == SIPTransaction::Retrans)) {
8152 	m_tr2->setAcknowledge(createPasstroughSDP(msg,true,m_rtpForward));
8153 	detachTransaction2();
8154 	return true;
8155     }
8156 
8157     if (!(m_tr2->isIncoming() && (m_tr2->getState() == SIPTransaction::Process))) {
8158 	msg.setParam("error","failure");
8159 	msg.setParam("reason","Incompatible Transaction State");
8160 	return false;
8161     }
8162     if (*oper == YSTRING("notify")) {
8163 	bool rtpSave = m_rtpForward;
8164 	m_rtpForward = msg.getBoolValue(YSTRING("rtp_forward"),m_rtpForward);
8165 	MimeSdpBody* sdp = createPasstroughSDP(msg,true,m_rtpForward);
8166 	if (!sdp) {
8167 	    m_rtpForward = rtpSave;
8168 	    m_tr2->setResponse(500,"Server failed to build the SDP");
8169 	    detachTransaction2();
8170 	    return false;
8171 	}
8172 	if (m_rtpForward != rtpSave)
8173 	    TraceDebug(m_traceId,this,DebugInfo,"RTP forwarding changed: %s -> %s",
8174 		String::boolText(rtpSave),String::boolText(m_rtpForward));
8175 	const SIPMessage* m1 = m_tr2->initialMessage();
8176 	updateTarget(m1);
8177 	SIPMessage* m = new SIPMessage(m1,200);
8178 	m->setBody(sdp);
8179 	copySipHeaders(*m,msg);
8180 	m_tr2->setResponse(m);
8181 	if (m_tr2->autoAck())
8182 	    detachTransaction2();
8183 	m->deref();
8184 	return true;
8185     }
8186     else if (*oper == YSTRING("reject")) {
8187 	m_tr2->setResponse(msg.getIntValue(YSTRING("error"),dict_errors,488),msg.getValue(YSTRING("reason")));
8188 	detachTransaction2();
8189 	return true;
8190     }
8191     return false;
8192 }
8193 
msgControl(Message & msg)8194 bool YateSIPConnection::msgControl(Message& msg)
8195 {
8196     bool ok = false;
8197     if (msg[YSTRING("operation")] == YSTRING("query")) {
8198 	msg.setParam("sip_uri",m_uri);
8199 	msg.setParam("sip_callid",callid());
8200 	String tmp;
8201 	tmp << "<" << m_dialog.localURI << ">";
8202 	if (m_dialog.localTag)
8203 	    tmp << ";tag=" << m_dialog.localTag;
8204 	msg.setParam("sip_from",tmp);
8205 	tmp.clear();
8206 	tmp << "<" << m_dialog.remoteURI << ">";
8207 	if (m_dialog.remoteTag)
8208 	    tmp << ";tag=" << m_dialog.remoteTag;
8209 	msg.setParam("sip_to",tmp);
8210 	int32_t cseq = m_dialog.getLastCSeq();
8211 	if (cseq >= 0)
8212 	    msg.setParam("local_cseq",String(cseq));
8213 	if (m_dialog.remoteCSeq >= 0)
8214 	    msg.setParam("remote_cseq",String(m_dialog.remoteCSeq));
8215 	ok = true;
8216     }
8217     return Channel::msgControl(msg) || ok;
8218 }
8219 
endDisconnect(const Message & msg,bool handled)8220 void YateSIPConnection::endDisconnect(const Message& msg, bool handled)
8221 {
8222     const String* reason = msg.getParam(YSTRING("reason"));
8223     if (!TelEngine::null(reason)) {
8224 	int code = reason->toInteger(dict_errors);
8225 	if (code >= 300 && code <= 699)
8226 	    setReason(lookup(code,SIPResponses,*reason),code,driver());
8227 	else
8228 	    setReason(*reason,m_reasonCode,driver());
8229     }
8230     const char* sPrefix = msg.getValue(YSTRING("osip-prefix"));
8231     const char* mPrefix = msg.getValue(YSTRING("message-prefix"));
8232     if (!(sPrefix || mPrefix))
8233         return;
8234     paramMutex().lock();
8235     parameters().clearParams();
8236     if (sPrefix) {
8237 	parameters().setParam("osip-prefix",sPrefix);
8238 	parameters().copySubParams(msg,sPrefix,false);
8239     }
8240     if (mPrefix) {
8241 	parameters().setParam("message-prefix",mPrefix);
8242 	parameters().copySubParams(msg,mPrefix,false);
8243     }
8244     paramMutex().unlock();
8245 }
8246 
statusParams(String & str)8247 void YateSIPConnection::statusParams(String& str)
8248 {
8249     Channel::statusParams(str);
8250     if (m_line)
8251 	str << ",line=" << m_line;
8252     if (m_user)
8253 	str << ",user=" << m_user;
8254     if (m_rtpForward)
8255 	str << ",forward=" << (m_sdpForward ? "sdp" : "rtp");
8256     str << ",inviting=" << (m_tr != 0);
8257 }
8258 
callPrerouted(Message & msg,bool handled)8259 bool YateSIPConnection::callPrerouted(Message& msg, bool handled)
8260 {
8261     bool ok = Channel::callPrerouted(msg,handled);
8262     m_autoChangeParty = msg.getBoolValue(YSTRING("iautochangeparty"),m_autoChangeParty);
8263     if (msg.getBoolValue(YSTRING("ioutbound_party")))
8264 	ok = setParty(msg,true,"i",String::empty(),0,true) && ok;
8265     return ok;
8266 }
8267 
callRouted(Message & msg)8268 bool YateSIPConnection::callRouted(Message& msg)
8269 {
8270     // try to disable RTP forwarding earliest possible
8271     if (m_rtpForward) {
8272 	m_rtpForward = msg.getBoolValue(YSTRING("rtp_forward"));
8273 	m_sdpForward = msg.getBoolValue(YSTRING("forward_sdp"),m_sdpForward);
8274     }
8275     setRfc2833(msg.getParam(YSTRING("rfc2833")));
8276     updateRtpNatAddress(&msg);
8277     Channel::callRouted(msg);
8278     Lock lock(driver());
8279     if (m_hungup || !m_tr)
8280 	return false;
8281     if (m_tr->getState() == SIPTransaction::Process) {
8282 	m_tr->setTransCount(msg.getIntValue(YSTRING("isip_trans_count"),-1));
8283 	String s(msg.retValue());
8284 	if (s.startSkip("sip/",false) && s && msg.getBoolValue(YSTRING("redirect"))) {
8285 	    TraceDebug(m_traceId,this,DebugAll,"YateSIPConnection redirecting to '%s' [%p]",s.c_str(),this);
8286 	    String tmp(msg.getValue(YSTRING("calledname")));
8287 	    if (tmp) {
8288 		MimeHeaderLine::addQuotes(tmp);
8289 		tmp += " ";
8290 	    }
8291 	    s = tmp + "<" + s + ">";
8292 	    int code = msg.getIntValue(YSTRING("reason"),dict_errors,302);
8293 	    if ((code < 300) || (code > 399))
8294 		code = 302;
8295 	    SIPMessage* m = new SIPMessage(m_tr->initialMessage(),code);
8296 	    m->addHeader("Contact",s);
8297 	    tmp = msg.getValue(YSTRING("diversion"));
8298 	    if (tmp.trimBlanks() && tmp.toBoolean(true)) {
8299 		// if diversion is a boolean true use the dialog local URI
8300 		if (tmp.toBoolean(false))
8301 		    tmp = m_dialog.localURI;
8302 		if (!(tmp.startsWith("<") && tmp.endsWith(">")))
8303 		    tmp = "<" + tmp + ">";
8304 		MimeHeaderLine* hl = new MimeHeaderLine("Diversion",tmp);
8305 		tmp = msg.getValue(YSTRING("divert_reason"));
8306 		if (tmp) {
8307 		    MimeHeaderLine::addQuotes(tmp);
8308 		    hl->setParam("reason",tmp);
8309 		}
8310 		tmp = msg.getValue(YSTRING("divert_privacy"));
8311 		if (tmp) {
8312 		    MimeHeaderLine::addQuotes(tmp);
8313 		    hl->setParam("privacy",tmp);
8314 		}
8315 		tmp = msg.getValue(YSTRING("divert_screen"));
8316 		if (tmp) {
8317 		    MimeHeaderLine::addQuotes(tmp);
8318 		    hl->setParam("screen",tmp);
8319 		}
8320 		int cnt = msg.getIntValue(YSTRING("divert_counter"));
8321 		if ((cnt > 0) && (cnt < 99))
8322 		    hl->setParam("counter",String(cnt));
8323 		m->addHeader(hl);
8324 	    }
8325 	    copySipHeaders(*m,msg);
8326 	    m_tr->setResponse(m);
8327 	    m->deref();
8328 	    m_byebye = false;
8329 	    setReason("Redirected",code);
8330 	    setStatus("redirected");
8331 	    return false;
8332 	}
8333 
8334 	setFormatsExtra(msg,false);
8335 	updateFormats(msg);
8336 	if (msg.getBoolValue(YSTRING("progress"),s_progress))
8337 	    m_tr->setResponse(183);
8338     }
8339     return true;
8340 }
8341 
callAccept(Message & msg)8342 void YateSIPConnection::callAccept(Message& msg)
8343 {
8344     m_user = msg.getValue(s_username);
8345     if (m_authBye)
8346 	m_authBye = msg.getBoolValue(YSTRING("xsip_auth_bye"),true);
8347     if (m_rtpForward) {
8348 	m_rtpForward = (msg[YSTRING("rtp_forward")] == YSTRING("accepted"));
8349 	m_sdpForward = msg.getBoolValue(YSTRING("forward_sdp"),m_sdpForward);
8350     }
8351     if (m_tr && msg.getBoolValue("sdp_ack"))
8352 	m_tr->autoAck(false);
8353     m_secure = m_secure && msg.getBoolValue(YSTRING("secure"),true);
8354     // Update dtmf methods from message
8355     m_checkAllowInfo = msg.getBoolValue(YSTRING("icheck_allow_info"),m_checkAllowInfo);
8356     m_missingAllowInfoDefVal = msg.getBoolValue(YSTRING("imissing_allow_info"),m_missingAllowInfoDefVal);
8357     m_honorDtmfDetect = msg.getBoolValue(YSTRING("ihonor_dtmf_detect"),m_honorDtmfDetect);
8358     String* meths = msg.getParam(YSTRING("idtmfmethods"));
8359     if (meths) {
8360 	DtmfMethods old = m_dtmfMethods;
8361 	m_dtmfMethods.set(*meths,&old);
8362     }
8363     // Reset INFO?
8364     if (m_checkAllowInfo && m_tr && m_dtmfMethods.hasMethod(DtmfMethods::Info)) {
8365 	Lock lock(driver());
8366 	if (m_tr && !infoAllowed(m_tr->initialMessage()))
8367 	    m_dtmfMethods.reset(DtmfMethods::Info);
8368     }
8369     Channel::callAccept(msg);
8370 
8371     if ((m_reInviting == ReinviteNone) && !m_rtpForward && !isAnswered() &&
8372 	msg.getBoolValue(YSTRING("autoreinvite"),false)) {
8373 	// remember we want to switch to RTP forwarding when party answers
8374 	m_reInviting = ReinvitePending;
8375 	startPendingUpdate();
8376     }
8377 }
8378 
callRejected(const char * error,const char * reason,const Message * msg)8379 void YateSIPConnection::callRejected(const char* error, const char* reason, const Message* msg)
8380 {
8381     Channel::callRejected(error,reason,msg);
8382     setSilent(error);
8383     int code = lookup(error,dict_errors,500);
8384     if (code < 300 || code > 699)
8385 	code = 500;
8386     Lock lock(driver());
8387     if (m_tr && (m_tr->getState() == SIPTransaction::Process)) {
8388 	if ((code == 401) && (s_noAutoAuth != error)) {
8389 	    String r;
8390 	    m_tr->requestAuth(getGlobal(r,s_realm),m_domain,false);
8391 	}
8392 	else if (msg) {
8393 	    SIPMessage* m = new SIPMessage(m_tr->initialMessage(),code,reason);
8394 	    copySipHeaders(*m,*msg);
8395 	    m->setBody(buildSIPBody(const_cast<Message&>(*msg),0,"message-iprefix"));
8396 	    m_tr->setResponse(m);
8397 	    m->deref();
8398 	}
8399 	else
8400 	    m_tr->setResponse(code,reason);
8401     }
8402     setReason(reason,code);
8403 }
8404 
8405 // Start a client reINVITE transaction
startClientReInvite(NamedList & msg,bool rtpForward)8406 bool YateSIPConnection::startClientReInvite(NamedList& msg, bool rtpForward)
8407 {
8408     bool hadRtp = !m_rtpForward;
8409     bool forced = msg.getBoolValue(YSTRING("rtp_forced"));
8410     if (msg.getBoolValue(YSTRING("rtp_forward"),m_rtpForward) != rtpForward) {
8411 	if (forced)
8412 	    rtpForward = !rtpForward;
8413 	else {
8414 	    msg.setParam("error","failure");
8415 	    msg.setParam("reason","Mismatched RTP forwarding");
8416 	    return false;
8417 	}
8418     }
8419     m_rtpForward = rtpForward;
8420     // this is the point of no return
8421     if (hadRtp && !forced)
8422 	clearEndpoint();
8423     MimeSdpBody* sdp = 0;
8424     if (rtpForward)
8425 	sdp = createPasstroughSDP(msg,false,true);
8426     else {
8427 	updateSDP(msg);
8428 	sdp = createRtpSDP(true);
8429     }
8430     if (!(sdp || msg.getBoolValue(YSTRING("sdp_ack")))) {
8431 	msg.setParam("error","failure");
8432 	msg.setParam("reason","Could not build the SDP");
8433 	if (hadRtp) {
8434 	    TraceDebug(m_traceId,this,DebugWarn,"Could not build SDP for reINVITE, hanging up [%p]",this);
8435 	    disconnect("nomedia");
8436 	}
8437 	return false;
8438     }
8439     TraceDebug(m_traceId,this,DebugNote,"Initiating reINVITE (%s RTP before) [%p]",
8440 	hadRtp ? "had" : "no",this);
8441     SIPMessage* m = createDlgMsg("INVITE");
8442     copySipHeaders(*m,msg);
8443     if (s_privacy)
8444 	copyPrivacy(*m,msg);
8445     if (sdp)
8446 	m->setBody(sdp);
8447     else
8448 	m->addHeader(new MimeHeaderLine("Accept","application/sdp"));
8449     m_tr2 = plugin.ep()->engine()->addMessage(m,&m_autoChangeParty);
8450     if (m_tr2) {
8451 	m_tr2->ref();
8452 	m_tr2->setUserData(this);
8453 	if (!sdp)
8454 	    m_tr2->autoAck(false);
8455     }
8456     m->deref();
8457     return true;
8458 }
8459 
8460 // Emit pending update if possible, method is called with driver mutex hold
startPendingUpdate()8461 void YateSIPConnection::startPendingUpdate()
8462 {
8463     Lock mylock(driver());
8464     if (m_hungup || m_tr || m_tr2 || (m_reInviting != ReinvitePending))
8465 	return;
8466     if (m_rtpAddr.null()) {
8467 	TraceDebug(m_traceId,this,DebugWarn,"Cannot start update, remote RTP address unknown [%p]",this);
8468 	m_reInviting = ReinviteNone;
8469 	return;
8470     }
8471     if (!m_rtpMedia) {
8472 	TraceDebug(m_traceId,this,DebugWarn,"Cannot start update, remote media unknown [%p]",this);
8473 	m_reInviting = ReinviteNone;
8474 	return;
8475     }
8476     m_reInviting = ReinviteRequest;
8477     mylock.drop();
8478 
8479     Message msg("call.update");
8480     complete(msg);
8481     msg.addParam("operation","request");
8482     msg.addParam("rtp_forward","yes");
8483     msg.addParam("rtp_addr",m_rtpAddr);
8484     putMedia(msg);
8485     // if peer doesn't support updates fail the reINVITE
8486     if (!Engine::dispatch(msg)) {
8487 	TraceDebug(m_traceId,this,DebugWarn,"Cannot start update by '%s', %s: %s [%p]",
8488 	    getPeerId().c_str(),
8489 	    msg.getValue(YSTRING("error"),"not supported"),
8490 	    msg.getValue(YSTRING("reason"),"No reason provided"),this);
8491 	m_reInviting = ReinviteNone;
8492     }
8493 }
8494 
8495 // Build the 'call.route' and NOTIFY messages needed by the transfer thread
8496 // msg: 'call.route' message to create & fill
8497 // sipNotify: NOTIFY message to create & fill
8498 // sipRefer: received REFER message, refHdr: 'Refer-To' header
8499 // refHdr: The 'Refer-To' header
8500 // uri: The already parsed 'Refer-To' URI
8501 // replaces: An already checked Replaces parameter from 'Refer-To' or
8502 //  0 for unattended transfer
8503 // If return false, msg and sipNotify are 0
initTransfer(Message * & msg,SIPMessage * & sipNotify,const SIPMessage * sipRefer,const MimeHeaderLine * refHdr,const URI & uri,const MimeHeaderLine * replaces)8504 bool YateSIPConnection::initTransfer(Message*& msg, SIPMessage*& sipNotify,
8505     const SIPMessage* sipRefer, const MimeHeaderLine* refHdr,
8506     const URI& uri, const MimeHeaderLine* replaces)
8507 {
8508     // call.route
8509     msg = new Message("call.route");
8510     msg->addParam("id",getPeer()->id());
8511     if (m_billid)
8512 	msg->addParam("billid",m_billid);
8513     if (m_user)
8514 	msg->addParam(s_username,m_user);
8515 
8516     const MimeHeaderLine* sh = sipRefer->getHeader("To");                   // caller
8517     if (sh) {
8518 	URI uriCaller(*sh);
8519 	uriCaller.parse();
8520 	msg->addParam("caller",uriCaller.getUser());
8521 	msg->addParam("callername",uriCaller.getDescription());
8522     }
8523 
8524     if (replaces) {                                                        // called or replace
8525 	const String* fromTag = replaces->getParam("from-tag");
8526 	const String* toTag = replaces->getParam("to-tag");
8527 	msg->addParam("transfer_callid",*replaces);
8528 	msg->addParam("transfer_fromtag",c_safe(fromTag));
8529 	msg->addParam("transfer_totag",c_safe(toTag));
8530     }
8531     else {
8532 	msg->addParam("called",uri.getUser());
8533 	msg->addParam("calledname",uri.getDescription());
8534     }
8535 
8536     sh = sipRefer->getHeader("Referred-By");                               // diverter
8537     URI referBy;
8538     if (sh)
8539 	referBy = *sh;
8540     else
8541 	referBy = m_dialog.remoteURI;
8542     msg->addParam("diverter",referBy.getUser());
8543     msg->addParam("divertername",referBy.getDescription());
8544 
8545     msg->addParam("reason","transfer");                                    // reason
8546     // NOTIFY
8547     String tmp;
8548     const MimeHeaderLine* co = sipRefer->getHeader("Contact");
8549     // TODO: Handle contact: it might require a different transport
8550     // If we need another transport and is a connected one, try to delay party creation:
8551     //  we won't need it if the transfer fails
8552     // Set notify party from received REFER?
8553     // Remember: createDlgMsg() sets the party from channel's party
8554     TraceDebug(m_traceId,this,DebugStub,"initTransfer. Possible incomplete NOTIFY party creation [%p]",this);
8555     if (co) {
8556 	tmp = *co;
8557 	static const Regexp r("^[^<]*<\\([^>]*\\)>.*$");
8558 	if (tmp.matches(r))
8559 	    tmp = tmp.matchString(1);
8560     }
8561     sipNotify = createDlgMsg("NOTIFY",tmp);
8562     if (!sipNotify->getParty() && plugin.ep())
8563 	plugin.ep()->buildParty(sipNotify);
8564     if (!sipNotify->getParty()) {
8565 	DDebug(this,DebugAll,"initTransfer. Could not create party to send NOTIFY [%p]",this);
8566 	TelEngine::destruct(sipNotify);
8567 	TelEngine::destruct(msg);
8568 	return false;
8569     }
8570     copySipHeaders(*msg,*sipRefer);
8571     sipNotify->complete(plugin.ep()->engine());
8572     sipNotify->addHeader("Event","refer");
8573     sipNotify->addHeader("Subscription-State","terminated;reason=noresource");
8574     sipNotify->addHeader("Contact",sipRefer->uri);
8575     return true;
8576 }
8577 
8578 // Decode an application/isup body into 'msg' if configured to do so
decodeIsupBody(Message & msg,MimeBody * body)8579 bool YateSIPConnection::decodeIsupBody(Message& msg, MimeBody* body)
8580 {
8581     return doDecodeIsupBody(this,msg,body);
8582 }
8583 
8584 // Build the body of a SIP message from an engine message
buildSIPBody(Message & msg,MimeSdpBody * sdp,const char * prefixName)8585 MimeBody* YateSIPConnection::buildSIPBody(Message& msg, MimeSdpBody* sdp, const char* prefixName)
8586 {
8587     return doBuildSIPBody(this,msg,sdp,prefixName);
8588 }
8589 
8590 // Build the body of a hangup SIP message from disconnect parameters
buildSIPBody()8591 MimeBody* YateSIPConnection::buildSIPBody()
8592 {
8593     Message msg("");
8594     paramMutex().lock();
8595     msg.copyParams(parameters());
8596     paramMutex().unlock();
8597     return doBuildSIPBody(this,msg,0,"message-prefix");
8598 }
8599 
8600 // Update NAT address from params or transport
updateRtpNatAddress(NamedList * params)8601 void YateSIPConnection::updateRtpNatAddress(NamedList* params)
8602 {
8603     if (params)
8604 	m_rtpNatAddr = params->getValue(YSTRING("nat_address"),m_rtpNatAddr);
8605     if (!m_rtpNatAddr) {
8606 	YateSIPTransport* trans = transport(true);
8607 	if (trans) {
8608 	    trans->rtpNatAddr(m_rtpNatAddr);
8609 	    TelEngine::destruct(trans);
8610 	}
8611     }
8612     TraceDebug(m_traceId,this,DebugAll,"NAT address is '%s' [%p]",m_rtpNatAddr.c_str(),this);
8613 }
8614 
8615 // Process allow list. Get INFO support
infoAllowed(const SIPMessage * msg)8616 bool YateSIPConnection::infoAllowed(const SIPMessage* msg)
8617 {
8618     static const String s_infoName = "INFO";
8619     if (!msg)
8620 	return m_missingAllowInfoDefVal;
8621     bool ok = false;
8622     const MimeHeaderLine* hdr = msg->getHeader("Allow");
8623     if (hdr) {
8624 	ObjList* allows = hdr->split(',');
8625 	for (ObjList* o = allows->skipNull(); o; o = o->skipNext()) {
8626 	    String* s = static_cast<String*>(o->get());
8627 	    s->trimBlanks().toUpper();
8628 	    if (*s == s_infoName) {
8629 		ok = true;
8630 		break;
8631 	    }
8632 	}
8633 	TelEngine::destruct(allows);
8634     }
8635     else
8636 	ok = m_missingAllowInfoDefVal;
8637     XDebug(this,DebugAll,"infoAllowed: info=%u [%p]",ok,this);
8638     return ok;
8639 }
8640 
8641 // Send tone(s) using method
sendTone(Message & msg,const char * tone,int meth,bool & retVal)8642 bool YateSIPConnection::sendTone(Message& msg, const char* tone, int meth, bool& retVal)
8643 {
8644     bool ok = false;
8645     if (meth == DtmfMethods::Info) {
8646 	// Send INFO only if initial transaction finished
8647 	if (!m_tr) {
8648 	    const char* t = tone;
8649 	    for (; t && *t; t++) {
8650 		char c = *t;
8651 		for (int j = 0; j <= 16; j++) {
8652 		    if (s_dtmfs[j] != c)
8653 			continue;
8654 		    SIPMessage* m = createDlgMsg("INFO");
8655 		    if (!m)
8656 			break;
8657 		    copySipHeaders(*m,msg);
8658 		    String tmp;
8659 		    tmp << "Signal=" << j << "\r\n";
8660 		    m->setBody(new MimeStringBody("application/dtmf-relay",tmp));
8661 		    plugin.ep()->engine()->addMessage(m,&m_autoChangeParty);
8662 		    m->deref();
8663 		    break;
8664 		}
8665 	    }
8666 	    retVal = true;
8667 	    ok = true;
8668 	}
8669     }
8670     else if (meth == DtmfMethods::Rfc2833 || meth == DtmfMethods::Inband) {
8671 	// RFC2833 and inband require media to be started
8672 	if (m_rtpMedia && (m_mediaStatus == MediaStarted)) {
8673 	    ObjList* l = m_rtpMedia->find("audio");
8674 	    const SDPMedia* m = static_cast<const SDPMedia*>(l ? l->get() : 0);
8675 	    if (meth == DtmfMethods::Rfc2833) {
8676 		ok = m && m->rfc2833().toBoolean(true);
8677 		if (ok)
8678 		    msg.setParam("targetid",m->id());
8679 	    }
8680 	    else if (m) {
8681 		ok = dtmfInband(tone);
8682 		retVal = ok;
8683 	    }
8684 	}
8685     }
8686     XDebug(this,ok ? DebugAll : DebugNote,"sendTone(%s) meth=%s (%d) ok=%u [%p]",
8687 	tone,lookup(meth,DtmfMethods::s_methodName),meth,ok,this);
8688     return ok;
8689 }
8690 
8691 
YateSIPLine(const String & name)8692 YateSIPLine::YateSIPLine(const String& name)
8693     : String(name), Mutex(true,"YateSIPLine"), CallAccount(this),
8694       YateSIPPartyHolder(&plugin),
8695       m_resend(0), m_keepalive(0), m_interval(0), m_alive(0),
8696       m_flags(-1), m_trans(-1), m_tr(0), m_marked(false), m_valid(false),
8697       m_localPort(0), m_partyPort(0), m_localDetect(false),
8698       m_keepTcpOffline(s_lineKeepTcpOffline),
8699       m_matchPort(true), m_matchUser(true), m_forceNotify(false)
8700 {
8701     m_partyMutex = this;
8702     DDebug(&plugin,DebugInfo,"YateSIPLine::YateSIPLine('%s') [%p]",c_str(),this);
8703     s_lines.append(this);
8704 }
8705 
~YateSIPLine()8706 YateSIPLine::~YateSIPLine()
8707 {
8708     DDebug(&plugin,DebugInfo,"YateSIPLine::~YateSIPLine() '%s' [%p]",c_str(),this);
8709     s_lines.remove(this,false);
8710     logout();
8711 }
8712 
matchInbound(const String & addr,int port,const String & user) const8713 bool YateSIPLine::matchInbound(const String& addr, int port, const String& user) const
8714 {
8715     if (m_matchPort && port && (getPartyPort() != port))
8716 	return false;
8717     if (getPartyAddr() != addr)
8718 	return false;
8719     if (m_matchUser && user && (getUserName() != user))
8720 	return false;
8721     return true;
8722 }
8723 
setupAuth(SIPMessage * msg) const8724 void YateSIPLine::setupAuth(SIPMessage* msg) const
8725 {
8726     if (msg)
8727 	msg->setAutoAuth(getAuthName(),m_password);
8728 }
8729 
setValid(bool valid,const char * reason,const char * error)8730 void YateSIPLine::setValid(bool valid, const char* reason, const char* error)
8731 {
8732     DDebug(&plugin,DebugInfo,"YateSIPLine(%s) setValid(%u,%s) current=%u [%p]",
8733 	c_str(),valid,reason,m_valid,this);
8734     if ((m_valid == valid) && !(m_forceNotify || reason))
8735 	return;
8736     m_valid = valid;
8737     if (m_forceNotify || (m_registrar && m_username)) {
8738 	Message* m = new Message("user.notify");
8739 	m->addParam("account",*this);
8740 	m->addParam("protocol","sip");
8741 	m->addParam(s_username,m_username);
8742 	if (m_domain)
8743 	    m->addParam("domain",m_domain);
8744 	m->addParam("registered",String::boolText(valid));
8745 	m->addParam("reason",reason,false);
8746 	m->addParam("error",error,false);
8747 	Engine::enqueue(m);
8748     }
8749 }
8750 
changing()8751 void YateSIPLine::changing()
8752 {
8753     // we need to log out before any parameter changes
8754     logout();
8755 }
8756 
buildRegister(int expires)8757 SIPMessage* YateSIPLine::buildRegister(int expires)
8758 {
8759     String exp(expires);
8760     const char* scheme = sips() ? "sips:" : "sip:";
8761     String tmp = scheme;
8762     SocketAddr::appendAddr(tmp,m_registrar);
8763     SIPMessage* m = new SIPMessage("REGISTER",tmp);
8764     setSipParty(m,this);
8765     if (!m->getParty()) {
8766 	Debug(&plugin,DebugWarn,"Could not create party for '%s' [%p]",
8767 	    m_registrar.c_str(),this);
8768 	m->destruct();
8769 	return 0;
8770     }
8771     tmp.clear();
8772     if (m_display)
8773 	tmp = MimeHeaderLine::quote(m_display) + " ";
8774     tmp << "<" << scheme;
8775     tmp << m_username << "@";
8776     m->getParty()->appendAddr(tmp,true);
8777     tmp << ">";
8778     m->addHeader("Contact",tmp);
8779     m->addHeader("Expires",exp);
8780     tmp = "<";
8781     tmp << scheme << m_username << "@";
8782     SocketAddr::appendAddr(tmp,domain()) << ">";
8783     m->addHeader("To",tmp);
8784     if (m_callid)
8785 	m->addHeader("Call-ID",m_callid);
8786     if (!m_seq) {
8787 	m_seq = new SIPSequence(plugin.ep()->engine()->getNextCSeq() - 1);
8788 	m_seq->deref();
8789     }
8790     m->setSequence(m_seq);
8791     m->complete(plugin.ep()->engine(),m_username,domain(),0,m_flags);
8792     if (m_display) {
8793 	MimeHeaderLine* hl = const_cast<MimeHeaderLine*>(m->getHeader("From"));
8794 	if (hl) {
8795 	    String display = m_display;
8796 	    MimeHeaderLine::addQuotes(display);
8797 	    *hl = display + " " + *hl;
8798 	}
8799     }
8800     copySipHeaders(*m,registerParams());
8801     return m;
8802 }
8803 
login()8804 void YateSIPLine::login()
8805 {
8806     m_keepalive = 0;
8807     if (m_registrar.null() || m_username.null()) {
8808 	logout();
8809 	setValid(true);
8810 	if (m_alive)
8811 	    keepalive();
8812 	return;
8813     }
8814     DDebug(&plugin,DebugInfo,"YateSIPLine '%s' logging in [%p]",c_str(),this);
8815     clearTransaction();
8816     // prepare a sane resend interval, just in case something goes wrong
8817     int interval = m_interval / 2;
8818     if (interval) {
8819 	if (interval < 30)
8820 	    interval = 30;
8821 	else if (interval > 600)
8822 	    interval = 600;
8823 	m_resend = interval*(int64_t)1000000 + Time::now();
8824     }
8825 
8826     buildParty(false);
8827     if (m_localAddr && !m_localDetect) {
8828 	if (!m_localPort)
8829 	    m_localPort = sipPort(protocol() != Tls);
8830 	SIPParty* p = party();
8831 	if (p) {
8832 	    p->setAddr(m_localAddr,m_localPort,true);
8833 	    TelEngine::destruct(p);
8834 	}
8835     }
8836     // Wait for the transport to become valid
8837     Lock lckParty(m_partyMutex);
8838     YateSIPTransport* trans = transport();
8839     if (!(trans && trans->valid())) {
8840 	DDebug(&plugin,DebugInfo,
8841 	    "YateSIPLine '%s' delaying login (transport not ready) [%p]",c_str(),this);
8842 	return;
8843     }
8844     lckParty.drop();
8845     SIPMessage* m = buildRegister(m_interval);
8846     if (!m) {
8847 	setValid(false);
8848 	if (!m_keepTcpOffline)
8849 	    setParty();
8850 	return;
8851     }
8852 
8853     if (m_localDetect) {
8854 	Lock lck(m->getParty()->mutex());
8855 	if (m_localAddr.null())
8856 	    m_localAddr = m->getParty()->getLocalAddr();
8857 	if (!m_localPort)
8858 	    m_localPort = m->getParty()->getLocalPort();
8859     }
8860 
8861     DDebug(&plugin,DebugInfo,"YateSIPLine '%s' emiting %p [%p]",
8862 	c_str(),m,this);
8863     m_tr = plugin.ep()->engine()->addMessage(m);
8864     if (m_tr) {
8865 	m_tr->ref();
8866 	m_tr->setUserData(this);
8867 	m_tr->setTransCount(m_trans);
8868 	if (m_callid.null())
8869 	    m_callid = m_tr->getCallID();
8870     }
8871     m->deref();
8872 }
8873 
logout(bool sendLogout,const char * reason)8874 void YateSIPLine::logout(bool sendLogout, const char* reason)
8875 {
8876     m_resend = 0;
8877     m_keepalive = 0;
8878     if (sendLogout)
8879 	sendLogout = m_valid && m_registrar && m_username;
8880     clearTransaction();
8881     setValid(false,reason);
8882     if (m_localDetect) {
8883 	m_localAddr.clear();
8884 	m_localPort = 0;
8885     }
8886     if (sendLogout) {
8887 	DDebug(&plugin,DebugInfo,"YateSIPLine '%s' logging out [%p]",c_str(),this);
8888 	buildParty(false);
8889 	SIPMessage* m = buildRegister(0);
8890 	m_partyAddr.clear();
8891 	m_partyPort = 0;
8892 	if (!m)
8893 	    return;
8894 	plugin.ep()->engine()->addMessage(m);
8895 	m->deref();
8896     }
8897     m_callid.clear();
8898     m_seq = 0;
8899 }
8900 
process(SIPEvent * ev)8901 bool YateSIPLine::process(SIPEvent* ev)
8902 {
8903     DDebug(&plugin,DebugInfo,"YateSIPLine::process(%p) %s [%p]",
8904 	ev,SIPTransaction::stateName(ev->getState()),this);
8905     if (ev->getTransaction() != m_tr)
8906 	return false;
8907     if (ev->getState() == SIPTransaction::Cleared) {
8908 	clearTransaction();
8909 	setValid(false,"timeout");
8910 	if (!m_keepTcpOffline)
8911 	    setParty();
8912 	m_keepalive = 0;
8913 	Debug(&plugin,DebugWarn,"SIP line '%s' logon timeout",c_str());
8914 	return false;
8915     }
8916     const SIPMessage* msg = ev->getMessage();
8917     if (!(msg && msg->isAnswer()))
8918 	return false;
8919     if (ev->getState() != SIPTransaction::Process)
8920 	return false;
8921     clearTransaction();
8922     DDebug(&plugin,DebugAll,"YateSIPLine '%s' got answer %d [%p]",
8923 	c_str(),msg->code,this);
8924     int exp = m_interval;
8925     switch (msg->code) {
8926 	case 200:
8927 	    {
8928 		const MimeHeaderLine* hl = msg->getHeader("Contact");
8929 		if (hl) {
8930 		    const NamedString* e = hl->getParam("expires");
8931 		    if (e)
8932 			exp = e->toInteger(exp);
8933 		    else
8934 			hl = 0;
8935 		}
8936 		if (!hl) {
8937 		    hl = msg->getHeader("Expires");
8938 		    if (hl)
8939 			exp = hl->toInteger(exp);
8940 		}
8941 		if (exp <= 60)
8942 		    exp = 60;
8943 		else if ((exp > m_interval + 10) || (exp < m_interval - 10)) {
8944 		    Debug(&plugin,DebugNote,"SIP line '%s' changed expire interval from %d to %d",
8945 			c_str(),m_interval,exp);
8946 		    m_interval = exp;
8947 		}
8948 		// Reset transport timeout from expires or flow timer
8949 		resetTransportIdle(msg,m_alive ? m_alive : m_interval);
8950 	    }
8951 	    // re-register at 3/4 of the expire interval
8952 	    m_resend = exp * (int64_t)750000 + Time::now();
8953 	    m_keepalive = m_alive ? m_alive*(int64_t)1000000 + Time::now() : 0;
8954 	    detectLocal(msg);
8955 	    if (msg->getParty())
8956 		msg->getParty()->getAddr(m_partyAddr,m_partyPort,false);
8957 	    setValid(true);
8958 	    Debug(&plugin,DebugCall,"SIP line '%s' logon success to %s",
8959 		c_str(),SocketAddr::appendTo(m_partyAddr,m_partyPort).c_str());
8960 	    break;
8961 	default:
8962 	    // detect local address even from failed attempts - helps next time
8963 	    detectLocal(msg);
8964 	    setValid(false,msg->reason,lookup(msg->code,dict_errors,String(msg->code)));
8965 	    if (!m_keepTcpOffline)
8966 		setParty();
8967 	    Debug(&plugin,DebugWarn,"SIP line '%s' logon failure %d: %s",
8968 		c_str(),msg->code,msg->reason.safe());
8969     }
8970     return false;
8971 }
8972 
detectLocal(const SIPMessage * msg)8973 void YateSIPLine::detectLocal(const SIPMessage* msg)
8974 {
8975     if (!(m_localDetect && msg->getParty()))
8976 	return;
8977     String laddr = m_localAddr;
8978     int lport = m_localPort;
8979     MimeHeaderLine* hl = const_cast<MimeHeaderLine*>(msg->getHeader("Via"));
8980     if (hl) {
8981 	const NamedString* par = hl->getParam("received");
8982 	if (par)
8983 	    getAddrCheckIPv6(laddr,*par);
8984 	par = hl->getParam("rport");
8985 	if (par) {
8986 	    int port = par->toInteger(0,10);
8987 	    if (port > 0)
8988 		lport = port;
8989 	}
8990     }
8991     Lock lckParty(msg->getParty()->mutex());
8992     if (laddr.null())
8993 	laddr = msg->getParty()->getLocalAddr();
8994     if (!lport)
8995 	lport = msg->getParty()->getLocalPort();
8996     lckParty.drop();
8997     if ((laddr != m_localAddr) || (lport != m_localPort)) {
8998 	Debug(&plugin,DebugInfo,"Detected local address %s for SIP line '%s'",
8999 	    SocketAddr::appendTo(laddr,lport).c_str(),c_str());
9000 	m_localAddr = laddr;
9001 	m_localPort = lport;
9002 	// since local address changed register again in 2 seconds
9003 	m_resend = 2000000 + Time::now();
9004 	// Update now party local ip/port
9005 	SIPParty* p = party();
9006 	if (p) {
9007 	    p->setAddr(m_localAddr,m_localPort,true);
9008 	    TelEngine::destruct(p);
9009 	}
9010     }
9011 }
9012 
keepalive()9013 void YateSIPLine::keepalive()
9014 {
9015     if (!m_party)
9016         return;
9017     Lock lock(m_partyMutex);
9018     if (!m_party || m_party->isReliable())
9019         return;
9020     YateUDPParty* udp = static_cast<YateUDPParty*>(m_party);
9021     YateSIPUDPTransport* t = static_cast<YateSIPUDPTransport*>(m_party->getTransport());
9022     if (t) {
9023 	Debug(&plugin,DebugAll,"Sending UDP keepalive to %s for '%s'",
9024 	    udp->addr().addr().c_str(),c_str());
9025 	t->send("\r\n",2,udp->addr());
9026     }
9027     m_keepalive = m_alive ? m_alive*(int64_t)1000000 + Time::now() : 0;
9028 }
9029 
timer(const Time & when)9030 void YateSIPLine::timer(const Time& when)
9031 {
9032     if (!m_resend || (m_resend > when)) {
9033 	if (m_keepalive && (m_keepalive <= when))
9034 	    keepalive();
9035 	return;
9036     }
9037     m_resend = 0;
9038     login();
9039 }
9040 
clearTransaction()9041 void YateSIPLine::clearTransaction()
9042 {
9043     if (m_tr) {
9044 	DDebug(&plugin,DebugInfo,"YateSIPLine clearing transaction %p [%p]",
9045 	    m_tr,this);
9046 	m_tr->setUserData(0);
9047 	m_tr->deref();
9048 	m_tr = 0;
9049     }
9050 }
9051 
update(const Message & msg)9052 bool YateSIPLine::update(const Message& msg)
9053 {
9054     DDebug(&plugin,DebugInfo,"YateSIPLine::update() '%s' [%p]",c_str(),this);
9055     const String& oper = msg[YSTRING("operation")];
9056     if (oper == YSTRING("logout")) {
9057 	logout();
9058 	setParty();
9059 	return true;
9060     }
9061     pickAccountParams(msg);
9062     bool chg = sips(msg.getBoolValue(YSTRING("sips")));
9063     bool transChg = updateProto(msg);
9064     transChg = updateLocalAddr(msg) || transChg;
9065     chg = chg || transChg;
9066     chg = change(m_registrar,msg.getValue(YSTRING("registrar"),msg.getValue(YSTRING("server")))) || chg;
9067     chg = change(m_username,msg.getValue(s_username)) || chg;
9068     chg = change(m_authname,msg.getValue(YSTRING("authname"))) || chg;
9069     chg = change(m_password,msg.getValue(YSTRING("password"))) || chg;
9070     chg = change(m_domain,msg.getValue(YSTRING("domain"))) || chg;
9071     chg = change(m_flags,msg.getIntValue(YSTRING("xsip_flags"),-1)) || chg;
9072     m_trans = msg.getIntValue(YSTRING("xsip_trans_count"),-1);
9073     m_display = msg.getValue(YSTRING("description"));
9074     m_interval = msg.getIntValue(YSTRING("interval"),600);
9075     m_matchPort = msg.getBoolValue(YSTRING("match_port"),true);
9076     m_matchUser = msg.getBoolValue(YSTRING("match_user"),true);
9077     String tmp(msg.getValue(YSTRING("localaddress"),s_auto_nat ? "auto" : ""));
9078     // "auto", "yes", "enable" or "true" to autodetect local address
9079     m_localDetect = (tmp == YSTRING("auto")) || tmp.toBoolean(false);
9080     if (!m_localDetect) {
9081 	// "no", "disable" or "false" to just disable detection
9082 	if (!tmp.toBoolean(true))
9083 	    tmp.clear();
9084 	int port = 0;
9085 	if (tmp) {
9086 	    SocketAddr::split(tmp,tmp,port);
9087 	    if (!port)
9088 		port = sipPort(protocol() != Tls);
9089 	}
9090 	chg = change(m_localAddr,tmp) || chg;
9091 	chg = change(m_localPort,port) || chg;
9092     }
9093     String raddr;
9094     int rport = 0;
9095     const String& out = msg[YSTRING("outbound")];
9096     if (out)
9097 	SocketAddr::split(out,raddr,rport);
9098     if (!raddr && m_registrar)
9099 	SocketAddr::split(m_registrar,raddr,rport);
9100     if (!raddr)
9101 	raddr = m_transRemoteAddr;
9102     if (rport <= 0)
9103 	rport = sipPort(protocol() != Tls);
9104     bool rAddrChg = change(m_transRemoteAddr,raddr);
9105     rAddrChg = change(m_transRemotePort,rport) || rAddrChg;
9106     if (rAddrChg) {
9107 	transChg = true;
9108 	chg = true;
9109     }
9110     m_alive = msg.getIntValue(YSTRING("keepalive"),((m_localDetect && m_registrar) ? 25 : 0));
9111     // (Re)Set party
9112     if (transChg || !m_party) {
9113 	// Logout if not already done
9114 	if (!chg) {
9115 	    chg = true;
9116 	    logout();
9117 	}
9118 	buildParty();
9119 	if (!m_party)
9120 	    Debug(&plugin,DebugNote,"Line '%s' failed to set party [%p]",c_str(),this);
9121     }
9122     m_forceNotify = (protocol() == Tcp) || (protocol() == Tls);
9123     // if something changed we logged out so try to climb back
9124     if (chg || (oper == YSTRING("login")))
9125 	login();
9126     return chg;
9127 }
9128 
9129 // Transport status changed notification
transportChangedStatus(int stat,const String & reason)9130 void YateSIPLine::transportChangedStatus(int stat, const String& reason)
9131 {
9132     Debug(&plugin,DebugAll,"Line '%s' transport status is %s",
9133 	c_str(),YateSIPTransport::statusName(stat));
9134     YateSIPPartyHolder::transportChangedStatus(stat,reason);
9135     YateSIPTransport* trans = transport();
9136     if (stat == YateSIPTransport::Terminated) {
9137 	u_int64_t old = m_resend;
9138 	logout(trans && trans->udpTransport(),reason);
9139 	setParty();
9140 	// Try to re-login if set to do that
9141 	m_resend = old;
9142     }
9143     else if (stat == YateSIPTransport::Connected) {
9144 	if (trans) {
9145 	    Lock lock(trans);
9146 	    m_localAddr = trans->local().host();
9147 	    m_localPort = trans->local().port();
9148 	}
9149 	// Pending login
9150 	if (trans && m_resend)
9151 	    login();
9152 	else if (trans && trans->tcpTransport())
9153 	    setValid(true);
9154     }
9155 }
9156 
YateSIPGenerate(SIPMessage * m,int tries)9157 YateSIPGenerate::YateSIPGenerate(SIPMessage* m, int tries)
9158     : m_tr(0), m_code(0)
9159 {
9160     m_tr = plugin.ep()->engine()->addMessage(m);
9161     if (m_tr) {
9162 	m_tr->ref();
9163 	m_tr->setUserData(this);
9164 	m_tr->setTransCount(tries);
9165     }
9166     m->deref();
9167 }
9168 
~YateSIPGenerate()9169 YateSIPGenerate::~YateSIPGenerate()
9170 {
9171     clearTransaction();
9172 }
9173 
process(SIPEvent * ev)9174 bool YateSIPGenerate::process(SIPEvent* ev)
9175 {
9176     DDebug(&plugin,DebugInfo,"YateSIPGenerate::process(%p) %s [%p]",
9177 	ev,SIPTransaction::stateName(ev->getState()),this);
9178     if (ev->getTransaction() != m_tr)
9179 	return false;
9180     if (ev->getState() == SIPTransaction::Cleared) {
9181 	clearTransaction();
9182 	return false;
9183     }
9184     SIPMessage* msg = ev->getMessage();
9185     if (!(msg && msg->isAnswer()))
9186 	return false;
9187     if (ev->getState() != SIPTransaction::Process)
9188 	return false;
9189     m_msg = msg;
9190     clearTransaction();
9191     Debug(&plugin,DebugAll,"YateSIPGenerate got answer %d [%p]",
9192 	m_code,this);
9193     return false;
9194 }
9195 
clearTransaction()9196 void YateSIPGenerate::clearTransaction()
9197 {
9198     if (m_tr) {
9199 	DDebug(&plugin,DebugInfo,"YateSIPGenerate clearing transaction %p [%p]",
9200 	    m_tr,this);
9201 	m_code = m_tr->getResponseCode();
9202 	m_tr->setUserData(0);
9203 	m_tr->deref();
9204 	m_tr = 0;
9205     }
9206 }
9207 
9208 
received(Message & msg)9209 bool UserHandler::received(Message &msg)
9210 {
9211     String tmp(msg.getValue(YSTRING("protocol")));
9212     if (tmp != YSTRING("sip"))
9213 	return false;
9214     tmp = msg.getValue(YSTRING("account"));
9215     if (tmp.null())
9216 	return false;
9217     YateSIPLine* line = plugin.findLine(tmp);
9218     if (!line)
9219 	line = new YateSIPLine(tmp);
9220     line->update(msg);
9221     return true;
9222 }
9223 
9224 
received(Message & msg)9225 bool SipHandler::received(Message &msg)
9226 {
9227     const char* method = msg.getValue(YSTRING("method"));
9228     return method && plugin.sendMethod(msg,method);
9229 }
9230 
9231 
epTerminated(YateSIPEndPoint * ep)9232 void SIPDriver::epTerminated(YateSIPEndPoint* ep)
9233 {
9234     if (!(ep && ep == m_endpoint))
9235 	return;
9236     Debug(this,s_engineHalt ? DebugAll : DebugWarn,"Endpoint stopped");
9237     m_endpoint = 0;
9238 }
9239 
findCall(const String & callid,bool incRef)9240 YateSIPConnection* SIPDriver::findCall(const String& callid, bool incRef)
9241 {
9242     XDebug(this,DebugAll,"SIPDriver finding call '%s'",callid.c_str());
9243     Lock mylock(this);
9244     ObjList* l = channels().skipNull();
9245     for (; l; l = l->skipNext()) {
9246 	YateSIPConnection* c = static_cast<YateSIPConnection*>(l->get());
9247 	if (c->callid() == callid)
9248 	    return (incRef ? c->ref() : c->alive()) ? c : 0;
9249     }
9250     return 0;
9251 }
9252 
findDialog(const SIPDialog & dialog,bool incRef)9253 YateSIPConnection* SIPDriver::findDialog(const SIPDialog& dialog, bool incRef)
9254 {
9255     XDebug(this,DebugAll,"SIPDriver finding dialog '%s'",dialog.c_str());
9256     Lock mylock(this);
9257     ObjList* l = channels().skipNull();
9258     for (; l; l = l->skipNext()) {
9259 	YateSIPConnection* c = static_cast<YateSIPConnection*>(l->get());
9260 	if (c->dialog() &= dialog)
9261 	    return (incRef ? c->ref() : c->alive()) ? c : 0;
9262     }
9263     return 0;
9264 }
9265 
findDialog(const String & dialog,const String & fromTag,const String & toTag,bool incRef)9266 YateSIPConnection* SIPDriver::findDialog(const String& dialog, const String& fromTag,
9267     const String& toTag, bool incRef)
9268 {
9269     XDebug(this,DebugAll,"SIPDriver finding dialog '%s' fromTag='%s' toTag='%s'",
9270 	dialog.c_str(),fromTag.c_str(),toTag.c_str());
9271     Lock mylock(this);
9272     for (ObjList* o = channels().skipNull(); o; o = o->skipNext()) {
9273 	YateSIPConnection* c = static_cast<YateSIPConnection*>(o->get());
9274 	if (c->isDialog(dialog,fromTag,toTag))
9275 	    return (incRef ? c->ref() : c->alive()) ? c : 0;
9276     }
9277     return 0;
9278 }
9279 
9280 // find line by name
findLine(const String & line) const9281 YateSIPLine* SIPDriver::findLine(const String& line) const
9282 {
9283     if (line.null())
9284 	return 0;
9285     ObjList* l = s_lines.find(line);
9286     return l ? static_cast<YateSIPLine*>(l->get()) : 0;
9287 }
9288 
9289 // find line by party address and port
findLine(const String & addr,int port,const String & user,SIPParty * party)9290 YateSIPLine* SIPDriver::findLine(const String& addr, int port, const String& user, SIPParty* party)
9291 {
9292     YateSIPTCPTransport* tr = YOBJECT(YateSIPTCPTransport,party);
9293     if (tr && !tr->outgoing())
9294 	tr = 0;
9295     bool matchAddr = port && addr;
9296     if (!(tr || matchAddr))
9297 	return 0;
9298     Lock mylock(this);
9299     ObjList* l = s_lines.skipNull();
9300     for (; l; l = l->skipNext()) {
9301 	YateSIPLine* sl = static_cast<YateSIPLine*>(l->get());
9302 	if (tr && sl->isTransport(tr))
9303 	    return sl;
9304 	if (!matchAddr)
9305 	    continue;
9306 	if (sl->matchInbound(addr,port,user))
9307 	    return sl;
9308 	if (sl->getPartyPort() && (sl->getPartyPort() == port) && (sl->getPartyAddr() == addr)) {
9309 	    if (user && (sl->getUserName() != user))
9310 		continue;
9311 	    return sl;
9312 	}
9313     }
9314     return 0;
9315 }
9316 
9317 // Drop channels belonging using a given transport
9318 // Return the number of disconnected channels
transportTerminated(YateSIPTransport * trans)9319 unsigned int SIPDriver::transportTerminated(YateSIPTransport* trans)
9320 {
9321     unsigned int n = 0;
9322     lock();
9323     ListIterator iter(channels());
9324     while (true) {
9325 	RefPointer<YateSIPConnection> conn = static_cast<YateSIPConnection*>(iter.get());
9326 	unlock();
9327 	if (!conn)
9328 	    break;
9329 	if (conn->isTransport(trans)) {
9330 	    Debug(this,DebugNote,"Disconnecting '%s': transport terminated",
9331 		conn->id().c_str());
9332 	    n++;
9333 	    conn->disconnect("notransport");
9334 	}
9335 	conn = 0;
9336 	lock();
9337     }
9338     return n;
9339 }
9340 
9341 // check if a line is either empty or valid (logged in or no registrar)
validLine(const String & line)9342 bool SIPDriver::validLine(const String& line)
9343 {
9344     if (line.null())
9345 	return true;
9346     YateSIPLine* l = findLine(line);
9347     return l && l->valid();
9348 }
9349 
received(Message & msg,int id)9350 bool SIPDriver::received(Message& msg, int id)
9351 {
9352     if (id == Timer) {
9353 	ObjList* l = s_lines.skipNull();
9354 	for (; l; l = l->skipNext())
9355 	    static_cast<YateSIPLine*>(l->get())->timer(msg.msgTime());
9356     }
9357     else if (id == Stop) {
9358 	s_engineStop++;
9359 	dropAll(msg);
9360 	m_endpoint->cancelListener();
9361 	// Logout lines on first handle
9362 	// Delay engine.halt until all lines logged out, we have no more channels
9363 	//  and there are no more transactions in initial state
9364 	// This will give some time to TCP transports to send pending data
9365 	bool noHalt = false;
9366 	for (ObjList* o = s_lines.skipNull(); o; o = o->skipNext()) {
9367 	    YateSIPLine* line = static_cast<YateSIPLine*>(o->get());
9368 	    noHalt = noHalt || line->valid();
9369 	    if (s_engineStop == 1)
9370 		line->logout();
9371 	}
9372 	if (!noHalt) {
9373 	    Lock lock(this);
9374 	    noHalt = (0 != channels().skipNull());
9375 	}
9376 	if (!noHalt)
9377 	    noHalt = m_endpoint->engine()->hasInitialTransaction();
9378 	Debug(this,DebugAll,"Returning %s from %s handler",String::boolText(noHalt),msg.c_str());
9379 	return noHalt;
9380     }
9381     else if (id == Halt) {
9382 	s_engineHalt = true;
9383 	dropAll(msg);
9384 	channels().clear();
9385 	s_lines.clear();
9386 	// Clear transactions: they keep references to parties and transports
9387 	m_endpoint->engine()->clearTransactions();
9388 	m_endpoint->clearUdpTransports("Exiting");
9389 	// Wait for transports to terminate
9390 	unsigned int n = 100;
9391 	while (--n) {
9392 	    Lock lck(m_endpoint->m_mutex);
9393 	    if (!m_endpoint->m_transports.skipNull())
9394 		break;
9395 	    lck.drop();
9396 	    Thread::idle();
9397 	}
9398 	m_endpoint->m_mutex.lock();
9399 	n = m_endpoint->m_transports.count();
9400 	if (n)
9401 	    Debug(this,DebugCrit,"Exiting with %u transports in queue",n);
9402 	m_endpoint->m_mutex.unlock();
9403 	m_endpoint->cancel();
9404     }
9405     else if (id == Status) {
9406 	String target = msg.getValue(YSTRING("module"));
9407 	if (target && target.startsWith(name(),true) && !target.startsWith(prefix())) {
9408 	    msgStatus(msg);
9409 	    return false;
9410 	}
9411     }
9412     else if (id == Start) {
9413 	s_engineStart = true;
9414 	s_sslClientAvailable = socketSsl(0,false);
9415     }
9416     else if (id == MsgExecute) {
9417 	const String& dest = msg[YSTRING("callto")];
9418 	if (dest.startsWith(prefix()))
9419 	    return sendMethod(msg,"MESSAGE",true,dest.substr(prefix().length()));
9420 	return false;
9421     }
9422     else if (id == Help)
9423 	return onHelp(msg);
9424     return Driver::received(msg,id);
9425 }
9426 
hasLine(const String & line) const9427 bool SIPDriver::hasLine(const String& line) const
9428 {
9429     return line && findLine(line);
9430 }
9431 
msgExecute(Message & msg,String & dest)9432 bool SIPDriver::msgExecute(Message& msg, String& dest)
9433 {
9434     if (!msg.userData()) {
9435 	Debug(this,DebugWarn,"SIP call found but no data channel!");
9436 	return false;
9437     }
9438     const String& line = msg["line"];
9439     if (!validLine(line)) {
9440 	// asked to use a line but it's not registered
9441 	msg.setParam("error","offline");
9442 	return false;
9443     }
9444     YateSIPConnection* conn = new YateSIPConnection(msg,dest,msg.getValue(YSTRING("id")));
9445     if (msg.getBoolValue(YSTRING("stop_call"),false)) {
9446 	conn->destruct();
9447 	return true;
9448     }
9449     conn->initChan();
9450     if (conn->getTransaction()) {
9451 	CallEndpoint* ch = YOBJECT(CallEndpoint,msg.userData());
9452 	if (ch && conn->connect(ch,msg.getValue(YSTRING("reason")))) {
9453 	    conn->callConnect(msg);
9454 	    msg.setParam("peerid",conn->id());
9455 	    msg.setParam("targetid",conn->id());
9456 	    conn->deref();
9457 	    return true;
9458 	}
9459     }
9460     conn->destruct();
9461     return false;
9462 }
9463 
SIPDriver()9464 SIPDriver::SIPDriver()
9465     : Driver("sip","varchans"),
9466       m_parser("sip","SIP Call"),
9467       m_endpoint(0)
9468 {
9469     Output("Loaded module SIP Channel");
9470     m_parser.debugChain(this);
9471 }
9472 
~SIPDriver()9473 SIPDriver::~SIPDriver()
9474 {
9475     Output("Unloading module SIP Channel");
9476     TelEngine::destruct(s_authCopyHeader);
9477 }
9478 
initialize()9479 void SIPDriver::initialize()
9480 {
9481     Output("Initializing module SIP Channel");
9482     if (s_engineStart)
9483 	s_sslClientAvailable = socketSsl(0,false);
9484     s_cfg = Engine::configFile("ysipchan");
9485     s_globalMutex.lock();
9486     s_cfg.load();
9487     NamedList* general = s_cfg.getSection("general");
9488     TelEngine::destruct(s_authCopyHeader);
9489     if (general) {
9490 	String* dtmfMethods = general->getParam("dtmfmethods");
9491 	if (dtmfMethods) {
9492 	    if (!s_dtmfMethods.set(*dtmfMethods,0))
9493 		s_dtmfMethods.printMethods(this,DebugConf,*dtmfMethods);
9494 	}
9495 	else {
9496 	    s_dtmfMethods.setDefault();
9497 	    s_dtmfMethods.getDeprecatedDtmfMethod(*general,"dtmfinfo",DtmfMethods::Info,&s_warnDtmfInfoCfg);
9498 	    s_dtmfMethods.getDeprecatedDtmfMethod(*general,"dtmfinband",DtmfMethods::Inband,&s_warnDtmfInbandCfg);
9499 	}
9500 	const String& tmp = (*general)[YSTRING("auth_copy_headers")];
9501 	if (tmp) {
9502 	    s_authCopyHeader = tmp.split(',',false);
9503 	    ObjList* o = s_authCopyHeader->skipNull();
9504 	    if (o)
9505 		for (; o; o = o->skipNext())
9506 		    (static_cast<String*>(o->get()))->toLower();
9507 	    else
9508 		TelEngine::destruct(s_authCopyHeader);
9509 	}
9510     }
9511     else
9512 	s_dtmfMethods.setDefault();
9513     s_globalMutex.unlock();
9514     s_warnPacketUDP = true;
9515     s_checkAllowInfo = s_cfg.getBoolValue("general","check_allow_info",true);
9516     s_missingAllowInfoDefVal = s_cfg.getBoolValue("general","missing_allow_info",true);
9517     s_honorDtmfDetect = s_cfg.getBoolValue("general","honor_dtmf_detect",true);
9518     s_maxForwards = s_cfg.getIntValue("general","maxforwards",20);
9519     s_congRetry = s_cfg.getIntValue("general","congestion_retry",30,10,600);
9520     s_floodEvents = s_cfg.getIntValue("general","floodevents",100);
9521     s_floodProtection = s_cfg.getBoolValue("general","floodprotection",true);
9522     s_privacy = s_cfg.getBoolValue("general","privacy");
9523     s_auto_nat = s_cfg.getBoolValue("general","nat",true);
9524     s_progress = s_cfg.getBoolValue("general","progress",false);
9525     s_start_rtp = s_cfg.getBoolValue("general","rtp_start",false);
9526     s_multi_ringing = s_cfg.getBoolValue("general","multi_ringing",false);
9527     s_refresh_nosdp = s_cfg.getBoolValue("general","refresh_nosdp",true);
9528     s_update_target = s_cfg.getBoolValue("general","update_target",false);
9529     s_update_verify = s_cfg.getBoolValue("general","update_verify",false);
9530     s_preventive_bye = s_cfg.getBoolValue("general","preventive_bye",true);
9531     s_ignoreVia = s_cfg.getBoolValue("general","ignorevia",true);
9532     s_ipv6 = s_cfg.getBoolValue("general","ipv6_support",false);
9533     if (s_ipv6 && !SocketAddr::supports(SocketAddr::IPv6)) {
9534 	Debug(this,DebugConf,"Ignoring IPv6 support enable: not supported");
9535 	s_ipv6 = false;
9536     }
9537     s_printMsg = s_cfg.getBoolValue("general","printmsg",true);
9538     s_tcpMaxpkt = getMaxpkt(s_cfg.getIntValue("general","tcp_maxpkt",4096),4096);
9539     s_lineKeepTcpOffline = s_cfg.getBoolValue("general","line_keeptcpoffline",!Engine::clientMode());
9540     s_defEncoding = s_cfg.getIntValue("general","body_encoding",SipHandler::s_bodyEnc,SipHandler::BodyBase64);
9541     s_gen_async = s_cfg.getBoolValue("general","async_generic",true);
9542     s_sipt_isup = s_cfg.getBoolValue("sip-t","isup",false);
9543     s_enable_transfer = s_cfg.getBoolValue("general","transfer",!Engine::clientMode());
9544     s_enable_options = s_cfg.getBoolValue("options","enable",
9545 	s_cfg.getBoolValue("general","options",true));
9546     s_enable_message = s_cfg.getBoolValue("message","enable",false);
9547     s_auth_message = s_cfg.getBoolValue("message","auth_required",true);
9548     s_msg_async = s_cfg.getBoolValue("message","async_process",true);
9549     s_enable_register = s_cfg.getBoolValue("registrar","enable",
9550 	s_cfg.getBoolValue("general","registrar",!Engine::clientMode()));
9551     s_auth_register = s_cfg.getBoolValue("registrar","auth_required",true);
9552     s_expires_min = s_cfg.getIntValue("registrar","expires_min",EXPIRES_MIN);
9553     s_expires_def = s_cfg.getIntValue("registrar","expires_def",EXPIRES_DEF);
9554     s_expires_max = s_cfg.getIntValue("registrar","expires_max",EXPIRES_MAX);
9555     s_nat_refresh = s_cfg.getIntValue("registrar","nat_refresh",25);
9556     s_reg_async = s_cfg.getBoolValue("registrar","async_process",true);
9557     s_ack_required = !s_cfg.getBoolValue("hacks","ignore_missing_ack",false);
9558     s_1xx_formats = s_cfg.getBoolValue("hacks","1xx_change_formats",true);
9559     s_sdp_implicit = s_cfg.getBoolValue("hacks","sdp_implicit",true);
9560     s_rtp_preserve = s_cfg.getBoolValue("hacks","ignore_sdp_addr",false);
9561     s_changeParty2xx = s_cfg.getBoolValue("general","change_party_2xx",false);
9562     s_initialHeaders = s_cfg.getBoolValue("general","initial_headers");
9563     m_parser.initialize(s_cfg.getSection("codecs"),s_cfg.getSection("hacks"),s_cfg.getSection("general"));
9564     s_trace = s_cfg.getBoolValue("general","trace");
9565     if (!m_endpoint) {
9566 	Thread::Priority prio = Thread::priority(s_cfg.getValue("general","thread"));
9567 	unsigned int partyMutexCount = s_cfg.getIntValue("general","party_mutexcount",47,13,101);
9568 	m_endpoint = new YateSIPEndPoint(prio,partyMutexCount);
9569 	if (!(m_endpoint->Init())) {
9570 	    delete m_endpoint;
9571 	    m_endpoint = 0;
9572 	    return;
9573 	}
9574 	m_endpoint->startup();
9575 	setup();
9576 	installRelay(Halt);
9577 	installRelay(Progress);
9578 	installRelay(Update);
9579 	installRelay(Route);
9580 	installRelay(Status);
9581 	installRelay(Stop,"engine.stop");
9582 	installRelay(Start,"engine.start");
9583 	installRelay(MsgExecute);
9584 	installRelay(Help);
9585 	Engine::install(new UserHandler);
9586 	if (s_cfg.getBoolValue("general","generate"))
9587 	    Engine::install(new SipHandler);
9588     }
9589     else {
9590 	m_endpoint->engine()->initialize(s_cfg.getSection("general"));
9591 	loadLimits();
9592     }
9593     // Unsafe globals
9594     s_globalMutex.lock();
9595     s_realm = s_cfg.getValue("general","realm","Yate");
9596     s_tcpOutRtpip = s_cfg.getValue("general","tcp_out_rtp_localip");
9597     s_sslCertFile = s_cfg.getValue("general","ssl_certificate_file");
9598     s_sslKeyFile = s_cfg.getValue("general","ssl_key_file");
9599     s_globalMutex.unlock();
9600     // set max chans
9601     maxChans(s_cfg.getIntValue("general","maxchans",maxChans()));
9602     // Adjust here the TCP idle interval: it uses the SIP engine
9603     s_tcpIdle = tcpIdleInterval(s_cfg.getIntValue("general","tcp_idle",TCP_IDLE_DEF));
9604     s_tcpKeepalive = s_cfg.getIntValue("general","tcp_keepalive",s_tcpIdle);
9605     s_tcpKeepaliveFirst = s_cfg.getIntValue("general","tcp_keepalive_first",0,0);
9606     // Mark listeners
9607     m_endpoint->initializing(true);
9608     // Setup general listener
9609     NamedList dummy("general");
9610     NamedList* def = general;
9611     if (!def)
9612 	def = &dummy;
9613     NamedList* generalListener = s_cfg.getSection("listener general");
9614     if (generalListener)
9615 	setupListener("general",*generalListener,true,*def);
9616     else
9617 	setupListener("general",*def,true);
9618     // Setup listeners
9619     unsigned int n = s_cfg.sections();
9620     for (unsigned int i = 0; i < n; i++) {
9621 	NamedList* nl = s_cfg.getSection(i);
9622 	String name = nl ? nl->c_str() : "";
9623 	if (!name.startSkip("listener ",false))
9624 	    continue;
9625 	name.trimBlanks();
9626 	if (name && name != YSTRING("general"))
9627 	    setupListener(name,*nl,false,*def);
9628     }
9629     // Remove deleted listeners
9630     m_endpoint->initializing(false);
9631     // Everything set: update default udp transport
9632     m_endpoint->updateDefUdpTransport();
9633 }
9634 
genUpdate(Message & msg)9635 void SIPDriver::genUpdate(Message& msg)
9636 {
9637     DDebug(this,DebugInfo,"fill module.update message");
9638     Lock l(this);
9639     if (m_endpoint) {
9640 	msg.setParam("failed_auths",String(m_endpoint->failedAuths()));
9641 	msg.setParam("transaction_timeouts",String(m_endpoint->timedOutTrs()));
9642 	msg.setParam("bye_timeouts",String(m_endpoint->timedOutByes()));
9643     }
9644 }
9645 
9646 // Setup a listener from config
setupListener(const String & name,const NamedList & params,bool isGeneral,const NamedList & defs)9647 void SIPDriver::setupListener(const String& name, const NamedList& params,
9648     bool isGeneral, const NamedList& defs)
9649 {
9650     const String& type = params[YSTRING("type")];
9651     int proto = ProtocolHolder::lookupProtoAny(type);
9652     if (proto == ProtocolHolder::Unknown) {
9653 	proto = ProtocolHolder::Udp;
9654 	if (!isGeneral || type)
9655 	    Debug(this,DebugConf,"Invalid listener type '%s' in section '%s': defaults to %s",
9656 		type.c_str(),params.c_str(),ProtocolHolder::lookupProtoName(proto,false));
9657     }
9658     bool enabled = (params == YSTRING("general")) || params.getBoolValue(YSTRING("enable"),true);
9659     switch (proto) {
9660 	case ProtocolHolder::Udp:
9661 	    m_endpoint->cancelListener(name,"Type changed");
9662 	    m_endpoint->setupUdpTransport(name,enabled,params,defs);
9663 	    break;
9664 	case ProtocolHolder::Tcp:
9665 	case ProtocolHolder::Tls:
9666 	    m_endpoint->setupUdpTransport(name,false,NamedList::empty(),
9667 		NamedList::empty(),"Type changed");
9668 	    m_endpoint->setupListener(proto,name,enabled,params);
9669 	    break;
9670 	default:
9671 	    if (enabled)
9672 		Debug(this,DebugNote,"Unknown listener type '%s' in section '%s'",
9673 		    type.c_str(),params.c_str());
9674     }
9675 }
9676 
commandComplete(Message & msg,const String & partLine,const String & partWord)9677 bool SIPDriver::commandComplete(Message& msg, const String& partLine, const String& partWord)
9678 {
9679     if (!partLine || partLine == YSTRING("help")) {
9680 	itemComplete(msg.retValue(),name(),partWord);
9681 	return false;
9682     }
9683     if (partLine.startsWith(name())) {
9684 	String tmp = partLine;
9685 	if (!tmp.startSkip(name()))
9686 	    return Driver::commandComplete(msg,partLine,partWord);
9687 	if (!tmp)
9688 	    itemComplete(msg.retValue(),YSTRING("drop"),partWord);
9689 	else if (tmp == YSTRING("drop"))
9690 	    itemComplete(msg.retValue(),YSTRING("transport"),partWord);
9691 	else if (tmp == YSTRING("drop transport")) {
9692 	    if (m_endpoint)
9693 		m_endpoint->completeTransports(msg,partWord,false);
9694 	}
9695 	return true;
9696     }
9697     String cmd = s_statusCmd + " " + name();
9698     String overviewCmd = s_statusCmd + " overview " + name();
9699     if (partLine == cmd || partLine == overviewCmd) {
9700 	itemComplete(msg.retValue(),YSTRING("accounts"),partWord);
9701 	itemComplete(msg.retValue(),YSTRING("listeners"),partWord);
9702 	itemComplete(msg.retValue(),YSTRING("transports"),partWord);
9703     }
9704     String cmdTrans = cmd + " transports";
9705     String cmdOverViewTrans = overviewCmd + " transports";
9706     if (partLine == cmdTrans || partLine == cmdOverViewTrans) {
9707 	if (m_endpoint) {
9708 	    itemComplete(msg.retValue(),YSTRING("all"),partWord);
9709 	    itemComplete(msg.retValue(),YSTRING("udp"),partWord);
9710 	    itemComplete(msg.retValue(),YSTRING("tcp"),partWord);
9711 	    itemComplete(msg.retValue(),YSTRING("tls"),partWord);
9712 	    if (partLine == cmdTrans)
9713 		m_endpoint->completeTransports(msg,partWord);
9714 	}
9715     }
9716     else
9717     	return Driver::commandComplete(msg,partLine,partWord);
9718     return false;
9719 }
9720 
commandExecute(String & retVal,const String & line)9721 bool SIPDriver::commandExecute(String& retVal, const String& line)
9722 {
9723     if (!line.startsWith(name()))
9724 	return Driver::commandExecute(retVal,line);
9725     String tmp = line;
9726     if (!tmp.startSkip(name()))
9727 	return Driver::commandExecute(retVal,line);
9728     if (tmp.startSkip("drop transport")) {
9729 	if (!tmp)
9730 	    return false;
9731 	YateSIPTransport* t = m_endpoint ? m_endpoint->findTransport(tmp) : 0;
9732 	YateSIPTCPTransport* trans = t ? t->tcpTransport() : 0;
9733 	if (trans)
9734 	    trans->terminate("dropped");
9735 	TelEngine::destruct(t);
9736 	return trans != 0;
9737     }
9738     return false;
9739 }
9740 
msgStatus(Message & msg)9741 void SIPDriver::msgStatus(Message& msg)
9742 {
9743     String str = msg.getValue(YSTRING("module"));
9744     if (str.null() || str.startSkip(name())) {
9745 	str.trimBlanks();
9746 	if (str.null())
9747 	    Module::msgStatus(msg);
9748 	else if (str.startSkip("accounts"))
9749 	    msgStatusAccounts(msg);
9750 	else if (str.startSkip("transports")) {
9751 	    String tmp = str;
9752 	    tmp.trimBlanks().toLower();
9753 	    if (tmp == YSTRING("udp"))
9754 		msgStatusTransports(msg,true,false,false);
9755 	    else if (tmp == YSTRING("tcp"))
9756 		msgStatusTransports(msg,false,true,false);
9757 	    else if (tmp == YSTRING("tls"))
9758 		msgStatusTransports(msg,false,false,true);
9759 	    else if (!tmp || tmp == YSTRING("all"))
9760 		msgStatusTransports(msg,true,true,true);
9761 	    else if (msg.getBoolValue("details",true))
9762 		msgStatusTransport(msg,str);
9763 	}
9764 	else if (str.startSkip("listeners"))
9765 	    msgStatusListener(msg);
9766     }
9767 }
9768 
statusParams(String & str)9769 void SIPDriver::statusParams(String& str)
9770 {
9771     Driver::statusParams(str);
9772     if (m_endpoint && m_endpoint->engine())
9773 	str.append("transactions=",",") << m_endpoint->engine()->transactionCount();
9774 }
9775 
9776 // Build and dispatch a socket.ssl message
socketSsl(Socket ** sock,bool server,const String & context)9777 bool SIPDriver::socketSsl(Socket** sock, bool server, const String& context)
9778 {
9779     Message m("socket.ssl");
9780     m.addParam("module",name());
9781     m.addParam("server",String::boolText(server));
9782     m.addParam("context",context,false);
9783     if (!server) {
9784 	Lock lock(s_globalMutex);
9785 	m.addParam("certificate",s_sslCertFile,false);
9786 	m.addParam("key",s_sslKeyFile,false);
9787     }
9788     if (sock && *sock) {
9789 	SocketRef* p = new SocketRef(sock);
9790 	m.userData(p);
9791 	TelEngine::destruct(p);
9792     }
9793     else
9794         m.addParam("test",String::boolText(true));
9795     return Engine::dispatch(m);
9796 }
9797 
9798 // Send a SIP method
sendMethod(Message & msg,const char * method,bool msgExec,const char * target)9799 bool SIPDriver::sendMethod(Message& msg, const char* method, bool msgExec,
9800     const char* target)
9801 {
9802     Debug(this,DebugAll,"Sending method '%s'",method);
9803     if (!method)
9804 	return false;
9805     RefPointer<YateSIPConnection> conn;
9806     String uri = target;
9807     const char* id = msg.getValue(YSTRING("id"));
9808     if (id) {
9809 	lock();
9810 	conn = static_cast<YateSIPConnection*>(find(id));
9811 	unlock();
9812 	if (!conn) {
9813 	    msg.setParam("error","noconn");
9814 	    return false;
9815 	}
9816 	if (!(msgExec || uri))
9817 	    uri = conn->m_uri;
9818     }
9819     if (!msgExec)
9820 	uri = msg.getValue(YSTRING("uri"),uri);
9821     else if (!uri)
9822 	uri = msg.getValue(YSTRING("uri"));
9823     static const Regexp r("<\\([^>]\\+\\)>");
9824     if (uri.matches(r))
9825 	uri = uri.matchString(1);
9826     if (!uri) {
9827 	msg.setParam("error","failure");
9828 	return false;
9829     }
9830 
9831     int maxf = msg.getIntValue(YSTRING("antiloop"),s_maxForwards);
9832     if (maxf <= 0) {
9833 	Debug(this,DebugMild,"Blocking looping request '%s %s' [%p]",
9834 	    method,uri.c_str(),this);
9835 	msg.setParam("error","looping");
9836 	return false;
9837     }
9838 
9839     SIPMessage* sip = 0;
9840     const char* domain = msg.getValue(YSTRING("domain"));
9841     if (conn) {
9842 	sip = conn->createDlgMsg(method,uri);
9843 	conn = 0;
9844     }
9845     else {
9846 	YateSIPLine* line = findLine(msg.getValue(YSTRING("line")));
9847 	if (line && !line->valid()) {
9848 	    msg.setParam("error","offline");
9849 	    return false;
9850 	}
9851 	sip = new SIPMessage(method,uri);
9852 	YateSIPPartyHolder holder(this);
9853 	URI rUri(uri);
9854 	holder.sips(rUri.getProtocol() == YSTRING("sips"));
9855 	const char* host = msg.getValue("host",rUri.getHost());
9856 	int port = msg.getIntValue("port",rUri.getPort());
9857 	// Force party creation for SIPS: it will force used protocol to TLS
9858 	holder.setParty(msg,holder.sips(),String::empty(),host,port,true);
9859 	holder.setSipParty(sip,line,true,host,port);
9860 	if (line)
9861 	    domain = line->domain(domain);
9862     }
9863     if (!sip->getParty()) {
9864 	Debug(this,DebugWarn,"Could not create party to generate '%s'",
9865 	    sip->method.c_str());
9866 	TelEngine::destruct(sip);
9867 	msg.setParam("error","notransport");
9868 	return false;
9869     }
9870     sip->addHeader("Max-Forwards",String(maxf));
9871     copySipHeaders(*sip,msg,"sip_");
9872     copySipBody(*sip,msg);
9873     const char* user = msg.getValue(YSTRING("user"));
9874     sip->complete(ep()->engine(),user,domain,0,
9875 	msg.getIntValue(YSTRING("xsip_flags"),-1));
9876     user = msg.getValue(YSTRING("authname"),user);
9877     const char* pass = msg.getValue(YSTRING("password"));
9878     if (user && pass)
9879 	sip->setAutoAuth(user,pass);
9880     if (!msg.getBoolValue(YSTRING("wait"))) {
9881 	// no answer requested - start transaction and forget
9882 	ep()->engine()->addMessage(sip);
9883 	sip->deref();
9884 	return true;
9885     }
9886     YateSIPGenerate gen(sip,msg.getIntValue(YSTRING("xsip_trans_count"),-1));
9887     while (gen.busy())
9888 	Thread::idle();
9889     if (gen.code()) {
9890 	msg.setParam("code",String(gen.code()));
9891 	msg.clearParam("sip",'_');
9892 	msg.clearParam("xsip",'_');
9893 	if (gen.answer()) {
9894 	    copySipHeaders(msg,*gen.answer(),true,ep()->engine()->foreignAuth());
9895 	    copySipBody(msg,*gen.answer());
9896 	}
9897     }
9898     else
9899 	msg.clearParam("code");
9900     return true;
9901 }
9902 
onHelp(Message & msg)9903 bool SIPDriver::onHelp(Message& msg)
9904 {
9905     static const char* s_cmds = "  sip drop transport <name>\r\n";
9906     static const char* s_cmdsDesc = "Drop a tcp/tls transport\r\n";
9907 
9908     if (msg[YSTRING("line")] == name()) {
9909 	msg.retValue() << s_cmds << s_cmdsDesc;
9910 	return true;
9911     }
9912     msg.retValue() << s_cmds;
9913     return false;
9914 }
9915 
9916 // Add accounts status
msgStatusAccounts(Message & msg)9917 void SIPDriver::msgStatusAccounts(Message& msg)
9918 {
9919     msg.retValue().clear();
9920     msg.retValue() << "module=" << name();
9921     msg.retValue() << ",protocol=SIP";
9922     msg.retValue() << ",format=Username|Status;";
9923     msg.retValue() << "accounts=" << s_lines.count();
9924     if (!msg.getBoolValue("details",true)) {
9925 	msg.retValue() << "\r\n";
9926 	return;
9927     }
9928     String accounts = "";
9929     for (ObjList* o = s_lines.skipNull(); o; o = o->skipNext()) {
9930 	YateSIPLine* line = static_cast<YateSIPLine*>(o->get());
9931 	accounts.append(line->c_str(),",") << "=";
9932 	accounts.append(line->getUserName()) << "|";
9933 	accounts << (line->valid() ? "online" : "offline");
9934     }
9935     msg.retValue().append(accounts,";");
9936     msg.retValue() << "\r\n";
9937 }
9938 
9939 // Add transports status
msgStatusTransports(Message & msg,bool showUdp,bool showTcp,bool showTls)9940 void SIPDriver::msgStatusTransports(Message& msg, bool showUdp, bool showTcp, bool showTls)
9941 {
9942     msg.retValue().clear();
9943     msg.retValue() << "module=" << name();
9944     msg.retValue() << ",protocol=SIP";
9945     YateSIPUDPTransport* def = m_endpoint ? m_endpoint->defTransport() : 0;
9946     msg.retValue() << ",udp_default=" << (def ? def->toString() : String::empty());
9947     TelEngine::destruct(def);
9948     msg.retValue() << ",format=Proto|Status|Local|Remote|Outgoing|Reason;";
9949     String buf;
9950     unsigned int n = 0;
9951     if (m_endpoint) {
9952 	Lock lock(m_endpoint->m_mutex);
9953 	bool details = msg.getBoolValue("details",true);
9954 	for (ObjList* o = m_endpoint->m_transports.skipNull(); o; o = o->skipNext()) {
9955 	    YateSIPTransport* t = static_cast<YateSIPTransport*>(o->get());
9956 	    YateSIPTCPTransport* tcp = t->tcpTransport();
9957 	    if (!tcp) {
9958 		if (!showUdp)
9959 		    continue;
9960 	    }
9961 	    else if (!tcp->tls()) {
9962 		if (!showTcp)
9963 		    continue;
9964 	    }
9965 	    else if (!showTls)
9966 		continue;
9967 	    n++;
9968 	    if (!details)
9969 		continue;
9970 	    Lock lck(t);
9971 	    buf.append(String(n),",") << "=" << t->protoName() << "|";
9972 	    buf << YateSIPTransport::statusName(t->status()) << "|";
9973 	    buf << t->local().addr() << "|";
9974 	    if (tcp) {
9975 		buf << t->remote().addr() << "|";
9976 		buf << String::boolText(tcp->outgoing());
9977 	    }
9978 	    else
9979 		buf << "|";
9980 	    buf << "|" << t->m_reason;
9981 	}
9982     }
9983     msg.retValue() << "transports=" << n;
9984     msg.retValue().append(buf,";");
9985     msg.retValue() << "\r\n";
9986 }
9987 
9988 // Add listeners status
msgStatusListener(Message & msg)9989 void SIPDriver::msgStatusListener(Message& msg)
9990 {
9991     msg.retValue().clear();
9992     msg.retValue() << "module=" << name();
9993     msg.retValue() << ",protocol=SIP";
9994     msg.retValue() << ",format=Proto|Address|Status|Reason;";
9995     String buf;
9996     unsigned int n = 0;
9997     if (m_endpoint) {
9998 	bool details = msg.getBoolValue("details",true);
9999 	Lock lock(m_endpoint->m_mutex);
10000 	for (ObjList* o = m_endpoint->m_transports.skipNull(); o; o = o->skipNext()) {
10001 	    YateSIPTransport* t = static_cast<YateSIPTransport*>(o->get());
10002 	    YateSIPUDPTransport* udp = t->udpTransport();
10003 	    if (!udp)
10004 		continue;
10005 	    n++;
10006 	    if (!details)
10007 		continue;
10008 	    Lock lck(udp);
10009 	    buf.append(udp->toString(),",") << "=" << udp->protoName() << "|";
10010 	    if (udp->status() == YateSIPTransport::Connected)
10011 		buf << udp->local().addr() << "|Listening|";
10012 	    else
10013 		SocketAddr::appendTo(buf,udp->address(),udp->port()) << "|Idle|";
10014 	    buf << udp->m_reason;
10015 	}
10016 	if (details) {
10017 	    for (ObjList* o = m_endpoint->m_listeners.skipNull(); o; o = o->skipNext()) {
10018 		YateSIPTCPListener* l = static_cast<YateSIPTCPListener*>(o->get());
10019 		n++;
10020 		buf.append(l->toString(),",") << "=";
10021 		buf << l->protoName() << "|";
10022 		Lock lck(l->m_mutex);
10023 		if (l->listening())
10024 		    buf << l->local().addr() << "|Listening|";
10025 		else
10026 		    SocketAddr::appendTo(buf,l->address(),l->port()) << "|Idle|";
10027 		buf << l->m_reason;
10028 	    }
10029 	}
10030 	else
10031 	    n += m_endpoint->m_listeners.count();
10032     }
10033     msg.retValue() << "listeners=" << n;
10034     msg.retValue().append(buf,";");
10035     msg.retValue() << "\r\n";
10036 }
10037 
10038 // Add transport status
msgStatusTransport(Message & msg,const String & id)10039 void SIPDriver::msgStatusTransport(Message& msg, const String& id)
10040 {
10041     msg.retValue().clear();
10042     msg.retValue() << "module=" << name();
10043     msg.retValue() << ",protocol=SIP;";
10044     String tmp = id;
10045     tmp.trimBlanks();
10046     YateSIPTransport* t = m_endpoint ? m_endpoint->findTransport(tmp) : 0;
10047     if (t) {
10048 	YateSIPTCPTransport* tcp = t->tcpTransport();
10049 	t->lock();
10050 	msg.retValue() << "name=" << t->toString();
10051 	msg.retValue() << ",protocol=" << t->protoName();
10052 	msg.retValue() << ",status=" << YateSIPTransport::statusName(t->status());
10053 	msg.retValue() << ",statustime=" << (msg.msgTime().sec() - t->m_statusChgTime);
10054 	msg.retValue() << ",local=" << t->local().addr();
10055 	if (tcp) {
10056 	    msg.retValue() << ",remote=" << t->remote().addr();
10057 	    msg.retValue() << ",outgoing=" << String::boolText(tcp->outgoing());
10058 	}
10059 	String lines;
10060 	for (ObjList* ol = s_lines.skipNull(); ol; ol = ol->skipNext()) {
10061 	    YateSIPLine* line = static_cast<YateSIPLine*>(ol->get());
10062 	    if (line->isTransport(t))
10063 		lines.append(line->toString(),",");
10064 	}
10065 	msg.retValue() << ",lines=" << lines;
10066 	msg.retValue() << ",references=" << (t->refcount() - 1);
10067 	msg.retValue() << ",reason=" << t->m_reason;
10068 	t->unlock();
10069 	TelEngine::destruct(t);
10070     }
10071     msg.retValue() << "\r\n";
10072 }
10073 
10074 }; // anonymous namespace
10075 
10076 /* vi: set ts=8 sw=4 sts=4 noet: */
10077