Asterisk - The Open Source Telephony Project  GIT-master-8beac82
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 static int safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data, unsigned int generate_silence)
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 */
1506  if (generate_silence && ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
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 int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
1565 {
1566  return safe_sleep_conditional(chan, timeout_ms, cond, data, 1);
1567 }
1568 
1569 /*! \brief Wait, look for hangups */
1570 int ast_safe_sleep(struct ast_channel *chan, int ms)
1571 {
1572  return safe_sleep_conditional(chan, ms, NULL, NULL, 1);
1573 }
1574 
1576 {
1577  return safe_sleep_conditional(chan, ms, NULL, NULL, 0);
1578 }
1579 
1581 {
1582  /* Safe, even if already unlinked. */
1583  ao2_unlink(channels, chan);
1584  return ast_channel_unref(chan);
1585 }
1586 
1588 {
1589  init->str = NULL;
1592  init->valid = 0;
1593 }
1594 
1595 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1596 {
1597  if (dest == src) {
1598  /* Don't copy to self */
1599  return;
1600  }
1601 
1602  ast_free(dest->str);
1603  dest->str = ast_strdup(src->str);
1604  dest->char_set = src->char_set;
1605  dest->presentation = src->presentation;
1606  dest->valid = src->valid;
1607 }
1608 
1609 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1610 {
1611  init->str = NULL;
1612  init->char_set = guide->char_set;
1613  init->presentation = guide->presentation;
1614  init->valid = guide->valid;
1615 }
1616 
1617 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1618 {
1619  if (dest == src) {
1620  /* Don't set to self */
1621  return;
1622  }
1623 
1624  if (src->str && src->str != dest->str) {
1625  ast_free(dest->str);
1626  dest->str = ast_strdup(src->str);
1627  }
1628 
1629  dest->char_set = src->char_set;
1630  dest->presentation = src->presentation;
1631  dest->valid = src->valid;
1632 }
1633 
1635 {
1636  ast_free(doomed->str);
1637  doomed->str = NULL;
1638 }
1639 
1641 {
1642  init->str = NULL;
1643  init->plan = 0;/* Unknown */
1645  init->valid = 0;
1646 }
1647 
1648 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1649 {
1650  if (dest == src) {
1651  /* Don't copy to self */
1652  return;
1653  }
1654 
1655  ast_free(dest->str);
1656  dest->str = ast_strdup(src->str);
1657  dest->plan = src->plan;
1658  dest->presentation = src->presentation;
1659  dest->valid = src->valid;
1660 }
1661 
1662 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1663 {
1664  init->str = NULL;
1665  init->plan = guide->plan;
1666  init->presentation = guide->presentation;
1667  init->valid = guide->valid;
1668 }
1669 
1670 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1671 {
1672  if (dest == src) {
1673  /* Don't set to self */
1674  return;
1675  }
1676 
1677  if (src->str && src->str != dest->str) {
1678  ast_free(dest->str);
1679  dest->str = ast_strdup(src->str);
1680  }
1681 
1682  dest->plan = src->plan;
1683  dest->presentation = src->presentation;
1684  dest->valid = src->valid;
1685 }
1686 
1688 {
1689  ast_free(doomed->str);
1690  doomed->str = NULL;
1691 }
1692 
1694 {
1695  init->str = NULL;
1696  init->type = 0;
1697  init->odd_even_indicator = 0;
1698  init->valid = 0;
1699 }
1700 
1702 {
1703  if (dest == src) {
1704  /* Don't copy to self */
1705  return;
1706  }
1707 
1708  ast_free(dest->str);
1709  dest->str = ast_strdup(src->str);
1710  dest->type = src->type;
1712  dest->valid = src->valid;
1713 }
1714 
1716 {
1717  init->str = NULL;
1718  init->type = guide->type;
1719  init->odd_even_indicator = guide->odd_even_indicator;
1720  init->valid = guide->valid;
1721 }
1722 
1724 {
1725  if (dest == src) {
1726  /* Don't set to self */
1727  return;
1728  }
1729 
1730  if (src->str && src->str != dest->str) {
1731  ast_free(dest->str);
1732  dest->str = ast_strdup(src->str);
1733  }
1734 
1735  dest->type = src->type;
1737  dest->valid = src->valid;
1738 }
1739 
1741 {
1742  ast_free(doomed->str);
1743  doomed->str = NULL;
1744 }
1745 
1747 {
1748  update_id->name = 1;
1749  update_id->number = 1;
1750  update_id->subaddress = 1;
1751 }
1752 
1754 {
1755  ast_party_name_init(&init->name);
1756  ast_party_number_init(&init->number);
1758  init->tag = NULL;
1759 }
1760 
1761 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1762 {
1763  if (dest == src) {
1764  /* Don't copy to self */
1765  return;
1766  }
1767 
1768  ast_party_name_copy(&dest->name, &src->name);
1769  ast_party_number_copy(&dest->number, &src->number);
1771 
1772  ast_free(dest->tag);
1773  dest->tag = ast_strdup(src->tag);
1774 }
1775 
1776 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1777 {
1778  ast_party_name_set_init(&init->name, &guide->name);
1779  ast_party_number_set_init(&init->number, &guide->number);
1781  init->tag = NULL;
1782 }
1783 
1784 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1785 {
1786  if (dest == src) {
1787  /* Don't set to self */
1788  return;
1789  }
1790 
1791  if (!update || update->name) {
1792  ast_party_name_set(&dest->name, &src->name);
1793  }
1794  if (!update || update->number) {
1795  ast_party_number_set(&dest->number, &src->number);
1796  }
1797  if (!update || update->subaddress) {
1799  }
1800 
1801  if (src->tag && src->tag != dest->tag) {
1802  ast_free(dest->tag);
1803  dest->tag = ast_strdup(src->tag);
1804  }
1805 }
1806 
1807 void ast_party_id_free(struct ast_party_id *doomed)
1808 {
1809  ast_party_name_free(&doomed->name);
1810  ast_party_number_free(&doomed->number);
1812 
1813  ast_free(doomed->tag);
1814  doomed->tag = NULL;
1815 }
1816 
1818 {
1819  int number_priority;
1820  int number_value;
1821  int number_screening;
1822  int name_priority;
1823  int name_value;
1824 
1825  /* Determine name presentation priority. */
1826  if (!id->name.valid) {
1827  name_value = AST_PRES_UNAVAILABLE;
1828  name_priority = 3;
1829  } else {
1830  name_value = id->name.presentation & AST_PRES_RESTRICTION;
1831  switch (name_value) {
1832  case AST_PRES_RESTRICTED:
1833  name_priority = 0;
1834  break;
1835  case AST_PRES_ALLOWED:
1836  name_priority = 1;
1837  break;
1838  case AST_PRES_UNAVAILABLE:
1839  name_priority = 2;
1840  break;
1841  default:
1842  name_value = AST_PRES_UNAVAILABLE;
1843  name_priority = 3;
1844  break;
1845  }
1846  }
1847 
1848  /* Determine number presentation priority. */
1849  if (!id->number.valid) {
1850  number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1851  number_value = AST_PRES_UNAVAILABLE;
1852  number_priority = 3;
1853  } else {
1854  number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1855  number_value = id->number.presentation & AST_PRES_RESTRICTION;
1856  switch (number_value) {
1857  case AST_PRES_RESTRICTED:
1858  number_priority = 0;
1859  break;
1860  case AST_PRES_ALLOWED:
1861  number_priority = 1;
1862  break;
1863  case AST_PRES_UNAVAILABLE:
1864  number_priority = 2;
1865  break;
1866  default:
1867  number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1868  number_value = AST_PRES_UNAVAILABLE;
1869  number_priority = 3;
1870  break;
1871  }
1872  }
1873 
1874  /* Select the wining presentation value. */
1875  if (name_priority < number_priority) {
1876  number_value = name_value;
1877  }
1878  if (number_value == AST_PRES_UNAVAILABLE) {
1880  }
1881 
1882  return number_value | number_screening;
1883 }
1884 
1886 {
1887  id->name.valid = 0;
1888  id->number.valid = 0;
1889  id->subaddress.valid = 0;
1890 }
1891 
1893 {
1894  ast_party_id_free(id);
1895  ast_party_id_init(id);
1896 }
1897 
1898 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
1899 {
1900  struct ast_party_id merged;
1901 
1902  merged = *base;
1903  if (overlay->name.valid) {
1904  merged.name = overlay->name;
1905  }
1906  if (overlay->number.valid) {
1907  merged.number = overlay->number;
1908  }
1909  if (overlay->subaddress.valid) {
1910  merged.subaddress = overlay->subaddress;
1911  }
1912  /* Note the actual structure is returned and not a pointer to it! */
1913  return merged;
1914 }
1915 
1916 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
1917 {
1918  struct ast_party_id merged;
1919 
1920  merged = ast_party_id_merge(base, overlay);
1921  ast_party_id_copy(dest, &merged);
1922 }
1923 
1925 {
1926  init->number.str = NULL;
1927  init->number.plan = 0;/* Unknown */
1929  init->transit_network_select = 0;
1930 }
1931 
1932 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1933 {
1934  if (dest == src) {
1935  /* Don't copy to self */
1936  return;
1937  }
1938 
1939  ast_free(dest->number.str);
1940  dest->number.str = ast_strdup(src->number.str);
1941  dest->number.plan = src->number.plan;
1944 }
1945 
1946 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
1947 {
1948  init->number.str = NULL;
1949  init->number.plan = guide->number.plan;
1952 }
1953 
1954 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1955 {
1956  if (src->number.str && src->number.str != dest->number.str) {
1957  ast_free(dest->number.str);
1958  dest->number.str = ast_strdup(src->number.str);
1959  }
1960  dest->number.plan = src->number.plan;
1961 
1963 
1965 }
1966 
1968 {
1969  ast_free(doomed->number.str);
1970  doomed->number.str = NULL;
1972 }
1973 
1975 {
1976  ast_party_id_init(&init->id);
1977  ast_party_id_init(&init->ani);
1978  ast_party_id_init(&init->priv);
1979  init->ani2 = 0;
1980 }
1981 
1982 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
1983 {
1984  if (dest == src) {
1985  /* Don't copy to self */
1986  return;
1987  }
1988 
1989  ast_party_id_copy(&dest->id, &src->id);
1990  ast_party_id_copy(&dest->ani, &src->ani);
1991  ast_party_id_copy(&dest->priv, &src->priv);
1992  dest->ani2 = src->ani2;
1993 }
1994 
1995 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
1996 {
1997  ast_party_id_set_init(&init->id, &guide->id);
1998  ast_party_id_set_init(&init->ani, &guide->ani);
1999  ast_party_id_set_init(&init->priv, &guide->priv);
2000  init->ani2 = guide->ani2;
2001 }
2002 
2003 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2004 {
2005  ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2006  ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2007  ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2008  dest->ani2 = src->ani2;
2009 }
2010 
2012 {
2013  ast_party_id_free(&doomed->id);
2014  ast_party_id_free(&doomed->ani);
2015  ast_party_id_free(&doomed->priv);
2016 }
2017 
2019 {
2020  ast_party_id_init(&init->id);
2021  ast_party_id_init(&init->ani);
2022  ast_party_id_init(&init->priv);
2023  init->ani2 = 0;
2025 }
2026 
2028 {
2029  if (dest == src) {
2030  /* Don't copy to self */
2031  return;
2032  }
2033 
2034  ast_party_id_copy(&dest->id, &src->id);
2035  ast_party_id_copy(&dest->ani, &src->ani);
2036  ast_party_id_copy(&dest->priv, &src->priv);
2037  dest->ani2 = src->ani2;
2038  dest->source = src->source;
2039 }
2040 
2042 {
2043  ast_party_id_set_init(&init->id, &guide->id);
2044  ast_party_id_set_init(&init->ani, &guide->ani);
2045  ast_party_id_set_init(&init->priv, &guide->priv);
2046  init->ani2 = guide->ani2;
2047  init->source = guide->source;
2048 }
2049 
2051 {
2052  ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2053  ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2054  ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2055  dest->ani2 = src->ani2;
2056  dest->source = src->source;
2057 }
2058 
2060 {
2061  connected->id = caller->id;
2062  connected->ani = caller->ani;
2063  connected->priv = caller->priv;
2064  connected->ani2 = caller->ani2;
2066 }
2067 
2069 {
2070  ast_party_id_free(&doomed->id);
2071  ast_party_id_free(&doomed->ani);
2072  ast_party_id_free(&doomed->priv);
2073 }
2074 
2076 {
2077  init->str = NULL;
2079 }
2080 
2082 {
2083  if (dest == src) {
2084  return;
2085  }
2086 
2087  ast_free(dest->str);
2088  dest->str = ast_strdup(src->str);
2089  dest->code = src->code;
2090 }
2091 
2093 {
2094  init->str = NULL;
2095  init->code = guide->code;
2096 }
2097 
2099 {
2100  if (dest == src) {
2101  return;
2102  }
2103 
2104  if (src->str && src->str != dest->str) {
2105  ast_free(dest->str);
2106  dest->str = ast_strdup(src->str);
2107  }
2108 
2109  dest->code = src->code;
2110 }
2111 
2113 {
2114  ast_free(doomed->str);
2115 }
2116 
2117 
2119 {
2120  ast_party_id_init(&init->orig);
2121  ast_party_id_init(&init->from);
2122  ast_party_id_init(&init->to);
2123  ast_party_id_init(&init->priv_orig);
2124  ast_party_id_init(&init->priv_from);
2125  ast_party_id_init(&init->priv_to);
2128  init->count = 0;
2129 }
2130 
2132 {
2133  if (dest == src) {
2134  /* Don't copy to self */
2135  return;
2136  }
2137 
2138  ast_party_id_copy(&dest->orig, &src->orig);
2139  ast_party_id_copy(&dest->from, &src->from);
2140  ast_party_id_copy(&dest->to, &src->to);
2141  ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2142  ast_party_id_copy(&dest->priv_from, &src->priv_from);
2143  ast_party_id_copy(&dest->priv_to, &src->priv_to);
2146  dest->count = src->count;
2147 }
2148 
2150 {
2151  ast_party_id_set_init(&init->orig, &guide->orig);
2152  ast_party_id_set_init(&init->from, &guide->from);
2153  ast_party_id_set_init(&init->to, &guide->to);
2154  ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2155  ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2156  ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2159  init->count = guide->count;
2160 }
2161 
2163 {
2164  ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2165  ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2166  ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2167  ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2168  ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2169  ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2172  dest->count = src->count;
2173 }
2174 
2176 {
2177  ast_party_id_free(&doomed->orig);
2178  ast_party_id_free(&doomed->from);
2179  ast_party_id_free(&doomed->to);
2180  ast_party_id_free(&doomed->priv_orig);
2181  ast_party_id_free(&doomed->priv_from);
2182  ast_party_id_free(&doomed->priv_to);
2185 }
2186 
2187 /*! \brief Free a channel structure */
2188 static void ast_channel_destructor(void *obj)
2189 {
2190  struct ast_channel *chan = obj;
2191  struct ast_var_t *vardata;
2192  struct ast_frame *f;
2193  struct varshead *headp;
2194  struct ast_datastore *datastore;
2195  char device_name[AST_CHANNEL_NAME];
2196  ast_callid callid;
2197 
2198  ast_debug(1, "Channel %p '%s' destroying\n", chan, ast_channel_name(chan));
2199 
2200  /* Stop monitoring */
2201  if (ast_channel_monitor(chan)) {
2202  ast_channel_monitor(chan)->stop(chan, 0);
2203  }
2204 
2205  /* If there is native format music-on-hold state, free it */
2206  if (ast_channel_music_state(chan)) {
2207  ast_moh_cleanup(chan);
2208  }
2209 
2211 
2212  /* Things that may possibly raise Stasis messages shouldn't occur after this point */
2214 
2216  /* A channel snapshot should not be in the process of being staged now. */
2218 
2219  ast_channel_lock(chan);
2221  ast_channel_unlock(chan);
2222  }
2223 
2224  ast_channel_lock(chan);
2225 
2226  /* Get rid of each of the data stores on the channel */
2227  while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2228  /* Free the data store */
2229  ast_datastore_free(datastore);
2230 
2231  /* While the channel is locked, take the reference to its callid while we tear down the call. */
2232  callid = ast_channel_callid(chan);
2234 
2235  ast_channel_unlock(chan);
2236 
2237  /* Lock and unlock the channel just to be sure nobody has it locked still
2238  due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2239  ast_channel_lock(chan);
2240  ast_channel_unlock(chan);
2241 
2242  if (ast_channel_tech_pvt(chan)) {
2243  ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2245  }
2246 
2247  if (ast_channel_sched(chan)) {
2249  }
2250 
2252  char *dashptr;
2253 
2254  ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2255  if ((dashptr = strrchr(device_name, '-'))) {
2256  *dashptr = '\0';
2257  }
2258  } else {
2259  device_name[0] = '\0';
2260  }
2261 
2262  /* Free translators */
2263  if (ast_channel_readtrans(chan))
2265  if (ast_channel_writetrans(chan))
2267  if (ast_channel_pbx(chan))
2268  ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2269 
2270  /* Free formats */
2276 
2282 
2283  /* Close pipes if appropriate */
2285  if (ast_channel_timer(chan)) {
2287  ast_channel_timer_set(chan, NULL);
2288  }
2289  while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2290  ast_frfree(f);
2291 
2292  /* loop over the variables list, freeing all data and deleting list items */
2293  /* no need to lock the list, as the channel is already locked */
2294  headp = ast_channel_varshead(chan);
2295  while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2296  ast_var_delete(vardata);
2297 
2298  ast_app_group_discard(chan);
2299 
2300  /* Destroy the jitterbuffer */
2301  ast_jb_destroy(chan);
2302 
2303  if (ast_channel_cdr(chan)) {
2305  ast_channel_cdr_set(chan, NULL);
2306  }
2307 
2308  if (ast_channel_zone(chan)) {
2310  }
2311 
2313 
2314  if (device_name[0]) {
2315  /*
2316  * We have a device name to notify of a new state.
2317  *
2318  * Queue an unknown state, because, while we know that this particular
2319  * instance is dead, we don't know the state of all other possible
2320  * instances.
2321  */
2323  }
2324 
2326 
2329 
2331 }
2332 
2333 /*! \brief Free a dummy channel structure */
2334 static void ast_dummy_channel_destructor(void *obj)
2335 {
2336  struct ast_channel *chan = obj;
2337  struct ast_datastore *datastore;
2338  struct ast_var_t *vardata;
2339  struct varshead *headp;
2340 
2342 
2343  /* Get rid of each of the data stores on the channel */
2344  while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2345  /* Free the data store */
2346  ast_datastore_free(datastore);
2347  }
2348 
2354 
2355  /* loop over the variables list, freeing all data and deleting list items */
2356  /* no need to lock the list, as the channel is already locked */
2357  headp = ast_channel_varshead(chan);
2358  while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2359  ast_var_delete(vardata);
2360 
2361  if (ast_channel_cdr(chan)) {
2363  ast_channel_cdr_set(chan, NULL);
2364  }
2365 
2367 }
2368 
2370 {
2371  struct ast_datastore *datastore = NULL, *datastore2;
2372 
2373  AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2374  if (datastore->inheritance > 0) {
2375  datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2376  if (datastore2) {
2377  datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2378  datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2380  }
2381  }
2382  }
2383  return 0;
2384 }
2385 
2386 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2387 {
2388  int res = 0;
2389 
2391 
2392  return res;
2393 }
2394 
2395 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2396 {
2397  return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2398 }
2399 
2400 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2401 {
2402  struct ast_datastore *datastore = NULL;
2403 
2404  if (info == NULL)
2405  return NULL;
2406 
2407  AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2408  if (datastore->info != info) {
2409  continue;
2410  }
2411 
2412  if (uid == NULL) {
2413  /* matched by type only */
2414  break;
2415  }
2416 
2417  if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2418  /* Matched by type AND uid */
2419  break;
2420  }
2421  }
2422 
2423  return datastore;
2424 }
2425 
2426 /*! Set the file descriptor on the channel */
2427 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2428 {
2429  ast_channel_internal_fd_set(chan, which, fd);
2430  return;
2431 }
2432 
2434 {
2435  ast_channel_lock(chan);
2436 
2438 
2440  struct ast_frame *fr;
2441 
2442  /* If we have completely cleared the softhangup flag,
2443  * then we need to fully abort the hangup process. This requires
2444  * pulling the END_OF_Q frame out of the channel frame queue if it
2445  * still happens to be there. */
2446 
2447  fr = AST_LIST_LAST(ast_channel_readq(chan));
2448  if (fr && fr->frametype == AST_FRAME_CONTROL &&
2451  ast_frfree(fr);
2452  }
2453  }
2454 
2455  ast_channel_unlock(chan);
2456 }
2457 
2458 /*! \brief Softly hangup a channel, don't lock */
2459 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2460 {
2461  ast_debug(1, "Soft-Hanging (%#04x) up channel '%s'\n", (unsigned)cause, ast_channel_name(chan));
2462  /* Inform channel driver that we need to be hung up, if it cares */
2465  /* Interrupt any poll call or such */
2467  pthread_kill(ast_channel_blocker(chan), SIGURG);
2468  return 0;
2469 }
2470 
2471 /*! \brief Softly hangup a channel, lock */
2472 int ast_softhangup(struct ast_channel *chan, int cause)
2473 {
2474  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
2475  int res;
2476 
2477  ast_channel_lock(chan);
2478  res = ast_softhangup_nolock(chan, cause);
2479  blob = ast_json_pack("{s: i, s: b}",
2480  "cause", cause,
2481  "soft", 1);
2483  ast_channel_unlock(chan);
2484 
2485  return res;
2486 }
2487 
2488 static void free_translation(struct ast_channel *clonechan)
2489 {
2490  if (ast_channel_writetrans(clonechan)) {
2492  }
2493  if (ast_channel_readtrans(clonechan)) {
2495  }
2496  ast_channel_writetrans_set(clonechan, NULL);
2497  ast_channel_readtrans_set(clonechan, NULL);
2498 }
2499 
2500 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2501 {
2503 
2504  ast_channel_lock(chan);
2505  if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2506  ast_channel_hangupsource_set(chan, source);
2507  }
2508  ast_channel_unlock(chan);
2509 
2510  if (bridge) {
2511  ast_channel_lock(bridge);
2512  if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2513  ast_channel_hangupsource_set(bridge, source);
2514  }
2515  ast_channel_unlock(bridge);
2516  }
2517 }
2518 
2520 {
2521  return ast_channel_monitor(chan)
2524 }
2525 
2527 {
2528  return ast_channel_monitor(chan)
2531 }
2532 
2533 static void destroy_hooks(struct ast_channel *chan)
2534 {
2535  if (ast_channel_audiohooks(chan)) {
2538  }
2539 
2541 }
2542 
2543 /*! \brief Hangup a channel */
2544 void ast_hangup(struct ast_channel *chan)
2545 {
2546  /* Be NULL safe for RAII_VAR() usage. */
2547  if (!chan) {
2548  return;
2549  }
2550 
2551  ast_debug(1, "Channel %p '%s' hanging up. Refs: %d\n", chan, ast_channel_name(chan),
2552  ao2_ref(chan, 0));
2553 
2554  ast_autoservice_stop(chan);
2555 
2556  ast_channel_lock(chan);
2557 
2558  while (ast_channel_masq(chan) || ast_channel_masqr(chan)) {
2560  }
2561 
2562  /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2564 
2565  ast_channel_unlock(chan);
2566 
2567  /*
2568  * XXX if running the hangup handlers here causes problems
2569  * because the handlers take too long to execute, we could move
2570  * the meat of this function into another thread. A thread
2571  * where channels go to die.
2572  *
2573  * If this is done, ast_autoservice_chan_hangup_peer() will no
2574  * longer be needed.
2575  */
2577  ao2_unlink(channels, chan);
2578  ast_channel_lock(chan);
2579 
2580  destroy_hooks(chan);
2581 
2582  free_translation(chan);
2583  /* Close audio stream */
2584  if (ast_channel_stream(chan)) {
2587  }
2588  /* Close video stream */
2589  if (ast_channel_vstream(chan)) {
2592  }
2593  if (ast_channel_sched(chan)) {
2595  ast_channel_sched_set(chan, NULL);
2596  }
2597 
2598  if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2599  if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2601  }
2602  }
2605 
2607  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",
2609  ast_channel_blockproc(chan));
2610  ast_assert(0);
2611  }
2612 
2613  if (ast_channel_tech(chan)->hangup) {
2614  ast_channel_tech(chan)->hangup(chan);
2615  }
2616 
2617  ast_channel_unlock(chan);
2618 
2619  ast_cc_offer(chan);
2620 
2621  ast_channel_unref(chan);
2622 }
2623 
2624 /*!
2625  * \internal
2626  * \brief Set channel answered time if not already set.
2627  * \since 13.11.0
2628  *
2629  * \param chan Channel to set answered time.
2630  *
2631  * \return Nothing
2632  */
2633 static void set_channel_answer_time(struct ast_channel *chan)
2634 {
2635  if (ast_tvzero(ast_channel_answertime(chan))) {
2636  struct timeval answertime;
2637 
2638  answertime = ast_tvnow();
2639  ast_channel_answertime_set(chan, &answertime);
2640  }
2641 }
2642 
2643 
2645 {
2646  int res = 0;
2647  SCOPE_TRACE(1, "%s\n", ast_channel_name(chan));
2648 
2649  ast_channel_lock(chan);
2650 
2651  /* You can't answer an outbound call */
2653  ast_channel_unlock(chan);
2654  return 0;
2655  }
2656 
2657  /* Stop if we're a zombie or need a soft hangup */
2659  ast_channel_unlock(chan);
2660  return -1;
2661  }
2662 
2663  /*
2664  * Mark when incoming channel answered so we can know how
2665  * long the channel has been up.
2666  */
2668 
2669  ast_channel_unlock(chan);
2670 
2671  switch (ast_channel_state(chan)) {
2672  case AST_STATE_RINGING:
2673  case AST_STATE_RING:
2674  ast_channel_lock(chan);
2675  if (ast_channel_tech(chan)->answer_with_stream_topology) {
2676  res = ast_channel_tech(chan)->answer_with_stream_topology(chan, topology);
2677 
2678  } else if (ast_channel_tech(chan)->answer) {
2679  res = ast_channel_tech(chan)->answer(chan);
2680  }
2681  ast_setstate(chan, AST_STATE_UP);
2682  ast_channel_unlock(chan);
2683  break;
2684  case AST_STATE_UP:
2685  break;
2686  default:
2687  break;
2688  }
2689 
2690  ast_indicate(chan, -1);
2691 
2692  return res;
2693 }
2694 
2695 int ast_raw_answer(struct ast_channel *chan)
2696 {
2698 }
2699 
2700 int __ast_answer(struct ast_channel *chan, unsigned int delay)
2701 {
2702  int res = 0;
2703  enum ast_channel_state old_state;
2704  SCOPE_TRACE(1, "%s\n", ast_channel_name(chan));
2705 
2706  old_state = ast_channel_state(chan);
2707  if ((res = ast_raw_answer(chan))) {
2708  return res;
2709  }
2710 
2711  switch (old_state) {
2712  case AST_STATE_RINGING:
2713  case AST_STATE_RING:
2714  /* wait for media to start flowing, but don't wait any longer
2715  * than 'delay' or 500 milliseconds, whichever is longer
2716  */
2717  do {
2719  struct ast_frame *cur;
2720  struct ast_frame *new_frame;
2721  int timeout_ms = MAX(delay, 500);
2722  unsigned int done = 0;
2723  struct timeval start;
2724 
2726 
2727  start = ast_tvnow();
2728  for (;;) {
2729  int ms = ast_remaining_ms(start, timeout_ms);
2730  ms = ast_waitfor(chan, ms);
2731  if (ms < 0) {
2732  ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2733  res = -1;
2734  break;
2735  }
2736  if (ms == 0) {
2737  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));
2738  break;
2739  }
2740  cur = ast_read(chan);
2741  if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2742  (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2743  if (cur) {
2744  ast_frfree(cur);
2745  }
2746  res = -1;
2747  ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2748  break;
2749  }
2750 
2751  if ((new_frame = ast_frisolate(cur)) != cur) {
2752  ast_frfree(cur);
2753  }
2754 
2755  AST_LIST_INSERT_HEAD(&frames, new_frame, frame_list);
2756 
2757  /* if a specific delay period was requested, continue
2758  * until that delay has passed. don't stop just because
2759  * incoming media has arrived.
2760  */
2761  if (delay) {
2762  continue;
2763  }
2764 
2765  switch (new_frame->frametype) {
2766  /* all of these frametypes qualify as 'media' */
2767  case AST_FRAME_VOICE:
2768  case AST_FRAME_VIDEO:
2769  case AST_FRAME_TEXT:
2770  case AST_FRAME_TEXT_DATA:
2771  case AST_FRAME_DTMF_BEGIN:
2772  case AST_FRAME_DTMF_END:
2773  case AST_FRAME_IMAGE:
2774  case AST_FRAME_HTML:
2775  case AST_FRAME_MODEM:
2776  case AST_FRAME_RTCP:
2777  done = 1;
2778  break;
2779  case AST_FRAME_CONTROL:
2780  case AST_FRAME_IAX:
2783  case AST_FRAME_NULL:
2784  case AST_FRAME_CNG:
2785  break;
2786  }
2787 
2788  if (done) {
2789  break;
2790  }
2791  }
2792 
2793  ast_channel_lock(chan);
2794  while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2795  if (res == 0) {
2796  ast_queue_frame_head(chan, cur);
2797  }
2798  ast_frfree(cur);
2799  }
2800  ast_channel_unlock(chan);
2801  } while (0);
2802  break;
2803  default:
2804  break;
2805  }
2806 
2807  return res;
2808 }
2809 
2810 int ast_answer(struct ast_channel *chan)
2811 {
2812  SCOPE_TRACE(1, "%s\n", ast_channel_name(chan));
2813  return __ast_answer(chan, 0);
2814 }
2815 
2816 inline int ast_auto_answer(struct ast_channel *chan)
2817 {
2818  if (ast_channel_state(chan) == AST_STATE_UP) {
2819  /* Already answered */
2820  return 0;
2821  }
2822  return ast_answer(chan);
2823 }
2824 
2826 {
2827  ast_assert(NULL != chan);
2828 
2829  if (ast_tvzero(ast_channel_creationtime(chan))) {
2830  return 0;
2831  }
2833 }
2834 
2836 {
2837  return (ast_channel_get_duration_ms(chan) / 1000);
2838 }
2839 
2841 {
2842  ast_assert(NULL != chan);
2843 
2844  if (ast_tvzero(ast_channel_answertime(chan))) {
2845  return 0;
2846  }
2848 }
2849 
2851 {
2852  return (ast_channel_get_up_time_ms(chan) / 1000);
2853 }
2854 
2855 /*!
2856  * \brief Determine whether or not we have to trigger dtmf emulating using 50 fps timer events
2857  * especially when no voice frames are received during dtmf processing (direct media or muted
2858  * sender case using SIP INFO)
2859  */
2860 static inline int should_trigger_dtmf_emulating(struct ast_channel *chan)
2861 {
2863  /* We're in the middle of emulating a digit, or DTMF has been
2864  * explicitly deferred. Trigger dtmf with periodic 50 pfs timer events, then. */
2865  return 1;
2866  }
2867 
2868  if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
2870  /*
2871  * We're not in the middle of a digit, but it hasn't been long enough
2872  * since the last digit, so we'll have to trigger DTMF furtheron.
2873  * Using 2 times AST_MIN_DTMF_GAP to trigger readq reading for possible
2874  * buffered next dtmf event
2875  */
2876  return 1;
2877  }
2878 
2879  return 0;
2880 }
2881 
2882 static void deactivate_generator_nolock(struct ast_channel *chan)
2883 {
2884  if (ast_channel_generatordata(chan)) {
2885  struct ast_generator *generator = ast_channel_generator(chan);
2886 
2887  if (generator && generator->release) {
2888  generator->release(chan, ast_channel_generatordata(chan));
2889  }
2894  ast_settimeout(chan, 0, NULL, NULL);
2895  }
2896 }
2897 
2899 {
2900  ast_channel_lock(chan);
2902  if (should_trigger_dtmf_emulating(chan)) {
2903  /* if in the middle of dtmf emulation keep 50 tick per sec timer on rolling */
2905  }
2906  ast_channel_unlock(chan);
2907 }
2908 
2910 {
2911  struct ast_generator *generator;
2912 
2913  ast_channel_lock(chan);
2914  generator = ast_channel_generator(chan);
2915  if (generator && generator->write_format_change) {
2916  generator->write_format_change(chan, ast_channel_generatordata(chan));
2917  }
2918  ast_channel_unlock(chan);
2919 }
2920 
2921 static int generator_force(const void *data)
2922 {
2923  /* Called if generator doesn't have data */
2924  void *tmp;
2925  int res;
2926  int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2927  struct ast_channel *chan = (struct ast_channel *)data;
2928 
2929  ast_channel_lock(chan);
2930  tmp = ast_channel_generatordata(chan);
2932  if (ast_channel_generator(chan))
2933  generate = ast_channel_generator(chan)->generate;
2934  ast_channel_unlock(chan);
2935 
2936  if (!tmp || !generate) {
2937  return 0;
2938  }
2939 
2940  res = generate(chan, tmp, 0, ast_format_get_sample_rate(ast_channel_writeformat(chan)) / 50);
2941 
2942  ast_channel_lock(chan);
2943  if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
2944  ast_channel_generatordata_set(chan, tmp);
2945  }
2946  ast_channel_unlock(chan);
2947 
2948  if (res) {
2949  ast_debug(1, "Auto-deactivating generator\n");
2951  }
2952 
2953  return 0;
2954 }
2955 
2956 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2957 {
2958  int res = 0;
2959  void *generatordata = NULL;
2960 
2961  ast_channel_lock(chan);
2962  if (ast_channel_generatordata(chan)) {
2963  struct ast_generator *generator_old = ast_channel_generator(chan);
2964 
2965  if (generator_old && generator_old->release) {
2966  generator_old->release(chan, ast_channel_generatordata(chan));
2967  }
2968  }
2969  if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
2970  res = -1;
2971  }
2972  ast_channel_generatordata_set(chan, generatordata);
2973  if (!res) {
2974  ast_settimeout(chan, 50, generator_force, chan);
2975  ast_channel_generator_set(chan, gen);
2976  }
2977  ast_channel_unlock(chan);
2978 
2979  ast_prod(chan);
2980 
2981  return res;
2982 }
2983 
2984 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2985 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2986 {
2987  int winner = -1;
2988  ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2989  return winner;
2990 }
2991 
2992 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2993 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2994  int *exception, int *outfd, int *ms)
2995 {
2996  struct timeval start = { 0 , 0 };
2997  struct pollfd *pfds = NULL;
2998  int res;
2999  long rms;
3000  int x, y, max;
3001  int sz = nfds;
3002  struct timeval now = { 0, 0 };
3003  struct timeval whentohangup = { 0, 0 }, diff;
3004  struct ast_channel *winner = NULL;
3005  struct fdmap {
3006  int chan;
3007  int fdno;
3008  } *fdmap = NULL;
3009 
3010  if (outfd) {
3011  *outfd = -99999;
3012  }
3013  if (exception) {
3014  *exception = 0;
3015  }
3016 
3017  for (x = 0; x < n; x++) {
3018  ast_channel_lock(c[x]);
3019  if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3020  if (ast_tvzero(whentohangup))
3021  now = ast_tvnow();
3022  diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3023  if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3024  ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3025  /* Should already be hungup */
3027  ast_channel_unlock(c[x]);
3028  return c[x];
3029  }
3030  if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3031  whentohangup = diff;
3032  }
3033  sz += ast_channel_fd_count(c[x]);
3034  ast_channel_unlock(c[x]);
3035  }
3036 
3037  if (!sz) {
3038  return NULL;
3039  }
3040 
3041  pfds = ast_alloca(sizeof(*pfds) * sz);
3042  fdmap = ast_alloca(sizeof(*fdmap) * sz);
3043 
3044  /* Wait full interval */
3045  rms = *ms;
3046  /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3047  if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3048  rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3049  if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3050  rms = *ms;
3051  }
3052  } else if (!ast_tvzero(whentohangup) && rms < 0) {
3053  /* Tiny corner case... call would need to last >24 days */
3054  rms = INT_MAX;
3055  }
3056  /*
3057  * Build the pollfd array, putting the channels' fds first,
3058  * followed by individual fds. Order is important because
3059  * individual fd's must have priority over channel fds.
3060  */
3061  max = 0;
3062  for (x = 0; x < n; x++) {
3063  ast_channel_lock(c[x]);
3064  for (y = 0; y < ast_channel_fd_count(c[x]); y++) {
3065  fdmap[max].fdno = y; /* fd y is linked to this pfds */
3066  fdmap[max].chan = x; /* channel x is linked to this pfds */
3067  max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3068  }
3069  CHECK_BLOCKING(c[x]);
3070  ast_channel_unlock(c[x]);
3071  }
3072  /* Add the individual fds */
3073  for (x = 0; x < nfds; x++) {
3074  fdmap[max].chan = -1;
3075  max += ast_add_fd(&pfds[max], fds[x]);
3076  }
3077 
3078  if (*ms > 0) {
3079  start = ast_tvnow();
3080  }
3081 
3082  if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3083  do {
3084  int kbrms = rms;
3085  if (kbrms > 600000) {
3086  kbrms = 600000;
3087  }
3088  res = ast_poll(pfds, max, kbrms);
3089  if (!res) {
3090  rms -= kbrms;
3091  }
3092  } while (!res && (rms > 0));
3093  } else {
3094  res = ast_poll(pfds, max, rms);
3095  }
3096  for (x = 0; x < n; x++) {
3097  ast_channel_lock(c[x]);
3099  ast_channel_unlock(c[x]);
3100  }
3101  if (res < 0) { /* Simulate a timeout if we were interrupted */
3102  if (errno != EINTR) {
3103  *ms = -1;
3104  }
3105  return NULL;
3106  }
3107  if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3108  now = ast_tvnow();
3109  for (x = 0; x < n; x++) {
3110  if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3111  ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3113  if (winner == NULL) {
3114  winner = c[x];
3115  }
3116  }
3117  }
3118  }
3119  if (res == 0) { /* no fd ready, reset timeout and done */
3120  *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3121  return winner;
3122  }
3123  /*
3124  * Then check if any channel or fd has a pending event.
3125  * Remember to check channels first and fds last, as they
3126  * must have priority on setting 'winner'
3127  */
3128  for (x = 0; x < max; x++) {
3129  res = pfds[x].revents;
3130  if (res == 0) {
3131  continue;
3132  }
3133  if (fdmap[x].chan >= 0) { /* this is a channel */
3134  winner = c[fdmap[x].chan]; /* override previous winners */
3135  ast_channel_lock(winner);
3136  if (res & POLLPRI) {
3138  } else {
3140  }
3141  ast_channel_fdno_set(winner, fdmap[x].fdno);
3142  ast_channel_unlock(winner);
3143  } else { /* this is an fd */
3144  if (outfd) {
3145  *outfd = pfds[x].fd;
3146  }
3147  if (exception) {
3148  *exception = (res & POLLPRI) ? -1 : 0;
3149  }
3150  winner = NULL;
3151  }
3152  }
3153  if (*ms > 0) {
3154  *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3155  if (*ms < 0) {
3156  *ms = 0;
3157  }
3158  }
3159  return winner;
3160 }
3161 
3162 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3163 {
3164  return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3165 }
3166 
3167 int ast_waitfor(struct ast_channel *c, int ms)
3168 {
3169  if (ms < 0) {
3170  do {
3171  ms = 100000;
3172  ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3173  } while (!ms);
3174  } else {
3175  ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3176  }
3177  return ms;
3178 }
3179 
3180 int ast_waitfordigit(struct ast_channel *c, int ms)
3181 {
3182  return ast_waitfordigit_full(c, ms, NULL, -1, -1);
3183 }
3184 
3185 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3186 {
3187  return ast_settimeout_full(c, rate, func, data, 0);
3188 }
3189 
3190 int ast_settimeout_full(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data, unsigned int is_ao2_obj)
3191 {
3192  int res;
3193  unsigned int real_rate = rate, max_rate;
3194 
3195  ast_channel_lock(c);
3196 
3197  if (ast_channel_timingfd(c) == -1) {
3198  ast_channel_unlock(c);
3199  return -1;
3200  }
3201 
3202  if (!func) {
3203  rate = 0;
3204  data = NULL;
3205  }
3206 
3207  if (rate && rate > (max_rate = ast_timer_get_max_rate(ast_channel_timer(c)))) {
3208  real_rate = max_rate;
3209  }
3210 
3211  ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3212 
3213  res = ast_timer_set_rate(ast_channel_timer(c), real_rate);
3214 
3217  }
3218 
3219  ast_channel_timingfunc_set(c, func);
3220  ast_channel_timingdata_set(c, data);
3221 
3222  if (data && is_ao2_obj) {
3223  ao2_ref(data, 1);
3225  } else {
3227  }
3228 
3229  if (func == NULL && rate == 0 && ast_channel_fdno(c) == AST_TIMING_FD) {
3230  /* Clearing the timing func and setting the rate to 0
3231  * means that we don't want to be reading from the timingfd
3232  * any more. Setting c->fdno to -1 means we won't have any
3233  * errant reads from the timingfd, meaning we won't potentially
3234  * miss any important frames.
3235  */
3236  ast_channel_fdno_set(c, -1);
3237  }
3238 
3239  ast_channel_unlock(c);
3240 
3241  return res;
3242 }
3243 
3244 int ast_waitfordigit_full(struct ast_channel *c, int timeout_ms, const char *breakon, int audiofd, int cmdfd)
3245 {
3246  struct timeval start = ast_tvnow();
3247  int ms;
3248 
3249  /* Stop if we're a zombie or need a soft hangup */
3251  return -1;
3252 
3253  /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3255 
3256  /* Wait for a digit, no more than timeout_ms milliseconds total.
3257  * Or, wait indefinitely if timeout_ms is <0.
3258  */
3259  while ((ms = ast_remaining_ms(start, timeout_ms))) {
3260  struct ast_channel *rchan;
3261  int outfd = -1;
3262 
3263  errno = 0;
3264  /* While ast_waitfor_nandfds tries to help by reducing the timeout by how much was waited,
3265  * it is unhelpful if it waited less than a millisecond.
3266  */
3267  rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3268 
3269  if (!rchan && outfd < 0 && ms) {
3270  if (errno == 0 || errno == EINTR)
3271  continue;
3272  ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3274  return -1;
3275  } else if (outfd > -1) {
3276  /* The FD we were watching has something waiting */
3277  ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3279  return 1;
3280  } else if (rchan) {
3281  int res;
3282  struct ast_frame *f = ast_read(c);
3283 
3284  if (!f) {
3286 
3287  return -1;
3288  }
3289 
3290  switch (f->frametype) {
3291  case AST_FRAME_DTMF_BEGIN:
3292  break;
3293  case AST_FRAME_DTMF_END:
3294  res = f->subclass.integer;
3295  if (!breakon || strchr(breakon, res)) {
3296  ast_frfree(f);
3298  return res;
3299  }
3300  break;
3301  case AST_FRAME_CONTROL:
3302  switch (f->subclass.integer) {
3303  case AST_CONTROL_HANGUP:
3304  ast_frfree(f);
3306  return -1;
3312  /* Fall-through and treat as if it were a DTMF signal. Items
3313  * that perform stream control will handle this. */
3314  res = f->subclass.integer;
3315  ast_frfree(f);
3317  return res;
3319  case AST_CONTROL_RINGING:
3320  case AST_CONTROL_ANSWER:
3321  case AST_CONTROL_SRCUPDATE:
3322  case AST_CONTROL_SRCCHANGE:
3326  case AST_CONTROL_HOLD:
3327  case AST_CONTROL_UNHOLD:
3328  case AST_CONTROL_FLASH:
3329  case -1:
3330  /* Unimportant */
3331  break;
3332  default:
3333  ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3334  break;
3335  }
3336  break;
3337  case AST_FRAME_VOICE:
3338  /* Write audio if appropriate */
3339  if (audiofd > -1) {
3340  if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3341  ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3342  }
3343  }
3344  default:
3345  /* Ignore */
3346  break;
3347  }
3348  ast_frfree(f);
3349  }
3350  }
3351 
3353 
3354  return 0; /* Time is up */
3355 }
3356 
3360 };
3361 
3363 {
3364  switch (direction) {
3365  case DTMF_RECEIVED:
3366  return "Received";
3367  case DTMF_SENT:
3368  return "Sent";
3369  }
3370 
3371  return "?";
3372 }
3373 
3374 static void send_dtmf_begin_event(struct ast_channel *chan,
3375  enum DtmfDirection direction, const char digit)
3376 {
3377  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
3378  char digit_str[] = { digit, '\0' };
3379 
3380  blob = ast_json_pack("{ s: s, s: s }",
3381  "digit", digit_str,
3382  "direction", dtmf_direction_to_string(direction));
3383  if (!blob) {
3384  return;
3385  }
3386 
3388 }
3389 
3390 static void send_dtmf_end_event(struct ast_channel *chan,
3391  enum DtmfDirection direction, const char digit, long duration_ms)
3392 {
3393  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
3394  char digit_str[] = { digit, '\0' };
3395 
3396  blob = ast_json_pack("{ s: s, s: s, s: I }",
3397  "digit", digit_str,
3398  "direction", dtmf_direction_to_string(direction),
3399  "duration_ms", (ast_json_int_t)duration_ms);
3400  if (!blob) {
3401  return;
3402  }
3403 
3405 }
3406 
3407 static void send_flash_event(struct ast_channel *chan)
3408 {
3410 }
3411 
3412 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3413 {
3414  struct ast_generator *generator;
3415  void *gendata;
3416  int res;
3417  int samples;
3418 
3419  generator = ast_channel_generator(chan);
3420  if (!generator
3421  || !generator->generate
3422  || f->frametype != AST_FRAME_VOICE
3423  || !ast_channel_generatordata(chan)
3424  || ast_channel_timingfunc(chan)) {
3425  return;
3426  }
3427 
3428  /*
3429  * We must generate frames in phase locked mode since
3430  * we have no internal timer available.
3431  */
3433  float factor;
3435  samples = (int) (((float) f->samples) * factor);
3436  } else {
3437  samples = f->samples;
3438  }
3439 
3440  gendata = ast_channel_generatordata(chan);
3441  ast_channel_generatordata_set(chan, NULL); /* reset, to let writes go through */
3442 
3443  /*
3444  * This unlock is here based on two assumptions that hold true at
3445  * this point in the code. 1) this function is only called from
3446  * within __ast_read() and 2) all generators call ast_write() in
3447  * their generate callback.
3448  *
3449  * The reason this is added is so that when ast_write is called,
3450  * the lock that occurs there will not recursively lock the
3451  * channel. Doing this will allow deadlock avoidance to work in
3452  * deeper functions.
3453  */
3454  ast_channel_unlock(chan);
3455  res = generator->generate(chan, gendata, f->datalen, samples);
3456  ast_channel_lock(chan);
3457  if (generator == ast_channel_generator(chan)) {
3458  ast_channel_generatordata_set(chan, gendata);
3459  if (res) {
3460  ast_debug(1, "Auto-deactivating generator\n");
3462  }
3463  }
3464 }
3465 
3466 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3467 {
3468  struct ast_frame *fr = ast_channel_dtmff(chan);
3469 
3471  fr->subclass.integer = f->subclass.integer;
3472  fr->len = f->len;
3473 
3474  /* The only time this function will be called is for a frame that just came
3475  * out of the channel driver. So, we want to stick it on the tail of the
3476  * readq. */
3477 
3478  ast_queue_frame(chan, fr);
3479 }
3480 
3481 /*!
3482  * \brief Determine whether or not we should ignore DTMF in the readq
3483  */
3484 static inline int should_skip_dtmf(struct ast_channel *chan)
3485 {
3487  /* We're in the middle of emulating a digit, or DTMF has been
3488  * explicitly deferred. Skip this digit, then. */
3489  return 1;
3490  }
3491 
3492  if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
3494  /* We're not in the middle of a digit, but it hasn't been long enough
3495  * since the last digit, so we'll have to skip DTMF for now. */
3496  return 1;
3497  }
3498 
3499  return 0;
3500 }
3501 
3502 /*!
3503  * \brief calculates the number of samples to jump forward with in a monitor stream.
3504 
3505  * \note When using ast_seekstream() with the read and write streams of a monitor,
3506  * the number of samples to seek forward must be of the same sample rate as the stream
3507  * or else the jump will not be calculated correctly.
3508  *
3509  * \retval number of samples to seek forward after rate conversion.
3510  */
3511 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3512 {
3513  int diff = sample_rate - seek_rate;
3514 
3515  if (diff > 0) {
3516  samples = samples / (float) (sample_rate / seek_rate);
3517  } else if (diff < 0) {
3518  samples = samples * (float) (seek_rate / sample_rate);
3519  }
3520 
3521  return samples;
3522 }
3523 
3524 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio, int dropnondefault)
3525 {
3526  struct ast_frame *f = NULL; /* the return value */
3527  int prestate;
3528  int cause = 0;
3529  struct ast_stream *stream = NULL, *default_stream = NULL;
3530 
3531  /* this function is very long so make sure there is only one return
3532  * point at the end (there are only two exceptions to this).
3533  */
3534  ast_channel_lock(chan);
3535 
3536  /* Stop if we're a zombie or need a soft hangup */
3538  if (ast_channel_generator(chan))
3540 
3541  /*
3542  * It is possible for chan->_softhangup to be set and there
3543  * still be control frames that need to be read. Instead of
3544  * just going to 'done' in the case of ast_check_hangup(), we
3545  * need to queue the end-of-Q frame so that it can mark the end
3546  * of the read queue. If there are frames to be read,
3547  * ast_queue_control() will be called repeatedly, but will only
3548  * queue the first end-of-Q frame.
3549  */
3552  } else {
3553  goto done;
3554  }
3555  } else {
3556 #ifdef AST_DEVMODE
3557  /*
3558  * The ast_waitfor() code records which of the channel's file
3559  * descriptors reported that data is available. In theory,
3560  * ast_read() should only be called after ast_waitfor() reports
3561  * that a channel has data available for reading. However,
3562  * there still may be some edge cases throughout the code where
3563  * ast_read() is called improperly. This can potentially cause
3564  * problems, so if this is a developer build, make a lot of
3565  * noise if this happens so that it can be addressed.
3566  *
3567  * One of the potential problems is blocking on a dead channel.
3568  */
3569  if (ast_channel_fdno(chan) == -1) {
3571  "ast_read() on chan '%s' called with no recorded file descriptor.\n",
3572  ast_channel_name(chan));
3573  }
3574 #endif
3575  }
3576 
3577  prestate = ast_channel_state(chan);
3578 
3579  if (ast_channel_timingfd(chan) > -1 && ast_channel_fdno(chan) == AST_TIMING_FD) {
3580  enum ast_timer_event res;
3581  int trigger_dtmf_emulating = should_trigger_dtmf_emulating(chan);
3582 
3584 
3586 
3587  switch (res) {
3589  if (ast_timer_ack(ast_channel_timer(chan), 1) < 0) {
3590  ast_log(LOG_ERROR, "Failed to acknoweldge timer in ast_read\n");
3591  goto done;
3592  }
3593 
3594  if (ast_channel_timingfunc(chan)) {
3595  /* save a copy of func/data before unlocking the channel */
3597  void *data = ast_channel_timingdata(chan);
3598  int got_ref = 0;
3600  ao2_ref(data, 1);
3601  got_ref = 1;
3602  }
3603  ast_channel_fdno_set(chan, -1);
3604  ast_channel_unlock(chan);
3605  func(data);
3606  if (got_ref) {
3607  ao2_ref(data, -1);
3608  }
3609 
3610  if (trigger_dtmf_emulating) {
3611  /*
3612  * Since we're breaking out of this switch block and not
3613  * returning, we need to re-lock the channel.
3614  */
3615  ast_channel_lock(chan);
3616  /* generate null frame to trigger dtmf emulating */
3617  f = &ast_null_frame;
3618  break;
3619  }
3620  } else if (trigger_dtmf_emulating) {
3621  /* generate null frame to trigger dtmf emualating */
3622  f = &ast_null_frame;
3623  break;
3624  } else {
3626  /* generate very last null frame to trigger dtmf emulating */
3627  f = &ast_null_frame;
3628  break;
3629  }
3630 
3631  /* cannot 'goto done' because the channel is already unlocked */
3632  return &ast_null_frame;
3633 
3635  if (AST_LIST_EMPTY(ast_channel_readq(chan)) ||
3638  }
3639  break;
3640  }
3641 
3643  /* if the AST_GENERATOR_FD is set, call the generator with args
3644  * set to -1 so it can do whatever it needs to.
3645  */
3646  void *tmp = ast_channel_generatordata(chan);
3647  ast_channel_generatordata_set(chan, NULL); /* reset to let ast_write get through */
3648  ast_channel_generator(chan)->generate(chan, tmp, -1, -1);
3649  ast_channel_generatordata_set(chan, tmp);
3650  f = &ast_null_frame;
3651  ast_channel_fdno_set(chan, -1);
3652  goto done;
3655  }
3656 
3657  /* Read and ignore anything on the alertpipe, but read only
3658  one sizeof(blah) per frame that we send from it */
3660  f = &ast_null_frame;
3661  goto done;
3662  }
3663 
3664  /* Check for pending read queue */
3665  if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
3666  int skipped_dtmf_frame = 0;
3667  int skip_dtmf = should_skip_dtmf(chan);
3668 
3670  /* We have to be picky about which frame we pull off of the readq because
3671  * there are cases where we want to leave DTMF frames on the queue until
3672  * some later time. */
3673 
3674  if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3675  skipped_dtmf_frame = 1;
3676  continue;
3677  }
3678 
3680  break;
3681  }
3683 
3684  if (!f) {
3685  /* There were no acceptable frames on the readq. */
3686  f = &ast_null_frame;
3687  if (!skipped_dtmf_frame) {
3688  /*
3689  * Do not trigger alert pipe if only buffered dtmf begin or end frames
3690  * are left in the readq.
3691  */
3693  } else {
3694  /*
3695  * Safely disable continous timer events if only buffered dtmf begin or end
3696  * frames are left in the readq.
3697  */
3699  }
3700  }
3701 
3702  /* Interpret hangup and end-of-Q frames to return NULL */
3703  /* XXX why not the same for frames from the channel ? */
3704  if (f->frametype == AST_FRAME_CONTROL) {
3705  switch (f->subclass.integer) {
3706  case AST_CONTROL_HANGUP:
3708  cause = f->data.uint32;
3709  /* Fall through */
3710  case AST_CONTROL_END_OF_Q:
3711  ast_frfree(f);
3712  f = NULL;
3713  break;
3714  default:
3715  break;
3716  }
3717  } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
3718  if (ast_channel_tech(chan) && ast_channel_tech(chan)->read_stream) {
3721  } else {
3722  /* Since this channel driver does not support multistream determine the default stream this frame
3723  * originated from and update the frame to include it.
3724  */
3725  stream = default_stream = ast_channel_get_default_stream(chan, ast_format_get_type(f->subclass.format));
3726  /* In order to allow media to be passed up the underlying media type has to have a format negotiated on
3727  * the channel itself. In cases where this hasn't happened the channel driver is incorrectly passing up
3728  * a frame for a format that has not been negotiated. If this occurs just drop the frame as we have no
3729  * stream that it came from.
3730  */
3731  if (!stream) {
3732  ast_frfree(f);
3733  f = &ast_null_frame;
3734  } else {
3735  f->stream_num = ast_stream_get_position(stream);
3736  }
3737  }
3738  }
3739  } else {
3741  if (ast_channel_tech(chan)->exception)
3742  f = ast_channel_tech(chan)->exception(chan);
3743  else {
3744  ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", ast_channel_name(chan));
3745  f = &ast_null_frame;
3746  }
3747  /* Clear the exception flag */
3749  } else if (ast_channel_tech(chan) && ast_channel_tech(chan)->read_stream) {
3750  f = ast_channel_tech(chan)->read_stream(chan);
3751 
3752  /* This channel driver supports multistream so the stream_num on the frame is valid, the only
3753  * thing different is that we need to find the default stream so we know whether to invoke the
3754  * default stream logic or not (such as transcoding).
3755  */
3756  if (f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
3759  }
3760  } else if (ast_channel_tech(chan) && ast_channel_tech(chan)->read) {
3761  f = ast_channel_tech(chan)->read(chan);
3762 
3763  /* Since this channel driver does not support multistream determine the default stream this frame
3764  * originated from and update the frame to include it.
3765  */
3766  if (f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
3767  stream = default_stream = ast_channel_get_default_stream(chan, ast_format_get_type(f->subclass.format));
3768  if (!stream) {
3769  ast_frfree(f);
3770  f = &ast_null_frame;
3771  } else {
3772  f->stream_num = ast_stream_get_position(stream);
3773  }
3774  }
3775  }
3776  else
3777  ast_log(LOG_WARNING, "No read routine on channel %s\n", ast_channel_name(chan));
3778  }
3779 
3780  if (stream == default_stream) {
3781  /* Perform the framehook read event here. After the frame enters the framehook list
3782  * there is no telling what will happen, <insert mad scientist laugh here>!!! */
3784  }
3785 
3786  /*
3787  * Reset the recorded file descriptor that triggered this read so that we can
3788  * easily detect when ast_read() is called without properly using ast_waitfor().
3789  */
3790  ast_channel_fdno_set(chan, -1);
3791 
3792  if (f) {
3793  struct ast_frame *readq_tail = AST_LIST_LAST(ast_channel_readq(chan));
3794  struct ast_control_read_action_payload *read_action_payload;
3795  struct ast_party_connected_line connected;
3796  int hooked = 0;
3797 
3798  /* if the channel driver returned more than one frame, stuff the excess
3799  into the readq for the next ast_read call
3800  */
3801  if (AST_LIST_NEXT(f, frame_list)) {
3805  }
3806 
3807  if (dropnondefault && stream != default_stream) {
3808  /* If the frame originates from a non-default stream and the caller can not handle other streams
3809  * absorb the frame and replace it with a null one instead.
3810  */
3811  ast_frfree(f);
3812  f = &ast_null_frame;
3813  }
3814 
3815  switch (f->frametype) {
3816  case AST_FRAME_CONTROL:
3817  if (f->subclass.integer == AST_CONTROL_ANSWER) {
3818  if (prestate == AST_STATE_UP && ast_channel_is_bridged(chan)) {
3819  ast_debug(1, "Dropping duplicate answer!\n");
3820  ast_frfree(f);
3821  f = &ast_null_frame;
3822  } else {
3823  /*
3824  * Mark when outgoing channel answered so we can know how
3825  * long the channel has been up.
3826  */
3828 
3829  ast_setstate(chan, AST_STATE_UP);
3830  }
3831  } else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
3832  read_action_payload = f->data.ptr;
3833  switch (read_action_payload->action) {
3835  ast_party_connected_line_init(&connected);
3837  if (ast_connected_line_parse_data(read_action_payload->payload,
3838  read_action_payload->payload_size, &connected)) {
3839  ast_party_connected_line_free(&connected);
3840  break;
3841  }
3842  ast_channel_unlock(chan);
3843  if (ast_channel_connected_line_sub(NULL, chan, &connected, 0) &&
3844  ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
3846  read_action_payload->payload,
3847  read_action_payload->payload_size);
3848  }
3849  ast_party_connected_line_free(&connected);
3850  ast_channel_lock(chan);
3851  break;
3853  ast_channel_unlock(chan);
3854  ast_sendtext(chan, (const char *)read_action_payload->payload);
3855  ast_channel_lock(chan);
3856  break;
3858  ast_channel_unlock(chan);
3859  ast_sendtext_data(chan, (struct ast_msg_data *)read_action_payload->payload);
3860  ast_channel_lock(chan);
3861  break;
3862  }
3863  ast_frfree(f);
3864  f = &ast_null_frame;
3865  } else if (f->subclass.integer == AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE && dropnondefault) {
3866  /* The caller of this function is incapable of handling streams so we don't accept the change request
3867  * and stick to the streams currently on the channel.
3868  */
3870  ast_frfree(f);
3871  f = &ast_null_frame;
3872  } else if (f->subclass.integer == AST_CONTROL_STREAM_TOPOLOGY_CHANGED && dropnondefault) {
3873  /* The caller of this function is incapable of handling streams so we absorb the notification that the
3874  * stream topology has changed.
3875  */
3876  ast_frfree(f);
3877  f = &ast_null_frame;
3878  } else if (f->subclass.integer == AST_CONTROL_FLASH) {
3879  send_flash_event(chan);
3880  }
3881  break;
3882  case AST_FRAME_DTMF_END:
3884  ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, ast_channel_name(chan), f->len);
3885  /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3887  queue_dtmf_readq(chan, f);
3888  ast_frfree(f);
3889  f = &ast_null_frame;
3891  if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
3893  /* If it hasn't been long enough, defer this digit */
3894  queue_dtmf_readq(chan, f);
3895  ast_frfree(f);
3896  f = &ast_null_frame;
3897  } else {
3898  /* There was no begin, turn this into a begin and send the end later */
3899  struct timeval tv = ast_tvnow();
3903  ast_channel_dtmf_tv_set(chan, &tv);
3904  if (f->len) {
3905  if (f->len > option_dtmfminduration)
3907  else
3909  } else
3911  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));
3912 
3913  /*
3914  * Start generating 50 fps timer events (null frames) for dtmf emulating
3915  * independently from any existing incoming voice frames.
3916  * If channel generator is already activated in regular mode use these
3917  * timer events to generate null frames.
3918  */
3919  if (!ast_channel_generator(chan)) {
3921  }
3922  }
3923  if (ast_channel_audiohooks(chan)) {
3924  struct ast_frame *old_frame = f;
3925  /*!
3926  * \todo XXX It is possible to write a digit to the audiohook twice
3927  * if the digit was originally read while the channel was in autoservice. */
3929  if (old_frame != f)
3930  ast_frfree(old_frame);
3931  }
3932  } else {
3933  struct timeval now = ast_tvnow();
3935  ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
3937  if (!f->len)
3938  f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
3939 
3940  /* detect tones that were received on
3941  * the wire with durations shorter than
3942  * option_dtmfminduration and set f->len
3943  * to the actual duration of the DTMF
3944  * frames on the wire. This will cause
3945  * dtmf emulation to be triggered later
3946  * on.
3947  */
3949  f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
3950  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));
3951  }
3952  } else if (!f->len) {
3953  ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
3955  }
3957  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));
3961  ast_frfree(f);
3962  f = &ast_null_frame;
3963 
3964  /* Start generating 50 fps timer events (null frames) for dtmf emulating
3965  * independently from any existing incoming voice frames.
3966  * If channel generator is already activated in regular mode use these
3967  * timer events to generate null frames.
3968  */
3969  if (!ast_channel_generator(chan)) {
3971  }
3972  } else {
3973  ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
3974  if (f->len < option_dtmfminduration) {
3976  }
3977  ast_channel_dtmf_tv_set(chan, &now);
3978 
3979  /* Start generating 50 fps timer events (null frames) for dtmf emulating
3980  * independently from any existing incoming voice frames.
3981  * If channel generator is already activated in regular mode use these
3982  * timer events to generate null frames.
3983  */
3984  if (!ast_channel_generator(chan)) {
3986  }
3987  }
3988  if (ast_channel_audiohooks(chan)) {
3989  struct ast_frame *old_frame = f;
3991  if (old_frame != f)
3992  ast_frfree(old_frame);
3993  }
3994  }
3995  break;
3996  case AST_FRAME_DTMF_BEGIN:
3998  ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, ast_channel_name(chan));
4000  (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
4002  ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
4003  ast_frfree(f);
4004  f = &ast_null_frame;
4005  } else {
4006  struct timeval now = ast_tvnow();
4008  ast_channel_dtmf_tv_set(chan, &now);
4009  ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
4010  }
4011  break;
4012  case AST_FRAME_NULL:
4013  /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
4014  * is reached , because we want to make sure we pass at least one
4015  * voice frame through before starting the next digit, to ensure a gap
4016  * between DTMF digits. */
4018  struct timeval now = ast_tvnow();
4019  if (!ast_channel_emulate_dtmf_duration(chan)) {
4022  } else if (ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan)) >= ast_channel_emulate_dtmf_duration(chan)) {
4024  ast_frfree(f);
4025  f = ast_channel_dtmff(chan);
4028  f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
4029  ast_channel_dtmf_tv_set(chan, &now);
4032  ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, ast_channel_name(chan));
4033  if (ast_channel_audiohooks(chan)) {
4034  struct ast_frame *old_frame = f;
4036  if (old_frame != f) {
4037  ast_frfree(old_frame);
4038  }
4039  }
4040 
4041  /* Start generating 50 fps timer events (null frames) for dtmf emulating
4042  * independently from any existing incoming voice frames.
4043  * If channel generator is already activated in regular mode use these
4044  * timer events to generate null frames.
4045  */
4046  if (!ast_channel_generator(chan)) {
4048  }
4049  }
4050  }
4051  break;
4052  case AST_FRAME_VOICE:
4053  /* If media was received from a non-default stream don't perform any actions, let it just go through */
4054  if (stream != default_stream) {
4055  break;
4056  }
4057 
4058  /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
4059  * is reached , because we want to make sure we pass at least one
4060  * voice frame through before starting the next digit, to ensure a gap
4061  * between DTMF digits. */
4065  }
4066 
4067  if (dropaudio || ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF)) {
4068  if (dropaudio)
4069  ast_read_generator_actions(chan, f);
4070  ast_frfree(f);
4071  f = &ast_null_frame;
4072  }
4073 
4075  struct timeval now = ast_tvnow();
4078  ast_frfree(f);
4079  f = ast_channel_dtmff(chan);
4082  f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
4083  ast_channel_dtmf_tv_set(chan, &now);
4084  if (ast_channel_audiohooks(chan)) {
4085  struct ast_frame *old_frame = f;
4087  if (old_frame != f)
4088  ast_frfree(old_frame);
4089  }
4090  ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, ast_channel_name(chan));
4091  } else {
4092  /* Drop voice frames while we're still in the middle of the digit */
4093  ast_frfree(f);
4094  f = &ast_null_frame;
4095  }
4096  break;
4097  }
4098  if (f->frametype != AST_FRAME_VOICE) {
4099  break;
4100  }
4103  struct ast_format *core_format;
4104 
4105  /*
4106  * Note: This frame may not be one of the current native
4107  * formats. We may have gotten it out of the read queue from
4108  * a previous multi-frame translation, from a framehook
4109  * injected frame, or the device we're talking to isn't
4110  * respecting negotiated formats. Regardless we will accept
4111  * all frames.
4112  *
4113  * Update the read translation path to handle the new format
4114  * that just came in. If the core wants slinear we need to
4115  * setup a new translation path because the core is usually
4116  * doing something with the audio itself and may not handle
4117  * any other format. e.g., Softmix bridge, holding bridge
4118  * announcer channel, recording, AMD... Otherwise, we'll
4119  * setup to pass the frame as is to the core. In this case
4120  * the core doesn't care. The channel is likely in
4121  * autoservice, safesleep, or the channel is in a bridge.
4122  * Let the bridge technology deal with format compatibility
4123  * between the channels in the bridge.
4124  *
4125  * Beware of the transcode_via_slin and genericplc options as
4126  * they force any transcoding to go through slin on a bridge.
4127  * Unfortunately transcode_via_slin is enabled by default and
4128  * genericplc is enabled in the codecs.conf.sample file.
4129  *
4130  * XXX Only updating translation to slinear frames has some
4131  * corner cases if slinear is one of the native formats and
4132  * there are different sample rates involved. We might wind
4133  * up with conflicting translation paths between channels
4134  * where the read translation path on this channel reduces
4135  * the sample rate followed by a write translation path on
4136  * the peer channel that increases the sample rate.
4137  */
4138  core_format = ast_channel_readformat(chan);
4139  if (!ast_format_cache_is_slinear(core_format)) {
4140  core_format = f->subclass.format;
4141  }
4142  if (ast_set_read_format_path(chan, f->subclass.format, core_format)) {
4143  /* Drop frame. We couldn't make it compatible with the core. */
4144  ast_frfree(f);
4145  f = &ast_null_frame;
4146  break;
4147  }
4148  }
4149  /*
4150  * Send frame to audiohooks if present, if frametype is linear, to preserve
4151  * functional compatibility with previous behavior. If not linear, hold off
4152  * until transcoding is done where we are more likely to have a linear frame
4153  */
4155  /* Place hooked after declaration */
4156  struct ast_frame *old_frame = f;
4157  hooked = 1;
4158 
4160  if (old_frame != f) {
4161  ast_frfree(old_frame);
4162  }
4163  }
4164 
4165  if (ast_channel_monitor(chan) && ast_channel_monitor(chan)->read_stream) {
4166  /* XXX what does this do ? */
4167 #ifndef MONITOR_CONSTANT_DELAY
4168  int jump = ast_channel_outsmpl(chan) - ast_channel_insmpl(chan) - 4 * f->samples;
4169  if (jump >= 0) {
4172  ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
4173  if (ast_seekstream(ast_channel_monitor(chan)->read_stream, jump, SEEK_FORCECUR) == -1) {
4174  ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
4175  }
4177  } else {
4179  }
4180 #else
4181  int jump = calc_monitor_jump((ast_channel_outsmpl(chan) - ast_channel_insmpl(chan)),
4183  ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
4184  if (jump - MONITOR_DELAY >= 0) {
4185  if (ast_seekstream(ast_channel_monitor(chan)->read_stream, jump - f->samples, SEEK_FORCECUR) == -1) {
4186  ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
4187  }
4189  } else {
4190  ast_channel_insmpl(chan) += f->samples;
4191  }
4192 #endif
4194  if (ast_writestream(ast_channel_monitor(chan)->read_stream, f) < 0)
4195  ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
4196  }
4197  }
4198 
4199  if (ast_channel_readtrans(chan)
4201  f = ast_translate(ast_channel_readtrans(chan), f, 1);
4202  if (!f) {
4203  f = &ast_null_frame;
4204  }
4205  }
4206 
4207  /* Second chance at hooking a linear frame, also the last chance */
4208  if (ast_channel_audiohooks(chan) && !hooked) {
4209  struct ast_frame *old_frame = f;
4210 
4212  if (old_frame != f) {
4213  ast_frfree(old_frame);
4214  }
4215  }
4216 
4217  /*
4218  * It is possible for the translation process on the channel to have
4219  * produced multiple frames from the single input frame we passed it; if
4220  * this happens, queue the additional frames *before* the frames we may
4221  * have queued earlier. if the readq was empty, put them at the head of
4222  * the queue, and if it was not, put them just after the frame that was
4223  * at the end of the queue.
4224  */
4225  if (AST_LIST_NEXT(f, frame_list)) {
4226  struct ast_frame *cur, *multi_frame = AST_LIST_NEXT(f, frame_list);
4227 
4228  /* Mark these frames as being re-queued */
4229  for (cur = multi_frame; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
4231  }
4232 
4233  if (!readq_tail) {
4234  ast_queue_frame_head(chan, multi_frame);
4235  } else {
4236  __ast_queue_frame(chan, multi_frame, 0, readq_tail);
4237  }
4238  ast_frfree(multi_frame);
4240  }
4241 
4242  /*
4243  * Run generator sitting on the line if timing device not available
4244  * and synchronous generation of outgoing frames is necessary
4245  */
4246  ast_read_generator_actions(chan, f);
4247  break;
4248  case AST_FRAME_RTCP:
4249  /* Incoming RTCP feedback needs to get to the translator for
4250  * outgoing media, which means we treat it as an ast_write */
4251  if (ast_channel_writetrans(chan)) {
4253  }
4254  break;
4255  default:
4256  /* Just pass it on! */
4257  break;
4258  }
4259  } else {
4260  /* Make sure we always return NULL in the future */
4263  }
4264  if (cause)
4265  ast_channel_hangupcause_set(chan, cause);
4266  if (ast_channel_generator(chan))
4268  /* We no longer End the CDR here */
4269  }
4270 
4271  /* High bit prints debugging */
4272  if (ast_channel_fin(chan) & DEBUGCHAN_FLAG)
4273  ast_frame_dump(ast_channel_name(chan), f, "<<");
4275 
4276 done:
4278  ast_channel_generator(chan)->digit(chan, f->subclass.integer);
4279 
4281  /* The list gets recreated if audiohooks are added again later */
4284  }
4285  ast_channel_unlock(chan);
4286  return f;
4287 }
4288 
4289 struct ast_frame *ast_read(struct ast_channel *chan)
4290 {
4291  return __ast_read(chan, 0, 1);
4292 }
4293 
4295 {
4296  return __ast_read(chan, 0, 0);
4297 }
4298 
4300 {
4301  return __ast_read(chan, 1, 1);
4302 }
4303 
4305 {
4306  return __ast_read(chan, 1, 0);
4307 }
4308 
4309 int ast_indicate(struct ast_channel *chan, int condition)
4310 {
4311  return ast_indicate_data(chan, condition, NULL, 0);
4312 }
4313 
4315 {
4316  /* Don't include a default case here so that we get compiler warnings
4317  * when a new type is added. */
4318 
4319  switch (condition) {
4320  case AST_CONTROL_PROGRESS:
4322  case AST_CONTROL_VIDUPDATE:
4323  case AST_CONTROL_SRCUPDATE:
4324  case AST_CONTROL_SRCCHANGE:
4325  case AST_CONTROL_RADIO_KEY:
4327  case AST_CONTROL_OPTION:
4328  case AST_CONTROL_WINK:
4329  case AST_CONTROL_FLASH:
4330  case AST_CONTROL_OFFHOOK:
4332  case AST_CONTROL_ANSWER:
4333  case AST_CONTROL_HANGUP:
4336  case AST_CONTROL_TRANSFER:
4338  case _XXX_AST_CONTROL_T38:
4339  case AST_CONTROL_CC:
4341  case AST_CONTROL_AOC:
4342  case AST_CONTROL_END_OF_Q:
4343  case AST_CONTROL_MCID:
4359  break;
4360 
4363  case AST_CONTROL_BUSY:
4364  case AST_CONTROL_RINGING:
4365  case AST_CONTROL_RING:
4366  case AST_CONTROL_HOLD:
4367  /* You can hear these */
4368  return 1;
4369 
4370  case AST_CONTROL_UNHOLD:
4371  /* This is a special case. You stop hearing this. */
4372  break;
4373  }
4374 
4375  return 0;
4376 }
4377 
4378 void ast_channel_hangupcause_hash_set(struct ast_channel *chan, const struct ast_control_pvt_cause_code *cause_code, int datalen)
4379 {
4380  char causevar[256];
4381 
4382  if (ast_channel_dialed_causes_add(chan, cause_code, datalen)) {
4383  ast_log(LOG_WARNING, "Unable to store hangup cause for %s on %s\n", cause_code->chan_name, ast_channel_name(chan));
4384  }
4385 
4386  if (cause_code->emulate_sip_cause) {
4387  snprintf(causevar, sizeof(causevar), "HASH(SIP_CAUSE,%s)", cause_code->chan_name);
4388  ast_func_write(chan, causevar, cause_code->code);
4389  }
4390 }
4391 
4393 {
4394  if (!strcasecmp(flag, "default"))
4395  return DEFAULT_AMA_FLAGS;
4396  if (!strcasecmp(flag, "omit"))
4397  return AST_AMA_OMIT;
4398  if (!strcasecmp(flag, "billing"))
4399  return AST_AMA_BILLING;
4400  if (!strcasecmp(flag, "documentation"))
4401  return AST_AMA_DOCUMENTATION;
4402  return AST_AMA_NONE;
4403 }
4404 
4406 {
4407  switch (flag) {
4408  case AST_AMA_OMIT:
4409  return "OMIT";
4410  case AST_AMA_BILLING:
4411  return "BILLING";
4412  case AST_AMA_DOCUMENTATION:
4413  return "DOCUMENTATION";
4414  default:
4415  return "Unknown";
4416  }
4417 }
4418 
4419 /*!
4420  * \internal
4421  * \brief Preprocess connected line update.
4422  * \since 12.0.0
4423  *
4424  * \param chan channel to change the indication
4425  * \param data pointer to payload data
4426  * \param datalen size of payload data
4427  *
4428  * \note This function assumes chan is locked.
4429  *
4430  * \retval 0 keep going.
4431  * \retval -1 quit now.
4432  */
4433 static int indicate_connected_line(struct ast_channel *chan, const void *data, size_t datalen)
4434 {
4435  struct ast_party_connected_line *chan_connected = ast_channel_connected(chan);
4436  struct ast_party_connected_line *chan_indicated = ast_channel_connected_indicated(chan);
4437  struct ast_party_connected_line connected;
4438  unsigned char current[1024];
4439  unsigned char proposed[1024];
4440  int current_size;
4441  int proposed_size;
4442  int res;
4443 
4444  ast_party_connected_line_set_init(&connected, chan_connected);
4445  res = ast_connected_line_parse_data(data, datalen, &connected);
4446  if (!res) {
4447  ast_channel_set_connected_line(chan, &connected, NULL);
4448  }
4449  ast_party_connected_line_free(&connected);
4450  if (res) {
4451  return -1;
4452  }
4453 
4454  current_size = ast_connected_line_build_data(current, sizeof(current),
4455  chan_indicated, NULL);
4456  proposed_size = ast_connected_line_build_data(proposed, sizeof(proposed),
4457  chan_connected, NULL);
4458  if (current_size == -1 || proposed_size == -1) {
4459  return -1;
4460  }
4461 
4462  if (current_size == proposed_size && !memcmp(current, proposed, current_size)) {
4463  ast_debug(1, "%s: Dropping redundant connected line update \"%s\" <%s>.\n",
4464  ast_channel_name(chan),
4465  S_COR(chan_connected->id.name.valid, chan_connected->id.name.str, ""),
4466  S_COR(chan_connected->id.number.valid, chan_connected->id.number.str, ""));
4467  return -1;
4468  }
4469 
4470  ast_party_connected_line_copy(chan_indicated, chan_connected);
4471  return 0;
4472 }
4473 
4474 /*!
4475  * \internal
4476  * \brief Preprocess redirecting update.
4477  * \since 12.0.0
4478  *
4479  * \param chan channel to change the indication
4480  * \param data pointer to payload data
4481  * \param datalen size of payload data
4482  *
4483  * \note This function assumes chan is locked.
4484  *
4485  * \retval 0 keep going.
4486  * \retval -1 quit now.
4487  */
4488 static int indicate_redirecting(struct ast_channel *chan, const void *data, size_t datalen)
4489 {
4490  struct ast_party_redirecting redirecting;
4491  int res;
4492 
4494  res = ast_redirecting_parse_data(data, datalen, &redirecting);
4495  if (!res) {
4496  ast_channel_set_redirecting(chan, &redirecting, NULL);
4497  }
4498  ast_party_redirecting_free(&redirecting);
4499  return res ? -1 : 0;
4500 }
4501 
4502 static int indicate_data_internal(struct ast_channel *chan, int _condition, const void *data, size_t datalen)
4503 {
4504  /* By using an enum, we'll get compiler warnings for values not handled
4505  * in switch statements. */
4506  enum ast_control_frame_type condition = _condition;
4507  struct ast_tone_zone_sound *ts = NULL;
4508  const struct ast_control_t38_parameters *t38_parameters;
4509  int res;
4510 
4511  switch (condition) {
4513  if (indicate_connected_line(chan, data, datalen)) {
4514  res = 0;
4515  return res;
4516  }
4517  break;
4519  if (indicate_redirecting(chan, data, datalen)) {
4520  res = 0;
4521  return res;
4522  }
4523  break;
4524  case AST_CONTROL_HOLD:
4525  case AST_CONTROL_UNHOLD:
4526  ast_channel_hold_state_set(chan, _condition);
4527  break;
4529  t38_parameters = data;
4530  switch (t38_parameters->request_response) {
4532  case AST_T38_NEGOTIATED:
4534  break;
4536  case AST_T38_TERMINATED:
4537  case AST_T38_REFUSED:
4539  break;
4540  default:
4541  break;
4542  }
4543  break;
4544  default:
4545  break;
4546  }
4547 
4548  if (is_visible_indication(condition)) {
4549  /* A new visible indication is requested. */
4550  ast_channel_visible_indication_set(chan, _condition);
4551  } else if (condition == AST_CONTROL_UNHOLD || _condition < 0) {
4552  /* Visible indication is cleared/stopped. */
4554  }
4555 
4556  if (ast_channel_tech(chan)->indicate) {
4557  /* See if the channel driver can handle this condition. */
4558  res = ast_channel_tech(chan)->indicate(chan, _condition, data, datalen);
4559  } else {
4560  res = -1;
4561  }
4562 
4563  if (!res) {
4564  /* The channel driver successfully handled this indication */
4565  res = 0;
4566  return res;
4567  }
4568 
4569  /* The channel driver does not support this indication, let's fake
4570  * it by doing our own tone generation if applicable. */
4571 
4572  /*!\note If we compare the enumeration type, which does not have any
4573  * negative constants, the compiler may optimize this code away.
4574  * Therefore, we must perform an integer comparison here. */
4575  if (_condition < 0) {
4576  /* Stop any tones that are playing */
4577  ast_playtones_stop(chan);
4578  res = 0;
4579  return res;
4580  }
4581 
4582  /* Handle conditions that we have tones for. */
4583  switch (condition) {
4584  case _XXX_AST_CONTROL_T38:
4585  /* deprecated T.38 control frame */
4586  res = -1;
4587  return res;
4589  /* there is no way to provide 'default' behavior for these
4590  * control frames, so we need to return failure, but there
4591  * is also no value in the log message below being emitted
4592  * since failure to handle these frames is not an 'error'
4593  * so just return right now. in addition, we want to return
4594  * whatever value the channel driver returned, in case it
4595  * has some meaning.*/
4596  return res;
4597  case AST_CONTROL_RINGING:
4598  ts = ast_get_indication_tone(ast_channel_zone(chan), "ring");
4599  /* It is common practice for channel drivers to return -1 if trying
4600  * to indicate ringing on a channel which is up. The idea is to let the
4601  * core generate the ringing inband. However, we don't want the
4602  * warning message about not being able to handle the specific indication
4603  * to print nor do we want ast_indicate_data to return an "error" for this
4604  * condition
4605  */
4606  if (ast_channel_state(chan) == AST_STATE_UP) {
4607  res = 0;
4608  }
4609  break;
4610  case AST_CONTROL_BUSY:
4611  ts = ast_get_indication_tone(ast_channel_zone(chan), "busy");
4612  break;
4615  ts = ast_get_indication_tone(ast_channel_zone(chan), "congestion");
4616  break;
4618  ast_channel_hangupcause_hash_set(chan, data, datalen);
4619  res = 0;
4620  break;
4621  case AST_CONTROL_PROGRESS:
4623  case AST_CONTROL_VIDUPDATE:
4624  case AST_CONTROL_SRCUPDATE:
4625  case AST_CONTROL_SRCCHANGE:
4626  case AST_CONTROL_RADIO_KEY:
4628  case AST_CONTROL_OPTION:
4629  case AST_CONTROL_WINK:
4630  case AST_CONTROL_FLASH:
4631  case AST_CONTROL_OFFHOOK:
4633  case AST_CONTROL_ANSWER:
4634  case AST_CONTROL_HANGUP:
4635  case AST_CONTROL_RING:
4636  case AST_CONTROL_HOLD:
4637  case AST_CONTROL_UNHOLD:
4638  case AST_CONTROL_TRANSFER:
4641  case AST_CONTROL_CC:
4643  case AST_CONTROL_AOC:
4644  case AST_CONTROL_END_OF_Q:
4645  case AST_CONTROL_MCID:
4660  /* Nothing left to do for these. */
4661  res = 0;
4662  break;
4663  }
4664 
4665  if (ts) {
4666  /* We have a tone to play, yay. */
4667  ast_debug(1, "Driver for channel '%s' does not support indication %u, emulating it\n", ast_channel_name(chan), condition);
4668  res = ast_playtones_start(chan, 0, ts->data, 1);
4669  if (!res) {
4670  ast_test_suite_event_notify("RINGING_INBAND",
4671  "Channel: %s\r\n",
4672  ast_channel_name(chan));
4673  }
4674  ts = ast_tone_zone_sound_unref(ts);
4675  }
4676 
4677  if (res) {
4678  /* not handled */
4679  ast_log(LOG_WARNING, "Unable to handle indication %u for '%s'\n", condition, ast_channel_name(chan));
4680  }
4681 
4682  return res;
4683 }
4684 
4685 int ast_indicate_data(struct ast_channel *chan, int _condition, const void *data, size_t datalen)
4686 {
4687  int res;
4688  /* this frame is used by framehooks. if it is set, we must free it at the end of this function */
4689  struct ast_frame *awesome_frame = NULL;
4690 
4691  ast_channel_lock(chan);
4692 
4693  /* Don't bother if the channel is about to go away, anyway. */
4695  || (ast_check_hangup(chan) && !ast_channel_is_leaving_bridge(chan)))
4696  && _condition != AST_CONTROL_MASQUERADE_NOTIFY) {
4697  res = -1;
4698  goto indicate_cleanup;
4699  }
4700 
4702  /* Do framehooks now, do it, go, go now */
4703  struct ast_frame frame = {
4705  .subclass.integer = _condition,
4706  .data.ptr = (void *) data, /* this cast from const is only okay because we do the ast_frdup below */
4707  .datalen = datalen
4708  };
4709 
4710  /* we have now committed to freeing this frame */
4711  awesome_frame = ast_frdup(&frame);
4712 
4713  /* who knows what we will get back! the anticipation is killing me. */
4715  awesome_frame);
4716  if (!awesome_frame
4717  || awesome_frame->frametype != AST_FRAME_CONTROL) {
4718  res = 0;
4719  goto indicate_cleanup;
4720  }
4721 
4722  _condition = awesome_frame->subclass.integer;
4723  data = awesome_frame->data.ptr;
4724  datalen = awesome_frame->datalen;
4725  }
4726 
4727  res = indicate_data_internal(chan, _condition, data, datalen);
4728 
4729 indicate_cleanup:
4730  ast_channel_unlock(chan);
4731  if (awesome_frame) {
4732  ast_frfree(awesome_frame);
4733  }
4734 
4735  return res;
4736 }
4737 
4738 int ast_recvchar(struct ast_channel *chan, int timeout)
4739 {
4740  int c;
4741  char *buf = ast_recvtext(chan, timeout);
4742  if (buf == NULL)
4743  return -1; /* error or timeout */
4744  c = *(unsigned char *)buf;
4745  ast_free(buf);
4746  return c;
4747 }
4748 
4749 char *ast_recvtext(struct ast_channel *chan, int timeout)
4750 {
4751  int res;
4752  char *buf = NULL;
4753  struct timeval start = ast_tvnow();
4754  int ms;
4755 
4756  while ((ms = ast_remaining_ms(start, timeout))) {
4757  struct ast_frame *f;
4758 
4759  if (ast_check_hangup(chan)) {
4760  break;
4761  }
4762  res = ast_waitfor(chan, ms);
4763  if (res <= 0) {/* timeout or error */
4764  break;
4765  }
4766  f = ast_read(chan);
4767  if (f == NULL) {
4768  break; /* no frame */
4769  }
4771  ast_frfree(f);
4772  break;
4773  } else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
4774  buf = ast_strndup((char *) f->data.ptr, f->datalen); /* dup and break */
4775  ast_frfree(f);
4776  break;
4777  }
4778  ast_frfree(f);
4779  }
4780  return buf;
4781 }
4782 
4783 int ast_sendtext_data(struct ast_channel *chan, struct ast_msg_data *msg)
4784 {
4785  int res = 0;
4786  const char *body = ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_BODY);
4787  const char *content_type = ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_CONTENT_TYPE);
4788 
4789  ast_channel_lock(chan);
4790  /* Stop if we're a zombie or need a soft hangup */
4792  ast_channel_unlock(chan);
4793  return -1;
4794  }
4795 
4796  CHECK_BLOCKING(chan);
4797  if (ast_channel_tech(chan)->write_text
4798  && (ast_strlen_zero(content_type) || ast_begins_with(content_type, "text/"))
4800  struct ast_frame f;
4801  /* T.140 payload does not include the null byte terminator */
4802  size_t body_len = strlen(body);
4803 
4804  /* Process as T.140 text (moved here from ast_sendtext() */
4805  memset(&f, 0, sizeof(f));
4806  f.src = "DIALPLAN";
4809  f.datalen = body_len;
4811  f.data.