Asterisk - The Open Source Telephony Project  GIT-master-1f78ee9
channel.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18 
19 /*! \file
20  *
21  * \brief Channel Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25 
26 /*** MODULEINFO
27  <support_level>core</support_level>
28  ***/
29 
30 #include "asterisk.h"
31 
32 #include "asterisk/_private.h"
33 
34 #include <sys/time.h>
35 #include <signal.h>
36 #include <math.h>
37 
38 #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
39 
40 #include "asterisk/pbx.h"
41 #include "asterisk/frame.h"
42 #include "asterisk/mod_format.h"
43 #include "asterisk/sched.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/musiconhold.h"
46 #include "asterisk/say.h"
47 #include "asterisk/file.h"
48 #include "asterisk/cli.h"
49 #include "asterisk/translate.h"
50 #include "asterisk/manager.h"
51 #include "asterisk/chanvars.h"
52 #include "asterisk/linkedlists.h"
53 #include "asterisk/indications.h"
54 #include "asterisk/causes.h"
55 #include "asterisk/callerid.h"
56 #include "asterisk/utils.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/app.h"
59 #include "asterisk/transcap.h"
60 #include "asterisk/devicestate.h"
61 #include "asterisk/threadstorage.h"
62 #include "asterisk/slinfactory.h"
63 #include "asterisk/audiohook.h"
64 #include "asterisk/framehook.h"
65 #include "asterisk/timing.h"
66 #include "asterisk/autochan.h"
67 #include "asterisk/stringfields.h"
70 #include "asterisk/features.h"
71 #include "asterisk/bridge.h"
72 #include "asterisk/test.h"
74 #include "asterisk/max_forwards.h"
75 #include "asterisk/stream.h"
76 #include "asterisk/message.h"
77 
78 /*** DOCUMENTATION
79  ***/
80 
81 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
82 #if defined(HAVE_PRI)
83 #include "libpri.h"
84 #endif /* defined(HAVE_PRI) */
85 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
86 
87 /* uncomment if you have problems with 'monitoring' synchronized files */
88 #if 0
89 #define MONITOR_CONSTANT_DELAY
90 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
91 #endif
92 
93 static int chancount;
94 
95 unsigned long global_fin, global_fout;
96 
98 #define STATE2STR_BUFSIZE 32
99 
100 /*! Default amount of time to use when emulating a digit as a begin and end
101  * 100ms */
102 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
103 
104 #define DEFAULT_AMA_FLAGS AST_AMA_DOCUMENTATION
105 
106 /*! Minimum amount of time between the end of the last digit and the beginning
107  * of a new one - 45ms */
108 #define AST_MIN_DTMF_GAP 45
109 
110 /*! \brief List of channel drivers */
111 struct chanlist {
112  const struct ast_channel_tech *tech;
114 };
115 
116 /*! \brief the list of registered channel types */
118 
119 /*! \brief All active channels on the system */
120 static struct ao2_container *channels;
121 
122 /*! \brief map AST_CAUSE's to readable string representations
123  *
124  * \ref causes.h
125 */
126 struct causes_map {
127  int cause;
128  const char *name;
129  const char *desc;
130 };
131 
132 static const struct causes_map causes[] = {
133  { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
134  { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
135  { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
136  { AST_CAUSE_MISDIALLED_TRUNK_PREFIX, "MISDIALLED_TRUNK_PREFIX", "Misdialed trunk prefix" },
137  { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
138  { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
139  { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
140  { AST_CAUSE_NUMBER_PORTED_NOT_HERE, "NUMBER_PORTED_NOT_HERE", "Number ported elsewhere" },
141  { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
142  { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
143  { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
144  { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
145  { AST_CAUSE_SUBSCRIBER_ABSENT, "SUBSCRIBER_ABSENT", "Subscriber absent" },
146  { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
147  { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
148  { AST_CAUSE_REDIRECTED_TO_NEW_DESTINATION, "REDIRECTED_TO_NEW_DESTINATION", "Redirected to new destination" },
149  { AST_CAUSE_ANSWERED_ELSEWHERE, "ANSWERED_ELSEWHERE", "Answered elsewhere" },
150  { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
151  { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
152  { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
153  { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
154  { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
155  { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
156  { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
157  { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
158  { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
159  { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
160  { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
161  { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
162  { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
163  { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
164  { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
165  { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
166  { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
167  { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
168  { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
169  { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
170  { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
171  { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
172  { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
173  { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
174  { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
175  { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
176  { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
177  { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
178  { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
179  { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
180  { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
181  { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
182 };
183 
185 {
186  struct chanlist *cl;
187  struct ast_variable *var = NULL, *prev = NULL;
188 
191  if (prev) {
192  if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
193  prev = prev->next;
194  } else {
195  var = ast_variable_new(cl->tech->type, cl->tech->description, "");
196  prev = var;
197  }
198  }
200 
201  return var;
202 }
203 
204 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
205 static const char *party_number_ton2str(int ton)
206 {
207 #if defined(HAVE_PRI)
208  switch ((ton >> 4) & 0x07) {
209  case PRI_TON_INTERNATIONAL:
210  return "International";
211  case PRI_TON_NATIONAL:
212  return "National";
213  case PRI_TON_NET_SPECIFIC:
214  return "Network Specific";
215  case PRI_TON_SUBSCRIBER:
216  return "Subscriber";
217  case PRI_TON_ABBREVIATED:
218  return "Abbreviated";
219  case PRI_TON_RESERVED:
220  return "Reserved";
221  case PRI_TON_UNKNOWN:
222  default:
223  break;
224  }
225 #endif /* defined(HAVE_PRI) */
226  return "Unknown";
227 }
228 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
229 
230 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
231 static const char *party_number_plan2str(int plan)
232 {
233 #if defined(HAVE_PRI)
234  switch (plan & 0x0F) {
235  default:
236  case PRI_NPI_UNKNOWN:
237  break;
238  case PRI_NPI_E163_E164:
239  return "Public (E.163/E.164)";
240  case PRI_NPI_X121:
241  return "Data (X.121)";
242  case PRI_NPI_F69:
243  return "Telex (F.69)";
244  case PRI_NPI_NATIONAL:
245  return "National Standard";
246  case PRI_NPI_PRIVATE:
247  return "Private";
248  case PRI_NPI_RESERVED:
249  return "Reserved";
250  }
251 #endif /* defined(HAVE_PRI) */
252  return "Unknown";
253 }
254 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
255 
256 /*! \brief Show channel types - CLI command */
257 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
258 {
259 #define FORMAT "%-15.15s %-40.40s %-13.13s %-13.13s %-13.13s %-13.13s\n"
260  struct chanlist *cl;
261  int count_chan = 0;
262 
263  switch (cmd) {
264  case CLI_INIT:
265  e->command = "core show channeltypes";
266  e->usage =
267  "Usage: core show channeltypes\n"
268  " Lists available channel types registered in your\n"
269  " Asterisk server.\n";
270  return NULL;
271  case CLI_GENERATE:
272  return NULL;
273  }
274 
275  if (a->argc != 3)
276  return CLI_SHOWUSAGE;
277 
278  ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Presencestate", "Indications", "Transfer");
279  ast_cli(a->fd, FORMAT, "-------------", "-------------", "-------------", "-------------", "-------------", "-------------");
280 
283  ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
284  (cl->tech->devicestate) ? "yes" : "no",
285  (cl->tech->presencestate) ? "yes" : "no",
286  (cl->tech->indicate) ? "yes" : "no",
287  (cl->tech->transfer) ? "yes" : "no");
288  count_chan++;
289  }
291 
292  ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
293 
294  return CLI_SUCCESS;
295 
296 #undef FORMAT
297 }
298 
299 static char *complete_channeltypes(struct ast_cli_args *a)
300 {
301  struct chanlist *cl;
302  int wordlen;
303 
304  if (a->pos != 3) {
305  return NULL;
306  }
307 
308  wordlen = strlen(a->word);
309 
312  if (!strncasecmp(a->word, cl->tech->type, wordlen)) {
314  }
315  }
317 
318  return NULL;
319 }
320 
321 /*! \brief Show details about a channel driver - CLI command */
322 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
323 {
324  struct chanlist *cl = NULL;
325  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
326 
327  switch (cmd) {
328  case CLI_INIT:
329  e->command = "core show channeltype";
330  e->usage =
331  "Usage: core show channeltype <name>\n"
332  " Show details about the specified channel type, <name>.\n";
333  return NULL;
334  case CLI_GENERATE:
335  return complete_channeltypes(a);
336  }
337 
338  if (a->argc != 4)
339  return CLI_SHOWUSAGE;
340 
342 
344  if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
345  break;
346  }
347 
348 
349  if (!cl) {
350  ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
352  return CLI_FAILURE;
353  }
354 
355  ast_cli(a->fd,
356  "-- Info about channel driver: %s --\n"
357  " Device State: %s\n"
358  "Presence State: %s\n"
359  " Indication: %s\n"
360  " Transfer : %s\n"
361  " Capabilities: %s\n"
362  " Digit Begin: %s\n"
363  " Digit End: %s\n"
364  " Send HTML : %s\n"
365  " Image Support: %s\n"
366  " Text Support: %s\n",
367  cl->tech->type,
368  (cl->tech->devicestate) ? "yes" : "no",
369  (cl->tech->presencestate) ? "yes" : "no",
370  (cl->tech->indicate) ? "yes" : "no",
371  (cl->tech->transfer) ? "yes" : "no",
372  ast_format_cap_get_names(cl->tech->capabilities, &codec_buf),
373  (cl->tech->send_digit_begin) ? "yes" : "no",
374  (cl->tech->send_digit_end) ? "yes" : "no",
375  (cl->tech->send_html) ? "yes" : "no",
376  (cl->tech->send_image) ? "yes" : "no",
377  (cl->tech->send_text) ? "yes" : "no"
378 
379  );
380 
382 
383  return CLI_SUCCESS;
384 }
385 
386 static struct ast_cli_entry cli_channel[] = {
387  AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
388  AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
389 };
390 
391 static struct ast_frame *kill_read(struct ast_channel *chan)
392 {
393  /* Hangup channel. */
394  return NULL;
395 }
396 
397 static struct ast_frame *kill_exception(struct ast_channel *chan)
398 {
399  /* Hangup channel. */
400  return NULL;
401 }
402 
403 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
404 {
405  /* Hangup channel. */
406  return -1;
407 }
408 
409 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
410 {
411  /* No problem fixing up the channel. */
412  return 0;
413 }
414 
415 static int kill_hangup(struct ast_channel *chan)
416 {
418  return 0;
419 }
420 
421 /*!
422  * \brief Kill the channel channel driver technology descriptor.
423  *
424  * \details
425  * The purpose of this channel technology is to encourage the
426  * channel to hangup as quickly as possible.
427  *
428  * \note Used by DTMF atxfer and zombie channels.
429  */
431  .type = "Kill",
432  .description = "Kill channel (should not see this)",
433  .read = kill_read,
434  .exception = kill_exception,
435  .write = kill_write,
436  .fixup = kill_fixup,
437  .hangup = kill_hangup,
438 };
439 
440 /*! \brief Checks to see if a channel is needing hang up */
442 {
443  if (ast_channel_softhangup_internal_flag(chan)) /* yes if soft hangup flag set */
444  return 1;
445  if (ast_tvzero(*ast_channel_whentohangup(chan))) /* no if no hangup scheduled */
446  return 0;
447  if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0) /* no if hangup time has not come yet. */
448  return 0;
449  ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
450  ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(chan));
452  return 1;
453 }
454 
456 {
457  int res;
458  ast_channel_lock(chan);
459  res = ast_check_hangup(chan);
460  ast_channel_unlock(chan);
461  return res;
462 }
463 
465 {
466  ast_channel_lock(chan);
467 
468  if (causecode > 0) {
469  ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
470  ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));
471 
472  ast_channel_hangupcause_set(chan, causecode);
473  }
474 
476 
477  ast_channel_unlock(chan);
478 }
479 
480 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
481 {
482  struct ast_channel *chan = obj;
483 
485 
486  return 0;
487 }
488 
490 {
492 }
493 
494 /*! \brief returns number of active/allocated channels */
496 {
497  return channels ? ao2_container_count(channels) : 0;
498 }
499 
501 {
503 }
504 
505 /*! \brief Set when to hangup channel */
506 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
507 {
508  if (ast_tvzero(offset)) {
509  ast_channel_whentohangup_set(chan, &offset);
510  } else {
511  struct timeval tv = ast_tvadd(offset, ast_tvnow());
512  ast_channel_whentohangup_set(chan, &tv);
513  }
515  return;
516 }
517 
518 /*! \brief Compare a offset with when to hangup channel */
519 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
520 {
521  struct timeval whentohangup;
522 
524  return ast_tvzero(offset) ? 0 : -1;
525 
526  if (ast_tvzero(offset))
527  return 1;
528 
529  whentohangup = ast_tvadd(offset, ast_tvnow());
530 
531  return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
532 }
533 
534 /*! \brief Register a new telephony channel in Asterisk */
536 {
537  struct chanlist *chan;
538 
540 
542  if (!strcasecmp(tech->type, chan->tech->type)) {
543  ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
545  return -1;
546  }
547  }
548 
549  if (!(chan = ast_calloc(1, sizeof(*chan)))) {
551  return -1;
552  }
553  chan->tech = tech;
555 
556  ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
557 
558  ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
559 
561 
562  return 0;
563 }
564 
565 /*! \brief Unregister channel driver */
567 {
568  struct chanlist *chan;
569 
570  ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
571 
573 
575  if (chan->tech == tech) {
577  ast_free(chan);
578  ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
579  break;
580  }
581  }
583 
585 }
586 
587 /*! \brief Get handle to channel driver based on name */
588 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
589 {
590  struct chanlist *chanls;
591  const struct ast_channel_tech *ret = NULL;
592 
594 
595  AST_RWLIST_TRAVERSE(&backends, chanls, list) {
596  if (!strcasecmp(name, chanls->tech->type)) {
597  ret = chanls->tech;
598  break;
599  }
600  }
601 
603 
604  return ret;
605 }
606 
607 /*! \brief Gives the string form of a given hangup cause */
608 const char *ast_cause2str(int cause)
609 {
610  int x;
611 
612  for (x = 0; x < ARRAY_LEN(causes); x++) {
613  if (causes[x].cause == cause)
614  return causes[x].desc;
615  }
616 
617  return "Unknown";
618 }
619 
620 /*! \brief Convert a symbolic hangup cause to number */
621 int ast_str2cause(const char *name)
622 {
623  int x;
624 
625  for (x = 0; x < ARRAY_LEN(causes); x++)
626  if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
627  return causes[x].cause;
628 
629  return -1;
630 }
631 
632 /*! \brief Gives the string form of a given channel state.
633  *
634  * \note This function is not reentrant.
635  *
636  * \param state
637  */
639 {
640  char *buf;
641 
642  switch (state) {
643  case AST_STATE_DOWN:
644  return "Down";
645  case AST_STATE_RESERVED:
646  return "Rsrvd";
647  case AST_STATE_OFFHOOK:
648  return "OffHook";
649  case AST_STATE_DIALING:
650  return "Dialing";
651  case AST_STATE_RING:
652  return "Ring";
653  case AST_STATE_RINGING:
654  return "Ringing";
655  case AST_STATE_UP:
656  return "Up";
657  case AST_STATE_BUSY:
658  return "Busy";
660  return "Dialing Offhook";
661  case AST_STATE_PRERING:
662  return "Pre-ring";
663  case AST_STATE_MUTE:
664  return "Mute";
665  default:
667  return "Unknown";
668  snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%u)", state);
669  return buf;
670  }
671 }
672 
673 /*! \brief Gives the string form of a given transfer capability */
674 char *ast_transfercapability2str(int transfercapability)
675 {
676  switch (transfercapability) {
678  return "SPEECH";
680  return "DIGITAL";
682  return "RESTRICTED_DIGITAL";
684  return "3K1AUDIO";
686  return "DIGITAL_W_TONES";
687  case AST_TRANS_CAP_VIDEO:
688  return "VIDEO";
689  default:
690  return "UNKNOWN";
691  }
692 }
693 
694 /*! \brief Channel technology used to extract a channel from a running application. The
695  * channel created with this technology will be immediately hung up - most external
696  * applications won't ever want to see this.
697  */
698 static const struct ast_channel_tech surrogate_tech = {
699  .type = "Surrogate",
700  .description = "Surrogate channel used to pull channel from an application",
701  .properties = AST_CHAN_TP_INTERNAL,
702 };
703 
704 static const struct ast_channel_tech null_tech = {
705  .type = "NULL",
706  .description = "Null channel (should not see this)",
707 };
708 
709 static void ast_channel_destructor(void *obj);
710 static void ast_dummy_channel_destructor(void *obj);
711 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags);
712 
713 static int does_id_conflict(const char *uniqueid)
714 {
715  struct ast_channel *conflict;
716  size_t length = 0;
717 
718  if (ast_strlen_zero(uniqueid)) {
719  return 0;
720  }
721 
722  conflict = ast_channel_callback(ast_channel_by_uniqueid_cb, (char *) uniqueid, &length, OBJ_NOLOCK);
723  if (conflict) {
724  ast_log(LOG_ERROR, "Channel Unique ID '%s' already in use by channel %s(%p)\n",
725  uniqueid, ast_channel_name(conflict), conflict);
726  ast_channel_unref(conflict);
727  return 1;
728  }
729 
730  return 0;
731 }
732 
733 /*! \brief Create a new channel structure */
734 static struct ast_channel *__attribute__((format(printf, 15, 0)))
735 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
736  const char *acctcode, const char *exten, const char *context, const struct ast_assigned_ids *assignedids,
737  const struct ast_channel *requestor, enum ama_flags amaflag, struct ast_endpoint *endpoint,
738  const char *file, int line,
739  const char *function, const char *name_fmt, va_list ap)
740 {
741  struct ast_channel *tmp;
742  struct varshead *headp;
743  char *tech = "", *tech2 = NULL;
744  struct ast_format_cap *nativeformats;
745  struct ast_sched_context *schedctx;
746  struct ast_timer *timer;
747  struct timeval now;
748  const struct ast_channel_tech *channel_tech;
749  struct ast_stream_topology *topology;
750 
751  /* If shutting down, don't allocate any new channels */
752  if (ast_shutting_down()) {
753  ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
754  return NULL;
755  }
756 
757  tmp = __ast_channel_internal_alloc(ast_channel_destructor, assignedids, requestor,
758  file, line, function);
759  if (!tmp) {
760  /* Channel structure allocation failure. */
761  return NULL;
762  }
763 
765 
766  /*
767  * Init file descriptors to unopened state so
768  * the destructor can know not to close them.
769  */
770  ast_channel_timingfd_set(tmp, -1);
773 
775  if (!nativeformats) {
776  /*
777  * Aborting the channel creation. We do not need to complete staging
778  * the channel snapshot because the channel has not been finalized or
779  * linked into the channels container yet. Nobody else knows about
780  * this channel nor will anybody ever know about it.
781  */
782  return ast_channel_unref(tmp);
783  }
784  ast_format_cap_append(nativeformats, ast_format_none, 0);
785  ast_channel_nativeformats_set(tmp, nativeformats);
786  ao2_ref(nativeformats, -1);
787 
792 
793  if (!(schedctx = ast_sched_context_create())) {
794  ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
795  /* See earlier channel creation abort comment above. */
796  return ast_channel_unref(tmp);
797  }
798  ast_channel_sched_set(tmp, schedctx);
799 
805 
806  if (cid_name) {
807  ast_channel_caller(tmp)->id.name.valid = 1;
809  if (!ast_channel_caller(tmp)->id.name.str) {
810  /* See earlier channel creation abort comment above. */
811  return ast_channel_unref(tmp);
812  }
813  }
814  if (cid_num) {
815  ast_channel_caller(tmp)->id.number.valid = 1;
817  if (!ast_channel_caller(tmp)->id.number.str) {
818  /* See earlier channel creation abort comment above. */
819  return ast_channel_unref(tmp);
820  }
821  }
822 
823  if ((timer = ast_timer_open())) {
824  ast_channel_timer_set(tmp, timer);
825  if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
826  needqueue = 0;
827  }
829  }
830 
831  if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
832  /* See earlier channel creation abort comment above. */
833  return ast_channel_unref(tmp);
834  }
835 
836  if (!(topology = ast_stream_topology_alloc())) {
837  return ast_channel_unref(tmp);
838  }
840 
841  /* Always watch the alertpipe */
843  /* And timing pipe */
845 
846  /* Initial state */
849 
850  ast_channel_streamid_set(tmp, -1);
851  ast_channel_vstreamid_set(tmp, -1);
852 
855 
856  now = ast_tvnow();
857  ast_channel_creationtime_set(tmp, &now);
858 
860 
861  if (!ast_strlen_zero(name_fmt)) {
862  char *slash, *slash2;
863  /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
864  * And they all use slightly different formats for their name string.
865  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
866  * This means, that the stringfields must have a routine that takes the va_lists directly, and
867  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
868  * This new function was written so this can be accomplished.
869  */
870  ast_channel_name_build_va(tmp, name_fmt, ap);
872  if ((slash = strchr(tech, '/'))) {
873  if ((slash2 = strchr(slash + 1, '/'))) {
874  tech2 = slash + 1;
875  *slash2 = '\0';
876  }
877  *slash = '\0';
878  }
879  } else {
880  /*
881  * Start the string with '-' so it becomes an empty string
882  * in the destructor.
883  */
884  ast_channel_name_set(tmp, "-**Unknown**");
885  }
886 
887  if (amaflag != AST_AMA_NONE) {
888  ast_channel_amaflags_set(tmp, amaflag);
889  } else {
891  }
892 
893  if (!ast_strlen_zero(acctcode)) {
894  ast_channel_accountcode_set(tmp, acctcode);
895  }
896  ast_channel_language_set(tmp, ast_defaultlanguage);
897 
898  ast_channel_context_set(tmp, S_OR(context, "default"));
899  ast_channel_exten_set(tmp, S_OR(exten, "s"));
900  ast_channel_priority_set(tmp, 1);
901 
902  headp = ast_channel_varshead(tmp);
904 
908 
909  channel_tech = ast_get_channel_tech(tech);
910  if (!channel_tech && !ast_strlen_zero(tech2)) {
911  channel_tech = ast_get_channel_tech(tech2);
912  }
913  if (channel_tech) {
914  ast_channel_tech_set(tmp, channel_tech);
915  } else {
916  ast_channel_tech_set(tmp, &null_tech);
917  }
918 
919  /* You might scream "locking inversion" at seeing this but it is actually perfectly fine.
920  * Since the channel was just created nothing can know about it yet or even acquire it.
921  */
922  ast_channel_lock(tmp);
923 
924  ao2_lock(channels);
925 
926  if (assignedids && (does_id_conflict(assignedids->uniqueid) || does_id_conflict(assignedids->uniqueid2))) {
928  ao2_unlock(channels);
929  ast_channel_unlock(tmp);
930  /* See earlier channel creation abort comment above. */
931  return ast_channel_unref(tmp);
932  }
933 
934  /* Finalize and link into the channels container. */
937  ao2_link_flags(channels, tmp, OBJ_NOLOCK);
938 
939  ao2_unlock(channels);
940 
941  if (endpoint) {
942  ast_endpoint_add_channel(endpoint, tmp);
943  }
944 
945  /*
946  * And now, since the channel structure is built, and has its name, let
947  * the world know of its existance
948  */
950 
951  ast_debug(1, "Channel %p '%s' allocated\n", tmp, ast_channel_name(tmp));
952 
953  return tmp;
954 }
955 
956 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
957  const char *cid_name, const char *acctcode,
958  const char *exten, const char *context, const struct ast_assigned_ids *assignedids,
959  const struct ast_channel *requestor, enum ama_flags amaflag,
960  struct ast_endpoint *endpoint,
961  const char *file, int line, const char *function,
962  const char *name_fmt, ...)
963 {
964  va_list ap;
965  struct ast_channel *result;
966 
967  va_start(ap, name_fmt);
968  result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
969  assignedids, requestor, amaflag, endpoint, file, line, function, name_fmt, ap);
970  va_end(ap);
971 
972  return result;
973 }
974 
975 /* only do the minimum amount of work needed here to make a channel
976  * structure that can be used to expand channel vars */
977 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
978 {
979  struct ast_channel *tmp;
980  struct varshead *headp;
981 
983  file, line, function);
984  if (!tmp) {
985  /* Dummy channel structure allocation failure. */
986  return NULL;
987  }
988 
991 
992  /*
993  * Init file descriptors to unopened state just in case
994  * autoservice is called on the channel or something tries to
995  * read a frame from it.
996  */
997  ast_channel_timingfd_set(tmp, -1);
1000 
1002 
1004 
1005  headp = ast_channel_varshead(tmp);
1007 
1008  return tmp;
1009 }
1010 
1011 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1012 {
1013  struct ast_frame *f;
1014  struct ast_frame *cur;
1015  unsigned int new_frames = 0;
1016  unsigned int new_voice_frames = 0;
1017  unsigned int queued_frames = 0;
1018  unsigned int queued_voice_frames = 0;
1020 
1021  ast_channel_lock(chan);
1022 
1023  /*
1024  * Check the last frame on the queue if we are queuing the new
1025  * frames after it.
1026  */
1027  cur = AST_LIST_LAST(ast_channel_readq(chan));
1028  if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1029  switch (cur->subclass.integer) {
1030  case AST_CONTROL_END_OF_Q:
1031  if (fin->frametype == AST_FRAME_CONTROL
1032  && fin->subclass.integer == AST_CONTROL_HANGUP) {
1033  /*
1034  * Destroy the end-of-Q marker frame so we can queue the hangup
1035  * frame in its place.
1036  */
1038  ast_frfree(cur);
1039 
1040  /*
1041  * This has degenerated to a normal queue append anyway. Since
1042  * we just destroyed the last frame in the queue we must make
1043  * sure that "after" is NULL or bad things will happen.
1044  */
1045  after = NULL;
1046  break;
1047  }
1048  /* Fall through */
1049  case AST_CONTROL_HANGUP:
1050  /* Don't queue anything. */
1051  ast_channel_unlock(chan);
1052  return 0;
1053  default:
1054  break;
1055  }
1056  }
1057 
1058  /* Build copies of all the new frames and count them */
1060  for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1061  if (!(f = ast_frdup(cur))) {
1062  if (AST_LIST_FIRST(&frames)) {
1064  }
1065  ast_channel_unlock(chan);
1066  return -1;
1067  }
1068 
1070  new_frames++;
1071  if (f->frametype == AST_FRAME_VOICE) {
1072  new_voice_frames++;
1073  }
1074  }
1075 
1076  /* Count how many frames exist on the queue */
1078  queued_frames++;
1079  if (cur->frametype == AST_FRAME_VOICE) {
1080  queued_voice_frames++;
1081  }
1082  }
1083 
1084  if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1085  int count = 0;
1086  ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1088  /* Save the most recent frame */
1089  if (!AST_LIST_NEXT(cur, frame_list)) {
1090  break;
1091  } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1092  if (++count > 64) {
1093  break;
1094  }
1096  ast_frfree(cur);
1097 
1098  /* Read from the alert pipe for each flushed frame. */
1100  }
1101  }
1103  }
1104 
1105  if (after) {
1107  } else {
1108  if (head) {
1111  }
1113  }
1114 
1115  if (ast_channel_alert_writable(chan)) {
1116  /* Write to the alert pipe for each added frame */
1117  while (new_frames--) {
1118  if (ast_channel_alert_write(chan)) {
1119  ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %u): %s!\n",
1120  ast_channel_name(chan), queued_frames, strerror(errno));
1121  break;
1122  }
1123  }
1124  } else if (ast_channel_timingfd(chan) > -1) {
1126  } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1127  pthread_kill(ast_channel_blocker(chan), SIGURG);
1128  }
1129 
1130  ast_channel_unlock(chan);
1131 
1132  return 0;
1133 }
1134 
1135 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1136 {
1137  return __ast_queue_frame(chan, fin, 0, NULL);
1138 }
1139 
1141 {
1142  return __ast_queue_frame(chan, fin, 1, NULL);
1143 }
1144 
1145 /*! \brief Queue a hangup frame for channel */
1147 {
1148  struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1149  int res;
1150 
1151  /* Yeah, let's not change a lock-critical value without locking */
1152  ast_channel_lock(chan);
1155 
1156  res = ast_queue_frame(chan, &f);
1157  ast_channel_unlock(chan);
1158  return res;
1159 }
1160 
1161 /*! \brief Queue a hangup frame for channel */
1163 {
1164  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1165  struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1166  int res;
1167 
1168  if (cause >= 0) {
1169  f.data.uint32 = cause;
1170  }
1171 
1172  /* Yeah, let's not change a lock-critical value without locking */
1173  ast_channel_lock(chan);
1175  if (cause < 0) {
1177  }
1178  blob = ast_json_pack("{s: i}",
1179  "cause", cause);
1181 
1182  res = ast_queue_frame(chan, &f);
1183  ast_channel_unlock(chan);
1184  return res;
1185 }
1186 
1187 int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
1188 {
1189  struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HOLD };
1190  struct ast_json *blob = NULL;
1191  int res;
1192 
1193  if (!ast_strlen_zero(musicclass)) {
1194  f.data.ptr = (void *) musicclass;
1195  f.datalen = strlen(musicclass) + 1;
1196 
1197  blob = ast_json_pack("{s: s}",
1198  "musicclass", musicclass);
1199  }
1200 
1201  ast_channel_lock(chan);
1203  ast_channel_unlock(chan);
1204 
1205  res = ast_queue_frame(chan, &f);
1206 
1207  ast_json_unref(blob);
1208 
1209  return res;
1210 }
1211 
1213 {
1214  struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_UNHOLD };
1215  int res;
1216 
1217  ast_channel_lock(chan);
1219  ast_channel_unlock(chan);
1220 
1221  res = ast_queue_frame(chan, &f);
1222 
1223  return res;
1224 }
1225 
1226 /*! \brief Queue a control frame */
1228 {
1229  struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1230  return ast_queue_frame(chan, &f);
1231 }
1232 
1233 /*! \brief Queue a control frame with payload */
1235  const void *data, size_t datalen)
1236 {
1237  struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1238  return ast_queue_frame(chan, &f);
1239 }
1240 
1241 /*! \brief Set defer DTMF flag on channel */
1243 {
1244  int pre = 0;
1245 
1246  if (chan) {
1247  ast_channel_lock(chan);
1250  ast_channel_unlock(chan);
1251  }
1252  return pre;
1253 }
1254 
1255 /*! \brief Unset defer DTMF flag on channel */
1257 {
1258  if (chan) {
1260  }
1261 }
1262 
1264  void *data, int ao2_flags)
1265 {
1266  return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1267 }
1268 
1269 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1270 {
1271  struct ast_channel *chan = obj;
1272  const char *name = arg;
1273  size_t name_len = *(size_t *) data;
1274  int ret = CMP_MATCH;
1275 
1276  if (ast_strlen_zero(name)) {
1277  ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1278  return CMP_STOP;
1279  }
1280 
1281  ast_channel_lock(chan);
1282  if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1283  || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1284  ret = 0; /* name match failed, keep looking */
1285  }
1286  ast_channel_unlock(chan);
1287 
1288  return ret;
1289 }
1290 
1291 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1292 {
1293  struct ast_channel *chan = obj;
1294  char *context = arg;
1295  char *exten = data;
1296  int ret = CMP_MATCH;
1297 
1298  if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1299  ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1300  return CMP_STOP;
1301  }
1302 
1303  ast_channel_lock(chan);
1304  if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1305  ret = 0; /* Context match failed, continue */
1306  } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1307  ret = 0; /* Extension match failed, continue */
1308  }
1309  ast_channel_unlock(chan);
1310 
1311  return ret;
1312 }
1313 
1314 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1315 {
1316  struct ast_channel *chan = obj;
1317  char *uniqueid = arg;
1318  size_t id_len = *(size_t *) data;
1319  int ret = CMP_MATCH;
1320 
1321  if (ast_strlen_zero(uniqueid)) {
1322  ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1323  return CMP_STOP;
1324  }
1325 
1326  ast_channel_lock(chan);
1327  if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1328  || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1329  ret = 0; /* uniqueid match failed, keep looking */
1330  }
1331  ast_channel_unlock(chan);
1332 
1333  return ret;
1334 }
1335 
1337  /* storage for non-dynamically allocated iterator */
1338  struct ao2_iterator simple_iterator;
1339  /* pointer to the actual iterator (simple_iterator or a dynamically
1340  * allocated iterator)
1341  */
1343 };
1344 
1346 {
1348  ast_free(i);
1349 
1350  return NULL;
1351 }
1352 
1354 {
1355  struct ast_channel_iterator *i;
1356  char *l_exten = (char *) exten;
1357  char *l_context = (char *) context;
1358 
1359  if (!(i = ast_calloc(1, sizeof(*i)))) {
1360  return NULL;
1361  }
1362 
1364  l_context, l_exten, OBJ_MULTIPLE);
1365  if (!i->active_iterator) {
1366  ast_free(i);
1367  return NULL;
1368  }
1369 
1370  return i;
1371 }
1372 
1373 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1374 {
1375  struct ast_channel_iterator *i;
1376  char *l_name = (char *) name;
1377 
1378  if (!(i = ast_calloc(1, sizeof(*i)))) {
1379  return NULL;
1380  }
1381 
1383  l_name, &name_len,
1384  OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1385  if (!i->active_iterator) {
1386  ast_free(i);
1387  return NULL;
1388  }
1389 
1390  return i;
1391 }
1392 
1394 {
1395  struct ast_channel_iterator *i;
1396 
1397  if (!(i = ast_calloc(1, sizeof(*i)))) {
1398  return NULL;
1399  }
1400 
1401  i->simple_iterator = ao2_iterator_init(channels, 0);
1403 
1404  return i;
1405 }
1406 
1408 {
1410 }
1411 
1412 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1413 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1414 {
1415  ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1416  return CMP_STOP;
1417 }
1418 
1419 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1420 {
1421  struct ast_channel *chan;
1422  char *l_name = (char *) name;
1423 
1424  chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1425  (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1426  if (chan) {
1427  return chan;
1428  }
1429 
1430  if (ast_strlen_zero(l_name)) {
1431  /* We didn't have a name to search for so quit. */
1432  return NULL;
1433  }
1434 
1435  /* Now try a search for uniqueid. */
1436  return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1437 }
1438 
1440 {
1441  return ast_channel_get_by_name_prefix(name, 0);
1442 }
1443 
1444 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1445 {
1446  char *l_exten = (char *) exten;
1447  char *l_context = (char *) context;
1448 
1449  return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1450 }
1451 
1452 int ast_is_deferrable_frame(const struct ast_frame *frame)
1453 {
1454  /* Do not add a default entry in this switch statement. Each new
1455  * frame type should be addressed directly as to whether it should
1456  * be queued up or not.
1457  */
1458  switch (frame->frametype) {
1461  case AST_FRAME_CONTROL:
1462  case AST_FRAME_TEXT:
1463  case AST_FRAME_TEXT_DATA:
1464  case AST_FRAME_IMAGE:
1465  case AST_FRAME_HTML:
1466  return 1;
1467 
1468  case AST_FRAME_DTMF_END:
1469  case AST_FRAME_DTMF_BEGIN:
1470  case AST_FRAME_VOICE:
1471  case AST_FRAME_VIDEO:
1472  case AST_FRAME_NULL:
1473  case AST_FRAME_IAX:
1474  case AST_FRAME_CNG:
1475  case AST_FRAME_MODEM:
1476  case AST_FRAME_RTCP:
1477  return 0;
1478  }
1479  return 0;
1480 }
1481 
1482 /*! \brief Wait, look for hangups and condition arg */
1483 int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
1484 {
1485  struct ast_frame *f;
1486  struct ast_silence_generator *silgen = NULL;
1487  int res = 0;
1488  struct timeval start;
1489  int ms;
1490  AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1491 
1492  AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1493 
1494  /* If no other generator is present, start silencegen while waiting */
1496  silgen = ast_channel_start_silence_generator(chan);
1497  }
1498 
1499  start = ast_tvnow();
1500  while ((ms = ast_remaining_ms(start, timeout_ms))) {
1501  struct ast_frame *dup_f = NULL;
1502 
1503  if (cond && ((*cond)(data) == 0)) {
1504  break;
1505  }
1506  ms = ast_waitfor(chan, ms);
1507  if (ms < 0) {
1508  res = -1;
1509  break;
1510  }
1511  if (ms > 0) {
1512  f = ast_read(chan);
1513  if (!f) {
1514  res = -1;
1515  break;
1516  }
1517 
1518  if (!ast_is_deferrable_frame(f)) {
1519  ast_frfree(f);
1520  continue;
1521  }
1522 
1523  if ((dup_f = ast_frisolate(f))) {
1524  if (dup_f != f) {
1525  ast_frfree(f);
1526  }
1527  AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1528  }
1529  }
1530  }
1531 
1532  /* stop silgen if present */
1533  if (silgen) {
1534  ast_channel_stop_silence_generator(chan, silgen);
1535  }
1536 
1537  /* We need to free all the deferred frames, but we only need to
1538  * queue the deferred frames if there was no error and no
1539  * hangup was received
1540  */
1541  ast_channel_lock(chan);
1542  while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1543  if (!res) {
1544  ast_queue_frame_head(chan, f);
1545  }
1546  ast_frfree(f);
1547  }
1548  ast_channel_unlock(chan);
1549 
1550  return res;
1551 }
1552 
1553 /*! \brief Wait, look for hangups */
1554 int ast_safe_sleep(struct ast_channel *chan, int ms)
1555 {
1556  return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1557 }
1558 
1560 {
1561  /* Safe, even if already unlinked. */
1562  ao2_unlink(channels, chan);
1563  return ast_channel_unref(chan);
1564 }
1565 
1567 {
1568  init->str = NULL;
1571  init->valid = 0;
1572 }
1573 
1574 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1575 {
1576  if (dest == src) {
1577  /* Don't copy to self */
1578  return;
1579  }
1580 
1581  ast_free(dest->str);
1582  dest->str = ast_strdup(src->str);
1583  dest->char_set = src->char_set;
1584  dest->presentation = src->presentation;
1585  dest->valid = src->valid;
1586 }
1587 
1588 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1589 {
1590  init->str = NULL;
1591  init->char_set = guide->char_set;
1592  init->presentation = guide->presentation;
1593  init->valid = guide->valid;
1594 }
1595 
1596 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1597 {
1598  if (dest == src) {
1599  /* Don't set to self */
1600  return;
1601  }
1602 
1603  if (src->str && src->str != dest->str) {
1604  ast_free(dest->str);
1605  dest->str = ast_strdup(src->str);
1606  }
1607 
1608  dest->char_set = src->char_set;
1609  dest->presentation = src->presentation;
1610  dest->valid = src->valid;
1611 }
1612 
1614 {
1615  ast_free(doomed->str);
1616  doomed->str = NULL;
1617 }
1618 
1620 {
1621  init->str = NULL;
1622  init->plan = 0;/* Unknown */
1624  init->valid = 0;
1625 }
1626 
1627 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1628 {
1629  if (dest == src) {
1630  /* Don't copy to self */
1631  return;
1632  }
1633 
1634  ast_free(dest->str);
1635  dest->str = ast_strdup(src->str);
1636  dest->plan = src->plan;
1637  dest->presentation = src->presentation;
1638  dest->valid = src->valid;
1639 }
1640 
1641 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1642 {
1643  init->str = NULL;
1644  init->plan = guide->plan;
1645  init->presentation = guide->presentation;
1646  init->valid = guide->valid;
1647 }
1648 
1649 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1650 {
1651  if (dest == src) {
1652  /* Don't set to self */
1653  return;
1654  }
1655 
1656  if (src->str && src->str != dest->str) {
1657  ast_free(dest->str);
1658  dest->str = ast_strdup(src->str);
1659  }
1660 
1661  dest->plan = src->plan;
1662  dest->presentation = src->presentation;
1663  dest->valid = src->valid;
1664 }
1665 
1667 {
1668  ast_free(doomed->str);
1669  doomed->str = NULL;
1670 }
1671 
1673 {
1674  init->str = NULL;
1675  init->type = 0;
1676  init->odd_even_indicator = 0;
1677  init->valid = 0;
1678 }
1679 
1681 {
1682  if (dest == src) {
1683  /* Don't copy to self */
1684  return;
1685  }
1686 
1687  ast_free(dest->str);
1688  dest->str = ast_strdup(src->str);
1689  dest->type = src->type;
1691  dest->valid = src->valid;
1692 }
1693 
1695 {
1696  init->str = NULL;
1697  init->type = guide->type;
1698  init->odd_even_indicator = guide->odd_even_indicator;
1699  init->valid = guide->valid;
1700 }
1701 
1703 {
1704  if (dest == src) {
1705  /* Don't set to self */
1706  return;
1707  }
1708 
1709  if (src->str && src->str != dest->str) {
1710  ast_free(dest->str);
1711  dest->str = ast_strdup(src->str);
1712  }
1713 
1714  dest->type = src->type;
1716  dest->valid = src->valid;
1717 }
1718 
1720 {
1721  ast_free(doomed->str);
1722  doomed->str = NULL;
1723 }
1724 
1726 {
1727  update_id->name = 1;
1728  update_id->number = 1;
1729  update_id->subaddress = 1;
1730 }
1731 
1733 {
1734  ast_party_name_init(&init->name);
1735  ast_party_number_init(&init->number);
1737  init->tag = NULL;
1738 }
1739 
1740 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1741 {
1742  if (dest == src) {
1743  /* Don't copy to self */
1744  return;
1745  }
1746 
1747  ast_party_name_copy(&dest->name, &src->name);
1748  ast_party_number_copy(&dest->number, &src->number);
1750 
1751  ast_free(dest->tag);
1752  dest->tag = ast_strdup(src->tag);
1753 }
1754 
1755 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1756 {
1757  ast_party_name_set_init(&init->name, &guide->name);
1758  ast_party_number_set_init(&init->number, &guide->number);
1760  init->tag = NULL;
1761 }
1762 
1763 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1764 {
1765  if (dest == src) {
1766  /* Don't set to self */
1767  return;
1768  }
1769 
1770  if (!update || update->name) {
1771  ast_party_name_set(&dest->name, &src->name);
1772  }
1773  if (!update || update->number) {
1774  ast_party_number_set(&dest->number, &src->number);
1775  }
1776  if (!update || update->subaddress) {
1778  }
1779 
1780  if (src->tag && src->tag != dest->tag) {
1781  ast_free(dest->tag);
1782  dest->tag = ast_strdup(src->tag);
1783  }
1784 }
1785 
1786 void ast_party_id_free(struct ast_party_id *doomed)
1787 {
1788  ast_party_name_free(&doomed->name);
1789  ast_party_number_free(&doomed->number);
1791 
1792  ast_free(doomed->tag);
1793  doomed->tag = NULL;
1794 }
1795 
1797 {
1798  int number_priority;
1799  int number_value;
1800  int number_screening;
1801  int name_priority;
1802  int name_value;
1803 
1804  /* Determine name presentation priority. */
1805  if (!id->name.valid) {
1806  name_value = AST_PRES_UNAVAILABLE;
1807  name_priority = 3;
1808  } else {
1809  name_value = id->name.presentation & AST_PRES_RESTRICTION;
1810  switch (name_value) {
1811  case AST_PRES_RESTRICTED:
1812  name_priority = 0;
1813  break;
1814  case AST_PRES_ALLOWED:
1815  name_priority = 1;
1816  break;
1817  case AST_PRES_UNAVAILABLE:
1818  name_priority = 2;
1819  break;
1820  default:
1821  name_value = AST_PRES_UNAVAILABLE;
1822  name_priority = 3;
1823  break;
1824  }
1825  }
1826 
1827  /* Determine number presentation priority. */
1828  if (!id->number.valid) {
1829  number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1830  number_value = AST_PRES_UNAVAILABLE;
1831  number_priority = 3;
1832  } else {
1833  number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1834  number_value = id->number.presentation & AST_PRES_RESTRICTION;
1835  switch (number_value) {
1836  case AST_PRES_RESTRICTED:
1837  number_priority = 0;
1838  break;
1839  case AST_PRES_ALLOWED:
1840  number_priority = 1;
1841  break;
1842  case AST_PRES_UNAVAILABLE:
1843  number_priority = 2;
1844  break;
1845  default:
1846  number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1847  number_value = AST_PRES_UNAVAILABLE;
1848  number_priority = 3;
1849  break;
1850  }
1851  }
1852 
1853  /* Select the wining presentation value. */
1854  if (name_priority < number_priority) {
1855  number_value = name_value;
1856  }
1857  if (number_value == AST_PRES_UNAVAILABLE) {
1859  }
1860 
1861  return number_value | number_screening;
1862 }
1863 
1865 {
1866  id->name.valid = 0;
1867  id->number.valid = 0;
1868  id->subaddress.valid = 0;
1869 }
1870 
1872 {
1873  ast_party_id_free(id);
1874  ast_party_id_init(id);
1875 }
1876 
1877 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
1878 {
1879  struct ast_party_id merged;
1880 
1881  merged = *base;
1882  if (overlay->name.valid) {
1883  merged.name = overlay->name;
1884  }
1885  if (overlay->number.valid) {
1886  merged.number = overlay->number;
1887  }
1888  if (overlay->subaddress.valid) {
1889  merged.subaddress = overlay->subaddress;
1890  }
1891  /* Note the actual structure is returned and not a pointer to it! */
1892  return merged;
1893 }
1894 
1895 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
1896 {
1897  struct ast_party_id merged;
1898 
1899  merged = ast_party_id_merge(base, overlay);
1900  ast_party_id_copy(dest, &merged);
1901 }
1902 
1904 {
1905  init->number.str = NULL;
1906  init->number.plan = 0;/* Unknown */
1908  init->transit_network_select = 0;
1909 }
1910 
1911 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1912 {
1913  if (dest == src) {
1914  /* Don't copy to self */
1915  return;
1916  }
1917 
1918  ast_free(dest->number.str);
1919  dest->number.str = ast_strdup(src->number.str);
1920  dest->number.plan = src->number.plan;
1923 }
1924 
1925 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
1926 {
1927  init->number.str = NULL;
1928  init->number.plan = guide->number.plan;
1931 }
1932 
1933 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1934 {
1935  if (src->number.str && src->number.str != dest->number.str) {
1936  ast_free(dest->number.str);
1937  dest->number.str = ast_strdup(src->number.str);
1938  }
1939  dest->number.plan = src->number.plan;
1940 
1942 
1944 }
1945 
1947 {
1948  ast_free(doomed->number.str);
1949  doomed->number.str = NULL;
1951 }
1952 
1954 {
1955  ast_party_id_init(&init->id);
1956  ast_party_id_init(&init->ani);
1957  ast_party_id_init(&init->priv);
1958  init->ani2 = 0;
1959 }
1960 
1961 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
1962 {
1963  if (dest == src) {
1964  /* Don't copy to self */
1965  return;
1966  }
1967 
1968  ast_party_id_copy(&dest->id, &src->id);
1969  ast_party_id_copy(&dest->ani, &src->ani);
1970  ast_party_id_copy(&dest->priv, &src->priv);
1971  dest->ani2 = src->ani2;
1972 }
1973 
1974 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
1975 {
1976  ast_party_id_set_init(&init->id, &guide->id);
1977  ast_party_id_set_init(&init->ani, &guide->ani);
1978  ast_party_id_set_init(&init->priv, &guide->priv);
1979  init->ani2 = guide->ani2;
1980 }
1981 
1982 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
1983 {
1984  ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
1985  ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
1986  ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
1987  dest->ani2 = src->ani2;
1988 }
1989 
1991 {
1992  ast_party_id_free(&doomed->id);
1993  ast_party_id_free(&doomed->ani);
1994  ast_party_id_free(&doomed->priv);
1995 }
1996 
1998 {
1999  ast_party_id_init(&init->id);
2000  ast_party_id_init(&init->ani);
2001  ast_party_id_init(&init->priv);
2002  init->ani2 = 0;
2004 }
2005 
2007 {
2008  if (dest == src) {
2009  /* Don't copy to self */
2010  return;
2011  }
2012 
2013  ast_party_id_copy(&dest->id, &src->id);
2014  ast_party_id_copy(&dest->ani, &src->ani);
2015  ast_party_id_copy(&dest->priv, &src->priv);
2016  dest->ani2 = src->ani2;
2017  dest->source = src->source;
2018 }
2019 
2021 {
2022  ast_party_id_set_init(&init->id, &guide->id);
2023  ast_party_id_set_init(&init->ani, &guide->ani);
2024  ast_party_id_set_init(&init->priv, &guide->priv);
2025  init->ani2 = guide->ani2;
2026  init->source = guide->source;
2027 }
2028 
2030 {
2031  ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2032  ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2033  ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2034  dest->ani2 = src->ani2;
2035  dest->source = src->source;
2036 }
2037 
2039 {
2040  connected->id = caller->id;
2041  connected->ani = caller->ani;
2042  connected->priv = caller->priv;
2043  connected->ani2 = caller->ani2;
2045 }
2046 
2048 {
2049  ast_party_id_free(&doomed->id);
2050  ast_party_id_free(&doomed->ani);
2051  ast_party_id_free(&doomed->priv);
2052 }
2053 
2055 {
2056  init->str = NULL;
2058 }
2059 
2061 {
2062  if (dest == src) {
2063  return;
2064  }
2065 
2066  ast_free(dest->str);
2067  dest->str = ast_strdup(src->str);
2068  dest->code = src->code;
2069 }
2070 
2072 {
2073  init->str = NULL;
2074  init->code = guide->code;
2075 }
2076 
2078 {
2079  if (dest == src) {
2080  return;
2081  }
2082 
2083  if (src->str && src->str != dest->str) {
2084  ast_free(dest->str);
2085  dest->str = ast_strdup(src->str);
2086  }
2087 
2088  dest->code = src->code;
2089 }
2090 
2092 {
2093  ast_free(doomed->str);
2094 }
2095 
2096 
2098 {
2099  ast_party_id_init(&init->orig);
2100  ast_party_id_init(&init->from);
2101  ast_party_id_init(&init->to);
2102  ast_party_id_init(&init->priv_orig);
2103  ast_party_id_init(&init->priv_from);
2104  ast_party_id_init(&init->priv_to);
2107  init->count = 0;
2108 }
2109 
2111 {
2112  if (dest == src) {
2113  /* Don't copy to self */
2114  return;
2115  }
2116 
2117  ast_party_id_copy(&dest->orig, &src->orig);
2118  ast_party_id_copy(&dest->from, &src->from);
2119  ast_party_id_copy(&dest->to, &src->to);
2120  ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2121  ast_party_id_copy(&dest->priv_from, &src->priv_from);
2122  ast_party_id_copy(&dest->priv_to, &src->priv_to);
2125  dest->count = src->count;
2126 }
2127 
2129 {
2130  ast_party_id_set_init(&init->orig, &guide->orig);
2131  ast_party_id_set_init(&init->from, &guide->from);
2132  ast_party_id_set_init(&init->to, &guide->to);
2133  ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2134  ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2135  ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2138  init->count = guide->count;
2139 }
2140 
2142 {
2143  ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2144  ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2145  ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2146  ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2147  ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2148  ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2151  dest->count = src->count;
2152 }
2153 
2155 {
2156  ast_party_id_free(&doomed->orig);
2157  ast_party_id_free(&doomed->from);
2158  ast_party_id_free(&doomed->to);
2159  ast_party_id_free(&doomed->priv_orig);
2160  ast_party_id_free(&doomed->priv_from);
2161  ast_party_id_free(&doomed->priv_to);
2164 }
2165 
2166 /*! \brief Free a channel structure */
2167 static void ast_channel_destructor(void *obj)
2168 {
2169  struct ast_channel *chan = obj;
2170  struct ast_var_t *vardata;
2171  struct ast_frame *f;
2172  struct varshead *headp;
2173  struct ast_datastore *datastore;
2174  char device_name[AST_CHANNEL_NAME];
2175  ast_callid callid;
2176 
2177  ast_debug(1, "Channel %p '%s' destroying\n", chan, ast_channel_name(chan));
2178 
2179  /* Stop monitoring */
2180  if (ast_channel_monitor(chan)) {
2181  ast_channel_monitor(chan)->stop(chan, 0);
2182  }
2183 
2184  /* If there is native format music-on-hold state, free it */
2185  if (ast_channel_music_state(chan)) {
2186  ast_moh_cleanup(chan);
2187  }
2188 
2190 
2191  /* Things that may possibly raise Stasis messages shouldn't occur after this point */
2193 
2195  /* A channel snapshot should not be in the process of being staged now. */
2197 
2198  ast_channel_lock(chan);
2200  ast_channel_unlock(chan);
2201  }
2202 
2203  ast_channel_lock(chan);
2204 
2205  /* Get rid of each of the data stores on the channel */
2206  while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2207  /* Free the data store */
2208  ast_datastore_free(datastore);
2209 
2210  /* While the channel is locked, take the reference to its callid while we tear down the call. */
2211  callid = ast_channel_callid(chan);
2213 
2214  ast_channel_unlock(chan);
2215 
2216  /* Lock and unlock the channel just to be sure nobody has it locked still
2217  due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2218  ast_channel_lock(chan);
2219  ast_channel_unlock(chan);
2220 
2221  if (ast_channel_tech_pvt(chan)) {
2222  ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2224  }
2225 
2226  if (ast_channel_sched(chan)) {
2228  }
2229 
2231  char *dashptr;
2232 
2233  ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2234  if ((dashptr = strrchr(device_name, '-'))) {
2235  *dashptr = '\0';
2236  }
2237  } else {
2238  device_name[0] = '\0';
2239  }
2240 
2241  /* Free translators */
2242  if (ast_channel_readtrans(chan))
2244  if (ast_channel_writetrans(chan))
2246  if (ast_channel_pbx(chan))
2247  ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2248 
2249  /* Free formats */
2255 
2261 
2262  /* Close pipes if appropriate */
2264  if (ast_channel_timer(chan)) {
2266  ast_channel_timer_set(chan, NULL);
2267  }
2268  while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2269  ast_frfree(f);
2270 
2271  /* loop over the variables list, freeing all data and deleting list items */
2272  /* no need to lock the list, as the channel is already locked */
2273  headp = ast_channel_varshead(chan);
2274  while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2275  ast_var_delete(vardata);
2276 
2277  ast_app_group_discard(chan);
2278 
2279  /* Destroy the jitterbuffer */
2280  ast_jb_destroy(chan);
2281 
2282  if (ast_channel_cdr(chan)) {
2284  ast_channel_cdr_set(chan, NULL);
2285  }
2286 
2287  if (ast_channel_zone(chan)) {
2289  }
2290 
2292 
2293  if (device_name[0]) {
2294  /*
2295  * We have a device name to notify of a new state.
2296  *
2297  * Queue an unknown state, because, while we know that this particular
2298  * instance is dead, we don't know the state of all other possible
2299  * instances.
2300  */
2302  }
2303 
2305 
2308 
2310 }
2311 
2312 /*! \brief Free a dummy channel structure */
2313 static void ast_dummy_channel_destructor(void *obj)
2314 {
2315  struct ast_channel *chan = obj;
2316  struct ast_datastore *datastore;
2317  struct ast_var_t *vardata;
2318  struct varshead *headp;
2319 
2321 
2322  /* Get rid of each of the data stores on the channel */
2323  while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2324  /* Free the data store */
2325  ast_datastore_free(datastore);
2326  }
2327 
2333 
2334  /* loop over the variables list, freeing all data and deleting list items */
2335  /* no need to lock the list, as the channel is already locked */
2336  headp = ast_channel_varshead(chan);
2337  while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2338  ast_var_delete(vardata);
2339 
2340  if (ast_channel_cdr(chan)) {
2342  ast_channel_cdr_set(chan, NULL);
2343  }
2344 
2346 }
2347 
2349 {
2350  struct ast_datastore *datastore = NULL, *datastore2;
2351 
2352  AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2353  if (datastore->inheritance > 0) {
2354  datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2355  if (datastore2) {
2356  datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2357  datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2359  }
2360  }
2361  }
2362  return 0;
2363 }
2364 
2365 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2366 {
2367  int res = 0;
2368 
2370 
2371  return res;
2372 }
2373 
2374 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2375 {
2376  return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2377 }
2378 
2379 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2380 {
2381  struct ast_datastore *datastore = NULL;
2382 
2383  if (info == NULL)
2384  return NULL;
2385 
2386  AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2387  if (datastore->info != info) {
2388  continue;
2389  }
2390 
2391  if (uid == NULL) {
2392  /* matched by type only */
2393  break;
2394  }
2395 
2396  if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2397  /* Matched by type AND uid */
2398  break;
2399  }
2400  }
2401 
2402  return datastore;
2403 }
2404 
2405 /*! Set the file descriptor on the channel */
2406 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2407 {
2408  ast_channel_internal_fd_set(chan, which, fd);
2409  return;
2410 }
2411 
2413 {
2414  ast_channel_lock(chan);
2415 
2417 
2419  struct ast_frame *fr;
2420 
2421  /* If we have completely cleared the softhangup flag,
2422  * then we need to fully abort the hangup process. This requires
2423  * pulling the END_OF_Q frame out of the channel frame queue if it
2424  * still happens to be there. */
2425 
2426  fr = AST_LIST_LAST(ast_channel_readq(chan));
2427  if (fr && fr->frametype == AST_FRAME_CONTROL &&
2430  ast_frfree(fr);
2431  }
2432  }
2433 
2434  ast_channel_unlock(chan);
2435 }
2436 
2437 /*! \brief Softly hangup a channel, don't lock */
2438 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2439 {
2440  ast_debug(1, "Soft-Hanging (%#04x) up channel '%s'\n", (unsigned)cause, ast_channel_name(chan));
2441  /* Inform channel driver that we need to be hung up, if it cares */
2444  /* Interrupt any poll call or such */
2446  pthread_kill(ast_channel_blocker(chan), SIGURG);
2447  return 0;
2448 }
2449 
2450 /*! \brief Softly hangup a channel, lock */
2451 int ast_softhangup(struct ast_channel *chan, int cause)
2452 {
2453  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
2454  int res;
2455 
2456  ast_channel_lock(chan);
2457  res = ast_softhangup_nolock(chan, cause);
2458  blob = ast_json_pack("{s: i, s: b}",
2459  "cause", cause,
2460  "soft", 1);
2462  ast_channel_unlock(chan);
2463 
2464  return res;
2465 }
2466 
2467 static void free_translation(struct ast_channel *clonechan)
2468 {
2469  if (ast_channel_writetrans(clonechan)) {
2471  }
2472  if (ast_channel_readtrans(clonechan)) {
2474  }
2475  ast_channel_writetrans_set(clonechan, NULL);
2476  ast_channel_readtrans_set(clonechan, NULL);
2477 }
2478 
2479 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2480 {
2482 
2483  ast_channel_lock(chan);
2484  if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2485  ast_channel_hangupsource_set(chan, source);
2486  }
2487  ast_channel_unlock(chan);
2488 
2489  if (bridge) {
2490  ast_channel_lock(bridge);
2491  if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2492  ast_channel_hangupsource_set(bridge, source);
2493  }
2494  ast_channel_unlock(bridge);
2495  }
2496 }
2497 
2499 {
2500  return ast_channel_monitor(chan)
2503 }
2504 
2506 {
2507  return ast_channel_monitor(chan)
2510 }
2511 
2512 static void destroy_hooks(struct ast_channel *chan)
2513 {
2514  if (ast_channel_audiohooks(chan)) {
2517  }
2518 
2520 }
2521 
2522 /*! \brief Hangup a channel */
2523 void ast_hangup(struct ast_channel *chan)
2524 {
2525  /* Be NULL safe for RAII_VAR() usage. */
2526  if (!chan) {
2527  return;
2528  }
2529 
2530  ast_debug(1, "Channel %p '%s' hanging up. Refs: %d\n", chan, ast_channel_name(chan),
2531  ao2_ref(chan, 0));
2532 
2533  ast_autoservice_stop(chan);
2534 
2535  ast_channel_lock(chan);
2536 
2537  while (ast_channel_masq(chan) || ast_channel_masqr(chan)) {
2539  }
2540 
2541  /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2543 
2544  ast_channel_unlock(chan);
2545 
2546  /*
2547  * XXX if running the hangup handlers here causes problems
2548  * because the handlers take too long to execute, we could move
2549  * the meat of this function into another thread. A thread
2550  * where channels go to die.
2551  *
2552  * If this is done, ast_autoservice_chan_hangup_peer() will no
2553  * longer be needed.
2554  */
2556  ao2_unlink(channels, chan);
2557  ast_channel_lock(chan);
2558 
2559  destroy_hooks(chan);
2560 
2561  free_translation(chan);
2562  /* Close audio stream */
2563  if (ast_channel_stream(chan)) {
2566  }
2567  /* Close video stream */
2568  if (ast_channel_vstream(chan)) {
2571  }
2572  if (ast_channel_sched(chan)) {
2574  ast_channel_sched_set(chan, NULL);
2575  }
2576 
2577  if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2578  if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2580  }
2581  }
2584 
2586  ast_log(LOG_WARNING, "Hard hangup called by thread LWP %d on %s, while blocked by thread LWP %d in procedure %s! Expect a failure\n",
2588  ast_channel_blockproc(chan));
2589  ast_assert(0);
2590  }
2591 
2592  if (ast_channel_tech(chan)->hangup) {
2593  ast_channel_tech(chan)->hangup(chan);
2594  }
2595 
2596  ast_channel_unlock(chan);
2597 
2598  ast_cc_offer(chan);
2599 
2600  ast_channel_unref(chan);
2601 }
2602 
2603 /*!
2604  * \internal
2605  * \brief Set channel answered time if not already set.
2606  * \since 13.11.0
2607  *
2608  * \param chan Channel to set answered time.
2609  *
2610  * \return Nothing
2611  */
2612 static void set_channel_answer_time(struct ast_channel *chan)
2613 {
2614  if (ast_tvzero(ast_channel_answertime(chan))) {
2615  struct timeval answertime;
2616 
2617  answertime = ast_tvnow();
2618  ast_channel_answertime_set(chan, &answertime);
2619  }
2620 }
2621 
2622 int ast_raw_answer(struct ast_channel *chan)
2623 {
2624  int res = 0;
2625  SCOPE_TRACE(1, "%s\n", ast_channel_name(chan));
2626 
2627  ast_channel_lock(chan);
2628 
2629  /* You can't answer an outbound call */
2631  ast_channel_unlock(chan);
2632  return 0;
2633  }
2634 
2635  /* Stop if we're a zombie or need a soft hangup */
2637  ast_channel_unlock(chan);
2638  return -1;
2639  }
2640 
2641  /*
2642  * Mark when incoming channel answered so we can know how
2643  * long the channel has been up.
2644  */
2646 
2647  ast_channel_unlock(chan);
2648 
2649  switch (ast_channel_state(chan)) {
2650  case AST_STATE_RINGING:
2651  case AST_STATE_RING:
2652  ast_channel_lock(chan);
2653  if (ast_channel_tech(chan)->answer) {
2654  res = ast_channel_tech(chan)->answer(chan);
2655  }
2656  ast_setstate(chan, AST_STATE_UP);
2657  ast_channel_unlock(chan);
2658  break;
2659  case AST_STATE_UP:
2660  break;
2661  default:
2662  break;
2663  }
2664 
2665  ast_indicate(chan, -1);
2666 
2667  return res;
2668 }
2669 
2670 int __ast_answer(struct ast_channel *chan, unsigned int delay)
2671 {
2672  int res = 0;
2673  enum ast_channel_state old_state;
2674  SCOPE_TRACE(1, "%s\n", ast_channel_name(chan));
2675 
2676  old_state = ast_channel_state(chan);
2677  if ((res = ast_raw_answer(chan))) {
2678  return res;
2679  }
2680 
2681  switch (old_state) {
2682  case AST_STATE_RINGING:
2683  case AST_STATE_RING:
2684  /* wait for media to start flowing, but don't wait any longer
2685  * than 'delay' or 500 milliseconds, whichever is longer
2686  */
2687  do {
2689  struct ast_frame *cur;
2690  struct ast_frame *new_frame;
2691  int timeout_ms = MAX(delay, 500);
2692  unsigned int done = 0;
2693  struct timeval start;
2694 
2696 
2697  start = ast_tvnow();
2698  for (;;) {
2699  int ms = ast_remaining_ms(start, timeout_ms);
2700  ms = ast_waitfor(chan, ms);
2701  if (ms < 0) {
2702  ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2703  res = -1;
2704  break;
2705  }
2706  if (ms == 0) {
2707  ast_debug(2, "Didn't receive a media frame from %s within %u ms of answering. Continuing anyway\n", ast_channel_name(chan), MAX(delay, 500));
2708  break;
2709  }
2710  cur = ast_read(chan);
2711  if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2712  (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2713  if (cur) {
2714  ast_frfree(cur);
2715  }
2716  res = -1;
2717  ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2718  break;
2719  }
2720 
2721  if ((new_frame = ast_frisolate(cur)) != cur) {
2722  ast_frfree(cur);
2723  }
2724 
2725  AST_LIST_INSERT_HEAD(&frames, new_frame, frame_list);
2726 
2727  /* if a specific delay period was requested, continue
2728  * until that delay has passed. don't stop just because
2729  * incoming media has arrived.
2730  */
2731  if (delay) {
2732  continue;
2733  }
2734 
2735  switch (new_frame->frametype) {
2736  /* all of these frametypes qualify as 'media' */
2737  case AST_FRAME_VOICE:
2738  case AST_FRAME_VIDEO:
2739  case AST_FRAME_TEXT:
2740  case AST_FRAME_TEXT_DATA:
2741  case AST_FRAME_DTMF_BEGIN:
2742  case AST_FRAME_DTMF_END:
2743  case AST_FRAME_IMAGE:
2744  case AST_FRAME_HTML:
2745  case AST_FRAME_MODEM:
2746  case AST_FRAME_RTCP:
2747  done = 1;
2748  break;
2749  case AST_FRAME_CONTROL:
2750  case AST_FRAME_IAX:
2753  case AST_FRAME_NULL:
2754  case AST_FRAME_CNG:
2755  break;
2756  }
2757 
2758  if (done) {
2759  break;
2760  }
2761  }
2762 
2763  ast_channel_lock(chan);
2764  while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2765  if (res == 0) {
2766  ast_queue_frame_head(chan, cur);
2767  }
2768  ast_frfree(cur);
2769  }
2770  ast_channel_unlock(chan);
2771  } while (0);
2772  break;
2773  default:
2774  break;
2775  }
2776 
2777  return res;
2778 }
2779 
2780 int ast_answer(struct ast_channel *chan)
2781 {
2782  SCOPE_TRACE(1, "%s\n", ast_channel_name(chan));
2783  return __ast_answer(chan, 0);
2784 }
2785 
2786 inline int ast_auto_answer(struct ast_channel *chan)
2787 {
2788  if (ast_channel_state(chan) == AST_STATE_UP) {
2789  /* Already answered */
2790  return 0;
2791  }
2792  return ast_answer(chan);
2793 }
2794 
2796 {
2797  ast_assert(NULL != chan);
2798 
2799  if (ast_tvzero(ast_channel_creationtime(chan))) {
2800  return 0;
2801  }
2803 }
2804 
2806 {
2807  return (ast_channel_get_duration_ms(chan) / 1000);
2808 }
2809 
2811 {
2812  ast_assert(NULL != chan);
2813 
2814  if (ast_tvzero(ast_channel_answertime(chan))) {
2815  return 0;
2816  }
2818 }
2819 
2821 {
2822  return (ast_channel_get_up_time_ms(chan) / 1000);
2823 }
2824 
2825 /*!
2826  * \brief Determine whether or not we have to trigger dtmf emulating using 50 fps timer events
2827  * especially when no voice frames are received during dtmf processing (direct media or muted
2828  * sender case using SIP INFO)
2829  */
2830 static inline int should_trigger_dtmf_emulating(struct ast_channel *chan)
2831 {
2833  /* We're in the middle of emulating a digit, or DTMF has been
2834  * explicitly deferred. Trigger dtmf with periodic 50 pfs timer events, then. */
2835  return 1;
2836  }
2837 
2838  if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
2840  /*
2841  * We're not in the middle of a digit, but it hasn't been long enough
2842  * since the last digit, so we'll have to trigger DTMF furtheron.
2843  * Using 2 times AST_MIN_DTMF_GAP to trigger readq reading for possible
2844  * buffered next dtmf event
2845  */
2846  return 1;
2847  }
2848 
2849  return 0;
2850 }
2851 
2852 static void deactivate_generator_nolock(struct ast_channel *chan)
2853 {
2854  if (ast_channel_generatordata(chan)) {
2856 
2857  if (generator && generator->release) {
2858  generator->release(chan, ast_channel_generatordata(chan));
2859  }
2864  ast_settimeout(chan, 0, NULL, NULL);
2865  }
2866 }
2867 
2869 {
2870  ast_channel_lock(chan);
2872  if (should_trigger_dtmf_emulating(chan)) {
2873  /* if in the middle of dtmf emulation keep 50 tick per sec timer on rolling */
2875  }
2876  ast_channel_unlock(chan);
2877 }
2878 
2880 {
2881  struct ast_generator *generator;
2882 
2883  ast_channel_lock(chan);
2884  generator = ast_channel_generator(chan);
2885  if (generator && generator->write_format_change) {
2886  generator->write_format_change(chan, ast_channel_generatordata(chan));
2887  }
2888  ast_channel_unlock(chan);
2889 }
2890 
2891 static int generator_force(const void *data)
2892 {
2893  /* Called if generator doesn't have data */
2894  void *tmp;
2895  int res;
2896  int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2897  struct ast_channel *chan = (struct ast_channel *)data;
2898 
2899  ast_channel_lock(chan);
2900  tmp = ast_channel_generatordata(chan);
2902  if (ast_channel_generator(chan))
2903  generate = ast_channel_generator(chan)->generate;
2904  ast_channel_unlock(chan);
2905 
2906  if (!tmp || !generate) {
2907  return 0;
2908  }
2909 
2910  res = generate(chan, tmp, 0, ast_format_get_sample_rate(ast_channel_writeformat(chan)) / 50);
2911 
2912  ast_channel_lock(chan);
2913  if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
2914  ast_channel_generatordata_set(chan, tmp);
2915  }
2916  ast_channel_unlock(chan);
2917 
2918  if (res) {
2919  ast_debug(1, "Auto-deactivating generator\n");
2921  }
2922 
2923  return 0;
2924 }
2925 
2926 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2927 {
2928  int res = 0;
2929  void *generatordata = NULL;
2930 
2931  ast_channel_lock(chan);
2932  if (ast_channel_generatordata(chan)) {
2933  struct ast_generator *generator_old = ast_channel_generator(chan);
2934 
2935  if (generator_old && generator_old->release) {
2936  generator_old->release(chan, ast_channel_generatordata(chan));
2937  }
2938  }
2939  if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
2940  res = -1;
2941  }
2942  ast_channel_generatordata_set(chan, generatordata);
2943  if (!res) {
2944  ast_settimeout(chan, 50, generator_force, chan);
2945  ast_channel_generator_set(chan, gen);
2946  }
2947  ast_channel_unlock(chan);
2948 
2949  ast_prod(chan);
2950 
2951  return res;
2952 }
2953 
2954 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2955 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2956 {
2957  int winner = -1;
2958  ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2959  return winner;
2960 }
2961 
2962 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2963 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2964  int *exception, int *outfd, int *ms)
2965 {
2966  struct timeval start = { 0 , 0 };
2967  struct pollfd *pfds = NULL;
2968  int res;
2969  long rms;
2970  int x, y, max;
2971  int sz = nfds;
2972  struct timeval now = { 0, 0 };
2973  struct timeval whentohangup = { 0, 0 }, diff;
2974  struct ast_channel *winner = NULL;
2975  struct fdmap {
2976  int chan;
2977  int fdno;
2978  } *fdmap = NULL;
2979 
2980  if (outfd) {
2981  *outfd = -99999;
2982  }
2983  if (exception) {
2984  *exception = 0;
2985  }
2986 
2987  for (x = 0; x < n; x++) {
2988  ast_channel_lock(c[x]);
2989  if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
2990  if (ast_tvzero(whentohangup))
2991  now = ast_tvnow();
2992  diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
2993  if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2994  ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
2995  /* Should already be hungup */
2997  ast_channel_unlock(c[x]);
2998  return c[x];
2999  }
3000  if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3001  whentohangup = diff;
3002  }
3003  sz += ast_channel_fd_count(c[x]);
3004  ast_channel_unlock(c[x]);
3005  }
3006 
3007  if (!sz) {
3008  return NULL;
3009  }
3010 
3011  pfds = ast_alloca(sizeof(*pfds) * sz);
3012  fdmap = ast_alloca(sizeof(*fdmap) * sz);
3013 
3014  /* Wait full interval */
3015  rms = *ms;
3016  /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3017  if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3018  rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3019  if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3020  rms = *ms;
3021  }
3022  } else if (!ast_tvzero(whentohangup) && rms < 0) {
3023  /* Tiny corner case... call would need to last >24 days */
3024  rms = INT_MAX;
3025  }
3026  /*
3027  * Build the pollfd array, putting the channels' fds first,
3028  * followed by individual fds. Order is important because
3029  * individual fd's must have priority over channel fds.
3030  */
3031  max = 0;
3032  for (x = 0; x < n; x++) {
3033  ast_channel_lock(c[x]);
3034  for (y = 0; y < ast_channel_fd_count(c[x]); y++) {
3035  fdmap[max].fdno = y; /* fd y is linked to this pfds */
3036  fdmap[max].chan = x; /* channel x is linked to this pfds */
3037  max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3038  }
3039  CHECK_BLOCKING(c[x]);
3040  ast_channel_unlock(c[x]);
3041  }
3042  /* Add the individual fds */
3043  for (x = 0; x < nfds; x++) {
3044  fdmap[max].chan = -1;
3045  max += ast_add_fd(&pfds[max], fds[x]);
3046  }
3047 
3048  if (*ms > 0) {
3049  start = ast_tvnow();
3050  }
3051 
3052  if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3053  do {
3054  int kbrms = rms;
3055  if (kbrms > 600000) {
3056  kbrms = 600000;
3057  }
3058  res = ast_poll(pfds, max, kbrms);
3059  if (!res) {
3060  rms -= kbrms;
3061  }
3062  } while (!res && (rms > 0));
3063  } else {
3064  res = ast_poll(pfds, max, rms);
3065  }
3066  for (x = 0; x < n; x++) {
3067  ast_channel_lock(c[x]);
3069  ast_channel_unlock(c[x]);
3070  }
3071  if (res < 0) { /* Simulate a timeout if we were interrupted */
3072  if (errno != EINTR) {
3073  *ms = -1;
3074  }
3075  return NULL;
3076  }
3077  if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3078  now = ast_tvnow();
3079  for (x = 0; x < n; x++) {
3080  if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3081  ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3083  if (winner == NULL) {
3084  winner = c[x];
3085  }
3086  }
3087  }
3088  }
3089  if (res == 0) { /* no fd ready, reset timeout and done */
3090  *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3091  return winner;
3092  }
3093  /*
3094  * Then check if any channel or fd has a pending event.
3095  * Remember to check channels first and fds last, as they
3096  * must have priority on setting 'winner'
3097  */
3098  for (x = 0; x < max; x++) {
3099  res = pfds[x].revents;
3100  if (res == 0) {
3101  continue;
3102  }
3103  if (fdmap[x].chan >= 0) { /* this is a channel */
3104  winner = c[fdmap[x].chan]; /* override previous winners */
3105  ast_channel_lock(winner);
3106  if (res & POLLPRI) {
3108  } else {
3110  }
3111  ast_channel_fdno_set(winner, fdmap[x].fdno);
3112  ast_channel_unlock(winner);
3113  } else { /* this is an fd */
3114  if (outfd) {
3115  *outfd = pfds[x].fd;
3116  }
3117  if (exception) {
3118  *exception = (res & POLLPRI) ? -1 : 0;
3119  }
3120  winner = NULL;
3121  }
3122  }
3123  if (*ms > 0) {
3124  *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3125  if (*ms < 0) {
3126  *ms = 0;
3127  }
3128  }
3129  return winner;
3130 }
3131 
3132 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3133 {
3134  return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3135 }
3136 
3137 int ast_waitfor(struct ast_channel *c, int ms)
3138 {
3139  if (ms < 0) {
3140  do {
3141  ms = 100000;
3142  ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3143  } while (!ms);
3144  } else {
3145  ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3146  }
3147  return ms;
3148 }
3149 
3150 int ast_waitfordigit(struct ast_channel *c, int ms)
3151 {
3152  return ast_waitfordigit_full(c, ms, NULL, -1, -1);
3153 }
3154 
3155 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3156 {
3157  return ast_settimeout_full(c, rate, func, data, 0);
3158 }
3159 
3160 int ast_settimeout_full(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data, unsigned int is_ao2_obj)
3161 {
3162  int res;
3163  unsigned int real_rate = rate, max_rate;
3164 
3165  ast_channel_lock(c);
3166 
3167  if (ast_channel_timingfd(c) == -1) {
3168  ast_channel_unlock(c);
3169  return -1;
3170  }
3171 
3172  if (!func) {
3173  rate = 0;
3174  data = NULL;
3175  }
3176 
3177  if (rate && rate > (max_rate = ast_timer_get_max_rate(ast_channel_timer(c)))) {
3178  real_rate = max_rate;
3179  }
3180 
3181  ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3182 
3183  res = ast_timer_set_rate(ast_channel_timer(c), real_rate);
3184 
3187  }
3188 
3189  ast_channel_timingfunc_set(c, func);
3190  ast_channel_timingdata_set(c, data);
3191 
3192  if (data && is_ao2_obj) {
3193  ao2_ref(data, 1);
3195  } else {
3197  }
3198 
3199  if (func == NULL && rate == 0 && ast_channel_fdno(c) == AST_TIMING_FD) {
3200  /* Clearing the timing func and setting the rate to 0
3201  * means that we don't want to be reading from the timingfd
3202  * any more. Setting c->fdno to -1 means we won't have any
3203  * errant reads from the timingfd, meaning we won't potentially
3204  * miss any important frames.
3205  */
3206  ast_channel_fdno_set(c, -1);
3207  }
3208 
3209  ast_channel_unlock(c);
3210 
3211  return res;
3212 }
3213 
3214 int ast_waitfordigit_full(struct ast_channel *c, int timeout_ms, const char *breakon, int audiofd, int cmdfd)
3215 {
3216  struct timeval start = ast_tvnow();
3217  int ms;
3218 
3219  /* Stop if we're a zombie or need a soft hangup */
3221  return -1;
3222 
3223  /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3225 
3226  /* Wait for a digit, no more than timeout_ms milliseconds total.
3227  * Or, wait indefinitely if timeout_ms is <0.
3228  */
3229  while ((ms = ast_remaining_ms(start, timeout_ms))) {
3230  struct ast_channel *rchan;
3231  int outfd = -1;
3232 
3233  errno = 0;
3234  /* While ast_waitfor_nandfds tries to help by reducing the timeout by how much was waited,
3235  * it is unhelpful if it waited less than a millisecond.
3236  */
3237  rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3238 
3239  if (!rchan && outfd < 0 && ms) {
3240  if (errno == 0 || errno == EINTR)
3241  continue;
3242  ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3244  return -1;
3245  } else if (outfd > -1) {
3246  /* The FD we were watching has something waiting */
3247  ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3249  return 1;
3250  } else if (rchan) {
3251  int res;
3252  struct ast_frame *f = ast_read(c);
3253 
3254  if (!f) {
3256 
3257  return -1;
3258  }
3259 
3260  switch (f->frametype) {
3261  case AST_FRAME_DTMF_BEGIN:
3262  break;
3263  case AST_FRAME_DTMF_END:
3264  res = f->subclass.integer;
3265  if (!breakon || strchr(breakon, res)) {
3266  ast_frfree(f);
3268  return res;
3269  }
3270  break;
3271  case AST_FRAME_CONTROL:
3272  switch (f->subclass.integer) {
3273  case AST_CONTROL_HANGUP:
3274  ast_frfree(f);
3276  return -1;
3282  /* Fall-through and treat as if it were a DTMF signal. Items
3283  * that perform stream control will handle this. */
3284  res = f->subclass.integer;
3285  ast_frfree(f);
3287  return res;
3289  case AST_CONTROL_RINGING:
3290  case AST_CONTROL_ANSWER:
3291  case AST_CONTROL_SRCUPDATE:
3292  case AST_CONTROL_SRCCHANGE:
3296  case AST_CONTROL_HOLD:
3297  case AST_CONTROL_UNHOLD:
3298  case -1:
3299  /* Unimportant */
3300  break;
3301  default:
3302  ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3303  break;
3304  }
3305  break;
3306  case AST_FRAME_VOICE:
3307  /* Write audio if appropriate */
3308  if (audiofd > -1) {
3309  if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3310  ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3311  }
3312  }
3313  default:
3314  /* Ignore */
3315  break;
3316  }
3317  ast_frfree(f);
3318  }
3319  }
3320 
3322 
3323  return 0; /* Time is up */
3324 }
3325 
3329 };
3330 
3331 static const char *dtmf_direction_to_string(enum DtmfDirection direction)
3332 {
3333  switch (direction) {
3334  case DTMF_RECEIVED:
3335  return "Received";
3336  case DTMF_SENT:
3337  return "Sent";
3338  }
3339 
3340  return "?";
3341 }
3342 
3343 static void send_dtmf_begin_event(struct ast_channel *chan,
3344  enum DtmfDirection direction, const char digit)
3345 {
3346  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
3347  char digit_str[] = { digit, '\0' };
3348 
3349  blob = ast_json_pack("{ s: s, s: s }",
3350  "digit", digit_str,
3351  "direction", dtmf_direction_to_string(direction));
3352  if (!blob) {
3353  return;
3354  }
3355 
3357 }
3358 
3359 static void send_dtmf_end_event(struct ast_channel *chan,
3360  enum DtmfDirection direction, const char digit, long duration_ms)
3361 {
3362  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
3363  char digit_str[] = { digit, '\0' };
3364 
3365  blob = ast_json_pack("{ s: s, s: s, s: I }",
3366  "digit", digit_str,
3367  "direction", dtmf_direction_to_string(direction),
3368  "duration_ms", (ast_json_int_t)duration_ms);
3369  if (!blob) {
3370  return;
3371  }
3372 
3374 }
3375 
3376 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3377 {
3378  struct ast_generator *generator;
3379  void *gendata;
3380  int res;
3381  int samples;
3382 
3383  generator = ast_channel_generator(chan);
3384  if (!generator
3385  || !generator->generate
3386  || f->frametype != AST_FRAME_VOICE
3387  || !ast_channel_generatordata(chan)
3388  || ast_channel_timingfunc(chan)) {
3389  return;
3390  }
3391 
3392  /*
3393  * We must generate frames in phase locked mode since
3394  * we have no internal timer available.
3395  */
3397  float factor;
3399  samples = (int) (((float) f->samples) * factor);
3400  } else {
3401  samples = f->samples;
3402  }
3403 
3404  gendata = ast_channel_generatordata(chan);
3405  ast_channel_generatordata_set(chan, NULL); /* reset, to let writes go through */
3406 
3407  /*
3408  * This unlock is here based on two assumptions that hold true at
3409  * this point in the code. 1) this function is only called from
3410  * within __ast_read() and 2) all generators call ast_write() in
3411  * their generate callback.
3412  *
3413  * The reason this is added is so that when ast_write is called,
3414  * the lock that occurs there will not recursively lock the
3415  * channel. Doing this will allow deadlock avoidance to work in
3416  * deeper functions.
3417  */
3418  ast_channel_unlock(chan);
3419  res = generator->generate(chan, gendata, f->datalen, samples);
3420  ast_channel_lock(chan);
3421  if (generator == ast_channel_generator(chan)) {
3422  ast_channel_generatordata_set(chan, gendata);
3423  if (res) {
3424  ast_debug(1, "Auto-deactivating generator\n");
3426  }
3427  }
3428 }
3429 
3430 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3431 {
3432  struct ast_frame *fr = ast_channel_dtmff(chan);
3433 
3435  fr->subclass.integer = f->subclass.integer;
3436  fr->len = f->len;
3437 
3438  /* The only time this function will be called is for a frame that just came
3439  * out of the channel driver. So, we want to stick it on the tail of the
3440  * readq. */
3441 
3442  ast_queue_frame(chan, fr);
3443 }
3444 
3445 /*!
3446  * \brief Determine whether or not we should ignore DTMF in the readq
3447  */
3448 static inline int should_skip_dtmf(struct ast_channel *chan)
3449 {
3451  /* We're in the middle of emulating a digit, or DTMF has been
3452  * explicitly deferred. Skip this digit, then. */
3453  return 1;
3454  }
3455 
3456  if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
3458  /* We're not in the middle of a digit, but it hasn't been long enough
3459  * since the last digit, so we'll have to skip DTMF for now. */
3460  return 1;
3461  }
3462 
3463  return 0;
3464 }
3465 
3466 /*!
3467  * \brief calculates the number of samples to jump forward with in a monitor stream.
3468 
3469  * \note When using ast_seekstream() with the read and write streams of a monitor,
3470  * the number of samples to seek forward must be of the same sample rate as the stream
3471  * or else the jump will not be calculated correctly.
3472  *
3473  * \retval number of samples to seek forward after rate conversion.
3474  */
3475 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3476 {
3477  int diff = sample_rate - seek_rate;
3478 
3479  if (diff > 0) {
3480  samples = samples / (float) (sample_rate / seek_rate);
3481  } else if (diff < 0) {
3482  samples = samples * (float) (seek_rate / sample_rate);
3483  }
3484 
3485  return samples;
3486 }
3487 
3488 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio, int dropnondefault)
3489 {
3490  struct ast_frame *f = NULL; /* the return value */
3491  int prestate;
3492  int cause = 0;
3493  struct ast_stream *stream = NULL, *default_stream = NULL;
3494 
3495  /* this function is very long so make sure there is only one return
3496  * point at the end (there are only two exceptions to this).
3497  */
3498  ast_channel_lock(chan);
3499 
3500  /* Stop if we're a zombie or need a soft hangup */
3502  if (ast_channel_generator(chan))
3504 
3505  /*
3506  * It is possible for chan->_softhangup to be set and there
3507  * still be control frames that need to be read. Instead of
3508  * just going to 'done' in the case of ast_check_hangup(), we
3509  * need to queue the end-of-Q frame so that it can mark the end
3510  * of the read queue. If there are frames to be read,
3511  * ast_queue_control() will be called repeatedly, but will only
3512  * queue the first end-of-Q frame.
3513  */
3516  } else {
3517  goto done;
3518  }
3519  } else {
3520 #ifdef AST_DEVMODE
3521  /*
3522  * The ast_waitfor() code records which of the channel's file
3523  * descriptors reported that data is available. In theory,
3524  * ast_read() should only be called after ast_waitfor() reports
3525  * that a channel has data available for reading. However,
3526  * there still may be some edge cases throughout the code where
3527  * ast_read() is called improperly. This can potentially cause
3528  * problems, so if this is a developer build, make a lot of
3529  * noise if this happens so that it can be addressed.
3530  *
3531  * One of the potential problems is blocking on a dead channel.
3532  */
3533  if (ast_channel_fdno(chan) == -1) {
3535  "ast_read() on chan '%s' called with no recorded file descriptor.\n",
3536  ast_channel_name(chan));
3537  }
3538 #endif
3539  }
3540 
3541  prestate = ast_channel_state(chan);
3542 
3543  if (ast_channel_timingfd(chan) > -1 && ast_channel_fdno(chan) == AST_TIMING_FD) {
3544  enum ast_timer_event res;
3545  int trigger_dtmf_emulating = should_trigger_dtmf_emulating(chan);
3546 
3548 
3550 
3551  switch (res) {
3553  if (ast_timer_ack(ast_channel_timer(chan), 1) < 0) {
3554  ast_log(LOG_ERROR, "Failed to acknoweldge timer in ast_read\n");
3555  goto done;
3556  }
3557 
3558  if (ast_channel_timingfunc(chan)) {
3559  /* save a copy of func/data before unlocking the channel */
3561  void *data = ast_channel_timingdata(chan);
3562  int got_ref = 0;
3564  ao2_ref(data, 1);
3565  got_ref = 1;
3566  }
3567  ast_channel_fdno_set(chan, -1);
3568  ast_channel_unlock(chan);
3569  func(data);
3570  if (got_ref) {
3571  ao2_ref(data, -1);
3572  }
3573 
3574  if (trigger_dtmf_emulating) {
3575  /*
3576  * Since we're breaking out of this switch block and not
3577  * returning, we need to re-lock the channel.
3578  */
3579  ast_channel_lock(chan);
3580  /* generate null frame to trigger dtmf emulating */
3581  f = &ast_null_frame;
3582  break;
3583  }
3584  } else if (trigger_dtmf_emulating) {
3585  /* generate null frame to trigger dtmf emualating */
3586  f = &ast_null_frame;
3587  break;
3588  } else {
3590  /* generate very last null frame to trigger dtmf emulating */
3591  f = &ast_null_frame;
3592  break;
3593  }
3594 
3595  /* cannot 'goto done' because the channel is already unlocked */
3596  return &ast_null_frame;
3597 
3599  if (AST_LIST_EMPTY(ast_channel_readq(chan)) ||
3602  }
3603  break;
3604  }
3605 
3607  /* if the AST_GENERATOR_FD is set, call the generator with args
3608  * set to -1 so it can do whatever it needs to.
3609  */
3610  void *tmp = ast_channel_generatordata(chan);
3611  ast_channel_generatordata_set(chan, NULL); /* reset to let ast_write get through */
3612  ast_channel_generator(chan)->generate(chan, tmp, -1, -1);
3613  ast_channel_generatordata_set(chan, tmp);
3614  f = &ast_null_frame;
3615  ast_channel_fdno_set(chan, -1);
3616  goto done;
3619  }
3620 
3621  /* Read and ignore anything on the alertpipe, but read only
3622  one sizeof(blah) per frame that we send from it */
3624  f = &ast_null_frame;
3625  goto done;
3626  }
3627 
3628  /* Check for pending read queue */
3629  if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
3630  int skipped_dtmf_frame = 0;
3631  int skip_dtmf = should_skip_dtmf(chan);
3632 
3634  /* We have to be picky about which frame we pull off of the readq because
3635  * there are cases where we want to leave DTMF frames on the queue until
3636  * some later time. */
3637 
3638  if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3639  skipped_dtmf_frame = 1;
3640  continue;
3641  }
3642 
3644  break;
3645  }
3647 
3648  if (!f) {
3649  /* There were no acceptable frames on the readq. */
3650  f = &ast_null_frame;
3651  if (!skipped_dtmf_frame) {
3652  /*
3653  * Do not trigger alert pipe if only buffered dtmf begin or end frames
3654  * are left in the readq.
3655  */
3657  } else {
3658  /*
3659  * Safely disable continous timer events if only buffered dtmf begin or end
3660  * frames are left in the readq.
3661  */
3663  }
3664  }
3665 
3666  /* Interpret hangup and end-of-Q frames to return NULL */
3667  /* XXX why not the same for frames from the channel ? */
3668  if (f->frametype == AST_FRAME_CONTROL) {
3669  switch (f->subclass.integer) {
3670  case AST_CONTROL_HANGUP:
3672  cause = f->data.uint32;
3673  /* Fall through */
3674  case AST_CONTROL_END_OF_Q:
3675  ast_frfree(f);
3676  f = NULL;
3677  break;
3678  default:
3679  break;
3680  }
3681  } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
3682  if (ast_channel_tech(chan) && ast_channel_tech(chan)->read_stream) {
3685  } else {
3686  /* Since this channel driver does not support multistream determine the default stream this frame
3687  * originated from and update the frame to include it.
3688  */
3689  stream = default_stream = ast_channel_get_default_stream(chan, ast_format_get_type(f->subclass.format));
3690  /* In order to allow media to be passed up the underlying media type has to have a format negotiated on
3691  * the channel itself. In cases where this hasn't happened the channel driver is incorrectly passing up
3692  * a frame for a format that has not been negotiated. If this occurs just drop the frame as we have no
3693  * stream that it came from.
3694  */
3695  if (!stream) {
3696  ast_frfree(f);
3697  f = &ast_null_frame;
3698  } else {
3699  f->stream_num = ast_stream_get_position(stream);
3700  }
3701  }
3702  }
3703  } else {
3705  if (ast_channel_tech(chan)->exception)
3706  f = ast_channel_tech(chan)->exception(chan);
3707  else {
3708  ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", ast_channel_name(chan));
3709  f = &ast_null_frame;
3710  }
3711  /* Clear the exception flag */
3713  } else if (ast_channel_tech(chan) && ast_channel_tech(chan)->read_stream) {
3714  f = ast_channel_tech(chan)->read_stream(chan);
3715 
3716  /* This channel driver supports multistream so the stream_num on the frame is valid, the only
3717  * thing different is that we need to find the default stream so we know whether to invoke the
3718  * default stream logic or not (such as transcoding).
3719  */
3720  if (f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
3723  }
3724  } else if (ast_channel_tech(chan) && ast_channel_tech(chan)->read) {
3725  f = ast_channel_tech(chan)->read(chan);
3726 
3727  /* Since this channel driver does not support multistream determine the default stream this frame
3728  * originated from and update the frame to include it.
3729  */
3730  if (f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
3731  stream = default_stream = ast_channel_get_default_stream(chan, ast_format_get_type(f->subclass.format));
3732  if (!stream) {
3733  ast_frfree(f);
3734  f = &ast_null_frame;
3735  } else {
3736  f->stream_num = ast_stream_get_position(stream);
3737  }
3738  }
3739  }
3740  else
3741  ast_log(LOG_WARNING, "No read routine on channel %s\n", ast_channel_name(chan));
3742  }
3743 
3744  if (stream == default_stream) {
3745  /* Perform the framehook read event here. After the frame enters the framehook list
3746  * there is no telling what will happen, <insert mad scientist laugh here>!!! */
3748  }
3749 
3750  /*
3751  * Reset the recorded file descriptor that triggered this read so that we can
3752  * easily detect when ast_read() is called without properly using ast_waitfor().
3753  */
3754  ast_channel_fdno_set(chan, -1);
3755 
3756  if (f) {
3757  struct ast_frame *readq_tail = AST_LIST_LAST(ast_channel_readq(chan));
3758  struct ast_control_read_action_payload *read_action_payload;
3759  struct ast_party_connected_line connected;
3760  int hooked = 0;
3761 
3762  /* if the channel driver returned more than one frame, stuff the excess
3763  into the readq for the next ast_read call
3764  */
3765  if (AST_LIST_NEXT(f, frame_list)) {
3769  }
3770 
3771  if (dropnondefault && stream != default_stream) {
3772  /* If the frame originates from a non-default stream and the caller can not handle other streams
3773  * absorb the frame and replace it with a null one instead.
3774  */
3775  ast_frfree(f);
3776  f = &ast_null_frame;
3777  }
3778 
3779  switch (f->frametype) {
3780  case AST_FRAME_CONTROL:
3781  if (f->subclass.integer == AST_CONTROL_ANSWER) {
3782  if (prestate == AST_STATE_UP && ast_channel_is_bridged(chan)) {
3783  ast_debug(1, "Dropping duplicate answer!\n");
3784  ast_frfree(f);
3785  f = &ast_null_frame;
3786  } else {
3787  /*
3788  * Mark when outgoing channel answered so we can know how
3789  * long the channel has been up.
3790  */
3792 
3793  ast_setstate(chan, AST_STATE_UP);
3794  }
3795  } else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
3796  read_action_payload = f->data.ptr;
3797  switch (read_action_payload->action) {
3799  ast_party_connected_line_init(&connected);
3801  if (ast_connected_line_parse_data(read_action_payload->payload,
3802  read_action_payload->payload_size, &connected)) {
3803  ast_party_connected_line_free(&connected);
3804  break;
3805  }
3806  ast_channel_unlock(chan);
3807  if (ast_channel_connected_line_sub(NULL, chan, &connected, 0) &&
3808  ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
3810  read_action_payload->payload,
3811  read_action_payload->payload_size);
3812  }
3813  ast_party_connected_line_free(&connected);
3814  ast_channel_lock(chan);
3815  break;
3817  ast_channel_unlock(chan);
3818  ast_sendtext(chan, (const char *)read_action_payload->payload);
3819  ast_channel_lock(chan);
3820  break;
3822  ast_channel_unlock(chan);
3823  ast_sendtext_data(chan, (struct ast_msg_data *)read_action_payload->payload);
3824  ast_channel_lock(chan);
3825  break;
3826  }
3827  ast_frfree(f);
3828  f = &ast_null_frame;
3829  } else if (f->subclass.integer == AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE && dropnondefault) {
3830  /* The caller of this function is incapable of handling streams so we don't accept the change request
3831  * and stick to the streams currently on the channel.
3832  */
3834  ast_frfree(f);
3835  f = &ast_null_frame;
3836  } else if (f->subclass.integer == AST_CONTROL_STREAM_TOPOLOGY_CHANGED && dropnondefault) {
3837  /* The caller of this function is incapable of handling streams so we absorb the notification that the
3838  * stream topology has changed.
3839  */
3840  ast_frfree(f);
3841  f = &ast_null_frame;
3842  }
3843  break;
3844  case AST_FRAME_DTMF_END:
3846  ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, ast_channel_name(chan), f->len);
3847  /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3849  queue_dtmf_readq(chan, f);
3850  ast_frfree(f);
3851  f = &ast_null_frame;
3853  if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
3855  /* If it hasn't been long enough, defer this digit */
3856  queue_dtmf_readq(chan, f);
3857  ast_frfree(f);
3858  f = &ast_null_frame;
3859  } else {
3860  /* There was no begin, turn this into a begin and send the end later */
3861  struct timeval tv = ast_tvnow();
3865  ast_channel_dtmf_tv_set(chan, &tv);
3866  if (f->len) {
3867  if (f->len > option_dtmfminduration)
3869  else
3871  } else
3873  ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass.integer, ast_channel_emulate_dtmf_duration(chan), ast_channel_name(chan));
3874 
3875  /*
3876  * Start generating 50 fps timer events (null frames) for dtmf emulating
3877  * independently from any existing incoming voice frames.
3878  * If channel generator is already activated in regular mode use these
3879  * timer events to generate null frames.
3880  */
3881  if (!ast_channel_generator(chan)) {
3883  }
3884  }
3885  if (ast_channel_audiohooks(chan)) {
3886  struct ast_frame *old_frame = f;
3887  /*!
3888  * \todo XXX It is possible to write a digit to the audiohook twice
3889  * if the digit was originally read while the channel was in autoservice. */
3891  if (old_frame != f)
3892  ast_frfree(old_frame);
3893  }
3894  } else {
3895  struct timeval now = ast_tvnow();
3897  ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
3899  if (!f->len)
3900  f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
3901 
3902  /* detect tones that were received on
3903  * the wire with durations shorter than
3904  * option_dtmfminduration and set f->len
3905  * to the actual duration of the DTMF
3906  * frames on the wire. This will cause
3907  * dtmf emulation to be triggered later
3908  * on.
3909  */
3911  f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
3912  ast_log(LOG_DTMF, "DTMF end '%c' detected to have actual duration %ld on the wire, emulation will be triggered on %s\n", f->subclass.integer, f->len, ast_channel_name(chan));
3913  }
3914  } else if (!f->len) {
3915  ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
3917  }
3919  ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %u, emulating on %s\n", f->subclass.integer, f->len, option_dtmfminduration, ast_channel_name(chan));
3923  ast_frfree(f);
3924  f = &ast_null_frame;
3925 
3926  /* Start generating 50 fps timer events (null frames) for dtmf emulating
3927  * independently from any existing incoming voice frames.
3928  * If channel generator is already activated in regular mode use these
3929  * timer events to generate null frames.
3930  */
3931  if (!ast_channel_generator(chan)) {
3933  }
3934  } else {
3935  ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
3936  if (f->len < option_dtmfminduration) {
3938  }
3939  ast_channel_dtmf_tv_set(chan, &now);
3940 
3941  /* Start generating 50 fps timer events (null frames) for dtmf emulating
3942  * independently from any existing incoming voice frames.
3943  * If channel generator is already activated in regular mode use these
3944  * timer events to generate null frames.
3945  */
3946  if (!ast_channel_generator(chan)) {
3948  }
3949  }
3950  if (ast_channel_audiohooks(chan)) {
3951  struct ast_frame *old_frame = f;
3953  if (old_frame != f)
3954  ast_frfree(old_frame);
3955  }
3956  }
3957  break;
3958  case AST_FRAME_DTMF_BEGIN:
3960  ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, ast_channel_name(chan));
3962  (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
3964  ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
3965  ast_frfree(f);
3966  f = &ast_null_frame;
3967  } else {
3968  struct timeval now = ast_tvnow();
3970  ast_channel_dtmf_tv_set(chan, &now);
3971  ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
3972  }
3973  break;
3974  case AST_FRAME_NULL:
3975  /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3976  * is reached , because we want to make sure we pass at least one
3977  * voice frame through before starting the next digit, to ensure a gap
3978  * between DTMF digits. */
3980  struct timeval now = ast_tvnow();
3981  if (!ast_channel_emulate_dtmf_duration(chan)) {
3984  } else if (ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan)) >= ast_channel_emulate_dtmf_duration(chan)) {
3986  ast_frfree(f);
3987  f = ast_channel_dtmff(chan);
3990  f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
3991  ast_channel_dtmf_tv_set(chan, &now);
3994  ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, ast_channel_name(chan));
3995  if (ast_channel_audiohooks(chan)) {
3996  struct ast_frame *old_frame = f;
3998  if (old_frame != f) {
3999  ast_frfree(old_frame);
4000  }
4001  }
4002 
4003  /* Start generating 50 fps timer events (null frames) for dtmf emulating
4004  * independently from any existing incoming voice frames.
4005  * If channel generator is already activated in regular mode use these
4006  * timer events to generate null frames.
4007  */
4008  if (!ast_channel_generator(chan)) {
4010  }
4011  }
4012  }
4013  break;
4014  case AST_FRAME_VOICE:
4015  /* If media was received from a non-default stream don't perform any actions, let it just go through */
4016  if (stream != default_stream) {
4017  break;
4018  }
4019 
4020  /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
4021  * is reached , because we want to make sure we pass at least one
4022  * voice frame through before starting the next digit, to ensure a gap
4023  * between DTMF digits. */
4027  }
4028 
4029  if (dropaudio || ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF)) {
4030  if (dropaudio)
4031  ast_read_generator_actions(chan, f);
4032  ast_frfree(f);
4033  f = &ast_null_frame;
4034  }
4035 
4037  struct timeval now = ast_tvnow();
4040  ast_frfree(f);
4041  f = ast_channel_dtmff(chan);
4044  f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
4045  ast_channel_dtmf_tv_set(chan, &now);
4046  if (ast_channel_audiohooks(chan)) {
4047  struct ast_frame *old_frame = f;
4049  if (old_frame != f)
4050  ast_frfree(old_frame);
4051  }
4052  ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, ast_channel_name(chan));
4053  } else {
4054  /* Drop voice frames while we're still in the middle of the digit */
4055  ast_frfree(f);
4056  f = &ast_null_frame;
4057  }
4058  break;
4059  }
4060  if (f->frametype != AST_FRAME_VOICE) {
4061  break;
4062  }
4065  struct ast_format *core_format;
4066 
4067  /*
4068  * Note: This frame may not be one of the current native
4069  * formats. We may have gotten it out of the read queue from
4070  * a previous multi-frame translation, from a framehook
4071  * injected frame, or the device we're talking to isn't
4072  * respecting negotiated formats. Regardless we will accept
4073  * all frames.
4074  *
4075  * Update the read translation path to handle the new format
4076  * that just came in. If the core wants slinear we need to
4077  * setup a new translation path because the core is usually
4078  * doing something with the audio itself and may not handle
4079  * any other format. e.g., Softmix bridge, holding bridge
4080  * announcer channel, recording, AMD... Otherwise, we'll
4081  * setup to pass the frame as is to the core. In this case
4082  * the core doesn't care. The channel is likely in
4083  * autoservice, safesleep, or the channel is in a bridge.
4084  * Let the bridge technology deal with format compatibility
4085  * between the channels in the bridge.
4086  *
4087  * Beware of the transcode_via_slin and genericplc options as
4088  * they force any transcoding to go through slin on a bridge.
4089  * Unfortunately transcode_via_slin is enabled by default and
4090  * genericplc is enabled in the codecs.conf.sample file.
4091  *
4092  * XXX Only updating translation to slinear frames has some
4093  * corner cases if slinear is one of the native formats and
4094  * there are different sample rates involved. We might wind
4095  * up with conflicting translation paths between channels
4096  * where the read translation path on this channel reduces
4097  * the sample rate followed by a write translation path on
4098  * the peer channel that increases the sample rate.
4099  */
4100  core_format = ast_channel_readformat(chan);
4101  if (!ast_format_cache_is_slinear(core_format)) {
4102  core_format = f->subclass.format;
4103  }
4104  if (ast_set_read_format_path(chan, f->subclass.format, core_format)) {
4105  /* Drop frame. We couldn't make it compatible with the core. */
4106  ast_frfree(f);
4107  f = &ast_null_frame;
4108  break;
4109  }
4110  }
4111  /*
4112  * Send frame to audiohooks if present, if frametype is linear, to preserve
4113  * functional compatibility with previous behavior. If not linear, hold off
4114  * until transcoding is done where we are more likely to have a linear frame
4115  */
4117  /* Place hooked after declaration */
4118  struct ast_frame *old_frame = f;
4119  hooked = 1;
4120 
4122  if (old_frame != f) {
4123  ast_frfree(old_frame);
4124  }
4125  }
4126 
4127  if (ast_channel_monitor(chan) && ast_channel_monitor(chan)->read_stream) {
4128  /* XXX what does this do ? */
4129 #ifndef MONITOR_CONSTANT_DELAY
4130  int jump = ast_channel_outsmpl(chan) - ast_channel_insmpl(chan) - 4 * f->samples;
4131  if (jump >= 0) {
4134  ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
4135  if (ast_seekstream(ast_channel_monitor(chan)->read_stream, jump, SEEK_FORCECUR) == -1) {
4136  ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
4137  }
4139  } else {
4141  }
4142 #else
4143  int jump = calc_monitor_jump((ast_channel_outsmpl(chan) - ast_channel_insmpl(chan)),
4145  ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
4146  if (jump - MONITOR_DELAY >= 0) {
4147  if (ast_seekstream(ast_channel_monitor(chan)->read_stream, jump - f->samples, SEEK_FORCECUR) == -1) {
4148  ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
4149  }
4151  } else {
4152  ast_channel_insmpl(chan) += f->samples;
4153  }
4154 #endif
4156  if (ast_writestream(ast_channel_monitor(chan)->read_stream, f) < 0)
4157  ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
4158  }
4159  }
4160 
4161  if (ast_channel_readtrans(chan)
4163  f = ast_translate(ast_channel_readtrans(chan), f, 1);
4164  if (!f) {
4165  f = &ast_null_frame;
4166  }
4167  }
4168 
4169  /* Second chance at hooking a linear frame, also the last chance */
4170  if (ast_channel_audiohooks(chan) && !hooked) {
4171  struct ast_frame *old_frame = f;
4172 
4174  if (old_frame != f) {
4175  ast_frfree(old_frame);
4176  }
4177  }
4178 
4179  /*
4180  * It is possible for the translation process on the channel to have
4181  * produced multiple frames from the single input frame we passed it; if
4182  * this happens, queue the additional frames *before* the frames we may
4183  * have queued earlier. if the readq was empty, put them at the head of
4184  * the queue, and if it was not, put them just after the frame that was
4185  * at the end of the queue.
4186  */
4187  if (AST_LIST_NEXT(f, frame_list)) {
4188  struct ast_frame *cur, *multi_frame = AST_LIST_NEXT(f, frame_list);
4189 
4190  /* Mark these frames as being re-queued */
4191  for (cur = multi_frame; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
4193  }
4194 
4195  if (!readq_tail) {
4196  ast_queue_frame_head(chan, multi_frame);
4197  } else {
4198  __ast_queue_frame(chan, multi_frame, 0, readq_tail);
4199  }
4200  ast_frfree(multi_frame);
4202  }
4203 
4204  /*
4205  * Run generator sitting on the line if timing device not available
4206  * and synchronous generation of outgoing frames is necessary
4207  */
4208  ast_read_generator_actions(chan, f);
4209  break;
4210  case AST_FRAME_RTCP:
4211  /* Incoming RTCP feedback needs to get to the translator for
4212  * outgoing media, which means we treat it as an ast_write */
4213  if (ast_channel_writetrans(chan)) {
4215  }
4216  break;
4217  default:
4218  /* Just pass it on! */
4219  break;
4220  }
4221  } else {
4222  /* Make sure we always return NULL in the future */
4225  }
4226  if (cause)
4227  ast_channel_hangupcause_set(chan, cause);
4228  if (ast_channel_generator(chan))
4230  /* We no longer End the CDR here */
4231  }
4232 
4233  /* High bit prints debugging */
4234  if (ast_channel_fin(chan) & DEBUGCHAN_FLAG)
4235  ast_frame_dump(ast_channel_name(chan), f, "<<");
4237 
4238 done:
4240  ast_channel_generator(chan)->digit(chan, f->subclass.integer);
4241 
4243  /* The list gets recreated if audiohooks are added again later */
4246  }
4247  ast_channel_unlock(chan);
4248  return f;
4249 }
4250 
4251 struct ast_frame *ast_read(struct ast_channel *chan)
4252 {
4253  return __ast_read(chan, 0, 1);
4254 }
4255 
4257 {
4258  return __ast_read(chan, 0, 0);
4259 }
4260 
4262 {
4263  return __ast_read(chan, 1, 1);
4264 }
4265 
4267 {
4268  return __ast_read(chan, 1, 0);
4269 }
4270 
4271 int ast_indicate(struct ast_channel *chan, int condition)
4272 {
4273  return ast_indicate_data(chan, condition, NULL, 0);
4274 }
4275 
4277 {
4278  /* Don't include a default case here so that we get compiler warnings
4279  * when a new type is added. */
4280 
4281  switch (condition) {
4282  case AST_CONTROL_PROGRESS:
4284  case AST_CONTROL_VIDUPDATE:
4285  case AST_CONTROL_SRCUPDATE:
4286  case AST_CONTROL_SRCCHANGE:
4287  case AST_CONTROL_RADIO_KEY:
4289  case AST_CONTROL_OPTION:
4290  case AST_CONTROL_WINK:
4291  case AST_CONTROL_FLASH:
4292  case AST_CONTROL_OFFHOOK:
4294  case AST_CONTROL_ANSWER:
4295  case AST_CONTROL_HANGUP:
4298  case AST_CONTROL_TRANSFER:
4300  case _XXX_AST_CONTROL_T38:
4301  case AST_CONTROL_CC:
4303  case AST_CONTROL_AOC:
4304  case AST_CONTROL_END_OF_Q:
4305  case AST_CONTROL_MCID:
4321  break;
4322 
4325  case AST_CONTROL_BUSY:
4326  case AST_CONTROL_RINGING:
4327  case AST_CONTROL_RING:
4328  case AST_CONTROL_HOLD:
4329  /* You can hear these */
4330  return 1;
4331 
4332  case AST_CONTROL_UNHOLD:
4333  /* This is a special case. You stop hearing this. */
4334  break;
4335  }
4336 
4337  return 0;
4338 }
4339 
4340 void ast_channel_hangupcause_hash_set(struct ast_channel *chan, const struct ast_control_pvt_cause_code *cause_code, int datalen)
4341 {
4342  char causevar[256];
4343 
4344  if (ast_channel_dialed_causes_add(chan, cause_code, datalen)) {
4345  ast_log(LOG_WARNING, "Unable to store hangup cause for %s on %s\n", cause_code->chan_name, ast_channel_name(chan));
4346  }
4347 
4348  if (cause_code->emulate_sip_cause) {
4349  snprintf(causevar, sizeof(causevar), "HASH(SIP_CAUSE,%s)", cause_code->chan_name);
4350  ast_func_write(chan, causevar, cause_code->code);
4351  }
4352 }
4353 
4355 {
4356  if (!strcasecmp(flag, "default"))
4357  return DEFAULT_AMA_FLAGS;
4358  if (!strcasecmp(flag, "omit"))
4359  return AST_AMA_OMIT;
4360  if (!strcasecmp(flag, "billing"))
4361  return AST_AMA_BILLING;
4362  if (!strcasecmp(flag, "documentation"))
4363  return AST_AMA_DOCUMENTATION;
4364  return AST_AMA_NONE;
4365 }
4366 
4368 {
4369  switch (flag) {
4370  case AST_AMA_OMIT:
4371  return "OMIT";
4372  case AST_AMA_BILLING:
4373  return "BILLING";
4374  case AST_AMA_DOCUMENTATION:
4375  return "DOCUMENTATION";
4376  default:
4377  return "Unknown";
4378  }
4379 }
4380 
4381 /*!
4382  * \internal
4383  * \brief Preprocess connected line update.
4384  * \since 12.0.0
4385  *
4386  * \param chan channel to change the indication
4387  * \param data pointer to payload data
4388  * \param datalen size of payload data
4389  *
4390  * \note This function assumes chan is locked.
4391  *
4392  * \retval 0 keep going.
4393  * \retval -1 quit now.
4394  */
4395 static int indicate_connected_line(struct ast_channel *chan, const void *data, size_t datalen)
4396 {
4397  struct ast_party_connected_line *chan_connected = ast_channel_connected(chan);
4398  struct ast_party_connected_line *chan_indicated = ast_channel_connected_indicated(chan);
4399  struct ast_party_connected_line connected;
4400  unsigned char current[1024];
4401  unsigned char proposed[1024];
4402  int current_size;
4403  int proposed_size;
4404  int res;
4405 
4406  ast_party_connected_line_set_init(&connected, chan_connected);
4407  res = ast_connected_line_parse_data(data, datalen, &connected);
4408  if (!res) {
4409  ast_channel_set_connected_line(chan, &connected, NULL);
4410  }
4411  ast_party_connected_line_free(&connected);
4412  if (res) {
4413  return -1;
4414  }
4415 
4416  current_size = ast_connected_line_build_data(current, sizeof(current),
4417  chan_indicated, NULL);
4418  proposed_size = ast_connected_line_build_data(proposed, sizeof(proposed),
4419  chan_connected, NULL);
4420  if (current_size == -1 || proposed_size == -1) {
4421  return -1;
4422  }
4423 
4424  if (current_size == proposed_size && !memcmp(current, proposed, current_size)) {
4425  ast_debug(1, "%s: Dropping redundant connected line update \"%s\" <%s>.\n",
4426  ast_channel_name(chan),
4427  S_COR(chan_connected->id.name.valid, chan_connected->id.name.str, ""),
4428  S_COR(chan_connected->id.number.valid, chan_connected->id.number.str, ""));
4429  return -1;
4430  }
4431 
4432  ast_party_connected_line_copy(chan_indicated, chan_connected);
4433  return 0;
4434 }
4435 
4436 /*!
4437  * \internal
4438  * \brief Preprocess redirecting update.
4439  * \since 12.0.0
4440  *
4441  * \param chan channel to change the indication
4442  * \param data pointer to payload data
4443  * \param datalen size of payload data
4444  *
4445  * \note This function assumes chan is locked.
4446  *
4447  * \retval 0 keep going.
4448  * \retval -1 quit now.
4449  */
4450 static int indicate_redirecting(struct ast_channel *chan, const void *data, size_t datalen)
4451 {
4452  struct ast_party_redirecting redirecting;
4453  int res;
4454 
4456  res = ast_redirecting_parse_data(data, datalen, &redirecting);
4457  if (!res) {
4458  ast_channel_set_redirecting(chan, &redirecting, NULL);
4459  }
4460  ast_party_redirecting_free(&redirecting);
4461  return res ? -1 : 0;
4462 }
4463 
4464 static int indicate_data_internal(struct ast_channel *chan, int _condition, const void *data, size_t datalen)
4465 {
4466  /* By using an enum, we'll get compiler warnings for values not handled
4467  * in switch statements. */
4468  enum ast_control_frame_type condition = _condition;
4469  struct ast_tone_zone_sound *ts = NULL;
4470  const struct ast_control_t38_parameters *t38_parameters;
4471  int res;
4472 
4473  switch (condition) {
4475  if (indicate_connected_line(chan, data, datalen)) {
4476  res = 0;
4477  return res;
4478  }
4479  break;
4481  if (indicate_redirecting(chan, data, datalen)) {
4482  res = 0;
4483  return res;
4484  }
4485  break;
4486  case AST_CONTROL_HOLD:
4487  case AST_CONTROL_UNHOLD:
4488  ast_channel_hold_state_set(chan, _condition);
4489  break;
4491  t38_parameters = data;
4492  switch (t38_parameters->request_response) {
4494  case AST_T38_NEGOTIATED:
4496  break;
4498  case AST_T38_TERMINATED:
4499  case AST_T38_REFUSED:
4501  break;
4502  default:
4503  break;
4504  }
4505  break;
4506  default:
4507  break;
4508  }
4509 
4510  if (is_visible_indication(condition)) {
4511  /* A new visible indication is requested. */
4512  ast_channel_visible_indication_set(chan, _condition);
4513  } else if (condition == AST_CONTROL_UNHOLD || _condition < 0) {
4514  /* Visible indication is cleared/stopped. */
4516  }
4517 
4518  if (ast_channel_tech(chan)->indicate) {
4519  /* See if the channel driver can handle this condition. */
4520  res = ast_channel_tech(chan)->indicate(chan, _condition, data, datalen);
4521  } else {
4522  res = -1;
4523  }
4524 
4525  if (!res) {
4526  /* The channel driver successfully handled this indication */
4527  res = 0;
4528  return res;
4529  }
4530 
4531  /* The channel driver does not support this indication, let's fake
4532  * it by doing our own tone generation if applicable. */
4533 
4534  /*!\note If we compare the enumeration type, which does not have any
4535  * negative constants, the compiler may optimize this code away.
4536  * Therefore, we must perform an integer comparison here. */
4537  if (_condition < 0) {
4538  /* Stop any tones that are playing */
4539  ast_playtones_stop(chan);
4540  res = 0;
4541  return res;
4542  }
4543 
4544  /* Handle conditions that we have tones for. */
4545  switch (condition) {
4546  case _XXX_AST_CONTROL_T38:
4547  /* deprecated T.38 control frame */
4548  res = -1;
4549  return res;
4551  /* there is no way to provide 'default' behavior for these
4552  * control frames, so we need to return failure, but there
4553  * is also no value in the log message below being emitted
4554  * since failure to handle these frames is not an 'error'
4555  * so just return right now. in addition, we want to return
4556  * whatever value the channel driver returned, in case it
4557  * has some meaning.*/
4558  return res;
4559  case AST_CONTROL_RINGING:
4560  ts = ast_get_indication_tone(ast_channel_zone(chan), "ring");
4561  /* It is common practice for channel drivers to return -1 if trying
4562  * to indicate ringing on a channel which is up. The idea is to let the
4563  * core generate the ringing inband. However, we don't want the
4564  * warning message about not being able to handle the specific indication
4565  * to print nor do we want ast_indicate_data to return an "error" for this
4566  * condition
4567  */
4568  if (ast_channel_state(chan) == AST_STATE_UP) {
4569  res = 0;
4570  }
4571  break;
4572  case AST_CONTROL_BUSY:
4573  ts = ast_get_indication_tone(ast_channel_zone(chan), "busy");
4574  break;
4577  ts = ast_get_indication_tone(ast_channel_zone(chan), "congestion");
4578  break;
4580  ast_channel_hangupcause_hash_set(chan, data, datalen);
4581  res = 0;
4582  break;
4583  case AST_CONTROL_PROGRESS:
4585  case AST_CONTROL_VIDUPDATE:
4586  case AST_CONTROL_SRCUPDATE:
4587  case AST_CONTROL_SRCCHANGE:
4588  case AST_CONTROL_RADIO_KEY:
4590  case AST_CONTROL_OPTION:
4591  case AST_CONTROL_WINK:
4592  case AST_CONTROL_FLASH:
4593  case AST_CONTROL_OFFHOOK:
4595  case AST_CONTROL_ANSWER:
4596  case AST_CONTROL_HANGUP:
4597  case AST_CONTROL_RING:
4598  case AST_CONTROL_HOLD:
4599  case AST_CONTROL_UNHOLD:
4600  case AST_CONTROL_TRANSFER:
4603  case AST_CONTROL_CC:
4605  case AST_CONTROL_AOC:
4606  case AST_CONTROL_END_OF_Q:
4607  case AST_CONTROL_MCID:
4622  /* Nothing left to do for these. */
4623  res = 0;
4624  break;
4625  }
4626 
4627  if (ts) {
4628  /* We have a tone to play, yay. */
4629  ast_debug(1, "Driver for channel '%s' does not support indication %u, emulating it\n", ast_channel_name(chan), condition);
4630  res = ast_playtones_start(chan, 0, ts->data, 1);
4631  if (!res) {
4632  ast_test_suite_event_notify("RINGING_INBAND",
4633  "Channel: %s\r\n",
4634  ast_channel_name(chan));
4635  }
4636  ts = ast_tone_zone_sound_unref(ts);
4637  }
4638 
4639  if (res) {
4640  /* not handled */
4641  ast_log(LOG_WARNING, "Unable to handle indication %u for '%s'\n", condition, ast_channel_name(chan));
4642  }
4643 
4644  return res;
4645 }
4646 
4647 int ast_indicate_data(struct ast_channel *chan, int _condition, const void *data, size_t datalen)
4648 {
4649  int res;
4650  /* this frame is used by framehooks. if it is set, we must free it at the end of this function */
4651  struct ast_frame *awesome_frame = NULL;
4652 
4653  ast_channel_lock(chan);
4654 
4655  /* Don't bother if the channel is about to go away, anyway. */
4657  || (ast_check_hangup(chan) && !ast_channel_is_leaving_bridge(chan)))
4658  && _condition != AST_CONTROL_MASQUERADE_NOTIFY) {
4659  res = -1;
4660  goto indicate_cleanup;
4661  }
4662 
4664  /* Do framehooks now, do it, go, go now */
4665  struct ast_frame frame = {
4667  .subclass.integer = _condition,
4668  .data.ptr = (void *) data, /* this cast from const is only okay because we do the ast_frdup below */
4669  .datalen = datalen
4670  };
4671 
4672  /* we have now committed to freeing this frame */
4673  awesome_frame = ast_frdup(&frame);
4674 
4675  /* who knows what we will get back! the anticipation is killing me. */
4677  awesome_frame);
4678  if (!awesome_frame
4679  || awesome_frame->frametype != AST_FRAME_CONTROL) {
4680  res = 0;
4681  goto indicate_cleanup;
4682  }
4683 
4684  _condition = awesome_frame->subclass.integer;
4685  data = awesome_frame->data.ptr;
4686  datalen = awesome_frame->datalen;
4687  }
4688 
4689  res = indicate_data_internal(chan, _condition, data, datalen);
4690 
4691 indicate_cleanup:
4692  ast_channel_unlock(chan);
4693  if (awesome_frame) {
4694  ast_frfree(awesome_frame);
4695  }
4696 
4697  return res;
4698 }
4699 
4700 int ast_recvchar(struct ast_channel *chan, int timeout)
4701 {
4702  int c;
4703  char *buf = ast_recvtext(chan, timeout);
4704  if (buf == NULL)
4705  return -1; /* error or timeout */
4706  c = *(unsigned char *)buf;
4707  ast_free(buf);
4708  return c;
4709 }
4710 
4711 char *ast_recvtext(struct ast_channel *chan, int timeout)
4712 {
4713  int res;
4714  char *buf = NULL;
4715  struct timeval start = ast_tvnow();
4716  int ms;
4717 
4718  while ((ms = ast_remaining_ms(start, timeout))) {
4719  struct ast_frame *f;
4720 
4721  if (ast_check_hangup(chan)) {
4722  break;
4723  }
4724  res = ast_waitfor(chan, ms);
4725  if (res <= 0) {/* timeout or error */
4726  break;
4727  }
4728  f = ast_read(chan);
4729  if (f == NULL) {
4730  break; /* no frame */
4731  }
4733  ast_frfree(f);
4734  break;
4735  } else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
4736  buf = ast_strndup((char *) f->data.ptr, f->datalen); /* dup and break */
4737  ast_frfree(f);
4738  break;
4739  }
4740  ast_frfree(f);
4741  }
4742  return buf;
4743 }
4744 
4745 int ast_sendtext_data(struct ast_channel *chan, struct ast_msg_data *msg)
4746 {
4747  int res = 0;
4748  const char *body = ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_BODY);
4749  const char *content_type = ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_CONTENT_TYPE);
4750 
4751  ast_channel_lock(chan);
4752  /* Stop if we're a zombie or need a soft hangup */
4754  ast_channel_unlock(chan);
4755  return -1;
4756  }
4757 
4758  CHECK_BLOCKING(chan);
4759  if (ast_channel_tech(chan)->write_text
4760  && (ast_strlen_zero(content_type) || ast_begins_with(content_type, "text/"))
4762  struct ast_frame f;
4763  /* T.140 payload does not include the null byte terminator */
4764  size_t body_len = strlen(body);
4765 
4766  /* Process as T.140 text (moved here from ast_sendtext() */
4767  memset(&f, 0, sizeof(f));
4768  f.src = "DIALPLAN";
4771  f.datalen = body_len;
4773  f.data.ptr = ast_strdup(body);
4774  if (f.data.ptr) {
4775  res = ast_channel_tech(chan)->write_text(chan, &f);
4776  } else {
4777  res = -1;
4778  }
4779  ast_frfree(&f);
4780  } else if ((ast_channel_tech(chan)->properties & AST_CHAN_TP_SEND_TEXT_DATA)
4781  && ast_channel_tech(chan)->send_text_data) {
4782  /* Send enhanced message to a channel driver that supports it */
4783  ast_debug(1, "Sending TEXT_DATA from '%s' to %s:%s %s\n",
4786  ast_channel_name(chan), body);
4787  res = ast_channel_tech(chan)->send_text_data(chan, msg);
4788  } else if (ast_channel_tech(chan)->send_text
4789  && (ast_strlen_zero(content_type) || ast_begins_with(content_type, "text/"))) {
4790  /* Send the body of an enhanced message to a channel driver that supports only a char str */
4791  ast_debug(1, "Sending TEXT to %s: %s\n", ast_channel_name(chan), body);
4792  res = ast_channel_tech(chan)->send_text(chan, body);
4793  } else {
4794  ast_debug(1, "Channel technology does not support sending content type '%s' on channel '%s'\n",
4795  S_OR(content_type, "text/plain"), ast_channel_name(chan));
4796  res = -1;
4797  }
4799  ast_channel_unlock(chan);
4800  return res;
4801 }
4802 
4803 int ast_sendtext(struct ast_channel *chan, const char *text)
4804 {
4805  struct ast_msg_data *msg;
4806  int rc;
4807  struct ast_msg_data_attribute attrs[] =
4808  {
4809  {