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