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