Debian Codegraph @

Xpjproject/pjsip/src/pjsua2/endpoint.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18 #include <pjsua2/endpoint.hpp>
19 #include <pjsua2/call.hpp>
20 #include <pjsua2/presence.hpp>
21 #include <algorithm>
22 #include "util.hpp"
23
24 using namespace pj;
25 using namespace std;
26
27 #include <pjsua-lib/pjsua_internal.h> /* For retrieving pjsua threads */
28
29 #define THIS_FILE "endpoint.cpp"
30 #define MAX_STUN_SERVERS 32
31 #define TIMER_SIGNATURE 0x600D878A
32 #define MAX_CODEC_NUM 64
33
34 struct UserTimer
35 {
36 pj_uint32_t signature;
37 OnTimerParam prm;
38 pj_timer_entry entry;
39 };
40
41 Endpoint *Endpoint::instance_;
42
43 ///////////////////////////////////////////////////////////////////////////////
44
45 TlsInfo::TlsInfo()
46 : established(false),
47 protocol(0),
48 cipher(PJ_TLS_UNKNOWN_CIPHER),
49 verifyStatus(0),
50 empty(true)
51 {
52 }
53
54 bool TlsInfo::isEmpty() const
55 {
56 return empty;
57 }
58
59 void TlsInfo::fromPj(const pjsip_tls_state_info &info)
60 {
61 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK != 0
62 pj_ssl_sock_info *ssock_info = info.ssl_sock_info;
63 char straddr[PJ_INET6_ADDRSTRLEN+10];
64 const char *verif_msgs[32];
65 const char *cipher_name;
66 unsigned verif_msg_cnt;
67
68 empty = false;
69 established = PJ2BOOL(ssock_info->established);
70 protocol = ssock_info->proto;
71 cipher = ssock_info->cipher;
72 cipher_name = pj_ssl_cipher_name(ssock_info->cipher);
73 if (cipher_name) {
74 cipherName = cipher_name;
75 } else {
76 char tmp[32];
77 pj_ansi_snprintf(tmp, sizeof(tmp), "Cipher 0x%x", cipher);
78 cipherName = tmp;
79 }
80 pj_sockaddr_print(&ssock_info->local_addr, straddr, sizeof(straddr), 3);
81 localAddr = straddr;
82 pj_sockaddr_print(&ssock_info->remote_addr, straddr, sizeof(straddr),3);
83 remoteAddr = straddr;
84 verifyStatus = ssock_info->verify_status;
85 if (ssock_info->local_cert_info)
86 localCertInfo.fromPj(*ssock_info->local_cert_info);
87 if (ssock_info->remote_cert_info)
88 remoteCertInfo.fromPj(*ssock_info->remote_cert_info);
89
90 /* Dump server TLS certificate verification result */
91 verif_msg_cnt = PJ_ARRAY_SIZE(verif_msgs);
92 pj_ssl_cert_get_verify_status_strings(ssock_info->verify_status,
93 verif_msgs, &verif_msg_cnt);
94 for (unsigned i = 0; i < verif_msg_cnt; ++i) {
95 verifyMsgs.push_back(verif_msgs[i]);
96 }
97 #else
98 PJ_UNUSED_ARG(info);
99 #endif
100 }
101
102 SslCertInfo::SslCertInfo()
103 : version(0xFF),
104 validityGmt(false),
105 empty(true)
106 {
107 }
108
109 bool SslCertInfo::isEmpty() const
110 {
111 return empty;
112 }
113
114 void SslCertInfo::fromPj(const pj_ssl_cert_info &info)
115 {
116 empty = false;
117 version = info.version;
118 pj_memcpy(serialNo, info.serial_no, sizeof(info.serial_no));
119 subjectCn = pj2Str(info.subject.cn);
120 subjectInfo = pj2Str(info.subject.info);
121 issuerCn = pj2Str(info.issuer.cn);
122 issuerInfo = pj2Str(info.issuer.info);
123 validityStart.fromPj(info.validity.start);
124 validityEnd.fromPj(info.validity.end);
125 validityGmt = PJ2BOOL(info.validity.gmt);
126 raw = pj2Str(info.raw);
127
128 for (unsigned i = 0; i < info.subj_alt_name.cnt; i++) {
129 SslCertName cname;
130 cname.type = info.subj_alt_name.entry[i].type;
131 cname.name = pj2Str(info.subj_alt_name.entry[i].name);
132 subjectAltName.push_back(PJSUA2_MOVE(cname));
133 }
134 }
135
136 void DigestCredential::fromPj(const pjsip_digest_credential &prm)
137 {
138 realm = pj2Str(prm.realm);
139 pjsip_param *p = (pjsip_param*)prm.other_param.next;
140 while (p != &prm.other_param) {
141 otherParam[pj2Str(p->name)] = pj2Str(p->value);
142 p = p->next;
143 }
144 username = pj2Str(prm.username);
145 nonce = pj2Str(prm.nonce);
146 uri = pj2Str(prm.uri);
147 response = pj2Str(prm.response);
148 algorithm = pj2Str(prm.algorithm);
149 cnonce = pj2Str(prm.cnonce);
150 opaque = pj2Str(prm.opaque);
151 qop = pj2Str(prm.qop);
152 nc = pj2Str(prm.nc);
153 }
154
155 pjsip_digest_credential DigestCredential::toPj() const
156 {
157 pjsip_digest_credential credentials;
158 pj_list_init(&credentials.other_param);
159 credentials.realm = str2Pj(realm);
160 credentials.username = str2Pj(username);
161 for (std::map<std::string, std::string>::const_iterator it = otherParam.begin();
162 it != otherParam.end(); ++it) {
163 pjsip_param other_param;
164 other_param.name = str2Pj(it->first);
165 other_param.value = str2Pj(it->second);
166 pj_list_push_back(&credentials.other_param, &other_param);
167 }
168 credentials.nonce = str2Pj(nonce);
169 credentials.uri = str2Pj(uri);
170 credentials.response = str2Pj(response);
171 credentials.algorithm = str2Pj(algorithm);
172 credentials.cnonce = str2Pj(cnonce);
173 credentials.opaque = str2Pj(opaque);
174 credentials.qop = str2Pj(qop);
175 credentials.nc = str2Pj(nc);
176 return credentials;
177 }
178
179 void DigestChallenge::fromPj(const pjsip_digest_challenge &prm)
180 {
181 realm = pj2Str(prm.realm);
182 pjsip_param *p = (pjsip_param*)prm.other_param.next;
183 while (p != &prm.other_param) {
184 otherParam[pj2Str(p->name)] = pj2Str(p->value);
185 p = p->next;
186 }
187 domain = pj2Str(prm.domain);
188 nonce = pj2Str(prm.nonce);
189 opaque = pj2Str(prm.opaque);
190 stale = prm.stale;
191 algorithm = pj2Str(prm.algorithm);
192 qop = pj2Str(prm.qop);
193 }
194
195 pjsip_digest_challenge DigestChallenge::toPj() const
196 {
197 pjsip_digest_challenge challenge;
198 pj_list_init(&challenge.other_param);
199 challenge.realm = str2Pj(realm);
200 challenge.domain = str2Pj(domain);
201 for (std::map<std::string, std::string>::const_iterator it = otherParam.begin();
202 it != otherParam.end(); ++it) {
203 pjsip_param other_param;
204 other_param.name = str2Pj(it->first);
205 other_param.value = str2Pj(it->second);
206 pj_list_push_back(&challenge.other_param, &other_param);
207 }
208 challenge.nonce = str2Pj(nonce);
209 challenge.opaque = str2Pj(opaque);
210 challenge.stale = stale;
211 challenge.algorithm = str2Pj(algorithm);
212 challenge.qop = str2Pj(qop);
213 return challenge;
214 }
215
216 ///////////////////////////////////////////////////////////////////////////////
217 IpChangeParam::IpChangeParam()
218 {
219 pjsua_ip_change_param param;
220 pjsua_ip_change_param_default(&param);
221 fromPj(param);
222 }
223
224
225 pjsua_ip_change_param IpChangeParam::toPj() const
226 {
227 pjsua_ip_change_param param;
228 pjsua_ip_change_param_default(&param);
229
230 param.restart_listener = restartListener;
231 param.restart_lis_delay = restartLisDelay;
232 param.shutdown_transport = shutdownTransport;
233
234 return param;
235 }
236
237
238 void IpChangeParam::fromPj(const pjsua_ip_change_param &param)
239 {
240 restartListener = PJ2BOOL(param.restart_listener);
241 restartLisDelay = param.restart_lis_delay;
242 shutdownTransport = PJ2BOOL(param.shutdown_transport);
243 }
244
245 ///////////////////////////////////////////////////////////////////////////////
246 void OnAudioMediaOpCompletedParam::fromPj(const pjmedia_conf_op_info &info)
247 {
248 opType = info.op_type;
249 status = info.status;
250 switch (opType) {
251 case PJMEDIA_CONF_OP_ADD_PORT:
252 opParam.addInfo.mediaId = info.op_param.add_port.port;
253 break;
254 case PJMEDIA_CONF_OP_REMOVE_PORT:
255 opParam.removeInfo.mediaId = info.op_param.remove_port.port;
256 break;
257 case PJMEDIA_CONF_OP_CONNECT_PORTS:
258 opParam.connectInfo.mediaId = info.op_param.connect_ports.src;
259 opParam.connectInfo.targetMediaId = info.op_param.connect_ports.sink;
260 opParam.connectInfo.adjLevel = info.op_param.connect_ports.adj_level;
261 break;
262 case PJMEDIA_CONF_OP_DISCONNECT_PORTS:
263 opParam.disconnectInfo.mediaId = info.op_param.disconnect_ports.src;
264 opParam.disconnectInfo.targetMediaId =
265 info.op_param.disconnect_ports.sink;
266 break;
267 default:
268 break;
269 }
270 }
271
272 void OnVideoMediaOpCompletedParam::fromPj(const pjmedia_vid_conf_op_info &info)
273 {
274 opType = info.op_type;
275 status = info.status;
276 switch (opType) {
277 case PJMEDIA_VID_CONF_OP_ADD_PORT:
278 opParam.addInfo.mediaId = info.op_param.add_port.port;
279 break;
280 case PJMEDIA_VID_CONF_OP_REMOVE_PORT:
281 opParam.removeInfo.mediaId = info.op_param.remove_port.port;
282 break;
283 case PJMEDIA_VID_CONF_OP_CONNECT_PORTS:
284 opParam.connectInfo.mediaId = info.op_param.connect_ports.src;
285 opParam.connectInfo.targetMediaId = info.op_param.connect_ports.sink;
286 break;
287 case PJMEDIA_VID_CONF_OP_DISCONNECT_PORTS:
288 opParam.disconnectInfo.mediaId = info.op_param.disconnect_ports.src;
289 opParam.disconnectInfo.targetMediaId =
290 info.op_param.disconnect_ports.sink;
291 break;
292 case PJMEDIA_VID_CONF_OP_UPDATE_PORT:
293 opParam.updateInfo.mediaId = info.op_param.update_port.port;
294 break;
295 default:
296 break;
297 }
298 }
299
300 ///////////////////////////////////////////////////////////////////////////////
301 UaConfig::UaConfig()
302 : mainThreadOnly(false)
303 {
304 pjsua_config ua_cfg;
305
306 pjsua_config_default(&ua_cfg);
307 fromPj(ua_cfg);
308 }
309
310 void UaConfig::fromPj(const pjsua_config &ua_cfg)
311 {
312 unsigned i;
313
314 this->maxCalls = ua_cfg.max_calls;
315 this->threadCnt = ua_cfg.thread_cnt;
316 this->userAgent = pj2Str(ua_cfg.user_agent);
317
318 for (i=0; i<ua_cfg.nameserver_count; ++i) {
319 this->nameserver.push_back(pj2Str(ua_cfg.nameserver[i]));
320 }
321
322 for (i=0; i<ua_cfg.stun_srv_cnt; ++i) {
323 this->stunServer.push_back(pj2Str(ua_cfg.stun_srv[i]));
324 }
325 for (i=0; i<ua_cfg.outbound_proxy_cnt; ++i) {
326 this->outboundProxies.push_back(pj2Str(ua_cfg.outbound_proxy[i]));
327 }
328
329 this->stunTryIpv6 = PJ2BOOL(ua_cfg.stun_try_ipv6);
330 this->stunIgnoreFailure = PJ2BOOL(ua_cfg.stun_ignore_failure);
331 this->natTypeInSdp = ua_cfg.nat_type_in_sdp;
332 this->mwiUnsolicitedEnabled = PJ2BOOL(ua_cfg.enable_unsolicited_mwi);
333 this->enableUpnp = PJ2BOOL(ua_cfg.enable_upnp);
334 this->upnpIfName = pj2Str(ua_cfg.upnp_if_name);
335 this->noRefersub = PJ2BOOL(ua_cfg.no_refer_sub);
336 }
337
338 pjsua_config UaConfig::toPj() const
339 {
340 unsigned i;
341 pjsua_config pua_cfg;
342
343 pjsua_config_default(&pua_cfg);
344
345 pua_cfg.max_calls = this->maxCalls;
346 pua_cfg.thread_cnt = this->threadCnt;
347 pua_cfg.user_agent = str2Pj(this->userAgent);
348
349 for (i=0; i<this->nameserver.size() && i<PJ_ARRAY_SIZE(pua_cfg.nameserver);
350 ++i)
351 {
352 pua_cfg.nameserver[i] = str2Pj(this->nameserver[i]);
353 }
354 pua_cfg.nameserver_count = i;
355
356 for (i=0; i<this->stunServer.size() && i<PJ_ARRAY_SIZE(pua_cfg.stun_srv);
357 ++i)
358 {
359 pua_cfg.stun_srv[i] = str2Pj(this->stunServer[i]);
360 }
361 pua_cfg.stun_srv_cnt = i;
362
363 for (i=0; i<this->outboundProxies.size() &&
364 i<PJ_ARRAY_SIZE(pua_cfg.outbound_proxy); ++i)
365 {
366 pua_cfg.outbound_proxy[i] = str2Pj(this->outboundProxies[i]);
367 }
368 pua_cfg.outbound_proxy_cnt= i;
369
370 pua_cfg.nat_type_in_sdp = this->natTypeInSdp;
371 pua_cfg.enable_unsolicited_mwi = this->mwiUnsolicitedEnabled;
372 pua_cfg.stun_try_ipv6 = this->stunTryIpv6;
373 pua_cfg.stun_ignore_failure = this->stunIgnoreFailure;
374 pua_cfg.enable_upnp = this->enableUpnp;
375 pua_cfg.upnp_if_name = str2Pj(this->upnpIfName);
376 pua_cfg.no_refer_sub = this->noRefersub;
377
378 return pua_cfg;
379 }
380
381 void UaConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error)
382 {
383 ContainerNode this_node = node.readContainer("UaConfig");
384
385 NODE_READ_UNSIGNED( this_node, maxCalls);
386 NODE_READ_UNSIGNED( this_node, threadCnt);
387 NODE_READ_BOOL ( this_node, mainThreadOnly);
388 NODE_READ_STRINGV ( this_node, nameserver);
389 NODE_READ_STRING ( this_node, userAgent);
390 NODE_READ_STRINGV ( this_node, stunServer);
391 NODE_READ_BOOL ( this_node, stunTryIpv6);
392 NODE_READ_BOOL ( this_node, stunIgnoreFailure);
393 NODE_READ_INT ( this_node, natTypeInSdp);
394 NODE_READ_BOOL ( this_node, mwiUnsolicitedEnabled);
395 NODE_READ_BOOL ( this_node, enableUpnp);
396 NODE_READ_STRING ( this_node, upnpIfName);
397 NODE_READ_BOOL_OPT( this_node, noRefersub);
398 }
399
400 void UaConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error)
401 {
402 ContainerNode this_node = node.writeNewContainer("UaConfig");
403
404 NODE_WRITE_UNSIGNED( this_node, maxCalls);
405 NODE_WRITE_UNSIGNED( this_node, threadCnt);
406 NODE_WRITE_BOOL ( this_node, mainThreadOnly);
407 NODE_WRITE_STRINGV ( this_node, nameserver);
408 NODE_WRITE_STRING ( this_node, userAgent);
409 NODE_WRITE_STRINGV ( this_node, stunServer);
410 NODE_WRITE_BOOL ( this_node, stunTryIpv6);
411 NODE_WRITE_BOOL ( this_node, stunIgnoreFailure);
412 NODE_WRITE_INT ( this_node, natTypeInSdp);
413 NODE_WRITE_BOOL ( this_node, mwiUnsolicitedEnabled);
414 NODE_WRITE_BOOL ( this_node, enableUpnp);
415 NODE_WRITE_STRING ( this_node, upnpIfName);
416 NODE_WRITE_BOOL ( this_node, noRefersub);
417 }
418
419 ///////////////////////////////////////////////////////////////////////////////
420
421 LogConfig::LogConfig()
422 {
423 pjsua_logging_config lc;
424
425 pjsua_logging_config_default(&lc);
426 fromPj(lc);
427 }
428
429 void LogConfig::fromPj(const pjsua_logging_config &lc)
430 {
431 this->msgLogging = lc.msg_logging;
432 this->level = lc.level;
433 this->consoleLevel = lc.console_level;
434 this->decor = lc.decor;
435 this->filename = pj2Str(lc.log_filename);
436 this->fileFlags = lc.log_file_flags;
437 this->writer = NULL;
438 }
439
440 pjsua_logging_config LogConfig::toPj() const
441 {
442 pjsua_logging_config lc;
443
444 pjsua_logging_config_default(&lc);
445
446 lc.msg_logging = this->msgLogging;
447 lc.level = this->level;
448 lc.console_level = this->consoleLevel;
449 lc.decor = this->decor;
450 lc.log_file_flags = this->fileFlags;
451 lc.log_filename = str2Pj(this->filename);
452
453 return lc;
454 }
455
456 void LogConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error)
457 {
458 ContainerNode this_node = node.readContainer("LogConfig");
459
460 NODE_READ_UNSIGNED( this_node, msgLogging);
461 NODE_READ_UNSIGNED( this_node, level);
462 NODE_READ_UNSIGNED( this_node, consoleLevel);
463 NODE_READ_UNSIGNED( this_node, decor);
464 NODE_READ_STRING ( this_node, filename);
465 NODE_READ_UNSIGNED( this_node, fileFlags);
466 }
467
468 void LogConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error)
469 {
470 ContainerNode this_node = node.writeNewContainer("LogConfig");
471
472 NODE_WRITE_UNSIGNED( this_node, msgLogging);
473 NODE_WRITE_UNSIGNED( this_node, level);
474 NODE_WRITE_UNSIGNED( this_node, consoleLevel);
475 NODE_WRITE_UNSIGNED( this_node, decor);
476 NODE_WRITE_STRING ( this_node, filename);
477 NODE_WRITE_UNSIGNED( this_node, fileFlags);
478 }
479
480 ///////////////////////////////////////////////////////////////////////////////
481
482 MediaConfig::MediaConfig()
483 {
484 pjsua_media_config mc;
485
486 pjsua_media_config_default(&mc);
487 fromPj(mc);
488 }
489
490 void MediaConfig::fromPj(const pjsua_media_config &mc)
491 {
492 this->clockRate = mc.clock_rate;
493 this->sndClockRate = mc.snd_clock_rate;
494 this->sndUseSwClock = PJ2BOOL(mc.snd_use_sw_clock);
495 this->channelCount = mc.channel_count;
496 this->audioFramePtime = mc.audio_frame_ptime;
497 this->maxMediaPorts = mc.max_media_ports;
498 this->confThreads = mc.conf_threads;
499 this->hasIoqueue = PJ2BOOL(mc.has_ioqueue);
500 this->threadCnt = mc.thread_cnt;
501 this->quality = mc.quality;
502 this->ptime = mc.ptime;
503 this->noVad = PJ2BOOL(mc.no_vad);
504 this->ilbcMode = mc.ilbc_mode;
505 this->txDropPct = mc.tx_drop_pct;
506 this->rxDropPct = mc.rx_drop_pct;
507 this->ecOptions = mc.ec_options;
508 this->ecTailLen = mc.ec_tail_len;
509 this->sndRecLatency = mc.snd_rec_latency;
510 this->sndPlayLatency = mc.snd_play_latency;
511 this->jbInit = mc.jb_init;
512 this->jbMinPre = mc.jb_min_pre;
513 this->jbMaxPre = mc.jb_max_pre;
514 this->jbMax = mc.jb_max;
515 this->jbDiscardAlgo = mc.jb_discard_algo;
516 this->sndAutoCloseTime = mc.snd_auto_close_time;
517 this->vidPreviewEnableNative = PJ2BOOL(mc.vid_preview_enable_native);
518 }
519
520 pjsua_media_config MediaConfig::toPj() const
521 {
522 pjsua_media_config mcfg;
523
524 pjsua_media_config_default(&mcfg);
525
526 mcfg.clock_rate = this->clockRate;
527 mcfg.snd_clock_rate = this->sndClockRate;
528 mcfg.snd_use_sw_clock = this->sndUseSwClock;
529 mcfg.channel_count = this->channelCount;
530 mcfg.audio_frame_ptime = this->audioFramePtime;
531 mcfg.max_media_ports = this->maxMediaPorts;
532 mcfg.conf_threads = this->confThreads;
533 mcfg.has_ioqueue = this->hasIoqueue;
534 mcfg.thread_cnt = this->threadCnt;
535 mcfg.quality = this->quality;
536 mcfg.ptime = this->ptime;
537 mcfg.no_vad = this->noVad;
538 mcfg.ilbc_mode = this->ilbcMode;
539 mcfg.tx_drop_pct = this->txDropPct;
540 mcfg.rx_drop_pct = this->rxDropPct;
541 mcfg.ec_options = this->ecOptions;
542 mcfg.ec_tail_len = this->ecTailLen;
543 mcfg.snd_rec_latency = this->sndRecLatency;
544 mcfg.snd_play_latency = this->sndPlayLatency;
545 mcfg.jb_init = this->jbInit;
546 mcfg.jb_min_pre = this->jbMinPre;
547 mcfg.jb_max_pre = this->jbMaxPre;
548 mcfg.jb_max = this->jbMax;
549 mcfg.jb_discard_algo = this->jbDiscardAlgo;
550 mcfg.snd_auto_close_time = this->sndAutoCloseTime;
551 mcfg.vid_preview_enable_native = this->vidPreviewEnableNative;
552
553 return mcfg;
554 }
555
556 void MediaConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error)
557 {
558 ContainerNode this_node = node.readContainer("MediaConfig");
559
560 NODE_READ_UNSIGNED( this_node, clockRate);
561 NODE_READ_UNSIGNED( this_node, sndClockRate);
562 NODE_READ_UNSIGNED( this_node, channelCount);
563 NODE_READ_UNSIGNED( this_node, audioFramePtime);
564 NODE_READ_UNSIGNED( this_node, maxMediaPorts);
565 NODE_READ_UNSIGNED( this_node, confThreads);
566 NODE_READ_BOOL ( this_node, hasIoqueue);
567 NODE_READ_UNSIGNED( this_node, threadCnt);
568 NODE_READ_UNSIGNED( this_node, quality);
569 NODE_READ_UNSIGNED( this_node, ptime);
570 NODE_READ_BOOL ( this_node, noVad);
571 NODE_READ_UNSIGNED( this_node, ilbcMode);
572 NODE_READ_UNSIGNED( this_node, txDropPct);
573 NODE_READ_UNSIGNED( this_node, rxDropPct);
574 NODE_READ_UNSIGNED( this_node, ecOptions);
575 NODE_READ_UNSIGNED( this_node, ecTailLen);
576 NODE_READ_UNSIGNED( this_node, sndRecLatency);
577 NODE_READ_UNSIGNED( this_node, sndPlayLatency);
578 NODE_READ_INT ( this_node, jbInit);
579 NODE_READ_INT ( this_node, jbMinPre);
580 NODE_READ_INT ( this_node, jbMaxPre);
581 NODE_READ_INT ( this_node, jbMax);
582 NODE_READ_NUM_T ( this_node, pjmedia_jb_discard_algo, jbDiscardAlgo);
583 NODE_READ_INT ( this_node, sndAutoCloseTime);
584 NODE_READ_BOOL ( this_node, vidPreviewEnableNative);
585 NODE_READ_BOOL ( this_node, sndUseSwClock);
586 }
587
588 void MediaConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error)
589 {
590 ContainerNode this_node = node.writeNewContainer("MediaConfig");
591
592 NODE_WRITE_UNSIGNED( this_node, clockRate);
593 NODE_WRITE_UNSIGNED( this_node, sndClockRate);
594 NODE_WRITE_UNSIGNED( this_node, channelCount);
595 NODE_WRITE_UNSIGNED( this_node, audioFramePtime);
596 NODE_WRITE_UNSIGNED( this_node, maxMediaPorts);
597 NODE_WRITE_UNSIGNED( this_node, confThreads);
598 NODE_WRITE_BOOL ( this_node, hasIoqueue);
599 NODE_WRITE_UNSIGNED( this_node, threadCnt);
600 NODE_WRITE_UNSIGNED( this_node, quality);
601 NODE_WRITE_UNSIGNED( this_node, ptime);
602 NODE_WRITE_BOOL ( this_node, noVad);
603 NODE_WRITE_UNSIGNED( this_node, ilbcMode);
604 NODE_WRITE_UNSIGNED( this_node, txDropPct);
605 NODE_WRITE_UNSIGNED( this_node, rxDropPct);
606 NODE_WRITE_UNSIGNED( this_node, ecOptions);
607 NODE_WRITE_UNSIGNED( this_node, ecTailLen);
608 NODE_WRITE_UNSIGNED( this_node, sndRecLatency);
609 NODE_WRITE_UNSIGNED( this_node, sndPlayLatency);
610 NODE_WRITE_INT ( this_node, jbInit);
611 NODE_WRITE_INT ( this_node, jbMinPre);
612 NODE_WRITE_INT ( this_node, jbMaxPre);
613 NODE_WRITE_INT ( this_node, jbMax);
614 NODE_WRITE_NUM_T ( this_node, pjmedia_jb_discard_algo, jbDiscardAlgo);
615 NODE_WRITE_INT ( this_node, sndAutoCloseTime);
616 NODE_WRITE_BOOL ( this_node, vidPreviewEnableNative);
617 NODE_WRITE_BOOL ( this_node, sndUseSwClock);
618 }
619
620 ///////////////////////////////////////////////////////////////////////////////
621
622 void EpConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error)
623 {
624 ContainerNode this_node = node.readContainer("EpConfig");
625 NODE_READ_OBJ( this_node, uaConfig);
626 NODE_READ_OBJ( this_node, logConfig);
627 NODE_READ_OBJ( this_node, medConfig);
628 }
629
630 void EpConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error)
631 {
632 ContainerNode this_node = node.writeNewContainer("EpConfig");
633 NODE_WRITE_OBJ( this_node, uaConfig);
634 NODE_WRITE_OBJ( this_node, logConfig);
635 NODE_WRITE_OBJ( this_node, medConfig);
636 }
637
638 ///////////////////////////////////////////////////////////////////////////////
639 /* Class to post log to main thread */
640 struct PendingLog : public PendingJob
641 {
642 LogEntry entry;
643 virtual void execute(bool is_pending)
644 {
645 PJ_UNUSED_ARG(is_pending);
646 Endpoint::instance().utilLogWrite(entry);
647 }
648 };
649
650 ///////////////////////////////////////////////////////////////////////////////
651 /*
652 * Endpoint instance
653 */
654 Endpoint::Endpoint():
655 #if !DEPRECATED_FOR_TICKET_2232
656 mediaListMutex(NULL),
657 #endif
658 writer(NULL), threadDescMutex(NULL), mainThreadOnly(false),
659 mainThread(NULL), pendingJobSize(0)
660 {
661 if (instance_) {
662 PJSUA2_RAISE_ERROR(PJ_EEXISTS);
663 }
664
665 audioDevMgr = new AudDevManager();
666 videoDevMgr = new VidDevManager();
667
668 instance_ = this;
669 }
670
671 Endpoint& Endpoint::instance() PJSUA2_THROW(Error)
672 {
673 if (!instance_) {
674 PJSUA2_RAISE_ERROR(PJ_ENOTFOUND);
675 }
676 return *instance_;
677 }
678
679 Endpoint::~Endpoint()
680 {
681 while (!pendingJobs.empty()) {
682 delete pendingJobs.front();
683 pendingJobs.pop_front();
684 }
685
686 #if !DEPRECATED_FOR_TICKET_2232
687 clearCodecInfoList(codecInfoList);
688 clearCodecInfoList(videoCodecInfoList);
689 #endif
690
691 delete audioDevMgr;
692 delete videoDevMgr;
693
694 try {
695 libDestroy();
696 } catch (Error &err) {
697 // Ignore
698 PJ_UNUSED_ARG(err);
699 }
700
701 instance_ = NULL;
702 }
703
704 void Endpoint::utilAddPendingJob(PendingJob *job)
705 {
706 enum {
707 MAX_PENDING_JOBS = 1024
708 };
709
710 /* See if we can execute immediately */
711 if (!mainThreadOnly || pj_thread_this()==mainThread) {
712 job->execute(false);
713 delete job;
714 return;
715 }
716
717 if (pendingJobSize > MAX_PENDING_JOBS) {
718 enum { NUMBER_TO_DISCARD = 5 };
719
720 pj_enter_critical_section();
721 for (unsigned i=0; i<NUMBER_TO_DISCARD; ++i) {
722 delete pendingJobs.back();
723 pendingJobs.pop_back();
724 }
725
726 pendingJobSize -= NUMBER_TO_DISCARD;
727 pj_leave_critical_section();
728
729 utilLogWrite(1, THIS_FILE,
730 "*** ERROR: Job queue full!! Jobs discarded!!! ***");
731 }
732
733 pj_enter_critical_section();
734 pendingJobs.push_back(job);
735 pendingJobSize++;
736 pj_leave_critical_section();
737 }
738
739 /* Handle log callback */
740 void Endpoint::utilLogWrite(LogEntry &entry)
741 {
742 if (!writer) return;
743
744 if (mainThreadOnly && pj_thread_this() != mainThread) {
745 PendingLog *job = new PendingLog;
746 job->entry = entry;
747 utilAddPendingJob(job);
748 } else {
749 writer->write(entry);
750 }
751 }
752
753 pj_status_t Endpoint::onCredAuth(OnCredAuthParam &prm)
754 {
755 PJ_UNUSED_ARG(prm);
756 return PJ_ENOTSUP;
757 }
758
759 /* Run pending jobs only in main thread */
760 void Endpoint::performPendingJobs()
761 {
762 if (pj_thread_this() != mainThread)
763 return;
764
765 if (pendingJobSize == 0)
766 return;
767
768 for (;;) {
769 PendingJob *job = NULL;
770
771 pj_enter_critical_section();
772 if (pendingJobSize != 0) {
773 job = pendingJobs.front();
774 pendingJobs.pop_front();
775 pendingJobSize--;
776 }
777 pj_leave_critical_section();
778
779 if (job) {
780 job->execute(true);
781 delete job;
782 } else
783 break;
784 }
785 }
786
787 ///////////////////////////////////////////////////////////////////////////////
788 /*
789 * Endpoint static callbacks
790 */
791 void Endpoint::logFunc(int level, const char *data, int len)
792 {
793 Endpoint &ep = Endpoint::instance();
794
795 if (!ep.writer)
796 return;
797
798 LogEntry entry;
799 entry.level = level;
800 entry.msg = string(data, len);
801 entry.threadId = (long)(size_t)pj_thread_this();
802 entry.threadName = string(pj_thread_get_name(pj_thread_this()));
803
804 ep.utilLogWrite(entry);
805 }
806
807 void Endpoint::stun_resolve_cb(const pj_stun_resolve_result *res)
808 {
809 Endpoint &ep = Endpoint::instance();
810
811 if (!res)
812 return;
813
814 OnNatCheckStunServersCompleteParam prm;
815
816 prm.userData = res->token;
817 prm.status = res->status;
818 if (res->status == PJ_SUCCESS) {
819 char straddr[PJ_INET6_ADDRSTRLEN+10];
820
821 prm.name = string(res->name.ptr, res->name.slen);
822 pj_sockaddr_print(&res->addr, straddr, sizeof(straddr), 3);
823 prm.addr = straddr;
824 }
825
826 ep.onNatCheckStunServersComplete(prm);
827 }
828
829 void Endpoint::on_timer(pj_timer_heap_t *timer_heap,
830 pj_timer_entry *entry)
831 {
832 PJ_UNUSED_ARG(timer_heap);
833
834 Endpoint &ep = Endpoint::instance();
835 UserTimer *ut = (UserTimer*) entry->user_data;
836
837 if (ut->signature != TIMER_SIGNATURE)
838 return;
839
840 /* Best effort to handle race condition with utilTimerCancel() */
841 ut->signature = 0xFFFFFFFE;
842
843 ep.onTimer(ut->prm);
844 delete ut;
845 }
846
847 void Endpoint::on_nat_detect(const pj_stun_nat_detect_result *res)
848 {
849 Endpoint &ep = Endpoint::instance();
850
851 if (!res)
852 return;
853
854 OnNatDetectionCompleteParam prm;
855
856 prm.status = res->status;
857 prm.reason = res->status_text;
858 prm.natType = res->nat_type;
859 prm.natTypeName = res->nat_type_name;
860
861 ep.onNatDetectionComplete(prm);
862 }
863
864 void Endpoint::on_transport_state( pjsip_transport *tp,
865 pjsip_transport_state state,
866 const pjsip_transport_state_info *info)
867 {
868 Endpoint &ep = Endpoint::instance();
869
870 OnTransportStateParam prm;
871
872 prm.hnd = (TransportHandle)tp;
873 prm.type = tp->type_name;
874 prm.state = state;
875 prm.lastError = info ? info->status : PJ_SUCCESS;
876
877 #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0
878 if (!pj_ansi_stricmp(tp->type_name, "tls") && info && info->ext_info &&
879 (state == PJSIP_TP_STATE_CONNECTED ||
880 ((pjsip_tls_state_info*)info->ext_info)->
881 ssl_sock_info->verify_status != PJ_SUCCESS))
882 {
883 prm.tlsInfo.fromPj(*((pjsip_tls_state_info*)info->ext_info));
884 }
885 #endif
886
887 ep.onTransportState(prm);
888 }
889
890 ///////////////////////////////////////////////////////////////////////////////
891 /*
892 * Account static callbacks
893 */
894
895 Account *Endpoint::lookupAcc(int acc_id, const char *op)
896 {
897 Account *acc = Account::lookup(acc_id);
898 if (!acc) {
899 PJ_LOG(1,(THIS_FILE,
900 "Error: cannot find Account instance for account id %d in "
901 "%s", acc_id, op));
902 }
903
904 return acc;
905 }
906
907 Call *Endpoint::lookupCall(int call_id, const char *op)
908 {
909 Call *call = Call::lookup(call_id);
910 if (!call) {
911 PJ_LOG(1,(THIS_FILE,
912 "Error: cannot find Call instance for call id %d in "
913 "%s", call_id, op));
914 }
915
916 return call;
917 }
918
919 void Endpoint::on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id,
920 pjsip_rx_data *rdata)
921 {
922 Account *acc = lookupAcc(acc_id, "on_incoming_call()");
923 if (!acc) {
924 pjsua_call_hangup(call_id, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL);
925 return;
926 }
927
928 pjsua_call *call = &pjsua_var.calls[call_id];
929 if (!call->incoming_data) {
930 /* This happens when the incoming call callback has been called from
931 * inside the on_create_media_transport() callback. So we simply
932 * return here to avoid calling the callback twice.
933 */
934 return;
935 }
936
937 /* call callback */
938 OnIncomingCallParam prm;
939 prm.callId = call_id;
940 prm.rdata.fromPj(*rdata);
941
942 acc->onIncomingCall(prm);
943
944 /* Free cloned rdata. */
945 pjsip_rx_data_free_cloned(call->incoming_data);
946 call->incoming_data = NULL;
947
948 /* disconnect if callback doesn't handle the call */
949 pjsua_call_info ci;
950
951 pjsua_call_get_info(call_id, &ci);
952 if (!pjsua_call_get_user_data(call_id) &&
953 ci.state != PJSIP_INV_STATE_DISCONNECTED)
954 {
955 pjsua_call_hangup(call_id, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL);
956 }
957 }
958
959 void Endpoint::on_reg_started(pjsua_acc_id acc_id, pj_bool_t renew)
960 {
961 Account *acc = lookupAcc(acc_id, "on_reg_started()");
962 if (!acc) {
963 return;
964 }
965
966 OnRegStartedParam prm;
967 prm.renew = PJ2BOOL(renew);
968 acc->onRegStarted(prm);
969 }
970
971 void Endpoint::on_reg_state2(pjsua_acc_id acc_id, pjsua_reg_info *info)
972 {
973 Account *acc = lookupAcc(acc_id, "on_reg_state2()");
974 if (!acc) {
975 return;
976 }
977
978 OnRegStateParam prm;
979 prm.status = info->cbparam->status;
980 prm.code = (pjsip_status_code) info->cbparam->code;
981 prm.reason = pj2Str(info->cbparam->reason);
982 if (info->cbparam->rdata)
983 prm.rdata.fromPj(*info->cbparam->rdata);
984 prm.expiration = info->cbparam->expiration;
985
986 acc->onRegState(prm);
987 }
988
989 void Endpoint::on_acc_send_request(pjsua_acc_id acc_id,
990 void *token,
991 pjsip_event *event)
992 {
993 Account *acc = lookupAcc(acc_id, "on_acc_send_request:response()");
994 if (!acc) {
995 return;
996 }
997
998 OnSendRequestParam prm;
999 prm.userData = token;
1000 prm.e.fromPj(*event);
1001
1002 acc->onSendRequest(prm);
1003 }
1004
1005 void Endpoint::on_incoming_subscribe(pjsua_acc_id acc_id,
1006 pjsua_srv_pres *srv_pres,
1007 pjsua_buddy_id buddy_id,
1008 const pj_str_t *from,
1009 pjsip_rx_data *rdata,
1010 pjsip_status_code *code,
1011 pj_str_t *reason,
1012 pjsua_msg_data *msg_data)
1013 {
1014 PJ_UNUSED_ARG(buddy_id);
1015 PJ_UNUSED_ARG(srv_pres);
1016
1017 Account *acc = lookupAcc(acc_id, "on_incoming_subscribe()");
1018 if (!acc) {
1019 /* default behavior should apply */
1020 return;
1021 }
1022
1023 OnIncomingSubscribeParam prm;
1024 prm.srvPres = srv_pres;
1025 prm.fromUri = pj2Str(*from);
1026 prm.rdata.fromPj(*rdata);
1027 prm.code = *code;
1028 prm.reason = pj2Str(*reason);
1029 prm.txOption.fromPj(*msg_data);
1030
1031 acc->onIncomingSubscribe(prm);
1032
1033 *code = prm.code;
1034 acc->tmpReason = prm.reason;
1035 *reason = str2Pj(acc->tmpReason);
1036 prm.txOption.toPj(*msg_data);
1037 }
1038
1039 void Endpoint::on_pager2(pjsua_call_id call_id,
1040 const pj_str_t *from,
1041 const pj_str_t *to,
1042 const pj_str_t *contact,
1043 const pj_str_t *mime_type,
1044 const pj_str_t *body,
1045 pjsip_rx_data *rdata,
1046 pjsua_acc_id acc_id)
1047 {
1048 OnInstantMessageParam prm;
1049 prm.fromUri = pj2Str(*from);
1050 prm.toUri = pj2Str(*to);
1051 prm.contactUri = pj2Str(*contact);
1052 prm.contentType = pj2Str(*mime_type);
1053 prm.msgBody = pj2Str(*body);
1054 prm.rdata.fromPj(*rdata);
1055
1056 if (call_id != PJSUA_INVALID_ID) {
1057 Call *call = lookupCall(call_id, "on_pager2()");
1058 if (!call) {
1059 /* Ignored */
1060 return;
1061 }
1062
1063 call->onInstantMessage(prm);
1064 } else {
1065 Account *acc = lookupAcc(acc_id, "on_pager2()");
1066 if (!acc) {
1067 /* Ignored */
1068 return;
1069 }
1070
1071 acc->onInstantMessage(prm);
1072 }
1073 }
1074
1075 void Endpoint::on_pager_status2( pjsua_call_id call_id,
1076 const pj_str_t *to,
1077 const pj_str_t *body,
1078 void *user_data,
1079 pjsip_status_code status,
1080 const pj_str_t *reason,
1081 pjsip_tx_data *tdata,
1082 pjsip_rx_data *rdata,
1083 pjsua_acc_id acc_id)
1084 {
1085 PJ_UNUSED_ARG(tdata);
1086
1087 OnInstantMessageStatusParam prm;
1088 prm.userData = user_data;
1089 prm.toUri = pj2Str(*to);
1090 prm.msgBody = pj2Str(*body);
1091 prm.code = status;
1092 prm.reason = pj2Str(*reason);
1093 if (rdata)
1094 prm.rdata.fromPj(*rdata);
1095
1096 if (call_id != PJSUA_INVALID_ID) {
1097 Call *call = lookupCall(call_id, "on_pager_status2()");
1098 if (!call) {
1099 /* Ignored */
1100 return;
1101 }
1102
1103 call->onInstantMessageStatus(prm);
1104 } else {
1105 Account *acc = lookupAcc(acc_id, "on_pager_status2()");
1106 if (!acc) {
1107 /* Ignored */
1108 return;
1109 }
1110
1111 acc->onInstantMessageStatus(prm);
1112 }
1113 }
1114
1115 void Endpoint::on_typing2( pjsua_call_id call_id,
1116 const pj_str_t *from,
1117 const pj_str_t *to,
1118 const pj_str_t *contact,
1119 pj_bool_t is_typing,
1120 pjsip_rx_data *rdata,
1121 pjsua_acc_id acc_id)
1122 {
1123 OnTypingIndicationParam prm;
1124 prm.fromUri = pj2Str(*from);
1125 prm.toUri = pj2Str(*to);
1126 prm.contactUri = pj2Str(*contact);
1127 prm.isTyping = is_typing != 0;
1128 prm.rdata.fromPj(*rdata);
1129
1130 if (call_id != PJSUA_INVALID_ID) {
1131 Call *call = lookupCall(call_id, "on_typing2()");
1132 if (!call) {
1133 /* Ignored */
1134 return;
1135 }
1136
1137 call->onTypingIndication(prm);
1138 } else {
1139 Account *acc = lookupAcc(acc_id, "on_typing2()");
1140 if (!acc) {
1141 /* Ignored */
1142 return;
1143 }
1144
1145 acc->onTypingIndication(prm);
1146 }
1147 }
1148
1149 void Endpoint::on_mwi_info(pjsua_acc_id acc_id,
1150 pjsua_mwi_info *mwi_info)
1151 {
1152 OnMwiInfoParam prm;
1153
1154 if (mwi_info->evsub) {
1155 prm.state = pjsip_evsub_get_state(mwi_info->evsub);
1156 } else {
1157 /* Unsolicited MWI */
1158 prm.state = PJSIP_EVSUB_STATE_NULL;
1159 }
1160 prm.rdata.fromPj(*mwi_info->rdata);
1161
1162 Account *acc = lookupAcc(acc_id, "on_mwi_info()");
1163 if (!acc) {
1164 /* Ignored */
1165 return;
1166 }
1167
1168 acc->onMwiInfo(prm);
1169 }
1170
1171 AuthChallenge::AuthChallenge()
1172 : param_(NULL), deferred_(false), consumed_(false),
1173 cloned_rdata_(NULL), auth_sess_(NULL), token_(NULL), tdata_(NULL),
1174 acc_id_(PJSUA_INVALID_ID)
1175 {}
1176
1177 AuthChallenge::~AuthChallenge()
1178 {
1179 if (deferred_ && !consumed_ && auth_sess_ && token_) {
1180 /* Capture sess/token under PJSUA_LOCK, then call async_abandon
1181 * outside the lock to avoid lock-order inversion.
1182 */
1183 pjsip_auth_clt_sess *sess = NULL;
1184 void *tok = NULL;
1185 if (PJSUA_TRY_LOCK() == PJ_SUCCESS) {
1186 if (pjsua_acc_is_valid(acc_id_)) {
1187 sess = auth_sess_;
1188 tok = token_;
1189 }
1190 PJSUA_UNLOCK();
1191 } else {
1192 /* Try-lock failed (e.g. GC finalizer during shutdown).
1193 * Still abandon the token to release its grp_lock ref.
1194 * The signature check inside async_abandon provides safety
1195 * if the token was already consumed.
1196 */
1197 sess = auth_sess_;
1198 tok = token_;
1199 }
1200 if (sess && tok)
1201 pjsip_auth_clt_async_abandon(sess, tok);
1202 }
1203 if (cloned_rdata_)
1204 pjsip_rx_data_free_cloned(cloned_rdata_);
1205 if (deferred_ && tdata_)
1206 pjsip_tx_data_dec_ref(tdata_);
1207 }
1208
1209 AuthChallenge* AuthChallenge::defer()
1210 {
1211 if (!param_ || consumed_ || deferred_)
1212 PJSUA2_RAISE_ERROR(PJ_EINVALIDOP);
1213
1214 pjsip_rx_data *cloned = NULL;
1215 if (param_->rdata) {
1216 pj_status_t st = pjsip_rx_data_clone(param_->rdata, 0, &cloned);
1217 PJSUA2_CHECK_EXPR(st);
1218 }
1219
1220 AuthChallenge *d = new AuthChallenge();
1221 d->deferred_ = true;
1222 d->cloned_rdata_ = cloned;
1223 d->auth_sess_ = param_->auth_sess;
1224 d->token_ = param_->token;
1225 d->tdata_ = param_->tdata;
1226 d->acc_id_ = param_->acc_id;
1227
1228 if (d->tdata_)
1229 pjsip_tx_data_add_ref(d->tdata_);
1230
1231 param_->handled = PJ_TRUE;
1232 consumed_ = true;
1233 param_ = NULL;
1234 return d;
1235 }
1236
1237 pj_status_t AuthChallenge::respond()
1238 {
1239 if (consumed_) return PJ_EINVALIDOP;
1240
1241 pjsip_auth_clt_sess *sess;
1242 void *tok; pjsip_rx_data *rd; pjsip_tx_data *td;
1243
1244 if (deferred_) {
1245 PJSUA_LOCK();
1246 if (!pjsua_acc_is_valid(acc_id_)) {
1247 PJSUA_UNLOCK();
1248 consumed_ = true;
1249 return PJ_EINVALIDOP;
1250 }
1251 sess = auth_sess_; tok = token_;
1252 rd = cloned_rdata_; td = tdata_;
1253 } else {
1254 if (!param_) return PJ_EINVALIDOP;
1255 sess = param_->auth_sess; tok = param_->token;
1256 rd = (pjsip_rx_data*)param_->rdata; td = param_->tdata;
1257 }
1258
1259 /* Call reinit_req while still holding PJSUA_LOCK (deferred path) so
1260 * that a concurrent pjsua_acc_del() cannot zero the auth session.
1261 * reinit_req does not acquire tsx grp_lock, so no lock-order issue.
1262 */
1263 pjsip_tx_data *new_tdata = NULL;
1264 pj_status_t status = pjsip_auth_clt_reinit_req(sess, rd, td, &new_tdata);
1265
1266 /* Release PJSUA_LOCK before send/abandon to prevent lock-order-
1267 * inversion with tsx grp_lock (send_impl may call pjsip_regc_send
1268 * which acquires regc grp_lock, while SIP callbacks acquire
1269 * tsx grp_lock then PJSUA_LOCK — opposite order).
1270 */
1271 if (deferred_)
1272 PJSUA_UNLOCK();
1273
1274 if (status == PJ_SUCCESS && new_tdata) {
1275 status = pjsip_auth_clt_async_send_req(sess, tok, new_tdata);
1276 if (status != PJ_SUCCESS) {
1277 /* send_req may fail without consuming the token (e.g. account
1278 * deleted between unlock and send) — abandon to release the
1279 * token's grp_lock reference. If the token was already
1280 * consumed, abandon will harmlessly return PJ_EINVAL.
1281 */
1282 pjsip_auth_clt_async_abandon(sess, tok);
1283 }
1284 } else {
1285 pjsip_auth_clt_async_abandon(sess, tok);
1286 if (status == PJ_SUCCESS)
1287 status = PJ_EINVALIDOP;
1288 }
1289
1290 consumed_ = true;
1291 if (!deferred_ && param_)
1292 param_->handled = PJ_TRUE;
1293 return status;
1294 }
1295
1296 pj_status_t AuthChallenge::respond(const AuthCredInfoVector &creds)
1297 {
1298 if (consumed_) return PJ_EINVALIDOP;
1299
1300 pjsip_auth_clt_sess *sess;
1301
1302 if (deferred_) {
1303 PJSUA_LOCK();
1304 if (!pjsua_acc_is_valid(acc_id_)) {
1305 PJSUA_UNLOCK();
1306 consumed_ = true;
1307 return PJ_EINVALIDOP;
1308 }
1309 sess = auth_sess_;
1310 } else {
1311 sess = param_ ? param_->auth_sess : NULL;
1312 }
1313 if (!sess) return PJ_EINVALIDOP;
1314
1315 /* Apply provided credentials to the auth session */
1316 pjsip_cred_info ci[PJSUA_ACC_MAX_PROXIES];
1317 unsigned count = (unsigned)creds.size();
1318 if (count > PJ_ARRAY_SIZE(ci))
1319 count = PJ_ARRAY_SIZE(ci);
1320 for (unsigned i = 0; i < count; ++i)
1321 ci[i] = creds[i].toPj();
1322 pj_status_t status = pjsip_auth_clt_set_credentials(sess, count, ci);
1323
1324 if (deferred_)
1325 PJSUA_UNLOCK();
1326
1327 if (status != PJ_SUCCESS) {
1328 abandon();
1329 return status;
1330 }
1331
1332 return respond();
1333 }
1334
1335 pj_status_t AuthChallenge::abandon()
1336 {
1337 if (consumed_) return PJ_EINVALIDOP;
1338
1339 pjsip_auth_clt_sess *sess;
1340 void *tok;
1341 if (deferred_) {
1342 PJSUA_LOCK();
1343 if (!pjsua_acc_is_valid(acc_id_)) {
1344 /* Account deleted — skip abandon. The token's grp_lock ref
1345 * will leak, but calling abandon would dereference user_data
1346 * (e.g. regc) which has already been destroyed by
1347 * pjsua_acc_del(). A proper fix requires pjsua_acc_del()
1348 * to consume outstanding auth tokens before destruction.
1349 */
1350 PJSUA_UNLOCK();
1351 consumed_ = true;
1352 return PJ_EINVALIDOP;
1353 }
1354 sess = auth_sess_; tok = token_;
1355 /* Release PJSUA_LOCK before abandon to prevent lock-order
1356 * inversion — abandon_impl may call regc/inv callbacks that
1357 * acquire tsx grp_lock, and SIP callbacks acquire tsx grp_lock
1358 * then PJSUA_LOCK (opposite order).
1359 */
1360 PJSUA_UNLOCK();
1361 } else {
1362 if (!param_) return PJ_EINVALIDOP;
1363 sess = param_->auth_sess; tok = param_->token;
1364 }
1365
1366 pj_status_t status = pjsip_auth_clt_async_abandon(sess, tok);
1367 consumed_ = true;
1368 if (!deferred_ && param_)
1369 param_->handled = PJ_TRUE;
1370 return status;
1371 }
1372
1373 bool AuthChallenge::isValid() const
1374 {
1375 if (consumed_) return false;
1376 if (deferred_)
1377 return auth_sess_ != NULL && pjsua_acc_is_valid(acc_id_);
1378 return param_ != NULL;
1379 }
1380
1381 void Endpoint::on_auth_challenge(pjsua_on_auth_challenge_param *param)
1382 {
1383 Account *acc = lookupAcc(param->acc_id, "on_auth_challenge()");
1384 if (!acc) {
1385 /* No account — leave handled=false, sync fallback */
1386 return;
1387 }
1388
1389 OnAuthChallengeParam prm;
1390 prm.accId = param->acc_id;
1391 prm.callId = param->call_id;
1392 if (param->rdata)
1393 prm.rdata.fromPj(*(pjsip_rx_data*)param->rdata);
1394 prm.challenge.param_ = param;
1395
1396 acc->onAuthChallenge(prm);
1397 /* If app called respond(), abandon(), or defer(), param->handled is
1398 * PJ_TRUE. If not (default no-op), param->handled stays PJ_FALSE →
1399 * sync fallback.
1400 */
1401 }
1402
1403 void Endpoint::on_acc_find_for_incoming(const pjsip_rx_data *rdata,
1404 pjsua_acc_id* acc_id)
1405 {
1406 OnSelectAccountParam prm;
1407
1408 pj_assert(rdata && acc_id);
1409 prm.rdata.fromPj(*((pjsip_rx_data *)rdata));
1410 prm.accountIndex = *acc_id;
1411
1412 instance_->onSelectAccount(prm);
1413
1414 *acc_id = prm.accountIndex;
1415 }
1416
1417 void Endpoint::on_buddy_state(pjsua_buddy_id buddy_id)
1418 {
1419 Buddy b(buddy_id);
1420 Buddy *buddy = b.getOriginalInstance();
1421 if (!buddy || !buddy->isValid()) {
1422 /* Ignored */
1423 return;
1424 }
1425
1426 buddy->onBuddyState();
1427 }
1428
1429 void Endpoint::on_buddy_dlg_event_state(pjsua_buddy_id buddy_id)
1430 {
1431 Buddy b(buddy_id);
1432 Buddy *buddy = b.getOriginalInstance();
1433 if (!buddy || !buddy->isValid()) {
1434 /* Ignored */
1435 return;
1436 }
1437
1438 buddy->onBuddyDlgEventState();
1439 }
1440
1441 void Endpoint::on_buddy_evsub_state(pjsua_buddy_id buddy_id,
1442 pjsip_evsub *sub,
1443 pjsip_event *event)
1444 {
1445 PJ_UNUSED_ARG(sub);
1446
1447 Buddy b(buddy_id);
1448 Buddy *buddy = b.getOriginalInstance();
1449 if (!buddy || !buddy->isValid()) {
1450 /* Ignored */
1451 return;
1452 }
1453
1454 OnBuddyEvSubStateParam prm;
1455 prm.e.fromPj(*event);
1456
1457 buddy->onBuddyEvSubState(prm);
1458 }
1459
1460 void Endpoint::on_buddy_evsub_dlg_event_state(pjsua_buddy_id buddy_id,
1461 pjsip_evsub *sub,
1462 pjsip_event *event)
1463 {
1464 PJ_UNUSED_ARG(sub);
1465
1466 Buddy b(buddy_id);
1467 Buddy *buddy = b.getOriginalInstance();
1468 if (!buddy || !buddy->isValid()) {
1469 /* Ignored */
1470 return;
1471 }
1472
1473 OnBuddyEvSubStateParam prm;
1474 prm.e.fromPj(*event);
1475
1476 buddy->onBuddyEvSubDlgEventState(prm);
1477 }
1478
1479 // Call callbacks
1480 void Endpoint::on_call_state(pjsua_call_id call_id, pjsip_event *e)
1481 {
1482 Call *call = Call::lookup(call_id);
1483 if (!call) {
1484 return;
1485 }
1486
1487 OnCallStateParam prm;
1488 prm.e.fromPj(*e);
1489
1490 call->processStateChange(prm);
1491 /* If the state is DISCONNECTED, call may have already been deleted
1492 * by the application in the callback, so do not access it anymore here.
1493 */
1494 }
1495
1496 void Endpoint::on_call_tsx_state(pjsua_call_id call_id,
1497 pjsip_transaction *tsx,
1498 pjsip_event *e)
1499 {
1500 PJ_UNUSED_ARG(tsx);
1501
1502 Call *call = Call::lookup(call_id);
1503 if (!call) {
1504 return;
1505 }
1506
1507 OnCallTsxStateParam prm;
1508 prm.e.fromPj(*e);
1509
1510 call->onCallTsxState(prm);
1511 }
1512
1513 void Endpoint::on_call_media_state(pjsua_call_id call_id)
1514 {
1515 Call *call = Call::lookup(call_id);
1516 if (!call) {
1517 return;
1518 }
1519
1520 OnCallMediaStateParam prm;
1521 call->processMediaUpdate(prm);
1522 }
1523
1524 void Endpoint::on_call_sdp_created(pjsua_call_id call_id,
1525 pjmedia_sdp_session *sdp,
1526 pj_pool_t *pool,
1527 const pjmedia_sdp_session *rem_sdp)
1528 {
1529 Call *call = Call::lookup(call_id);
1530 if (!call) {
1531 return;
1532 }
1533
1534 OnCallSdpCreatedParam prm;
1535 string orig_sdp;
1536
1537 prm.sdp.fromPj(*sdp);
1538 orig_sdp = prm.sdp.wholeSdp;
1539 if (rem_sdp)
1540 prm.remSdp.fromPj(*rem_sdp);
1541
1542 call->onCallSdpCreated(prm);
1543
1544 /* Check if application modifies the SDP */
1545 if (orig_sdp != prm.sdp.wholeSdp) {
1546 pjmedia_sdp_session *new_sdp;
1547 pj_str_t dup_new_sdp;
1548 pj_str_t new_sdp_str = {(char*)prm.sdp.wholeSdp.c_str(),
1549 (pj_ssize_t)prm.sdp.wholeSdp.size()};
1550 pj_status_t status;
1551
1552 pj_strdup(pool, &dup_new_sdp, &new_sdp_str);
1553 status = pjmedia_sdp_parse(pool, dup_new_sdp.ptr,
1554 dup_new_sdp.slen, &new_sdp);
1555 if (status != PJ_SUCCESS) {
1556 PJ_PERROR(4,(THIS_FILE, status,
1557 "Failed to parse the modified SDP"));
1558 } else {
1559 pj_memcpy(sdp, new_sdp, sizeof(*sdp));
1560 }
1561 }
1562 }
1563
1564 void Endpoint::on_stream_precreate(pjsua_call_id call_id,
1565 pjsua_on_stream_precreate_param *param)
1566 {
1567 Call *call = Call::lookup(call_id);
1568 if (!call) {
1569 return;
1570 }
1571
1572 OnStreamPreCreateParam prm;
1573 prm.streamIdx = param->stream_idx;
1574 prm.streamInfo.fromPj(param->stream_info);
1575
1576 call->onStreamPreCreate(prm);
1577
1578 /* Copy back only the fields which are allowed to be changed. */
1579 if (param->stream_info.type == PJMEDIA_TYPE_AUDIO) {
1580 param->stream_info.info.aud.jb_init = prm.streamInfo.jbInit;
1581 param->stream_info.info.aud.jb_min_pre = prm.streamInfo.jbMinPre;
1582 param->stream_info.info.aud.jb_max_pre = prm.streamInfo.jbMaxPre;
1583 param->stream_info.info.aud.jb_max = prm.streamInfo.jbMax;
1584 param->stream_info.info.aud.jb_discard_algo = prm.streamInfo.jbDiscardAlgo;
1585 #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0)
1586 param->stream_info.info.aud.use_ka = prm.streamInfo.useKa;
1587 #endif
1588 param->stream_info.info.aud.rtcp_sdes_bye_disabled = prm.streamInfo.rtcpSdesByeDisabled;
1589 param->stream_info.info.aud.rx_event_pt = prm.streamInfo.audRxEventPt;
1590 } else if (param->stream_info.type == PJMEDIA_TYPE_VIDEO) {
1591 param->stream_info.info.vid.jb_init = prm.streamInfo.jbInit;
1592 param->stream_info.info.vid.jb_min_pre = prm.streamInfo.jbMinPre;
1593 param->stream_info.info.vid.jb_max_pre = prm.streamInfo.jbMaxPre;
1594 param->stream_info.info.vid.jb_max = prm.streamInfo.jbMax;
1595 #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0)
1596 param->stream_info.info.vid.use_ka = prm.streamInfo.useKa;
1597 #endif
1598 param->stream_info.info.vid.rtcp_sdes_bye_disabled = prm.streamInfo.rtcpSdesByeDisabled;
1599 param->stream_info.info.vid.codec_param->enc_fmt = prm.streamInfo.vidCodecParam.encFmt.toPj();
1600
1601 }
1602 }
1603
1604 void Endpoint::on_stream_created2(pjsua_call_id call_id,
1605 pjsua_on_stream_created_param *param)
1606 {
1607 Call *call = Call::lookup(call_id);
1608 if (!call) {
1609 return;
1610 }
1611
1612 OnStreamCreatedParam prm;
1613 prm.stream = param->stream;
1614 prm.streamIdx = param->stream_idx;
1615 prm.destroyPort = (param->destroy_port != PJ_FALSE);
1616 prm.pPort = (MediaPort)param->port;
1617
1618 call->onStreamCreated(prm);
1619
1620 param->destroy_port = prm.destroyPort;
1621 param->port = (pjmedia_port *)prm.pPort;
1622 }
1623
1624 void Endpoint::on_stream_destroyed(pjsua_call_id call_id,
1625 pjmedia_stream *strm,
1626 unsigned stream_idx)
1627 {
1628 Call *call = Call::lookup(call_id);
1629 if (!call) {
1630 /* This can happen for call disconnection case. The callback
1631 * should have been called from on_call_state() instead.
1632 */
1633 return;
1634 }
1635
1636 OnStreamDestroyedParam prm;
1637 prm.stream = strm;
1638 prm.streamIdx = stream_idx;
1639
1640 call->onStreamDestroyed(prm);
1641 }
1642
1643 struct PendingOnDtmfDigitCallback : public PendingJob
1644 {
1645 int call_id;
1646 OnDtmfDigitParam prm;
1647
1648 virtual void execute(bool is_pending)
1649 {
1650 PJ_UNUSED_ARG(is_pending);
1651
1652 Call *call = Call::lookup(call_id);
1653 if (!call)
1654 return;
1655
1656 call->onDtmfDigit(prm);
1657 }
1658 };
1659
1660 void Endpoint::on_dtmf_digit(pjsua_call_id call_id, int digit)
1661 {
1662 Call *call = Call::lookup(call_id);
1663 if (!call) {
1664 return;
1665 }
1666
1667 PendingOnDtmfDigitCallback *job = new PendingOnDtmfDigitCallback;
1668 job->call_id = call_id;
1669 char buf[10];
1670 pj_ansi_snprintf(buf, sizeof(buf), "%c", digit);
1671 job->prm.digit = string(buf);
1672
1673 Endpoint::instance().utilAddPendingJob(job);
1674 }
1675
1676 void Endpoint::on_dtmf_digit2(pjsua_call_id call_id,
1677 const pjsua_dtmf_info *info)
1678 {
1679 Call *call = Call::lookup(call_id);
1680 if (!call) {
1681 return;
1682 }
1683
1684 PendingOnDtmfDigitCallback *job = new PendingOnDtmfDigitCallback;
1685 job->call_id = call_id;
1686 char buf[10];
1687 pj_ansi_snprintf(buf, sizeof(buf), "%c", info->digit);
1688 job->prm.digit = string(buf);
1689 job->prm.method = info->method;
1690 job->prm.duration = info->duration;
1691
1692 Endpoint::instance().utilAddPendingJob(job);
1693 }
1694
1695 struct PendingOnDtmfEventCallback : public PendingJob
1696 {
1697 int call_id;
1698 OnDtmfEventParam prm;
1699
1700 virtual void execute(bool is_pending)
1701 {
1702 PJ_UNUSED_ARG(is_pending);
1703
1704 Call *call = Call::lookup(call_id);
1705 if (!call)
1706 return;
1707
1708 call->onDtmfEvent(prm);
1709
1710 /* If this event indicates a new DTMF digit, invoke onDtmfDigit
1711 * as well.
1712 * Note that the duration is pretty much useless in this context as it
1713 * will most likely equal the ptime of one frame received via RTP in
1714 * milliseconds. Since the application can't receive updates to the
1715 * duration via this interface and the total duration of the event is
1716 * not known yet, just indicate an unknown duration.
1717 */
1718 if (!(prm.flags & PJMEDIA_STREAM_DTMF_IS_UPDATE)) {
1719 OnDtmfDigitParam prmBasic;
1720 prmBasic.method = prm.method;
1721 prmBasic.digit = prm.digit;
1722 prmBasic.duration = PJSUA_UNKNOWN_DTMF_DURATION;
1723 call->onDtmfDigit(prmBasic);
1724 }
1725 }
1726 };
1727
1728 void Endpoint::on_dtmf_event(pjsua_call_id call_id,
1729 const pjsua_dtmf_event* event)
1730 {
1731 Call *call = Call::lookup(call_id);
1732 if (!call) {
1733 return;
1734 }
1735
1736 PendingOnDtmfEventCallback *job = new PendingOnDtmfEventCallback;
1737 job->call_id = call_id;
1738 char buf[10];
1739 pj_ansi_snprintf(buf, sizeof(buf), "%c", event->digit);
1740 job->prm.method = event->method;
1741 job->prm.timestamp = event->timestamp;
1742 job->prm.digit = string(buf);
1743 job->prm.duration = event->duration;
1744 job->prm.flags = event->flags;
1745
1746 Endpoint::instance().utilAddPendingJob(job);
1747 }
1748
1749 struct PendingOnCallRxTextCallback : public PendingJob
1750 {
1751 int call_id;
1752 OnCallRxTextParam prm;
1753
1754 virtual void execute(bool is_pending)
1755 {
1756 PJ_UNUSED_ARG(is_pending);
1757
1758 Call *call = Call::lookup(call_id);
1759 if (!call)
1760 return;
1761
1762 call->onCallRxText(prm);
1763 }
1764 };
1765
1766 void Endpoint::on_call_rx_text(pjsua_call_id call_id,
1767 const pjsua_txt_stream_data *data)
1768 {
1769 Call *call = Call::lookup(call_id);
1770 if (!call) {
1771 return;
1772 }
1773
1774 PendingOnCallRxTextCallback *job = new PendingOnCallRxTextCallback;
1775 job->call_id = call_id;
1776 job->prm.fromPj(*data);
1777
1778 Endpoint::instance().utilAddPendingJob(job);
1779 }
1780
1781 void Endpoint::on_call_transfer_request2(pjsua_call_id call_id,
1782 const pj_str_t *dst,
1783 pjsip_status_code *code,
1784 pjsua_call_setting *opt)
1785 {
1786 Call *call = Call::lookup(call_id);
1787 if (!call) {
1788 return;
1789 }
1790
1791 OnCallTransferRequestParam prm;
1792 prm.dstUri = pj2Str(*dst);
1793 prm.statusCode = *code;
1794 prm.opt.fromPj(*opt);
1795 prm.newCall = NULL;
1796
1797 call->onCallTransferRequest(prm);
1798
1799 *code = prm.statusCode;
1800 *opt = prm.opt.toPj();
1801 if (*code/100 <= 2) {
1802 if (prm.newCall) {
1803 /* Sanity checks */
1804 pj_assert(prm.newCall->id == PJSUA_INVALID_ID);
1805 pj_assert(prm.newCall->acc == call->acc);
1806
1807 /* We don't manage (e.g: create, delete) the call child,
1808 * so let's just override any existing child.
1809 */
1810 call->child = prm.newCall;
1811 call->child->id = PJSUA_INVALID_ID;
1812
1813 /* The newCall shares the same user_data as the parent call,
1814 * the next Call::lookup(new_call_id) will assign the call ID
1815 * and update user_data for the newCall.
1816 */
1817 } else {
1818 PJ_LOG(3,(THIS_FILE,
1819 "Warning: application reuses Call instance in "
1820 "call transfer (call ID:%d)", call_id));
1821 }
1822 }
1823 }
1824
1825 void Endpoint::on_call_transfer_status(pjsua_call_id call_id,
1826 int st_code,
1827 const pj_str_t *st_text,
1828 pj_bool_t final,
1829 pj_bool_t *p_cont)
1830 {
1831 Call *call = Call::lookup(call_id);
1832 if (!call) {
1833 return;
1834 }
1835
1836 OnCallTransferStatusParam prm;
1837 prm.statusCode = (pjsip_status_code)st_code;
1838 prm.reason = pj2Str(*st_text);
1839 prm.finalNotify = PJ2BOOL(final);
1840 prm.cont = PJ2BOOL(*p_cont);
1841
1842 call->onCallTransferStatus(prm);
1843
1844 *p_cont = prm.cont;
1845 }
1846
1847 void Endpoint::on_call_replace_request2(pjsua_call_id call_id,
1848 pjsip_rx_data *rdata,
1849 int *st_code,
1850 pj_str_t *st_text,
1851 pjsua_call_setting *opt)
1852 {
1853 Call *call = Call::lookup(call_id);
1854 if (!call) {
1855 return;
1856 }
1857
1858 OnCallReplaceRequestParam prm;
1859 prm.rdata.fromPj(*rdata);
1860 prm.statusCode = (pjsip_status_code)*st_code;
1861 prm.reason = pj2Str(*st_text);
1862 prm.opt.fromPj(*opt);
1863 prm.newCall = NULL;
1864
1865 call->onCallReplaceRequest(prm);
1866
1867 *st_code = prm.statusCode;
1868 *st_text = str2Pj(prm.reason);
1869 *opt = prm.opt.toPj();
1870 if (prm.newCall && prm.newCall != call) {
1871 /* Sanity checks */
1872 pj_assert(prm.newCall->id == PJSUA_INVALID_ID);
1873 pj_assert(prm.newCall->acc == call->acc);
1874
1875 /* We don't manage (e.g: create, delete) the call child,
1876 * so let's just override any existing child.
1877 */
1878 call->child = prm.newCall;
1879 call->child->id = PJSUA_INVALID_ID;
1880
1881 /* The newCall shares the same user_data as the parent call,
1882 * the next Call::lookup(new_call_id) will assign the call ID
1883 * and update user_data for the newCall.
1884 */
1885 } else {
1886 PJ_LOG(3,(THIS_FILE,
1887 "Warning: application has not created new Call instance "
1888 "for call replace request (call ID:%d)", call_id));
1889 }
1890 }
1891
1892 void Endpoint::on_call_replaced(pjsua_call_id old_call_id,
1893 pjsua_call_id new_call_id)
1894 {
1895 /* Lookup the new call first, to avoid Call::lookup() overwriting
1896 * Call.id (to the new Call).
1897 */
1898 Call *new_call = Call::lookup(new_call_id);
1899
1900 Call *call = Call::lookup(old_call_id);
1901 if (!call) {
1902 return;
1903 }
1904
1905 /* Check if new call object has not been created in
1906 * onCallReplaceRequest().
1907 */
1908 if (new_call == call)
1909 new_call = NULL;
1910
1911 OnCallReplacedParam prm;
1912 prm.newCallId = new_call_id;
1913 prm.newCall = new_call;
1914
1915 call->onCallReplaced(prm);
1916
1917 if (prm.newCall && prm.newCall != call) {
1918 /* Sanity checks */
1919 pj_assert(prm.newCall->id == new_call_id);
1920 pj_assert(prm.newCall->acc == call->acc);
1921 pj_assert(pjsua_call_get_user_data(new_call_id) == prm.newCall);
1922
1923 /* Warn if new_call created in onCallReplaceRequest() is changed */
1924 if (new_call && new_call != prm.newCall) {
1925 PJ_LOG(3,(THIS_FILE,
1926 "Warning: application has created a new Call instance "
1927 "in onCallReplaceRequest, but created another in "
1928 "onCallReplaced (call ID:%d)",
1929 new_call_id));
1930 }
1931 } else {
1932 PJ_LOG(3,(THIS_FILE,
1933 "Warning: application has not created new Call instance "
1934 "for call replace (old call ID:%d, new call ID:%d)",
1935 old_call_id, new_call_id));
1936 }
1937 }
1938
1939 void Endpoint::on_call_rx_offer(pjsua_call_id call_id,
1940 const pjmedia_sdp_session *offer,
1941 void *reserved,
1942 pjsip_status_code *code,
1943 pjsua_call_setting *opt)
1944 {
1945 PJ_UNUSED_ARG(reserved);
1946
1947 Call *call = Call::lookup(call_id);
1948 if (!call) {
1949 return;
1950 }
1951
1952 OnCallRxOfferParam prm;
1953 prm.offer.fromPj(*offer);
1954 prm.statusCode = *code;
1955 prm.opt.fromPj(*opt);
1956
1957 call->onCallRxOffer(prm);
1958
1959 *code = prm.statusCode;
1960 *opt = prm.opt.toPj();
1961 }
1962
1963 void Endpoint::on_call_rx_reinvite(pjsua_call_id call_id,
1964 const pjmedia_sdp_session *offer,
1965 pjsip_rx_data *rdata,
1966 void *reserved,
1967 pj_bool_t *async,
1968 pjsip_status_code *code,
1969 pjsua_call_setting *opt)
1970 {
1971 PJ_UNUSED_ARG(reserved);
1972
1973 Call *call = Call::lookup(call_id);
1974 if (!call) {
1975 return;
1976 }
1977
1978 OnCallRxReinviteParam prm;
1979 prm.offer.fromPj(*offer);
1980 prm.rdata.fromPj(*rdata);
1981 prm.isAsync = PJ2BOOL(*async);
1982 prm.statusCode = *code;
1983 prm.opt.fromPj(*opt);
1984
1985 call->onCallRxReinvite(prm);
1986
1987 *async = prm.isAsync;
1988 *code = prm.statusCode;
1989 *opt = prm.opt.toPj();
1990 }
1991
1992 void Endpoint::on_call_tx_offer(pjsua_call_id call_id,
1993 void *reserved,
1994 pjsua_call_setting *opt)
1995 {
1996 PJ_UNUSED_ARG(reserved);
1997
1998 Call *call = Call::lookup(call_id);
1999 if (!call) {
2000 return;
2001 }
2002
2003 OnCallTxOfferParam prm;
2004 prm.opt.fromPj(*opt);
2005
2006 call->onCallTxOffer(prm);
2007
2008 *opt = prm.opt.toPj();
2009 }
2010
2011 pjsip_redirect_op Endpoint::on_call_redirected(pjsua_call_id call_id,
2012 const pjsip_uri *target,
2013 const pjsip_event *e)
2014 {
2015 Call *call = Call::lookup(call_id);
2016 if (!call) {
2017 return PJSIP_REDIRECT_STOP;
2018 }
2019
2020 OnCallRedirectedParam prm;
2021 char uristr[PJSIP_MAX_URL_SIZE];
2022 int len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, target, uristr,
2023 sizeof(uristr));
2024 if (len < 1) {
2025 pj_ansi_strxcpy(uristr, "--URI too long--", sizeof(uristr));
2026 }
2027 prm.targetUri = string(uristr);
2028 if (e)
2029 prm.e.fromPj(*e);
2030 else
2031 prm.e.type = PJSIP_EVENT_UNKNOWN;
2032
2033 return call->onCallRedirected(prm);
2034 }
2035
2036
2037 struct PendingOnMediaTransportCallback : public PendingJob
2038 {
2039 int call_id;
2040 OnCallMediaTransportStateParam prm;
2041
2042 virtual void execute(bool is_pending)
2043 {
2044 PJ_UNUSED_ARG(is_pending);
2045
2046 Call *call = Call::lookup(call_id);
2047 if (!call)
2048 return;
2049
2050 call->onCallMediaTransportState(prm);
2051 }
2052 };
2053
2054 pj_status_t
2055 Endpoint::on_call_media_transport_state(pjsua_call_id call_id,
2056 const pjsua_med_tp_state_info *info)
2057 {
2058 Call *call = Call::lookup(call_id);
2059 if (!call) {
2060 return PJ_SUCCESS;
2061 }
2062
2063 PendingOnMediaTransportCallback *job = new PendingOnMediaTransportCallback;
2064
2065 job->call_id = call_id;
2066 job->prm.medIdx = info->med_idx;
2067 job->prm.state = info->state;
2068 job->prm.status = info->status;
2069 job->prm.sipErrorCode = info->sip_err_code;
2070
2071 Endpoint::instance().utilAddPendingJob(job);
2072
2073 return PJ_SUCCESS;
2074 }
2075
2076 struct PendingOnMediaEventCallback : public PendingJob
2077 {
2078 int call_id;
2079 OnCallMediaEventParam prm;
2080
2081 virtual void execute(bool is_pending)
2082 {
2083 if (is_pending) {
2084 /* Can't do this anymore, pointer is invalid */
2085 prm.ev.pjMediaEvent = NULL;
2086 }
2087
2088 if (call_id == PJSUA_INVALID_ID) {
2089 OnMediaEventParam prm2;
2090 prm2.ev = prm.ev;
2091 Endpoint::instance().onMediaEvent(prm2);
2092 } else {
2093 Call *call = Call::lookup(call_id);
2094
2095 if (call)
2096 call->onCallMediaEvent(prm);
2097 }
2098 }
2099 };
2100
2101 void Endpoint::on_media_event(pjmedia_event *event)
2102 {
2103 PendingOnMediaEventCallback *job = new PendingOnMediaEventCallback;
2104
2105 job->call_id = PJSUA_INVALID_ID;
2106 job->prm.medIdx = 0;
2107 job->prm.ev.fromPj(*event);
2108
2109 Endpoint::instance().utilAddPendingJob(job);
2110 }
2111
2112 void Endpoint::on_call_media_event(pjsua_call_id call_id,
2113 unsigned med_idx,
2114 pjmedia_event *event)
2115 {
2116 PendingOnMediaEventCallback *job = new PendingOnMediaEventCallback;
2117
2118 job->call_id = call_id;
2119 job->prm.medIdx = med_idx;
2120 job->prm.ev.fromPj(*event);
2121
2122 Endpoint::instance().utilAddPendingJob(job);
2123 }
2124
2125 pjmedia_transport*
2126 Endpoint::on_create_media_transport(pjsua_call_id call_id,
2127 unsigned media_idx,
2128 pjmedia_transport *base_tp,
2129 unsigned flags)
2130 {
2131 Call *call = Call::lookup(call_id);
2132 if (!call) {
2133 pjsua_call *in_call = &pjsua_var.calls[call_id];
2134 if (in_call->incoming_data) {
2135 /* This can happen when there is an incoming call but the
2136 * on_incoming_call() callback hasn't been called. So we need to
2137 * call the callback here.
2138 */
2139 on_incoming_call(in_call->acc_id, call_id, in_call->incoming_data);
2140
2141 /* New call should already be created by app. */
2142 call = Call::lookup(call_id);
2143 if (!call) {
2144 return base_tp;
2145 }
2146 if (in_call->inv->dlg->mod_data[pjsua_var.mod.id] == NULL) {
2147 /* This will enabled notification for fail events related to
2148 * the call via on_call_state() and on_call_tsx_state().
2149 */
2150 in_call->inv->dlg->mod_data[pjsua_var.mod.id] = in_call;
2151 in_call->inv->mod_data[pjsua_var.mod.id] = in_call;
2152 ++pjsua_var.call_cnt;
2153 }
2154 } else {
2155 return base_tp;
2156 }
2157 }
2158
2159 OnCreateMediaTransportParam prm;
2160 prm.mediaIdx = media_idx;
2161 prm.mediaTp = base_tp;
2162 prm.flags = flags;
2163
2164 call->onCreateMediaTransport(prm);
2165
2166 return (pjmedia_transport *)prm.mediaTp;
2167 }
2168
2169 void Endpoint::on_create_media_transport_srtp(pjsua_call_id call_id,
2170 unsigned media_idx,
2171 pjmedia_srtp_setting *srtp_opt)
2172 {
2173 Call *call = Call::lookup(call_id);
2174 if (!call) {
2175 pjsua_call *in_call = &pjsua_var.calls[call_id];
2176 if (in_call->incoming_data) {
2177 /* This can happen when there is an incoming call but the
2178 * on_incoming_call() callback hasn't been called. So we need to
2179 * call the callback here.
2180 */
2181 on_incoming_call(in_call->acc_id, call_id, in_call->incoming_data);
2182
2183 /* New call should already be created by app. */
2184 call = Call::lookup(call_id);
2185 if (!call) {
2186 return;
2187 }
2188 } else {
2189 return;
2190 }
2191 }
2192
2193 OnCreateMediaTransportSrtpParam prm;
2194 prm.mediaIdx = media_idx;
2195 prm.srtpUse = srtp_opt->use;
2196 for (unsigned i = 0; i < srtp_opt->crypto_count; i++) {
2197 SrtpCrypto crypto;
2198
2199 crypto.key = pj2Str(srtp_opt->crypto[i].key);
2200 crypto.name = pj2Str(srtp_opt->crypto[i].name);
2201 crypto.flags = srtp_opt->crypto[i].flags;
2202 prm.cryptos.push_back(PJSUA2_MOVE(crypto));
2203 }
2204
2205 call->onCreateMediaTransportSrtp(prm);
2206
2207 srtp_opt->use = prm.srtpUse;
2208 srtp_opt->crypto_count = (unsigned)prm.cryptos.size();
2209 for (unsigned i = 0; i < srtp_opt->crypto_count; i++) {
2210 srtp_opt->crypto[i].key = str2Pj(prm.cryptos[i].key);
2211 srtp_opt->crypto[i].name = str2Pj(prm.cryptos[i].name);
2212 srtp_opt->crypto[i].flags = prm.cryptos[i].flags;
2213 }
2214 }
2215
2216 void Endpoint::on_ip_change_progress(pjsua_ip_change_op op,
2217 pj_status_t status,
2218 const pjsua_ip_change_op_info *info)
2219 {
2220 Endpoint &ep = Endpoint::instance();
2221 OnIpChangeProgressParam param;
2222
2223 param.op = op;
2224 param.status = status;
2225 switch (op) {
2226 case PJSUA_IP_CHANGE_OP_RESTART_LIS:
2227 param.transportId = info->lis_restart.transport_id;
2228 break;
2229 case PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP:
2230 param.accId = info->acc_shutdown_tp.acc_id;
2231 break;
2232 case PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT:
2233 param.accId = info->acc_update_contact.acc_id;
2234 param.regInfo.code = info->acc_update_contact.code;
2235 param.regInfo.isRegister =
2236 PJ2BOOL(info->acc_update_contact.is_register);
2237 break;
2238 case PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS:
2239 param.accId = info->acc_hangup_calls.acc_id;
2240 param.callId = info->acc_hangup_calls.call_id;
2241 break;
2242 case PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS:
2243 param.accId = info->acc_reinvite_calls.acc_id;
2244 param.callId = info->acc_reinvite_calls.call_id;
2245 break;
2246 default:
2247 param.accId = PJSUA_INVALID_ID;
2248 break;
2249 }
2250 ep.onIpChangeProgress(param);
2251 }
2252
2253 ///////////////////////////////////////////////////////////////////////////////
2254 /*
2255 * Endpoint library operations
2256 */
2257 Version Endpoint::libVersion() const
2258 {
2259 Version ver;
2260 ver.major = PJ_VERSION_NUM_MAJOR;
2261 ver.minor = PJ_VERSION_NUM_MINOR;
2262 ver.rev = PJ_VERSION_NUM_REV;
2263 ver.suffix = PJ_VERSION_NUM_EXTRA;
2264 ver.full = pj_get_version();
2265 ver.numeric = PJ_VERSION_NUM;
2266 return ver;
2267 }
2268
2269 void Endpoint::libCreate() PJSUA2_THROW(Error)
2270 {
2271 PJSUA2_CHECK_EXPR( pjsua_create() );
2272 mainThread = pj_thread_this();
2273
2274 /* Register library main thread */
2275 threadDescMap[pj_thread_this()] = NULL;
2276 }
2277
2278 pjsua_state Endpoint::libGetState() const
2279 {
2280 return pjsua_get_state();
2281 }
2282
2283 void Endpoint::libInit(const EpConfig &prmEpConfig) PJSUA2_THROW(Error)
2284 {
2285 pjsua_config ua_cfg;
2286 pjsua_logging_config log_cfg;
2287 pjsua_media_config med_cfg;
2288
2289 ua_cfg = prmEpConfig.uaConfig.toPj();
2290 log_cfg = prmEpConfig.logConfig.toPj();
2291 med_cfg = prmEpConfig.medConfig.toPj();
2292
2293 /* Setup log callback */
2294 if (prmEpConfig.logConfig.writer) {
2295 this->writer = prmEpConfig.logConfig.writer;
2296 log_cfg.cb = &Endpoint::logFunc;
2297 }
2298 mainThreadOnly = prmEpConfig.uaConfig.mainThreadOnly;
2299
2300 /* Setup UA callbacks */
2301 pj_bzero(&ua_cfg.cb, sizeof(ua_cfg.cb));
2302 ua_cfg.cb.on_nat_detect = &Endpoint::on_nat_detect;
2303 ua_cfg.cb.on_transport_state = &Endpoint::on_transport_state;
2304
2305 ua_cfg.cb.on_acc_send_request = &Endpoint::on_acc_send_request;
2306 ua_cfg.cb.on_incoming_call = &Endpoint::on_incoming_call;
2307 ua_cfg.cb.on_reg_started = &Endpoint::on_reg_started;
2308 ua_cfg.cb.on_reg_state2 = &Endpoint::on_reg_state2;
2309 ua_cfg.cb.on_incoming_subscribe = &Endpoint::on_incoming_subscribe;
2310 ua_cfg.cb.on_pager2 = &Endpoint::on_pager2;
2311 ua_cfg.cb.on_pager_status2 = &Endpoint::on_pager_status2;
2312 ua_cfg.cb.on_typing2 = &Endpoint::on_typing2;
2313 ua_cfg.cb.on_mwi_info = &Endpoint::on_mwi_info;
2314 ua_cfg.cb.on_buddy_state = &Endpoint::on_buddy_state;
2315 ua_cfg.cb.on_buddy_evsub_state = &Endpoint::on_buddy_evsub_state;
2316 ua_cfg.cb.on_buddy_dlg_event_state = &Endpoint::on_buddy_dlg_event_state;
2317 ua_cfg.cb.on_buddy_evsub_dlg_event_state = &Endpoint::on_buddy_evsub_dlg_event_state;
2318 ua_cfg.cb.on_acc_find_for_incoming = &Endpoint::on_acc_find_for_incoming;
2319 ua_cfg.cb.on_ip_change_progress = &Endpoint::on_ip_change_progress;
2320
2321 /* Call callbacks */
2322 ua_cfg.cb.on_call_state = &Endpoint::on_call_state;
2323 ua_cfg.cb.on_call_tsx_state = &Endpoint::on_call_tsx_state;
2324 ua_cfg.cb.on_call_media_state = &Endpoint::on_call_media_state;
2325 ua_cfg.cb.on_call_sdp_created = &Endpoint::on_call_sdp_created;
2326 ua_cfg.cb.on_stream_precreate = &Endpoint::on_stream_precreate;
2327 ua_cfg.cb.on_stream_created2 = &Endpoint::on_stream_created2;
2328 ua_cfg.cb.on_stream_destroyed = &Endpoint::on_stream_destroyed;
2329 //ua_cfg.cb.on_dtmf_digit = &Endpoint::on_dtmf_digit;
2330 //ua_cfg.cb.on_dtmf_digit2 = &Endpoint::on_dtmf_digit2;
2331 ua_cfg.cb.on_dtmf_event = &Endpoint::on_dtmf_event;
2332 ua_cfg.cb.on_call_rx_text = &Endpoint::on_call_rx_text;
2333 ua_cfg.cb.on_call_transfer_request2 = &Endpoint::on_call_transfer_request2;
2334 ua_cfg.cb.on_call_transfer_status = &Endpoint::on_call_transfer_status;
2335 ua_cfg.cb.on_call_replace_request2 = &Endpoint::on_call_replace_request2;
2336 ua_cfg.cb.on_call_replaced = &Endpoint::on_call_replaced;
2337 ua_cfg.cb.on_call_rx_offer = &Endpoint::on_call_rx_offer;
2338 ua_cfg.cb.on_call_rx_reinvite = &Endpoint::on_call_rx_reinvite;
2339 ua_cfg.cb.on_call_tx_offer = &Endpoint::on_call_tx_offer;
2340 ua_cfg.cb.on_call_redirected = &Endpoint::on_call_redirected;
2341 ua_cfg.cb.on_call_media_transport_state =
2342 &Endpoint::on_call_media_transport_state;
2343 ua_cfg.cb.on_media_event = &Endpoint::on_media_event;
2344 ua_cfg.cb.on_call_media_event = &Endpoint::on_call_media_event;
2345 ua_cfg.cb.on_create_media_transport = &Endpoint::on_create_media_transport;
2346 ua_cfg.cb.on_stun_resolution_complete =
2347 &Endpoint::stun_resolve_cb;
2348 ua_cfg.cb.on_rejected_incoming_call = &Endpoint::on_rejected_incoming_call;
2349 ua_cfg.cb.on_conf_op_completed = &Endpoint::on_conf_op_completed;
2350 ua_cfg.cb.on_vid_conf_op_completed = &Endpoint::on_vid_conf_op_completed;
2351 ua_cfg.cb.on_auth_challenge = &Endpoint::on_auth_challenge;
2352
2353 /* Init! */
2354 PJSUA2_CHECK_EXPR( pjsua_init(&ua_cfg, &log_cfg, &med_cfg) );
2355
2356 /* Register worker threads */
2357 int i = pjsua_var.ua_cfg.thread_cnt;
2358 while (i) {
2359 pj_thread_t *t = pjsua_var.thread[--i];
2360 if (t)
2361 threadDescMap[t] = NULL;
2362 }
2363
2364 /* Register media endpoint worker thread */
2365 pjmedia_endpt *medept = pjsua_get_pjmedia_endpt();
2366 i = pjmedia_endpt_get_thread_count(medept);
2367 while (i) {
2368 pj_thread_t *t = pjmedia_endpt_get_thread(medept, --i);
2369 if (t)
2370 threadDescMap[t] = NULL;
2371 }
2372
2373 PJSUA2_CHECK_EXPR( pj_mutex_create_simple(pjsua_var.pool, "threadDesc",
2374 &threadDescMutex) );
2375
2376 #if !DEPRECATED_FOR_TICKET_2232
2377 PJSUA2_CHECK_EXPR( pj_mutex_create_recursive(pjsua_var.pool, "mediaList",
2378 &mediaListMutex) );
2379 #endif
2380 }
2381
2382 void Endpoint::libStart() PJSUA2_THROW(Error)
2383 {
2384 PJSUA2_CHECK_EXPR(pjsua_start());
2385 }
2386
2387 void Endpoint::libRegisterThread(const string &name) PJSUA2_THROW(Error)
2388 {
2389 pj_thread_t *thread;
2390 pj_thread_desc *desc;
2391 pj_status_t status;
2392
2393 desc = (pj_thread_desc*)malloc(sizeof(pj_thread_desc));
2394 if (!desc) {
2395 PJSUA2_RAISE_ERROR(PJ_ENOMEM);
2396 }
2397
2398 pj_bzero(desc, sizeof(pj_thread_desc));
2399
2400 status = pj_thread_register(name.c_str(), *desc, &thread);
2401 if (status == PJ_SUCCESS) {
2402 pj_mutex_lock(threadDescMutex);
2403 threadDescMap[thread] = desc;
2404 pj_mutex_unlock(threadDescMutex);
2405 } else {
2406 free(desc);
2407 PJSUA2_RAISE_ERROR(status);
2408 }
2409 }
2410
2411 bool Endpoint::libIsThreadRegistered()
2412 {
2413 if (pj_thread_is_registered()) {
2414 bool found;
2415
2416 pj_mutex_lock(threadDescMutex);
2417 /* Recheck again if it exists in the thread description map */
2418 found = (threadDescMap.find(pj_thread_this()) != threadDescMap.end());
2419 pj_mutex_unlock(threadDescMutex);
2420
2421 return found;
2422 }
2423
2424 return false;
2425 }
2426
2427 void Endpoint::libStopWorkerThreads()
2428 {
2429 pjsua_stop_worker_threads();
2430 }
2431
2432 int Endpoint::libHandleEvents(unsigned msec_timeout)
2433 {
2434 performPendingJobs();
2435 return pjsua_handle_events(msec_timeout);
2436 }
2437
2438 void Endpoint::libDestroy(unsigned flags) PJSUA2_THROW(Error)
2439 {
2440 pj_status_t status;
2441
2442 if (threadDescMutex) {
2443 pj_mutex_destroy(threadDescMutex);
2444 threadDescMutex = NULL;
2445 }
2446
2447 #if !DEPRECATED_FOR_TICKET_2232
2448 while(mediaList.size() > 0) {
2449 AudioMedia *cur_media = mediaList[0];
2450 delete cur_media; /* this will remove itself from the list */
2451 }
2452
2453 if (mediaListMutex) {
2454 pj_mutex_destroy(mediaListMutex);
2455 mediaListMutex = NULL;
2456 }
2457 #endif
2458
2459 status = pjsua_destroy2(flags);
2460
2461 delete this->writer;
2462 this->writer = NULL;
2463
2464 #if PJ_LOG_MAX_LEVEL >= 1
2465 if (pj_log_get_log_func() == &Endpoint::logFunc) {
2466 pj_log_set_log_func(NULL);
2467 }
2468 #endif
2469
2470 /* Clean up thread descriptors */
2471 std::map<pj_thread_t*, pj_thread_desc*>::iterator i;
2472 for (i = threadDescMap.begin(); i != threadDescMap.end(); ++i) {
2473 pj_thread_desc* d = (*i).second;
2474 if (d != NULL)
2475 free(d);
2476 }
2477 threadDescMap.clear();
2478
2479 PJSUA2_CHECK_RAISE_ERROR(status);
2480 }
2481
2482 pj_oshandle_t Endpoint::libGetSipIoqueueHandle()
2483 {
2484 pjsip_endpoint* endp = pjsua_get_pjsip_endpt();
2485 pj_ioqueue_t* ioq = pjsip_endpt_get_ioqueue(endp);
2486 return pj_ioqueue_get_os_handle(ioq);
2487 }
2488
2489 ///////////////////////////////////////////////////////////////////////////////
2490 /*
2491 * Endpoint Utilities
2492 */
2493 string Endpoint::utilStrError(pj_status_t prmErr)
2494 {
2495 char errmsg[PJ_ERR_MSG_SIZE];
2496 pj_strerror(prmErr, errmsg, sizeof(errmsg));
2497 return errmsg;
2498 }
2499
2500 static void ept_log_write(int level, const char *sender,
2501 const char *format, ...)
2502 {
2503 #if PJ_LOG_MAX_LEVEL >= 1
2504 va_list arg;
2505 va_start(arg, format);
2506 pj_log(sender, level, format, arg );
2507 va_end(arg);
2508 #endif
2509 }
2510
2511 void Endpoint::utilLogWrite(int prmLevel,
2512 const string &prmSender,
2513 const string &prmMsg)
2514 {
2515 ept_log_write(prmLevel, prmSender.c_str(), "%s", prmMsg.c_str());
2516 }
2517
2518 pj_status_t Endpoint::utilVerifySipUri(const string &prmUri)
2519 {
2520 return pjsua_verify_sip_url(prmUri.c_str());
2521 }
2522
2523 pj_status_t Endpoint::utilVerifyUri(const string &prmUri)
2524 {
2525 return pjsua_verify_url(prmUri.c_str());
2526 }
2527
2528 Token Endpoint::utilTimerSchedule(unsigned prmMsecDelay,
2529 Token prmUserData) PJSUA2_THROW(Error)
2530 {
2531 UserTimer *ut;
2532 pj_time_val delay;
2533 pj_status_t status;
2534
2535 ut = new UserTimer;
2536 ut->signature = TIMER_SIGNATURE;
2537 ut->prm.msecDelay = prmMsecDelay;
2538 ut->prm.userData = prmUserData;
2539 pj_timer_entry_init(&ut->entry, 1, ut, &Endpoint::on_timer);
2540
2541 delay.sec = 0;
2542 delay.msec = prmMsecDelay;
2543 pj_time_val_normalize(&delay);
2544
2545 status = pjsua_schedule_timer(&ut->entry, &delay);
2546 if (status != PJ_SUCCESS) {
2547 delete ut;
2548 PJSUA2_CHECK_RAISE_ERROR(status);
2549 }
2550
2551 return (Token)ut;
2552 }
2553
2554 void Endpoint::utilTimerCancel(Token prmTimerToken)
2555 {
2556 UserTimer *ut = (UserTimer*)(void*)prmTimerToken;
2557
2558 if (ut->signature != TIMER_SIGNATURE) {
2559 PJ_LOG(1,(THIS_FILE,
2560 "Invalid timer token in Endpoint::utilTimerCancel()"));
2561 return;
2562 }
2563
2564 ut->entry.id = 0;
2565 ut->signature = 0xFFFFFFFE;
2566 pjsua_cancel_timer(&ut->entry);
2567
2568 delete ut;
2569 }
2570
2571 IntVector Endpoint::utilSslGetAvailableCiphers() PJSUA2_THROW(Error)
2572 {
2573 #if PJ_HAS_SSL_SOCK
2574 pj_ssl_cipher ciphers[PJ_SSL_SOCK_MAX_CIPHERS];
2575 unsigned count = PJ_ARRAY_SIZE(ciphers);
2576
2577 PJSUA2_CHECK_EXPR( pj_ssl_cipher_get_availables(ciphers, &count) );
2578
2579 return IntVector(ciphers, ciphers + count);
2580 #else
2581 return IntVector();
2582 #endif
2583 }
2584
2585 ///////////////////////////////////////////////////////////////////////////////
2586 /*
2587 * Endpoint NAT operations
2588 */
2589 void Endpoint::natDetectType(void) PJSUA2_THROW(Error)
2590 {
2591 PJSUA2_CHECK_EXPR( pjsua_detect_nat_type() );
2592 }
2593
2594 pj_stun_nat_type Endpoint::natGetType() PJSUA2_THROW(Error)
2595 {
2596 pj_stun_nat_type type;
2597
2598 PJSUA2_CHECK_EXPR( pjsua_get_nat_type(&type) );
2599
2600 return type;
2601 }
2602
2603 void Endpoint::natUpdateStunServers(const StringVector &servers,
2604 bool wait) PJSUA2_THROW(Error)
2605 {
2606 pj_str_t srv[MAX_STUN_SERVERS];
2607 unsigned i, count = 0;
2608
2609 for (i=0; i<servers.size() && i<MAX_STUN_SERVERS; ++i) {
2610 srv[count].ptr = (char*)servers[i].c_str();
2611 srv[count].slen = servers[i].size();
2612 ++count;
2613 }
2614
2615 PJSUA2_CHECK_EXPR(pjsua_update_stun_servers(count, srv, wait) );
2616 }
2617
2618 void Endpoint::natCheckStunServers(const StringVector &servers,
2619 bool wait,
2620 Token token) PJSUA2_THROW(Error)
2621 {
2622 pj_str_t srv[MAX_STUN_SERVERS];
2623 unsigned i, count = 0;
2624
2625 for (i=0; i<servers.size() && i<MAX_STUN_SERVERS; ++i) {
2626 srv[count].ptr = (char*)servers[i].c_str();
2627 srv[count].slen = servers[i].size();
2628 ++count;
2629 }
2630
2631 PJSUA2_CHECK_EXPR(pjsua_resolve_stun_servers(count, srv, wait, token,
2632 &Endpoint::stun_resolve_cb) );
2633 }
2634
2635 void Endpoint::natCancelCheckStunServers(Token token,
2636 bool notify_cb) PJSUA2_THROW(Error)
2637 {
2638 PJSUA2_CHECK_EXPR( pjsua_cancel_stun_resolution(token, notify_cb) );
2639 }
2640
2641 ///////////////////////////////////////////////////////////////////////////////
2642 /*
2643 * Transport API
2644 */
2645 TransportId Endpoint::transportCreate(pjsip_transport_type_e type,
2646 const TransportConfig &cfg)
2647 PJSUA2_THROW(Error)
2648 {
2649 pjsua_transport_config tcfg;
2650 pjsua_transport_id tid;
2651
2652 tcfg = cfg.toPj();
2653 PJSUA2_CHECK_EXPR( pjsua_transport_create(type,
2654 &tcfg, &tid) );
2655
2656 return tid;
2657 }
2658
2659 IntVector Endpoint::transportEnum() const PJSUA2_THROW(Error)
2660 {
2661 pjsua_transport_id tids[32];
2662 unsigned count = PJ_ARRAY_SIZE(tids);
2663
2664 PJSUA2_CHECK_EXPR( pjsua_enum_transports(tids, &count) );
2665
2666 return IntVector(tids, tids+count);
2667 }
2668
2669 TransportInfo Endpoint::transportGetInfo(TransportId id) const PJSUA2_THROW(Error)
2670 {
2671 pjsua_transport_info pj_tinfo;
2672 TransportInfo tinfo;
2673
2674 PJSUA2_CHECK_EXPR( pjsua_transport_get_info(id, &pj_tinfo) );
2675 tinfo.fromPj(pj_tinfo);
2676
2677 return tinfo;
2678 }
2679
2680 #if 0
2681 // pjsua_transport_set_enable() not implemented
2682 void Endpoint::transportSetEnable(TransportId id, bool enabled)
2683 PJSUA2_THROW(Error)
2684 {
2685 PJSUA2_CHECK_EXPR( pjsua_transport_set_enable(id, enabled) );
2686 }
2687 #endif
2688
2689 void Endpoint::transportClose(TransportId id) PJSUA2_THROW(Error)
2690 {
2691 PJSUA2_CHECK_EXPR( pjsua_transport_close(id, PJ_FALSE) );
2692 }
2693
2694 void Endpoint::transportShutdown(TransportHandle tp) PJSUA2_THROW(Error)
2695 {
2696 PJSUA2_CHECK_EXPR( pjsip_transport_shutdown((pjsip_transport *)tp) );
2697 }
2698
2699 ///////////////////////////////////////////////////////////////////////////////
2700 /*
2701 * Call operations
2702 */
2703
2704 void Endpoint::hangupAllCalls(void)
2705 {
2706 pjsua_call_hangup_all();
2707 }
2708
2709 ///////////////////////////////////////////////////////////////////////////////
2710 /*
2711 * Media API
2712 */
2713 unsigned Endpoint::mediaMaxPorts() const
2714 {
2715 return pjsua_conf_get_max_ports();
2716 }
2717
2718 unsigned Endpoint::mediaActivePorts() const
2719 {
2720 return pjsua_conf_get_active_ports();
2721 }
2722
2723 #if !DEPRECATED_FOR_TICKET_2232
2724 const AudioMediaVector &Endpoint::mediaEnumPorts() const PJSUA2_THROW(Error)
2725 {
2726 return mediaList;
2727 }
2728 #endif
2729
2730 AudioMediaVector2 Endpoint::mediaEnumPorts2() const PJSUA2_THROW(Error)
2731 {
2732 AudioMediaVector2 amv2;
2733 pjsua_conf_port_id ids[PJSUA_MAX_CONF_PORTS];
2734 unsigned i, count = PJSUA_MAX_CONF_PORTS;
2735
2736 PJSUA2_CHECK_EXPR( pjsua_enum_conf_ports(ids, &count) );
2737 for (i = 0; i < count; ++i) {
2738 AudioMediaHelper am;
2739 am.setPortId(ids[i]);
2740 amv2.push_back(am);
2741 }
2742
2743 return amv2;
2744 }
2745
2746 VideoMediaVector Endpoint::mediaEnumVidPorts() const PJSUA2_THROW(Error)
2747 {
2748 #if PJSUA_HAS_VIDEO
2749 VideoMediaVector vmv;
2750 pjsua_conf_port_id ids[PJSUA_MAX_CONF_PORTS];
2751 unsigned i, count = PJSUA_MAX_CONF_PORTS;
2752
2753 PJSUA2_CHECK_EXPR( pjsua_vid_conf_enum_ports(ids, &count) );
2754 for (i = 0; i < count; ++i) {
2755 VideoMediaHelper vm;
2756 vm.setPortId(ids[i]);
2757 vmv.push_back(vm);
2758 }
2759
2760 return vmv;
2761 #else
2762 PJSUA2_RAISE_ERROR(PJ_EINVALIDOP);
2763 #endif
2764 }
2765
2766 void Endpoint::mediaAdd(AudioMedia &media)
2767 {
2768 #if !DEPRECATED_FOR_TICKET_2232
2769 /* mediaList serves mediaEnumPorts() only, once mediaEnumPorts()
2770 * is removed, this function implementation should be no-op.
2771 */
2772 pj_mutex_lock(mediaListMutex);
2773
2774 AudioMediaVector::iterator it = std::find(mediaList.begin(),
2775 mediaList.end(),
2776 &media);
2777
2778 if (it == mediaList.end())
2779 mediaList.push_back(&media);
2780 pj_mutex_unlock(mediaListMutex);
2781 #else
2782 PJ_UNUSED_ARG(media);
2783 #endif
2784 }
2785
2786 void Endpoint::mediaRemove(AudioMedia &media)
2787 {
2788 #if !DEPRECATED_FOR_TICKET_2232
2789 /* mediaList serves mediaEnumPorts() only, once mediaEnumPorts()
2790 * is removed, this function implementation should be no-op.
2791 */
2792 pj_mutex_lock(mediaListMutex);
2793 AudioMediaVector::iterator it = std::find(mediaList.begin(),
2794 mediaList.end(),
2795 &media);
2796
2797 if (it != mediaList.end())
2798 mediaList.erase(it);
2799 pj_mutex_unlock(mediaListMutex);
2800 #else
2801 PJ_UNUSED_ARG(media);
2802 #endif
2803 }
2804
2805 bool Endpoint::mediaExists(const AudioMedia &media) const
2806 {
2807 pjsua_conf_port_id id = media.getPortId();
2808 if (id == PJSUA_INVALID_ID || id >= (int)mediaMaxPorts())
2809 return false;
2810
2811 pjsua_conf_port_info pi;
2812 return (pjsua_conf_get_port_info(id, &pi) == PJ_SUCCESS);
2813 }
2814
2815 AudDevManager &Endpoint::audDevManager()
2816 {
2817 return *audioDevMgr;
2818 }
2819
2820 VidDevManager &Endpoint::vidDevManager()
2821 {
2822 return *videoDevMgr;
2823 }
2824
2825 /*
2826 * Codec operations.
2827 */
2828
2829 #if !DEPRECATED_FOR_TICKET_2232
2830 const CodecInfoVector &Endpoint::codecEnum() PJSUA2_THROW(Error)
2831 {
2832 pjsua_codec_info pj_codec[MAX_CODEC_NUM];
2833 unsigned count = MAX_CODEC_NUM;
2834
2835 PJSUA2_CHECK_EXPR( pjsua_enum_codecs(pj_codec, &count) );
2836
2837 updateCodecInfoList(pj_codec, count, codecInfoList);
2838 return codecInfoList;
2839 }
2840 #endif
2841
2842 CodecInfoVector2 Endpoint::codecEnum2() const PJSUA2_THROW(Error)
2843 {
2844 CodecInfoVector2 civ2;
2845 pjsua_codec_info pj_codec[MAX_CODEC_NUM];
2846 unsigned count = MAX_CODEC_NUM;
2847
2848 PJSUA2_CHECK_EXPR( pjsua_enum_codecs(pj_codec, &count) );
2849 for (unsigned i = 0; i<count; ++i) {
2850 CodecInfo codec_info;
2851 codec_info.fromPj(pj_codec[i]);
2852 civ2.push_back(PJSUA2_MOVE(codec_info));
2853 }
2854 return civ2;
2855 }
2856
2857 void Endpoint::codecSetPriority(const string &codec_id,
2858 pj_uint8_t priority) PJSUA2_THROW(Error)
2859 {
2860 pj_str_t codec_str = str2Pj(codec_id);
2861 PJSUA2_CHECK_EXPR( pjsua_codec_set_priority(&codec_str, priority) );
2862 }
2863
2864 CodecParam Endpoint::codecGetParam(const string &codec_id) const
2865 PJSUA2_THROW(Error)
2866 {
2867 CodecParam param;
2868 pjmedia_codec_param pj_param;
2869 pj_str_t codec_str = str2Pj(codec_id);
2870
2871 PJSUA2_CHECK_EXPR( pjsua_codec_get_param(&codec_str, &pj_param) );
2872
2873 param.fromPj(pj_param);
2874 return param;
2875 }
2876
2877 void Endpoint::codecSetParam(const string &codec_id,
2878 const CodecParam param) PJSUA2_THROW(Error)
2879 {
2880 pj_str_t codec_str = str2Pj(codec_id);
2881 pjmedia_codec_param pj_param = param.toPj();
2882
2883 PJSUA2_CHECK_EXPR( pjsua_codec_set_param(&codec_str, &pj_param) );
2884 }
2885
2886
2887 CodecOpusConfig Endpoint::getCodecOpusConfig() const PJSUA2_THROW(Error)
2888 {
2889 #if defined(PJMEDIA_HAS_OPUS_CODEC) && (PJMEDIA_HAS_OPUS_CODEC!=0)
2890 CodecOpusConfig config;
2891 pjmedia_codec_opus_config opus_cfg;
2892
2893 PJSUA2_CHECK_EXPR(pjmedia_codec_opus_get_config(&opus_cfg));
2894 config.fromPj(opus_cfg);
2895 return config;
2896 #else
2897 PJSUA2_RAISE_ERROR(PJ_ENOTSUP);
2898 #endif
2899 }
2900
2901 void Endpoint::setCodecOpusConfig(const CodecOpusConfig &opus_cfg)
2902 PJSUA2_THROW(Error)
2903 {
2904 #if defined(PJMEDIA_HAS_OPUS_CODEC) && (PJMEDIA_HAS_OPUS_CODEC!=0)
2905 const pj_str_t codec_id = {(char *)"opus", 4};
2906 pjmedia_codec_param param;
2907 pjmedia_codec_opus_config new_opus_cfg;
2908
2909 PJSUA2_CHECK_EXPR(pjsua_codec_get_param(&codec_id, &param));
2910 new_opus_cfg = opus_cfg.toPj();
2911
2912 PJSUA2_CHECK_EXPR(pjmedia_codec_opus_set_default_param(&new_opus_cfg,
2913 &param));
2914 #else
2915 PJ_UNUSED_ARG(opus_cfg);
2916
2917 PJSUA2_RAISE_ERROR(PJ_ENOTSUP);
2918 #endif
2919 }
2920
2921 CodecLyraConfig Endpoint::getCodecLyraConfig() const PJSUA2_THROW(Error)
2922 {
2923 #if defined(PJMEDIA_HAS_LYRA_CODEC) && (PJMEDIA_HAS_LYRA_CODEC!=0)
2924 CodecLyraConfig config;
2925 pjmedia_codec_lyra_config lyra_cfg;
2926
2927 PJSUA2_CHECK_EXPR(pjmedia_codec_lyra_get_config(&lyra_cfg));
2928 config.fromPj(lyra_cfg);
2929 return config;
2930 #else
2931 PJSUA2_RAISE_ERROR(PJ_ENOTSUP);
2932 #endif
2933 }
2934
2935 void Endpoint::setCodecLyraConfig(const CodecLyraConfig &lyra_cfg)
2936 PJSUA2_THROW(Error)
2937 {
2938 #if defined(PJMEDIA_HAS_LYRA_CODEC) && (PJMEDIA_HAS_LYRA_CODEC!=0)
2939 pjmedia_codec_lyra_config new_lyra_cfg;
2940 new_lyra_cfg = lyra_cfg.toPj();
2941
2942 PJSUA2_CHECK_EXPR(pjmedia_codec_lyra_set_config(&new_lyra_cfg));
2943 #else
2944 PJ_UNUSED_ARG(lyra_cfg);
2945
2946 PJSUA2_RAISE_ERROR(PJ_ENOTSUP);
2947 #endif
2948 }
2949
2950 void Endpoint::clearCodecInfoList(CodecInfoVector &codec_list)
2951 {
2952 for (unsigned i=0;i<codec_list.size();++i) {
2953 delete codec_list[i];
2954 }
2955 codec_list.clear();
2956 }
2957
2958 void Endpoint::updateCodecInfoList(pjsua_codec_info pj_codec[],
2959 unsigned count,
2960 CodecInfoVector &codec_list)
2961 {
2962 pj_enter_critical_section();
2963 clearCodecInfoList(codec_list);
2964 for (unsigned i = 0; i<count; ++i) {
2965 CodecInfo *codec_info = new CodecInfo;
2966
2967 codec_info->fromPj(pj_codec[i]);
2968 codec_list.push_back(codec_info);
2969 }
2970 pj_leave_critical_section();
2971 }
2972
2973 #if !DEPRECATED_FOR_TICKET_2232
2974 const CodecInfoVector &Endpoint::videoCodecEnum() PJSUA2_THROW(Error)
2975 {
2976 #if PJSUA_HAS_VIDEO
2977 pjsua_codec_info pj_codec[MAX_CODEC_NUM];
2978 unsigned count = MAX_CODEC_NUM;
2979
2980 PJSUA2_CHECK_EXPR(pjsua_vid_enum_codecs(pj_codec, &count));
2981
2982 updateCodecInfoList(pj_codec, count, videoCodecInfoList);
2983 #endif
2984 return videoCodecInfoList;
2985 }
2986 #endif
2987
2988 CodecInfoVector2 Endpoint::videoCodecEnum2() const PJSUA2_THROW(Error)
2989 {
2990 CodecInfoVector2 civ2;
2991 #if PJSUA_HAS_VIDEO
2992 pjsua_codec_info pj_codec[MAX_CODEC_NUM];
2993 unsigned count = MAX_CODEC_NUM;
2994
2995 PJSUA2_CHECK_EXPR(pjsua_vid_enum_codecs(pj_codec, &count));
2996 for (unsigned i = 0; i<count; ++i) {
2997 CodecInfo codec_info;
2998 codec_info.fromPj(pj_codec[i]);
2999 civ2.push_back(PJSUA2_MOVE(codec_info));
3000 }
3001 #endif
3002 return civ2;
3003 }
3004
3005 void Endpoint::videoCodecSetPriority(const string &codec_id,
3006 pj_uint8_t priority) PJSUA2_THROW(Error)
3007 {
3008 #if PJSUA_HAS_VIDEO
3009 pj_str_t codec_str = str2Pj(codec_id);
3010 PJSUA2_CHECK_EXPR(pjsua_vid_codec_set_priority(&codec_str, priority));
3011 #else
3012 PJ_UNUSED_ARG(codec_id);
3013 PJ_UNUSED_ARG(priority);
3014 #endif
3015 }
3016
3017 VidCodecParam Endpoint::getVideoCodecParam(const string &codec_id) const
3018 PJSUA2_THROW(Error)
3019 {
3020 VidCodecParam codec_param;
3021 #if PJSUA_HAS_VIDEO
3022 pjmedia_vid_codec_param pj_param;
3023 pj_str_t codec_str = str2Pj(codec_id);
3024
3025 PJSUA2_CHECK_EXPR(pjsua_vid_codec_get_param(&codec_str, &pj_param));
3026 codec_param.fromPj(pj_param);
3027 #else
3028 PJ_UNUSED_ARG(codec_id);
3029 #endif
3030 return codec_param;
3031 }
3032
3033 void Endpoint::setVideoCodecParam(const string &codec_id,
3034 const VidCodecParam &param)
3035 PJSUA2_THROW(Error)
3036 {
3037 #if PJSUA_HAS_VIDEO
3038 pj_str_t codec_str = str2Pj(codec_id);
3039 pjmedia_vid_codec_param pj_param = param.toPj();
3040
3041 PJSUA2_CHECK_EXPR(pjsua_vid_codec_set_param(&codec_str, &pj_param));
3042 #else
3043 PJ_UNUSED_ARG(codec_id);
3044 PJ_UNUSED_ARG(param);
3045 #endif
3046 }
3047
3048 void Endpoint::resetVideoCodecParam(const string &codec_id)
3049 PJSUA2_THROW(Error)
3050 {
3051 #if PJSUA_HAS_VIDEO
3052 pj_str_t codec_str = str2Pj(codec_id);
3053
3054 PJSUA2_CHECK_EXPR(pjsua_vid_codec_set_param(&codec_str, NULL));
3055 #else
3056 PJ_UNUSED_ARG(codec_id);
3057 #endif
3058 }
3059
3060 /*
3061 * Enumerate all SRTP crypto-suite names.
3062 */
3063 StringVector Endpoint::srtpCryptoEnum() PJSUA2_THROW(Error)
3064 {
3065 StringVector result;
3066 #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
3067 unsigned cnt = PJMEDIA_SRTP_MAX_CRYPTOS;
3068 pjmedia_srtp_crypto cryptos[PJMEDIA_SRTP_MAX_CRYPTOS];
3069
3070 PJSUA2_CHECK_EXPR(pjmedia_srtp_enum_crypto(&cnt, cryptos));
3071
3072 for (unsigned i = 0; i < cnt; ++i)
3073 result.push_back(pj2Str(cryptos[i].name));
3074 #endif
3075
3076 return result;
3077 }
3078
3079 void Endpoint::handleIpChange(const IpChangeParam &param) PJSUA2_THROW(Error)
3080 {
3081 pjsua_ip_change_param ip_change_param = param.toPj();
3082 PJSUA2_CHECK_EXPR(pjsua_handle_ip_change(&ip_change_param));
3083 }
3084
3085 pj_status_t Endpoint::on_auth_create_aka_response_callback(pj_pool_t *pool,
3086 const pjsip_digest_challenge *chal,
3087 const pjsip_cred_info *cred,
3088 const pj_str_t *method,
3089 pjsip_digest_credential *auth)
3090 {
3091 OnCredAuthParam prm;
3092
3093 prm.digestChallenge.fromPj(*chal);
3094 prm.credentialInfo.fromPj(*cred);
3095 prm.method = pj2Str(*method);
3096 prm.digestCredential.fromPj(*auth);
3097
3098 pj_status_t status = Endpoint::instance().onCredAuth(prm);
3099
3100 if (status == PJ_SUCCESS) {
3101 pjsip_digest_credential auth_new = prm.digestCredential.toPj();
3102
3103 // Duplicate in the pool, so that digestCredential
3104 // is allowed to be destructed at the end of the method.
3105 pj_strdup(pool, &auth->realm, &auth_new.realm);
3106 pj_strdup(pool, &auth->username, &auth_new.username);
3107 pj_strdup(pool, &auth->nonce, &auth_new.nonce);
3108 pj_strdup(pool, &auth->uri, &auth_new.uri);
3109 pj_strdup(pool, &auth->response, &auth_new.response);
3110 pj_strdup(pool, &auth->algorithm, &auth_new.algorithm);
3111 pj_strdup(pool, &auth->cnonce, &auth_new.cnonce);
3112 pj_strdup(pool, &auth->opaque, &auth_new.opaque);
3113 pj_strdup(pool, &auth->qop, &auth_new.qop);
3114 pj_strdup(pool, &auth->nc, &auth_new.nc);
3115 pjsip_param_clone(pool, &auth->other_param, &auth_new.other_param);
3116 }
3117 #if PJSIP_HAS_DIGEST_AKA_AUTH
3118 else if (status == PJ_ENOTSUP) {
3119 status = pjsip_auth_create_aka_response(pool, chal, cred, method,
3120 auth);
3121 }
3122 #endif
3123 return status;
3124 }
3125
3126 void Endpoint::on_rejected_incoming_call(
3127 const pjsua_on_rejected_incoming_call_param *param)
3128 {
3129 OnRejectedIncomingCallParam prm;
3130 prm.callId = param->call_id;
3131 prm.localInfo = pj2Str(param->local_info);
3132 prm.remoteInfo = pj2Str(param->remote_info);
3133 prm.statusCode = param->st_code;
3134 prm.reason = pj2Str(param->st_text);
3135 if (param->rdata)
3136 prm.rdata.fromPj(*param->rdata);
3137
3138 Endpoint::instance().onRejectedIncomingCall(prm);
3139 }
3140
3141 void Endpoint::on_conf_op_completed(const pjmedia_conf_op_info *info)
3142 {
3143 OnAudioMediaOpCompletedParam prm;
3144 prm.fromPj(*info);
3145
3146 Endpoint::instance().onAudioMediaOpCompleted(prm);
3147 }
3148
3149 void Endpoint::on_vid_conf_op_completed(const pjmedia_vid_conf_op_info *info)
3150 {
3151 OnVideoMediaOpCompletedParam prm;
3152 prm.fromPj(*info);
3153
3154 Endpoint::instance().onVideoMediaOpCompleted(prm);
3155 }