1 /**
2  * @file src/call.c  Call Control
3  *
4  * Copyright (C) 2010 Creytiv.com
5  */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <ctype.h>
10 #include <time.h>
11 #include <re.h>
12 #include <baresip.h>
13 #include "core.h"
14 
15 
16 /** Magic number */
17 #define MAGIC 0xca11ca11
18 #include "magic.h"
19 
20 
21 #define FOREACH_STREAM						\
22 	for (le = call->streaml.head; le; le = le->next)
23 
24 /** Call constants */
25 enum {
26 	PTIME           = 20,    /**< Packet time for audio               */
27 };
28 
29 
30 /** Call States */
31 enum state {
32 	STATE_IDLE = 0,
33 	STATE_INCOMING,
34 	STATE_OUTGOING,
35 	STATE_RINGING,
36 	STATE_EARLY,
37 	STATE_ESTABLISHED,
38 	STATE_TERMINATED
39 };
40 
41 /** SIP Call Control object */
42 struct call {
43 	MAGIC_DECL                /**< Magic number for debugging           */
44 	struct le le;             /**< Linked list element                  */
45 	struct ua *ua;            /**< SIP User-agent                       */
46 	struct account *acc;      /**< Account (ref.)                       */
47 	struct sipsess *sess;     /**< SIP Session                          */
48 	struct sdp_session *sdp;  /**< SDP Session                          */
49 	struct sipsub *sub;       /**< Call transfer REFER subscription     */
50 	struct sipnot *not;       /**< REFER/NOTIFY client                  */
51 	struct list streaml;      /**< List of mediastreams (struct stream) */
52 	struct audio *audio;      /**< Audio stream                         */
53 #ifdef USE_VIDEO
54 	struct video *video;      /**< Video stream                         */
55 	struct bfcp *bfcp;        /**< BFCP Client                          */
56 #endif
57 	enum state state;         /**< Call state                           */
58 	char *local_uri;          /**< Local SIP uri                        */
59 	char *local_name;         /**< Local display name                   */
60 	char *peer_uri;           /**< Peer SIP Address                     */
61 	char *peer_name;          /**< Peer display name                    */
62 	char *id;                 /**< Cached session call-id               */
63 	struct tmr tmr_inv;       /**< Timer for incoming calls             */
64 	struct tmr tmr_dtmf;      /**< Timer for incoming DTMF events       */
65 	time_t time_start;        /**< Time when call started               */
66 	time_t time_conn;         /**< Time when call initiated             */
67 	time_t time_stop;         /**< Time when call stopped               */
68 	bool outgoing;            /**< True if outgoing, false if incoming  */
69 	bool got_offer;           /**< Got SDP Offer from Peer              */
70 	bool on_hold;             /**< True if call is on hold              */
71 	struct mnat_sess *mnats;  /**< Media NAT session                    */
72 	bool mnat_wait;           /**< Waiting for MNAT to establish        */
73 	struct menc_sess *mencs;  /**< Media encryption session state       */
74 	int af;                   /**< Preferred Address Family             */
75 	uint16_t scode;           /**< Termination status code              */
76 	call_event_h *eh;         /**< Event handler                        */
77 	call_dtmf_h *dtmfh;       /**< DTMF handler                         */
78 	void *arg;                /**< Handler argument                     */
79 
80 	struct config_avt config_avt;    /**< AVT config                    */
81 	struct config_call config_call;  /**< Call config                   */
82 
83 	uint32_t rtp_timeout_ms;  /**< RTP Timeout in [ms]                  */
84 	uint32_t linenum;         /**< Line number from 1 to N              */
85 };
86 
87 
88 static int send_invite(struct call *call);
89 
90 
state_name(enum state st)91 static const char *state_name(enum state st)
92 {
93 	switch (st) {
94 
95 	case STATE_IDLE:        return "IDLE";
96 	case STATE_INCOMING:    return "INCOMING";
97 	case STATE_OUTGOING:    return "OUTGOING";
98 	case STATE_RINGING:     return "RINGING";
99 	case STATE_EARLY:       return "EARLY";
100 	case STATE_ESTABLISHED: return "ESTABLISHED";
101 	case STATE_TERMINATED:  return "TERMINATED";
102 	default:                return "???";
103 	}
104 }
105 
106 
set_state(struct call * call,enum state st)107 static void set_state(struct call *call, enum state st)
108 {
109 	call->state = st;
110 }
111 
112 
call_stream_start(struct call * call,bool active)113 static void call_stream_start(struct call *call, bool active)
114 {
115 	const struct sdp_format *sc;
116 	int err;
117 
118 	/* Audio Stream */
119 	sc = sdp_media_rformat(stream_sdpmedia(audio_strm(call->audio)), NULL);
120 	if (sc) {
121 		struct aucodec *ac = sc->data;
122 
123 		if (ac) {
124 			err  = audio_encoder_set(call->audio, sc->data,
125 						 sc->pt, sc->params);
126 			if (err) {
127 				warning("call: start:"
128 					" audio_encoder_set error: %m\n", err);
129 			}
130 			err |= audio_decoder_set(call->audio, sc->data,
131 						 sc->pt, sc->params);
132 			if (err) {
133 				warning("call: start:"
134 					" audio_decoder_set error: %m\n", err);
135 			}
136 
137 			if (!err) {
138 				err = audio_start(call->audio);
139 				if (err) {
140 					warning("call: start:"
141 						" audio_start error: %m\n",
142 						err);
143 				}
144 			}
145 		}
146 		else {
147 			info("call: no common audio-codecs..\n");
148 		}
149 	}
150 	else {
151 		info("call: audio stream is disabled..\n");
152 	}
153 
154 #ifdef USE_VIDEO
155 	/* Video Stream */
156 	sc = sdp_media_rformat(stream_sdpmedia(video_strm(call->video)), NULL);
157 	if (sc) {
158 		err  = video_encoder_set(call->video, sc->data, sc->pt,
159 					 sc->params);
160 		err |= video_decoder_set(call->video, sc->data, sc->pt,
161 					 sc->rparams);
162 		if (!err && !video_is_started(call->video)) {
163 			err = video_start(call->video, call->peer_uri);
164 		}
165 		if (err) {
166 			warning("call: video stream error: %m\n", err);
167 		}
168 	}
169 	else if (call->video) {
170 		info("call: video stream is disabled..\n");
171 	}
172 
173 	if (call->bfcp) {
174 		err = bfcp_start(call->bfcp);
175 		if (err) {
176 			warning("call: could not start BFCP: %m\n", err);
177 		}
178 	}
179 #endif
180 
181 	if (active) {
182 		struct le *le;
183 
184 		tmr_cancel(&call->tmr_inv);
185 		call->time_start = time(NULL);
186 
187 		FOREACH_STREAM {
188 			stream_reset(le->data);
189 		}
190 	}
191 }
192 
193 
call_stream_stop(struct call * call)194 static void call_stream_stop(struct call *call)
195 {
196 	if (!call)
197 		return;
198 
199 	call->time_stop = time(NULL);
200 
201 	/* Audio */
202 	audio_stop(call->audio);
203 
204 	/* Video */
205 #ifdef USE_VIDEO
206 	video_stop(call->video);
207 #endif
208 
209 	tmr_cancel(&call->tmr_inv);
210 }
211 
212 
call_event_handler(struct call * call,enum call_event ev,const char * fmt,...)213 static void call_event_handler(struct call *call, enum call_event ev,
214 			       const char *fmt, ...)
215 {
216 	call_event_h *eh = call->eh;
217 	void *eh_arg = call->arg;
218 	char buf[256];
219 	va_list ap;
220 
221 	if (!eh)
222 		return;
223 
224 	va_start(ap, fmt);
225 	(void)re_vsnprintf(buf, sizeof(buf), fmt, ap);
226 	va_end(ap);
227 
228 	eh(call, ev, buf, eh_arg);
229 }
230 
231 
invite_timeout(void * arg)232 static void invite_timeout(void *arg)
233 {
234 	struct call *call = arg;
235 
236 	info("%s: Local timeout after %u seconds\n",
237 	     call->peer_uri, call->config_call.local_timeout);
238 
239 	call_event_handler(call, CALL_EVENT_CLOSED, "Local timeout");
240 }
241 
242 
243 /** Called when all media streams are established */
mnat_handler(int err,uint16_t scode,const char * reason,void * arg)244 static void mnat_handler(int err, uint16_t scode, const char *reason,
245 			 void *arg)
246 {
247 	struct call *call = arg;
248 	MAGIC_CHECK(call);
249 
250 	if (err) {
251 		warning("call: medianat '%s' failed: %m\n",
252 			call->acc->mnatid, err);
253 		call_event_handler(call, CALL_EVENT_CLOSED, "%m", err);
254 		return;
255 	}
256 	else if (scode) {
257 		warning("call: medianat failed: %u %s\n", scode, reason);
258 		call_event_handler(call, CALL_EVENT_CLOSED, "%u %s",
259 				   scode, reason);
260 		return;
261 	}
262 
263 	info("call: media-nat `%s' established\n", call->acc->mnatid);
264 
265 	/* Re-INVITE */
266 	if (!call->mnat_wait) {
267 		info("call: medianat established -- sending Re-INVITE\n");
268 		(void)call_modify(call);
269 		return;
270 	}
271 
272 	call->mnat_wait = false;
273 
274 	switch (call->state) {
275 
276 	case STATE_OUTGOING:
277 		(void)send_invite(call);
278 		break;
279 
280 	case STATE_INCOMING:
281 		call_event_handler(call, CALL_EVENT_INCOMING, call->peer_uri);
282 		break;
283 
284 	default:
285 		break;
286 	}
287 }
288 
289 
update_media(struct call * call)290 static int update_media(struct call *call)
291 {
292 	const struct sdp_format *sc;
293 	struct le *le;
294 	int err = 0;
295 
296 	debug("call: update media\n");
297 
298 	/* media attributes */
299 	audio_sdp_attr_decode(call->audio);
300 
301 #ifdef USE_VIDEO
302 	if (call->video)
303 		video_sdp_attr_decode(call->video);
304 #endif
305 
306 	/* Update each stream */
307 	FOREACH_STREAM {
308 		stream_update(le->data);
309 	}
310 
311 	if (call->acc->mnat && call->acc->mnat->updateh && call->mnats)
312 		err = call->acc->mnat->updateh(call->mnats);
313 
314 	sc = sdp_media_rformat(stream_sdpmedia(audio_strm(call->audio)), NULL);
315 	if (sc) {
316 		struct aucodec *ac = sc->data;
317 		if (ac) {
318 			err  = audio_decoder_set(call->audio, sc->data,
319 						 sc->pt, sc->params);
320 			err |= audio_encoder_set(call->audio, sc->data,
321 						 sc->pt, sc->params);
322 		}
323 		else {
324 			info("no common audio-codecs..\n");
325 		}
326 	}
327 	else {
328 		info("audio stream is disabled..\n");
329 	}
330 
331 #ifdef USE_VIDEO
332 	sc = sdp_media_rformat(stream_sdpmedia(video_strm(call->video)), NULL);
333 	if (sc) {
334 		err = video_encoder_set(call->video, sc->data,
335 					sc->pt, sc->params);
336 		if (err) {
337 			warning("call: video stream error: %m\n", err);
338 			return err;
339 		}
340 
341 		if (!video_is_started(call->video)) {
342 			err = video_start(call->video, call->peer_uri);
343 			if (err) {
344 				warning("call: update: failed to"
345 					" start video (%m)\n", err);
346 			}
347 		}
348 	}
349 	else if (call->video) {
350 		info("video stream is disabled..\n");
351 		video_stop(call->video);
352 	}
353 #endif
354 
355 	return err;
356 }
357 
358 
print_summary(const struct call * call)359 static void print_summary(const struct call *call)
360 {
361 	uint32_t dur = call_duration(call);
362 	if (!dur)
363 		return;
364 
365 	info("%s: Call with %s terminated (duration: %H)\n",
366 	     call->local_uri, call->peer_uri, fmt_human_time, &dur);
367 }
368 
369 
call_destructor(void * arg)370 static void call_destructor(void *arg)
371 {
372 	struct call *call = arg;
373 
374 	if (call->state != STATE_IDLE)
375 		print_summary(call);
376 
377 	call_stream_stop(call);
378 	list_unlink(&call->le);
379 	tmr_cancel(&call->tmr_dtmf);
380 
381 	mem_deref(call->sess);
382 	mem_deref(call->id);
383 	mem_deref(call->local_uri);
384 	mem_deref(call->local_name);
385 	mem_deref(call->peer_uri);
386 	mem_deref(call->peer_name);
387 	mem_deref(call->audio);
388 #ifdef USE_VIDEO
389 	mem_deref(call->video);
390 	mem_deref(call->bfcp);
391 #endif
392 	mem_deref(call->sdp);
393 	mem_deref(call->mnats);
394 	mem_deref(call->mencs);
395 	mem_deref(call->sub);
396 	mem_deref(call->not);
397 	mem_deref(call->acc);
398 }
399 
400 
audio_event_handler(int key,bool end,void * arg)401 static void audio_event_handler(int key, bool end, void *arg)
402 {
403 	struct call *call = arg;
404 	MAGIC_CHECK(call);
405 
406 	info("received event: '%c' (end=%d)\n", key, end);
407 
408 	if (call->dtmfh)
409 		call->dtmfh(call, end ? KEYCODE_REL : key, call->arg);
410 }
411 
412 
audio_error_handler(int err,const char * str,void * arg)413 static void audio_error_handler(int err, const char *str, void *arg)
414 {
415 	struct call *call = arg;
416 	MAGIC_CHECK(call);
417 
418 	if (err) {
419 		warning("call: audio device error: %m (%s)\n", err, str);
420 	}
421 
422 	call_stream_stop(call);
423 	call_event_handler(call, CALL_EVENT_CLOSED, str);
424 }
425 
426 
427 #ifdef USE_VIDEO
video_error_handler(int err,const char * str,void * arg)428 static void video_error_handler(int err, const char *str, void *arg)
429 {
430 	struct call *call = arg;
431 	MAGIC_CHECK(call);
432 
433 	warning("call: video device error: %m (%s)\n", err, str);
434 
435 	call_stream_stop(call);
436 	call_event_handler(call, CALL_EVENT_CLOSED, str);
437 }
438 #endif
439 
440 
menc_error_handler(int err,void * arg)441 static void menc_error_handler(int err, void *arg)
442 {
443 	struct call *call = arg;
444 	MAGIC_CHECK(call);
445 
446 	warning("call: mediaenc '%s' error: %m\n", call->acc->mencid, err);
447 
448 	call_stream_stop(call);
449 	call_event_handler(call, CALL_EVENT_CLOSED, "mediaenc failed");
450 }
451 
452 
stream_error_handler(struct stream * strm,int err,void * arg)453 static void stream_error_handler(struct stream *strm, int err, void *arg)
454 {
455 	struct call *call = arg;
456 	MAGIC_CHECK(call);
457 
458 	info("call: error in \"%s\" rtp stream (%m)\n",
459 		sdp_media_name(stream_sdpmedia(strm)), err);
460 
461 	call->scode = 701;
462 	set_state(call, STATE_TERMINATED);
463 
464 	call_stream_stop(call);
465 	call_event_handler(call, CALL_EVENT_CLOSED, "rtp stream error");
466 }
467 
468 
assign_linenum(uint32_t * linenum,const struct list * lst)469 static int assign_linenum(uint32_t *linenum, const struct list *lst)
470 {
471 	uint32_t num;
472 
473 	for (num=CALL_LINENUM_MIN; num<CALL_LINENUM_MAX; num++) {
474 
475 		if (!call_find_linenum(lst, num)) {
476 			*linenum = num;
477 			return 0;
478 		}
479 	}
480 
481 	return ENOENT;
482 }
483 
484 
485 /**
486  * Allocate a new Call state object
487  *
488  * @param callp       Pointer to allocated Call state object
489  * @param cfg         Global configuration
490  * @param lst         List of call objects
491  * @param local_name  Local display name (optional)
492  * @param local_uri   Local SIP uri
493  * @param acc         Account parameters
494  * @param ua          User-Agent
495  * @param prm         Call parameters
496  * @param msg         SIP message for incoming calls
497  * @param xcall       Optional call to inherit properties from
498  * @param dnsc        DNS Client
499  * @param eh          Call event handler
500  * @param arg         Handler argument
501  *
502  * @return 0 if success, otherwise errorcode
503  */
call_alloc(struct call ** callp,const struct config * cfg,struct list * lst,const char * local_name,const char * local_uri,struct account * acc,struct ua * ua,const struct call_prm * prm,const struct sip_msg * msg,struct call * xcall,struct dnsc * dnsc,call_event_h * eh,void * arg)504 int call_alloc(struct call **callp, const struct config *cfg, struct list *lst,
505 	       const char *local_name, const char *local_uri,
506 	       struct account *acc, struct ua *ua, const struct call_prm *prm,
507 	       const struct sip_msg *msg, struct call *xcall,
508 	       struct dnsc *dnsc,
509 	       call_event_h *eh, void *arg)
510 {
511 	struct call *call;
512 	struct le *le;
513 	struct stream_param stream_prm;
514 	enum vidmode vidmode = prm ? prm->vidmode : VIDMODE_OFF;
515 	bool use_video = true, got_offer = false;
516 	int label = 0;
517 	int err = 0;
518 
519 	if (!cfg || !local_uri || !acc || !ua || !prm)
520 		return EINVAL;
521 
522 	debug("call: alloc with params laddr=%j, af=%s, use_rtp=%d\n",
523 	      &prm->laddr, net_af2name(prm->af), prm->use_rtp);
524 
525 	memset(&stream_prm, 0, sizeof(stream_prm));
526 	stream_prm.use_rtp = prm->use_rtp;
527 
528 	call = mem_zalloc(sizeof(*call), call_destructor);
529 	if (!call)
530 		return ENOMEM;
531 
532 	MAGIC_INIT(call);
533 
534 	call->config_avt = cfg->avt;
535 	call->config_call = cfg->call;
536 
537 	tmr_init(&call->tmr_inv);
538 
539 	call->acc    = mem_ref(acc);
540 	call->ua     = ua;
541 	call->state  = STATE_IDLE;
542 	call->eh     = eh;
543 	call->arg    = arg;
544 	call->af     = prm ? prm->af : AF_INET;
545 
546 	err = str_dup(&call->local_uri, local_uri);
547 	if (local_name)
548 		err |= str_dup(&call->local_name, local_name);
549 	if (err)
550 		goto out;
551 
552 	/* Init SDP info */
553 	err = sdp_session_alloc(&call->sdp, &prm->laddr);
554 	if (err)
555 		goto out;
556 
557 	err = sdp_session_set_lattr(call->sdp, true,
558 				    "tool", "baresip " BARESIP_VERSION);
559 	if (err)
560 		goto out;
561 
562 	/* Check for incoming SDP Offer */
563 	if (msg && mbuf_get_left(msg->mb))
564 		got_offer = true;
565 
566 	/* Initialise media NAT handling */
567 	if (acc->mnat) {
568 		err = acc->mnat->sessh(&call->mnats,
569 				       dnsc, call->af,
570 				       acc->stun_host, acc->stun_port,
571 				       acc->stun_user, acc->stun_pass,
572 				       call->sdp, !got_offer,
573 				       mnat_handler, call);
574 		if (err) {
575 			warning("call: medianat session: %m\n", err);
576 			goto out;
577 		}
578 	}
579 	call->mnat_wait = true;
580 
581 	/* Media encryption */
582 	if (acc->menc) {
583 		if (acc->menc->sessh) {
584 			err = acc->menc->sessh(&call->mencs, call->sdp,
585 						!got_offer,
586 						menc_error_handler, call);
587 			if (err) {
588 				warning("call: mediaenc session: %m\n", err);
589 				goto out;
590 			}
591 		}
592 	}
593 
594 	/* Audio stream */
595 	err = audio_alloc(&call->audio, &stream_prm, cfg, call,
596 			  call->sdp, ++label,
597 			  acc->mnat, call->mnats, acc->menc, call->mencs,
598 			  acc->ptime, account_aucodecl(call->acc), !got_offer,
599 			  audio_event_handler, audio_error_handler, call);
600 	if (err)
601 		goto out;
602 
603 #ifdef USE_VIDEO
604 	/* We require at least one video codec, and at least one
605 	   video source or video display */
606 	use_video = (vidmode != VIDMODE_OFF)
607 		&& (list_head(account_vidcodecl(call->acc)) != NULL)
608 		&& (NULL != vidsrc_find(baresip_vidsrcl(), NULL)
609 		    || NULL != vidisp_find(baresip_vidispl(), NULL));
610 
611 	debug("call: use_video=%d\n", use_video);
612 
613 	/* Video stream */
614 	if (use_video) {
615 		err = video_alloc(&call->video, &stream_prm, cfg,
616 				  call, call->sdp, ++label,
617 				  acc->mnat, call->mnats,
618 				  acc->menc, call->mencs,
619 				  "main",
620 				  account_vidcodecl(call->acc),
621 				  video_error_handler, call);
622 		if (err)
623 			goto out;
624  	}
625 
626 	if (str_isset(cfg->bfcp.proto)) {
627 
628 		err = bfcp_alloc(&call->bfcp, call->sdp,
629 				 cfg->bfcp.proto, !got_offer,
630 				 acc->mnat, call->mnats);
631 		if (err)
632 			goto out;
633 	}
634 #else
635 	(void)use_video;
636 	(void)vidmode;
637 #endif
638 
639 	/* inherit certain properties from original call */
640 	if (xcall) {
641 		call->not = mem_ref(xcall->not);
642 	}
643 
644 	FOREACH_STREAM {
645 		struct stream *strm = le->data;
646 		stream_set_error_handler(strm, stream_error_handler, call);
647 	}
648 
649 	if (cfg->avt.rtp_timeout) {
650 		call_enable_rtp_timeout(call, cfg->avt.rtp_timeout*1000);
651 	}
652 
653 	err = assign_linenum(&call->linenum, lst);
654 	if (err) {
655 		warning("call: could not assign linenumber\n");
656 		goto out;
657 	}
658 
659 	/* NOTE: The new call must always be added to the tail of list,
660 	 *       which indicates the current call.
661 	 */
662 	list_append(lst, &call->le, call);
663 
664  out:
665 	if (err)
666 		mem_deref(call);
667 	else if (callp)
668 		*callp = call;
669 
670 	return err;
671 }
672 
673 
call_connect(struct call * call,const struct pl * paddr)674 int call_connect(struct call *call, const struct pl *paddr)
675 {
676 	struct sip_addr addr;
677 	int err;
678 
679 	if (!call || !paddr)
680 		return EINVAL;
681 
682 	info("call: connecting to '%r'..\n", paddr);
683 
684 	call->outgoing = true;
685 
686 	/* if the peer-address is a full SIP address then we need
687 	 * to parse it and extract the SIP uri part.
688 	 */
689 	if (0 == sip_addr_decode(&addr, paddr) && addr.dname.p) {
690 		err = pl_strdup(&call->peer_uri, &addr.auri);
691 	}
692 	else {
693 		err = pl_strdup(&call->peer_uri, paddr);
694 	}
695 	if (err)
696 		return err;
697 
698 	set_state(call, STATE_OUTGOING);
699 
700 	/* If we are using asyncronous medianat like STUN/TURN, then
701 	 * wait until completed before sending the INVITE */
702 	if (!call->acc->mnat)
703 		err = send_invite(call);
704 
705 	return err;
706 }
707 
708 
709 /**
710  * Update the current call by sending Re-INVITE or UPDATE
711  *
712  * @param call Call object
713  *
714  * @return 0 if success, otherwise errorcode
715  */
call_modify(struct call * call)716 int call_modify(struct call *call)
717 {
718 	struct mbuf *desc;
719 	int err;
720 
721 	if (!call)
722 		return EINVAL;
723 
724 	err = call_sdp_get(call, &desc, true);
725 	if (!err)
726 		err = sipsess_modify(call->sess, desc);
727 
728 	mem_deref(desc);
729 
730 	return err;
731 }
732 
733 
call_hangup(struct call * call,uint16_t scode,const char * reason)734 int call_hangup(struct call *call, uint16_t scode, const char *reason)
735 {
736 	int err = 0;
737 
738 	if (!call)
739 		return EINVAL;
740 
741 	if (call->config_avt.rtp_stats)
742 		call_set_xrtpstat(call);
743 
744 	switch (call->state) {
745 
746 	case STATE_INCOMING:
747 		if (scode < 400) {
748 			scode = 486;
749 			reason = "Rejected";
750 		}
751 		info("call: rejecting incoming call from %s (%u %s)\n",
752 		     call->peer_uri, scode, reason);
753 		(void)sipsess_reject(call->sess, scode, reason, NULL);
754 		break;
755 
756 	default:
757 		info("call: terminate call '%s' with %s\n",
758 		     sip_dialog_callid(sipsess_dialog(call->sess)),
759 		     call->peer_uri);
760 
761 		call->sess = mem_deref(call->sess);
762 		break;
763 	}
764 
765 	set_state(call, STATE_TERMINATED);
766 
767 	call_stream_stop(call);
768 
769 	return err;
770 }
771 
772 
call_progress(struct call * call)773 int call_progress(struct call *call)
774 {
775 	struct mbuf *desc;
776 	int err;
777 
778 	if (!call)
779 		return EINVAL;
780 
781 	tmr_cancel(&call->tmr_inv);
782 
783 	err = call_sdp_get(call, &desc, false);
784 	if (err)
785 		return err;
786 
787 	err = sipsess_progress(call->sess, 183, "Session Progress",
788 			       desc, "Allow: %s\r\n", uag_allowed_methods());
789 
790 	if (!err)
791 		call_stream_start(call, false);
792 
793 	mem_deref(desc);
794 
795 	return 0;
796 }
797 
798 
call_answer(struct call * call,uint16_t scode)799 int call_answer(struct call *call, uint16_t scode)
800 {
801 	struct mbuf *desc;
802 	int err;
803 
804 	if (!call || !call->sess)
805 		return EINVAL;
806 
807 	if (STATE_INCOMING != call->state) {
808 		info("call: answer: call is not in incoming state (%s)\n",
809 		     state_name(call->state));
810 		return 0;
811 	}
812 
813 	info("answering call from %s with %u\n", call->peer_uri, scode);
814 
815 	if (call->got_offer) {
816 
817 		err = update_media(call);
818 		if (err)
819 			return err;
820 	}
821 
822 	err = sdp_encode(&desc, call->sdp, !call->got_offer);
823 	if (err)
824 		return err;
825 
826 	err = sipsess_answer(call->sess, scode, "Answering", desc,
827 			     "Allow: %s\r\n", uag_allowed_methods());
828 
829 	mem_deref(desc);
830 
831 	return err;
832 }
833 
834 
835 /**
836  * Check if the current call has an active audio stream
837  *
838  * @param call  Call object
839  *
840  * @return True if active stream, otherwise false
841  */
call_has_audio(const struct call * call)842 bool call_has_audio(const struct call *call)
843 {
844 	if (!call)
845 		return false;
846 
847 	return sdp_media_has_media(stream_sdpmedia(audio_strm(call->audio)));
848 }
849 
850 
851 /**
852  * Check if the current call has an active video stream
853  *
854  * @param call  Call object
855  *
856  * @return True if active stream, otherwise false
857  */
call_has_video(const struct call * call)858 bool call_has_video(const struct call *call)
859 {
860 	if (!call)
861 		return false;
862 
863 #ifdef USE_VIDEO
864 	return sdp_media_has_media(stream_sdpmedia(video_strm(call->video)));
865 #else
866 	return false;
867 #endif
868 }
869 
870 
871 /**
872  * Put the current call on hold/resume
873  *
874  * @param call  Call object
875  * @param hold  True to hold, false to resume
876  *
877  * @return 0 if success, otherwise errorcode
878  */
call_hold(struct call * call,bool hold)879 int call_hold(struct call *call, bool hold)
880 {
881 	struct le *le;
882 
883 	if (!call || !call->sess)
884 		return EINVAL;
885 
886 	if (hold == call->on_hold)
887 		return 0;
888 
889 	info("call: %s %s\n", hold ? "hold" : "resume", call->peer_uri);
890 
891 	call->on_hold = hold;
892 
893 	FOREACH_STREAM
894 		stream_hold(le->data, hold);
895 
896 	return call_modify(call);
897 }
898 
899 
call_sdp_get(const struct call * call,struct mbuf ** descp,bool offer)900 int call_sdp_get(const struct call *call, struct mbuf **descp, bool offer)
901 {
902 	return sdp_encode(descp, call->sdp, offer);
903 }
904 
905 
call_id(const struct call * call)906 const char *call_id(const struct call *call)
907 {
908 	return call ? call->id : NULL;
909 }
910 
911 
call_peeruri(const struct call * call)912 const char *call_peeruri(const struct call *call)
913 {
914 	return call ? call->peer_uri : NULL;
915 }
916 
917 
call_localuri(const struct call * call)918 const char *call_localuri(const struct call *call)
919 {
920 	return call ? call->local_uri : NULL;
921 }
922 
923 
924 /**
925  * Get the name of the peer
926  *
927  * @param call  Call object
928  *
929  * @return Peer name
930  */
call_peername(const struct call * call)931 const char *call_peername(const struct call *call)
932 {
933 	return call ? call->peer_name : NULL;
934 }
935 
936 
call_debug(struct re_printf * pf,const struct call * call)937 int call_debug(struct re_printf *pf, const struct call *call)
938 {
939 	int err;
940 
941 	if (!call)
942 		return 0;
943 
944 	err = re_hprintf(pf, "===== Call debug (%s) =====\n",
945 			 state_name(call->state));
946 
947 	/* SIP Session debug */
948 	err |= re_hprintf(pf,
949 			  " local_uri: %s <%s>\n"
950 			  " peer_uri:  %s <%s>\n"
951 			  " af=%s id=%s\n",
952 			  call->local_name, call->local_uri,
953 			  call->peer_name, call->peer_uri,
954 			  net_af2name(call->af), call->id);
955 	err |= re_hprintf(pf, " direction: %s\n",
956 			  call->outgoing ? "Outgoing" : "Incoming");
957 
958 	/* SDP debug */
959 	err |= sdp_session_debug(pf, call->sdp);
960 
961 	return err;
962 }
963 
964 
print_duration(struct re_printf * pf,const struct call * call)965 static int print_duration(struct re_printf *pf, const struct call *call)
966 {
967 	const uint32_t dur = call_duration(call);
968 	const uint32_t sec = dur%60%60;
969 	const uint32_t min = dur/60%60;
970 	const uint32_t hrs = dur/60/60;
971 
972 	return re_hprintf(pf, "%u:%02u:%02u", hrs, min, sec);
973 }
974 
975 
call_status(struct re_printf * pf,const struct call * call)976 int call_status(struct re_printf *pf, const struct call *call)
977 {
978 	struct le *le;
979 	int err;
980 
981 	if (!call)
982 		return EINVAL;
983 
984 	switch (call->state) {
985 
986 	case STATE_EARLY:
987 	case STATE_ESTABLISHED:
988 		break;
989 	default:
990 		return 0;
991 	}
992 
993 	err = re_hprintf(pf, "\r[%H]", print_duration, call);
994 
995 	FOREACH_STREAM
996 		err |= stream_print(pf, le->data);
997 
998 	err |= re_hprintf(pf, " (bit/s)");
999 
1000 #ifdef USE_VIDEO
1001 	if (call->video)
1002 		err |= video_print(pf, call->video);
1003 #endif
1004 
1005 	return err;
1006 }
1007 
1008 
call_jbuf_stat(struct re_printf * pf,const struct call * call)1009 int call_jbuf_stat(struct re_printf *pf, const struct call *call)
1010 {
1011 	struct le *le;
1012 	int err = 0;
1013 
1014 	if (!call)
1015 		return EINVAL;
1016 
1017 	FOREACH_STREAM
1018 		err |= stream_jbuf_stat(pf, le->data);
1019 
1020 	return err;
1021 }
1022 
1023 
call_info(struct re_printf * pf,const struct call * call)1024 int call_info(struct re_printf *pf, const struct call *call)
1025 {
1026 	if (!call)
1027 		return 0;
1028 
1029 	return re_hprintf(pf, "[line %u]  %H  %9s  %s  %s", call->linenum,
1030 			  print_duration, call,
1031 			  state_name(call->state),
1032 			  call->on_hold ? "(on hold)" : "         ",
1033 			  call->peer_uri);
1034 }
1035 
1036 
1037 /**
1038  * Send a DTMF digit to the peer
1039  *
1040  * @param call  Call object
1041  * @param key   DTMF digit to send (KEYCODE_REL for key release)
1042  *
1043  * @return 0 if success, otherwise errorcode
1044  */
call_send_digit(struct call * call,char key)1045 int call_send_digit(struct call *call, char key)
1046 {
1047 	if (!call)
1048 		return EINVAL;
1049 
1050 	return audio_send_digit(call->audio, key);
1051 }
1052 
1053 
call_get_ua(const struct call * call)1054 struct ua *call_get_ua(const struct call *call)
1055 {
1056 	return call ? call->ua : NULL;
1057 }
1058 
1059 
call_account(const struct call * call)1060 struct account *call_account(const struct call *call)
1061 {
1062 	return call ? call->acc : NULL;
1063 }
1064 
1065 
auth_handler(char ** username,char ** password,const char * realm,void * arg)1066 static int auth_handler(char **username, char **password,
1067 			const char *realm, void *arg)
1068 {
1069 	struct account *acc = arg;
1070 	return account_auth(acc, username, password, realm);
1071 }
1072 
1073 
sipsess_offer_handler(struct mbuf ** descp,const struct sip_msg * msg,void * arg)1074 static int sipsess_offer_handler(struct mbuf **descp,
1075 				 const struct sip_msg *msg, void *arg)
1076 {
1077 	const bool got_offer = mbuf_get_left(msg->mb);
1078 	struct call *call = arg;
1079 	int err;
1080 
1081 	MAGIC_CHECK(call);
1082 
1083 	info("call: got re-INVITE%s\n", got_offer ? " (SDP Offer)" : "");
1084 
1085 	if (got_offer) {
1086 
1087 		/* Decode SDP Offer */
1088 		err = sdp_decode(call->sdp, msg->mb, true);
1089 		if (err) {
1090 			warning("call: reinvite: could not decode SDP offer:"
1091 				" %m\n", err);
1092 			return err;
1093 		}
1094 
1095 		err = update_media(call);
1096 		if (err)
1097 			return err;
1098 	}
1099 
1100 	/* Encode SDP Answer */
1101 	return sdp_encode(descp, call->sdp, !got_offer);
1102 }
1103 
1104 
sipsess_answer_handler(const struct sip_msg * msg,void * arg)1105 static int sipsess_answer_handler(const struct sip_msg *msg, void *arg)
1106 {
1107 	struct call *call = arg;
1108 	int err;
1109 
1110 	MAGIC_CHECK(call);
1111 
1112 	if (msg_ctype_cmp(&msg->ctyp, "multipart", "mixed"))
1113 		(void)sdp_decode_multipart(&msg->ctyp.params, msg->mb);
1114 
1115 	err = sdp_decode(call->sdp, msg->mb, false);
1116 	if (err) {
1117 		warning("call: could not decode SDP answer: %m\n", err);
1118 		return err;
1119 	}
1120 
1121 	err = update_media(call);
1122 	if (err)
1123 		return err;
1124 
1125 	return 0;
1126 }
1127 
1128 
sipsess_estab_handler(const struct sip_msg * msg,void * arg)1129 static void sipsess_estab_handler(const struct sip_msg *msg, void *arg)
1130 {
1131 	struct call *call = arg;
1132 
1133 	MAGIC_CHECK(call);
1134 
1135 	(void)msg;
1136 
1137 	if (call->state == STATE_ESTABLISHED)
1138 		return;
1139 
1140 	set_state(call, STATE_ESTABLISHED);
1141 
1142 	call_stream_start(call, true);
1143 
1144 	if (call->rtp_timeout_ms) {
1145 
1146 		struct le *le;
1147 
1148 		FOREACH_STREAM {
1149 			struct stream *strm = le->data;
1150 			stream_enable_rtp_timeout(strm, call->rtp_timeout_ms);
1151 		}
1152 	}
1153 
1154 	/* the transferor will hangup this call */
1155 	if (call->not) {
1156 		(void)call_notify_sipfrag(call, 200, "OK");
1157 	}
1158 
1159 	/* must be done last, the handler might deref this call */
1160 	call_event_handler(call, CALL_EVENT_ESTABLISHED, call->peer_uri);
1161 }
1162 
1163 
1164 #ifdef USE_VIDEO
call_handle_info_req(struct call * call,const struct sip_msg * req)1165 static void call_handle_info_req(struct call *call, const struct sip_msg *req)
1166 {
1167 	struct pl body;
1168 	bool pfu;
1169 	int err;
1170 
1171 	(void)call;
1172 
1173 	pl_set_mbuf(&body, req->mb);
1174 
1175 	err = mctrl_handle_media_control(&body, &pfu);
1176 	if (err)
1177 		return;
1178 
1179 	if (pfu) {
1180 		video_update_picture(call->video);
1181 	}
1182 }
1183 #endif
1184 
1185 
dtmfend_handler(void * arg)1186 static void dtmfend_handler(void *arg)
1187 {
1188 	struct call *call = arg;
1189 
1190 	if (call->dtmfh)
1191 		call->dtmfh(call, KEYCODE_REL, call->arg);
1192 }
1193 
1194 
sipsess_info_handler(struct sip * sip,const struct sip_msg * msg,void * arg)1195 static void sipsess_info_handler(struct sip *sip, const struct sip_msg *msg,
1196 				 void *arg)
1197 {
1198 	struct call *call = arg;
1199 
1200 	if (msg_ctype_cmp(&msg->ctyp, "application", "dtmf-relay")) {
1201 
1202 		struct pl body, sig, dur;
1203 		int err;
1204 
1205 		pl_set_mbuf(&body, msg->mb);
1206 
1207 		err  = re_regex(body.p, body.l, "Signal=[0-9*#a-d]+", &sig);
1208 		err |= re_regex(body.p, body.l, "Duration=[0-9]+", &dur);
1209 
1210 		if (err || !pl_isset(&sig) || sig.l == 0) {
1211 			(void)sip_reply(sip, msg, 400, "Bad Request");
1212 		}
1213 		else {
1214 			char s = toupper(sig.p[0]);
1215 			uint32_t duration = pl_u32(&dur);
1216 
1217 			info("received DTMF: '%c' (duration=%r)\n", s, &dur);
1218 
1219 			(void)sip_reply(sip, msg, 200, "OK");
1220 
1221 			if (call->dtmfh) {
1222 				tmr_start(&call->tmr_dtmf, duration,
1223 					  dtmfend_handler, call);
1224 				call->dtmfh(call, s, call->arg);
1225 			}
1226 		}
1227 	}
1228 #ifdef USE_VIDEO
1229 	else if (msg_ctype_cmp(&msg->ctyp,
1230 			       "application", "media_control+xml")) {
1231 		call_handle_info_req(call, msg);
1232 		(void)sip_reply(sip, msg, 200, "OK");
1233 	}
1234 #endif
1235 	else {
1236 		(void)sip_reply(sip, msg, 488, "Not Acceptable Here");
1237 	}
1238 }
1239 
1240 
sipnot_close_handler(int err,const struct sip_msg * msg,void * arg)1241 static void sipnot_close_handler(int err, const struct sip_msg *msg,
1242 				 void *arg)
1243 {
1244 	struct call *call = arg;
1245 
1246 	if (err)
1247 		info("call: notification closed: %m\n", err);
1248 	else if (msg)
1249 		info("call: notification closed: %u %r\n",
1250 		     msg->scode, &msg->reason);
1251 
1252 	call->not = mem_deref(call->not);
1253 }
1254 
1255 
sipsess_refer_handler(struct sip * sip,const struct sip_msg * msg,void * arg)1256 static void sipsess_refer_handler(struct sip *sip, const struct sip_msg *msg,
1257 				  void *arg)
1258 {
1259 	struct call *call = arg;
1260 	const struct sip_hdr *hdr;
1261 	int err;
1262 
1263 	/* get the transfer target */
1264 	hdr = sip_msg_hdr(msg, SIP_HDR_REFER_TO);
1265 	if (!hdr) {
1266 		warning("call: bad REFER request from %r\n", &msg->from.auri);
1267 		(void)sip_reply(sip, msg, 400, "Missing Refer-To header");
1268 		return;
1269 	}
1270 
1271 	/* The REFER creates an implicit subscription.
1272 	 * Reply 202 to the REFER request
1273 	 */
1274 	call->not = mem_deref(call->not);
1275 	err = sipevent_accept(&call->not, uag_sipevent_sock(), msg,
1276 			      sipsess_dialog(call->sess), NULL,
1277 			      202, "Accepted", 60, 60, 60,
1278 			      ua_cuser(call->ua), "message/sipfrag",
1279 			      auth_handler, call->acc, true,
1280 			      sipnot_close_handler, call,
1281 			      "Allow: %s\r\n", uag_allowed_methods());
1282 	if (err) {
1283 		warning("call: refer: sipevent_accept failed: %m\n", err);
1284 		return;
1285 	}
1286 
1287 	(void)call_notify_sipfrag(call, 100, "Trying");
1288 
1289 	call_event_handler(call, CALL_EVENT_TRANSFER, "%r", &hdr->val);
1290 }
1291 
1292 
sipsess_close_handler(int err,const struct sip_msg * msg,void * arg)1293 static void sipsess_close_handler(int err, const struct sip_msg *msg,
1294 				  void *arg)
1295 {
1296 	struct call *call = arg;
1297 	char reason[128] = "";
1298 
1299 	MAGIC_CHECK(call);
1300 
1301 	if (err) {
1302 		info("%s: session closed: %m\n", call->peer_uri, err);
1303 
1304 		(void)re_snprintf(reason, sizeof(reason), "%m", err);
1305 
1306 		if (call->not) {
1307 			(void)call_notify_sipfrag(call, 500, "%m", err);
1308 		}
1309 	}
1310 	else if (msg) {
1311 
1312 		call->scode = msg->scode;
1313 
1314 		(void)re_snprintf(reason, sizeof(reason), "%u %r",
1315 				  msg->scode, &msg->reason);
1316 
1317 		info("%s: session closed: %u %r\n",
1318 		     call->peer_uri, msg->scode, &msg->reason);
1319 
1320 		if (call->not) {
1321 			(void)call_notify_sipfrag(call, msg->scode,
1322 						  "%r", &msg->reason);
1323 		}
1324 	}
1325 	else {
1326 		info("%s: session closed\n", call->peer_uri);
1327 	}
1328 
1329 	call_stream_stop(call);
1330 	call_event_handler(call, CALL_EVENT_CLOSED, reason);
1331 }
1332 
1333 
have_common_audio_codecs(const struct call * call)1334 static bool have_common_audio_codecs(const struct call *call)
1335 {
1336 	const struct sdp_format *sc;
1337 	struct aucodec *ac;
1338 
1339 	sc = sdp_media_rformat(stream_sdpmedia(audio_strm(call->audio)), NULL);
1340 	if (!sc)
1341 		return false;
1342 
1343 	ac = sc->data;  /* note: this will exclude telephone-event */
1344 
1345 	return ac != NULL;
1346 }
1347 
1348 
call_accept(struct call * call,struct sipsess_sock * sess_sock,const struct sip_msg * msg)1349 int call_accept(struct call *call, struct sipsess_sock *sess_sock,
1350 		const struct sip_msg *msg)
1351 {
1352 	bool got_offer;
1353 	int err;
1354 
1355 	if (!call || !msg)
1356 		return EINVAL;
1357 
1358 	call->outgoing = false;
1359 
1360 	got_offer = (mbuf_get_left(msg->mb) > 0);
1361 
1362 	err = pl_strdup(&call->peer_uri, &msg->from.auri);
1363 	if (err)
1364 		return err;
1365 
1366 	if (pl_isset(&msg->from.dname)) {
1367 		err = pl_strdup(&call->peer_name, &msg->from.dname);
1368 		if (err)
1369 			return err;
1370 	}
1371 
1372 	if (got_offer) {
1373 		struct sdp_media *m;
1374 		const struct sa *raddr;
1375 
1376 		err = sdp_decode(call->sdp, msg->mb, true);
1377 		if (err)
1378 			return err;
1379 
1380 		call->got_offer = true;
1381 
1382 		/*
1383 		 * Each media description in the SDP answer MUST
1384 		 * use the same network type as the corresponding
1385 		 * media description in the offer.
1386 		 *
1387 		 * See RFC 6157
1388 		 */
1389 		m = stream_sdpmedia(audio_strm(call->audio));
1390 		raddr = sdp_media_raddr(m);
1391 
1392 		if (sa_af(raddr) != call->af) {
1393 			info("call: incompatible address-family"
1394 			     " (local=%s, remote=%s)\n",
1395 			     net_af2name(call->af),
1396 			     net_af2name(sa_af(raddr)));
1397 
1398 			sip_treply(NULL, uag_sip(), msg,
1399 				   488, "Not Acceptable Here");
1400 
1401 			call_event_handler(call, CALL_EVENT_CLOSED,
1402 					   "Wrong address family");
1403 			return 0;
1404 		}
1405 
1406 		/* Check if we have any common audio codecs, after
1407 		 * the SDP offer has been parsed
1408 		 */
1409 		if (!have_common_audio_codecs(call)) {
1410 			info("call: no common audio codecs - rejected\n");
1411 
1412 			sip_treply(NULL, uag_sip(), msg,
1413 				   488, "Not Acceptable Here");
1414 
1415 			call_event_handler(call, CALL_EVENT_CLOSED,
1416 					   "No audio codecs");
1417 
1418 			return 0;
1419 		}
1420 	}
1421 
1422 	err = sipsess_accept(&call->sess, sess_sock, msg, 180, "Ringing",
1423 			     ua_cuser(call->ua), "application/sdp", NULL,
1424 			     auth_handler, call->acc, true,
1425 			     sipsess_offer_handler, sipsess_answer_handler,
1426 			     sipsess_estab_handler, sipsess_info_handler,
1427 			     sipsess_refer_handler, sipsess_close_handler,
1428 			     call, "Allow: %s\r\n", uag_allowed_methods());
1429 	if (err) {
1430 		warning("call: sipsess_accept: %m\n", err);
1431 		return err;
1432 	}
1433 
1434 	err = str_dup(&call->id,
1435 		      sip_dialog_callid(sipsess_dialog(call->sess)));
1436 	if (err)
1437 		return err;
1438 
1439 	set_state(call, STATE_INCOMING);
1440 
1441 	/* New call */
1442 	if (call->config_call.local_timeout) {
1443 		tmr_start(&call->tmr_inv, call->config_call.local_timeout*1000,
1444 			  invite_timeout, call);
1445 	}
1446 
1447 	if (!call->acc->mnat)
1448 		call_event_handler(call, CALL_EVENT_INCOMING, call->peer_uri);
1449 
1450 	return err;
1451 }
1452 
1453 
sipsess_progr_handler(const struct sip_msg * msg,void * arg)1454 static void sipsess_progr_handler(const struct sip_msg *msg, void *arg)
1455 {
1456 	struct call *call = arg;
1457 	bool media;
1458 
1459 	MAGIC_CHECK(call);
1460 
1461 	info("call: SIP Progress: %u %r (%r/%r)\n",
1462 	     msg->scode, &msg->reason, &msg->ctyp.type, &msg->ctyp.subtype);
1463 
1464 	if (msg->scode <= 100)
1465 		return;
1466 
1467 	/* check for 18x and content-type
1468 	 *
1469 	 * 1. start media-stream if application/sdp
1470 	 * 2. play local ringback tone if not
1471 	 *
1472 	 * we must also handle changes to/from 180 and 183,
1473 	 * so we reset the media-stream/ringback each time.
1474 	 */
1475 	if (msg_ctype_cmp(&msg->ctyp, "application", "sdp")
1476 	    && mbuf_get_left(msg->mb)
1477 	    && !sdp_decode(call->sdp, msg->mb, false)) {
1478 		media = true;
1479 	}
1480 	else if (msg_ctype_cmp(&msg->ctyp, "multipart", "mixed") &&
1481 		 !sdp_decode_multipart(&msg->ctyp.params, msg->mb) &&
1482 		 !sdp_decode(call->sdp, msg->mb, false)) {
1483 		media = true;
1484 	}
1485 	else
1486 		media = false;
1487 
1488 	switch (msg->scode) {
1489 
1490 	case 180:
1491 		set_state(call, STATE_RINGING);
1492 		break;
1493 
1494 	case 183:
1495 		set_state(call, STATE_EARLY);
1496 		break;
1497 	}
1498 
1499 	call_stream_stop(call);
1500 
1501 	if (media)
1502 		call_stream_start(call, false);
1503 
1504 	if (media)
1505 		call_event_handler(call, CALL_EVENT_PROGRESS, call->peer_uri);
1506 	else
1507 		call_event_handler(call, CALL_EVENT_RINGING, call->peer_uri);
1508 
1509 	if (media)
1510 		update_media(call);
1511 }
1512 
1513 
send_invite(struct call * call)1514 static int send_invite(struct call *call)
1515 {
1516 	const char *routev[1];
1517 	struct mbuf *desc;
1518 	int err;
1519 
1520 	routev[0] = ua_outbound(call->ua);
1521 
1522 	err = call_sdp_get(call, &desc, true);
1523 	if (err)
1524 		return err;
1525 
1526 	err = sipsess_connect(&call->sess, uag_sipsess_sock(),
1527 			      call->peer_uri,
1528 			      call->local_name,
1529 			      call->local_uri,
1530 			      ua_cuser(call->ua),
1531 			      routev[0] ? routev : NULL,
1532 			      routev[0] ? 1 : 0,
1533 			      "application/sdp", desc,
1534 			      auth_handler, call->acc, true,
1535 			      sipsess_offer_handler, sipsess_answer_handler,
1536 			      sipsess_progr_handler, sipsess_estab_handler,
1537 			      sipsess_info_handler, sipsess_refer_handler,
1538 			      sipsess_close_handler, call,
1539 			      "Allow: %s\r\n%H", uag_allowed_methods(),
1540 			      ua_print_supported, call->ua);
1541 	if (err) {
1542 		warning("call: sipsess_connect: %m\n", err);
1543 		goto out;
1544 	}
1545 
1546 	err = str_dup(&call->id,
1547 		      sip_dialog_callid(sipsess_dialog(call->sess)));
1548 
1549 	/* save call setup timer */
1550 	call->time_conn = time(NULL);
1551 
1552  out:
1553 	mem_deref(desc);
1554 
1555 	return err;
1556 }
1557 
1558 
1559 /**
1560  * Get the current call duration in seconds
1561  *
1562  * @param call  Call object
1563  *
1564  * @return Duration in seconds
1565  */
call_duration(const struct call * call)1566 uint32_t call_duration(const struct call *call)
1567 {
1568 	if (!call || !call->time_start)
1569 		return 0;
1570 
1571 	return (uint32_t)(time(NULL) - call->time_start);
1572 }
1573 
1574 
1575 /**
1576  * Get the current call setup time in seconds
1577  *
1578  * @param call  Call object
1579  *
1580  * @return Call setup in seconds
1581  */
call_setup_duration(const struct call * call)1582 uint32_t call_setup_duration(const struct call *call)
1583 {
1584 	if (!call || !call->time_conn || call->time_conn <= 0 )
1585 		return 0;
1586 
1587 	return (uint32_t)(call->time_start - call->time_conn);
1588 }
1589 
1590 
1591 /**
1592  * Get the audio object for the current call
1593  *
1594  * @param call  Call object
1595  *
1596  * @return Audio object
1597  */
call_audio(const struct call * call)1598 struct audio *call_audio(const struct call *call)
1599 {
1600 	return call ? call->audio : NULL;
1601 }
1602 
1603 
1604 /**
1605  * Get the video object for the current call
1606  *
1607  * @param call  Call object
1608  *
1609  * @return Video object
1610  */
call_video(const struct call * call)1611 struct video *call_video(const struct call *call)
1612 {
1613 #ifdef USE_VIDEO
1614 	return call ? call->video : NULL;
1615 #else
1616 	(void)call;
1617 	return NULL;
1618 #endif
1619 }
1620 
1621 
1622 /**
1623  * Get the list of media streams for the current call
1624  *
1625  * @param call  Call object
1626  *
1627  * @return List of media streams
1628  */
call_streaml(const struct call * call)1629 struct list *call_streaml(const struct call *call)
1630 {
1631 	return call ? (struct list *)&call->streaml : NULL;
1632 }
1633 
1634 
call_reset_transp(struct call * call,const struct sa * laddr)1635 int call_reset_transp(struct call *call, const struct sa *laddr)
1636 {
1637 	if (!call)
1638 		return EINVAL;
1639 
1640 	sdp_session_set_laddr(call->sdp, laddr);
1641 
1642 	return call_modify(call);
1643 }
1644 
1645 
call_notify_sipfrag(struct call * call,uint16_t scode,const char * reason,...)1646 int call_notify_sipfrag(struct call *call, uint16_t scode,
1647 			const char *reason, ...)
1648 {
1649 	struct mbuf *mb;
1650 	va_list ap;
1651 	int err;
1652 
1653 	if (!call)
1654 		return EINVAL;
1655 
1656 	mb = mbuf_alloc(512);
1657 	if (!mb)
1658 		return ENOMEM;
1659 
1660 	va_start(ap, reason);
1661 	(void)mbuf_printf(mb, "SIP/2.0 %u %v\n", scode, reason, &ap);
1662 	va_end(ap);
1663 
1664 	mb->pos = 0;
1665 
1666 	if (scode >= 200) {
1667 		err = sipevent_notify(call->not, mb, SIPEVENT_TERMINATED,
1668 				      SIPEVENT_NORESOURCE, 0);
1669 
1670 		call->not = mem_deref(call->not);
1671 	}
1672 	else {
1673 		err = sipevent_notify(call->not, mb, SIPEVENT_ACTIVE,
1674 				      SIPEVENT_NORESOURCE, 0);
1675 	}
1676 
1677 	mem_deref(mb);
1678 
1679 	return err;
1680 }
1681 
1682 
sipsub_notify_handler(struct sip * sip,const struct sip_msg * msg,void * arg)1683 static void sipsub_notify_handler(struct sip *sip, const struct sip_msg *msg,
1684 				  void *arg)
1685 {
1686 	struct call *call = arg;
1687 	struct pl scode, reason;
1688 	uint32_t sc;
1689 
1690 	if (re_regex((char *)mbuf_buf(msg->mb), mbuf_get_left(msg->mb),
1691 		     "SIP/2.0 [0-9]+ [^\r\n]+", &scode, &reason)) {
1692 		(void)sip_reply(sip, msg, 400, "Bad sipfrag");
1693 		return;
1694 	}
1695 
1696 	(void)sip_reply(sip, msg, 200, "OK");
1697 
1698 	sc = pl_u32(&scode);
1699 
1700 	if (sc >= 300) {
1701 		warning("call: transfer failed: %u %r\n", sc, &reason);
1702 		call_event_handler(call, CALL_EVENT_TRANSFER_FAILED,
1703 				   "%u %r", sc, &reason);
1704 	}
1705 	else if (sc >= 200) {
1706 		call_event_handler(call, CALL_EVENT_CLOSED, "Call transfered");
1707 	}
1708 }
1709 
1710 
sipsub_close_handler(int err,const struct sip_msg * msg,const struct sipevent_substate * substate,void * arg)1711 static void sipsub_close_handler(int err, const struct sip_msg *msg,
1712 				 const struct sipevent_substate *substate,
1713 				 void *arg)
1714 {
1715 	struct call *call = arg;
1716 
1717 	(void)substate;
1718 
1719 	call->sub = mem_deref(call->sub);
1720 
1721 	if (err) {
1722 		info("call: subscription closed: %m\n", err);
1723 	}
1724 	else if (msg && msg->scode >= 300) {
1725 		info("call: transfer failed: %u %r\n",
1726 		     msg->scode, &msg->reason);
1727 		call_event_handler(call, CALL_EVENT_TRANSFER_FAILED,
1728 				   "%u %r", msg->scode, &msg->reason);
1729 	}
1730 }
1731 
1732 
normalize_uri(char ** out,const char * uri,const struct uri * luri)1733 static int normalize_uri(char **out, const char *uri, const struct uri *luri)
1734 {
1735 	struct uri uri2;
1736 	struct pl pl;
1737 	int err;
1738 
1739 	if (!out || !uri || !luri)
1740 		return EINVAL;
1741 
1742 	pl_set_str(&pl, uri);
1743 
1744 	if (0 == uri_decode(&uri2, &pl)) {
1745 
1746 		err = str_dup(out, uri);
1747 	}
1748 	else {
1749 		uri2 = *luri;
1750 
1751 		uri2.user     = pl;
1752 		uri2.password = pl_null;
1753 		uri2.params   = pl_null;
1754 
1755 		err = re_sdprintf(out, "%H", uri_encode, &uri2);
1756 	}
1757 
1758 	return err;
1759 }
1760 
1761 
1762 /**
1763  * Transfer the call to a target SIP uri
1764  *
1765  * @param call  Call object
1766  * @param uri   Target SIP uri
1767  *
1768  * @return 0 if success, otherwise errorcode
1769  */
call_transfer(struct call * call,const char * uri)1770 int call_transfer(struct call *call, const char *uri)
1771 {
1772 	char *nuri;
1773 	int err;
1774 
1775 	if (!call || !uri)
1776 		return EINVAL;
1777 
1778 	err = normalize_uri(&nuri, uri, &call->acc->luri);
1779 	if (err)
1780 		return err;
1781 
1782 	info("transferring call to %s\n", nuri);
1783 
1784 	call->sub = mem_deref(call->sub);
1785 	err = sipevent_drefer(&call->sub, uag_sipevent_sock(),
1786 			      sipsess_dialog(call->sess), ua_cuser(call->ua),
1787 			      auth_handler, call->acc, true,
1788 			      sipsub_notify_handler, sipsub_close_handler,
1789 			      call,
1790 			      "Refer-To: %s\r\n", nuri);
1791 	if (err) {
1792 		warning("call: sipevent_drefer: %m\n", err);
1793 	}
1794 
1795 	mem_deref(nuri);
1796 
1797 	return err;
1798 }
1799 
1800 
call_af(const struct call * call)1801 int call_af(const struct call *call)
1802 {
1803 	return call ? call->af : AF_UNSPEC;
1804 }
1805 
1806 
call_scode(const struct call * call)1807 uint16_t call_scode(const struct call *call)
1808 {
1809 	return call ? call->scode : 0;
1810 }
1811 
1812 
call_set_handlers(struct call * call,call_event_h * eh,call_dtmf_h * dtmfh,void * arg)1813 void call_set_handlers(struct call *call, call_event_h *eh,
1814 		       call_dtmf_h *dtmfh, void *arg)
1815 {
1816 	if (!call)
1817 		return;
1818 
1819 	if (eh)
1820 		call->eh    = eh;
1821 
1822 	if (dtmfh)
1823 		call->dtmfh = dtmfh;
1824 
1825 	if (arg)
1826 		call->arg   = arg;
1827 }
1828 
1829 
call_set_xrtpstat(struct call * call)1830 void call_set_xrtpstat(struct call *call)
1831 {
1832 	if (!call)
1833 		return;
1834 
1835 	sipsess_set_close_headers(call->sess,
1836 				  "X-RTP-Stat: %H\r\n",
1837 				  audio_print_rtpstat, call->audio);
1838 }
1839 
1840 
call_is_onhold(const struct call * call)1841 bool call_is_onhold(const struct call *call)
1842 {
1843 	return call ? call->on_hold : false;
1844 }
1845 
1846 
call_is_outgoing(const struct call * call)1847 bool call_is_outgoing(const struct call *call)
1848 {
1849 	return call ? call->outgoing : false;
1850 }
1851 
1852 
call_enable_rtp_timeout(struct call * call,uint32_t timeout_ms)1853 void call_enable_rtp_timeout(struct call *call, uint32_t timeout_ms)
1854 {
1855 	if (!call)
1856 		return;
1857 
1858 	call->rtp_timeout_ms = timeout_ms;
1859 }
1860 
1861 
1862 /**
1863  * Get the line number for this call
1864  *
1865  * @param call Call object
1866  *
1867  * @return Line number from 1 to N
1868  */
call_linenum(const struct call * call)1869 uint32_t call_linenum(const struct call *call)
1870 {
1871 	return call ? call->linenum : 0;
1872 }
1873 
1874 
call_find_linenum(const struct list * calls,uint32_t linenum)1875 struct call *call_find_linenum(const struct list *calls, uint32_t linenum)
1876 {
1877 	struct le *le;
1878 
1879 	for (le = list_head(calls); le; le = le->next) {
1880 		struct call *call = le->data;
1881 
1882 		if (linenum == call->linenum)
1883 			return call;
1884 	}
1885 
1886 	return NULL;
1887 }
1888 
1889 
call_set_current(struct list * calls,struct call * call)1890 void call_set_current(struct list *calls, struct call *call)
1891 {
1892 	if (!calls || !call)
1893 		return;
1894 
1895 	list_unlink(&call->le);
1896 	list_append(calls, &call->le, call);
1897 }
1898