Review Board 1.7.16


Prevent 'Bad Magic Number' caused when a channel is optimized out by masquerade

Review Request #928 - Created Sept. 17, 2010 and submitted

Alec Davis
trunk
16057, 17037, 17363, 17801
Reviewers
asterisk-dev
Asterisk
there are 2 main fixes here.

1). Prevent a further masquerade being planned if either original/clonechan(masq/masqr) are set.
2). While the actual masquerade happens keep the channels container locked for the full duration. 

There is a comment 'that the channels container can be freed' after both channels are locked and unlink, but that not the case.
Using the following test plan, calling 10020 creates 20 looped Local channel calls, that then get optimized out.

[test]
exten => 10000,1,Answer()
exten => 10000,n,Playback(test-tones-follow)
exten => 10000,n,Milliwatt()

exten => _1XXXX,1,Set(i=${MATH(${EXTEN}-1,int)})
exten => _1XXXX,n,Dial(Local/${i}@test)

After patch: normal expected channels.
    asterix*CLI> core show channels
    Channel              Location             State   Application(Data)
    DAHDI/35-1           10010@phones:2       Up      Dial(Local/10009@phones)
    Local/10000@phones-2 s@echo-test:4        Up      Echo()
    Local/10000@phones-2 (None)               Up      AppDial((Outgoing Line))
    3 active channels
    2 active calls
    97 calls processed
    asterix*CLI>


prior to the patch:
   'Bad Magic Number' would reqularly been seen.

   dead channels left in container
   asterix*CLI> core show channels
   Channel              Location             State   Application(Data)
   Local/10000@phones-2 s@echo-test:3        Up      Playback(echo-test)
   Local/10000@phones-2 (None)               Up      AppDial((Outgoing Line))
   2 active channels
   1 active call
   21 calls processed
   asterix*CLI>

Diff revision 2 (Latest)

1 2
1 2

  1. trunk/main/channel.c: Loading...
trunk/main/channel.c
Revision 287464 New Change
1
/*
1
/*
2
 * Asterisk -- An open source telephony toolkit.
2
 * Asterisk -- An open source telephony toolkit.
3
 *
3
 *
4
 * Copyright (C) 1999 - 2006, Digium, Inc.
4
 * Copyright (C) 1999 - 2006, Digium, Inc.
5
 *
5
 *
6
 * Mark Spencer <markster@digium.com>
6
 * Mark Spencer <markster@digium.com>
7
 *
7
 *
8
 * See http://www.asterisk.org for more information about
8
 * See http://www.asterisk.org for more information about
9
 * the Asterisk project. Please do not directly contact
9
 * the Asterisk project. Please do not directly contact
10
 * any of the maintainers of this project for assistance;
10
 * any of the maintainers of this project for assistance;
11
 * the project provides a web site, mailing lists and IRC
11
 * the project provides a web site, mailing lists and IRC
12
 * channels for your use.
12
 * channels for your use.
13
 *
13
 *
14
 * This program is free software, distributed under the terms of
14
 * This program is free software, distributed under the terms of
15
 * the GNU General Public License Version 2. See the LICENSE file
15
 * the GNU General Public License Version 2. See the LICENSE file
16
 * at the top of the source tree.
16
 * at the top of the source tree.
17
 */
17
 */
18

    
   
18

   
19
/*! \file
19
/*! \file
20
 *
20
 *
21
 * \brief Channel Management
21
 * \brief Channel Management
22
 *
22
 *
23
 * \author Mark Spencer <markster@digium.com>
23
 * \author Mark Spencer <markster@digium.com>
24
 */
24
 */
25

    
   
25

   
26
#include "asterisk.h"
26
#include "asterisk.h"
27

    
   
27

   
28
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
28
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29

    
   
29

   
30
#include "asterisk/_private.h"
30
#include "asterisk/_private.h"
31

    
   
31

   
32
#include <sys/time.h>
32
#include <sys/time.h>
33
#include <signal.h>
33
#include <signal.h>
34
#include <math.h>
34
#include <math.h>
35

    
   
35

   
36
#include "asterisk/paths.h"	/* use ast_config_AST_SYSTEM_NAME */
36
#include "asterisk/paths.h"	/* use ast_config_AST_SYSTEM_NAME */
37

    
   
37

   
38
#include "asterisk/pbx.h"
38
#include "asterisk/pbx.h"
39
#include "asterisk/frame.h"
39
#include "asterisk/frame.h"
40
#include "asterisk/mod_format.h"
40
#include "asterisk/mod_format.h"
41
#include "asterisk/sched.h"
41
#include "asterisk/sched.h"
42
#include "asterisk/channel.h"
42
#include "asterisk/channel.h"
43
#include "asterisk/musiconhold.h"
43
#include "asterisk/musiconhold.h"
44
#include "asterisk/say.h"
44
#include "asterisk/say.h"
45
#include "asterisk/file.h"
45
#include "asterisk/file.h"
46
#include "asterisk/cli.h"
46
#include "asterisk/cli.h"
47
#include "asterisk/translate.h"
47
#include "asterisk/translate.h"
48
#include "asterisk/manager.h"
48
#include "asterisk/manager.h"
49
#include "asterisk/cel.h"
49
#include "asterisk/cel.h"
50
#include "asterisk/chanvars.h"
50
#include "asterisk/chanvars.h"
51
#include "asterisk/linkedlists.h"
51
#include "asterisk/linkedlists.h"
52
#include "asterisk/indications.h"
52
#include "asterisk/indications.h"
53
#include "asterisk/monitor.h"
53
#include "asterisk/monitor.h"
54
#include "asterisk/causes.h"
54
#include "asterisk/causes.h"
55
#include "asterisk/callerid.h"
55
#include "asterisk/callerid.h"
56
#include "asterisk/utils.h"
56
#include "asterisk/utils.h"
57
#include "asterisk/lock.h"
57
#include "asterisk/lock.h"
58
#include "asterisk/app.h"
58
#include "asterisk/app.h"
59
#include "asterisk/transcap.h"
59
#include "asterisk/transcap.h"
60
#include "asterisk/devicestate.h"
60
#include "asterisk/devicestate.h"
61
#include "asterisk/sha1.h"
61
#include "asterisk/sha1.h"
62
#include "asterisk/threadstorage.h"
62
#include "asterisk/threadstorage.h"
63
#include "asterisk/slinfactory.h"
63
#include "asterisk/slinfactory.h"
64
#include "asterisk/audiohook.h"
64
#include "asterisk/audiohook.h"
65
#include "asterisk/timing.h"
65
#include "asterisk/timing.h"
66
#include "asterisk/autochan.h"
66
#include "asterisk/autochan.h"
67
#include "asterisk/stringfields.h"
67
#include "asterisk/stringfields.h"
68
#include "asterisk/global_datastores.h"
68
#include "asterisk/global_datastores.h"
69
#include "asterisk/data.h"
69
#include "asterisk/data.h"
70

    
   
70

   
71
#ifdef HAVE_EPOLL
71
#ifdef HAVE_EPOLL
72
#include <sys/epoll.h>
72
#include <sys/epoll.h>
73
#endif
73
#endif
74

    
   
74

   
75
#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
75
#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
76
#if defined(HAVE_PRI)
76
#if defined(HAVE_PRI)
77
#include "libpri.h"
77
#include "libpri.h"
78
#endif	/* defined(HAVE_PRI) */
78
#endif	/* defined(HAVE_PRI) */
79
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
79
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
80

    
   
80

   
81
struct ast_epoll_data {
81
struct ast_epoll_data {
82
	struct ast_channel *chan;
82
	struct ast_channel *chan;
83
	int which;
83
	int which;
84
};
84
};
85

    
   
85

   
86
/* uncomment if you have problems with 'monitoring' synchronized files */
86
/* uncomment if you have problems with 'monitoring' synchronized files */
87
#if 0
87
#if 0
88
#define MONITOR_CONSTANT_DELAY
88
#define MONITOR_CONSTANT_DELAY
89
#define MONITOR_DELAY	150 * 8		/*!< 150 ms of MONITORING DELAY */
89
#define MONITOR_DELAY	150 * 8		/*!< 150 ms of MONITORING DELAY */
90
#endif
90
#endif
91

    
   
91

   
92
/*! \brief Prevent new channel allocation if shutting down. */
92
/*! \brief Prevent new channel allocation if shutting down. */
93
static int shutting_down;
93
static int shutting_down;
94

    
   
94

   
95
static int uniqueint;
95
static int uniqueint;
96

    
   
96

   
97
unsigned long global_fin, global_fout;
97
unsigned long global_fin, global_fout;
98

    
   
98

   
99
AST_THREADSTORAGE(state2str_threadbuf);
99
AST_THREADSTORAGE(state2str_threadbuf);
100
#define STATE2STR_BUFSIZE   32
100
#define STATE2STR_BUFSIZE   32
101

    
   
101

   
102
/*! Default amount of time to use when emulating a digit as a begin and end 
102
/*! Default amount of time to use when emulating a digit as a begin and end 
103
 *  100ms */
103
 *  100ms */
104
#define AST_DEFAULT_EMULATE_DTMF_DURATION 100
104
#define AST_DEFAULT_EMULATE_DTMF_DURATION 100
105

    
   
105

   
106
/*! Minimum allowed digit length - 80ms */
106
/*! Minimum allowed digit length - 80ms */
107
#define AST_MIN_DTMF_DURATION 80
107
#define AST_MIN_DTMF_DURATION 80
108

    
   
108

   
109
/*! Minimum amount of time between the end of the last digit and the beginning 
109
/*! Minimum amount of time between the end of the last digit and the beginning 
110
 *  of a new one - 45ms */
110
 *  of a new one - 45ms */
111
#define AST_MIN_DTMF_GAP 45
111
#define AST_MIN_DTMF_GAP 45
112

    
   
112

   
113
/*! \brief List of channel drivers */
113
/*! \brief List of channel drivers */
114
struct chanlist {
114
struct chanlist {
115
	const struct ast_channel_tech *tech;
115
	const struct ast_channel_tech *tech;
116
	AST_LIST_ENTRY(chanlist) list;
116
	AST_LIST_ENTRY(chanlist) list;
117
};
117
};
118

    
   
118

   
119
#ifdef CHANNEL_TRACE
119
#ifdef CHANNEL_TRACE
120
/*! \brief Structure to hold channel context backtrace data */
120
/*! \brief Structure to hold channel context backtrace data */
121
struct ast_chan_trace_data {
121
struct ast_chan_trace_data {
122
	int enabled;
122
	int enabled;
123
	AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
123
	AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
124
};
124
};
125

    
   
125

   
126
/*! \brief Structure to save contexts where an ast_chan has been into */
126
/*! \brief Structure to save contexts where an ast_chan has been into */
127
struct ast_chan_trace {
127
struct ast_chan_trace {
128
	char context[AST_MAX_CONTEXT];
128
	char context[AST_MAX_CONTEXT];
129
	char exten[AST_MAX_EXTENSION];
129
	char exten[AST_MAX_EXTENSION];
130
	int priority;
130
	int priority;
131
	AST_LIST_ENTRY(ast_chan_trace) entry;
131
	AST_LIST_ENTRY(ast_chan_trace) entry;
132
};
132
};
133
#endif
133
#endif
134

    
   
134

   
135
/*! \brief the list of registered channel types */
135
/*! \brief the list of registered channel types */
136
static AST_RWLIST_HEAD_STATIC(backends, chanlist);
136
static AST_RWLIST_HEAD_STATIC(backends, chanlist);
137

    
   
137

   
138
#ifdef LOW_MEMORY
138
#ifdef LOW_MEMORY
139
#define NUM_CHANNEL_BUCKETS 61
139
#define NUM_CHANNEL_BUCKETS 61
140
#else
140
#else
141
#define NUM_CHANNEL_BUCKETS 1567
141
#define NUM_CHANNEL_BUCKETS 1567
142
#endif
142
#endif
143

    
   
143

   
144
#if 0	/* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
144
#if 0	/* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
145
#define DATA_EXPORT_CALLERID(MEMBER)				\
145
#define DATA_EXPORT_CALLERID(MEMBER)				\
146
	MEMBER(ast_callerid, cid_dnid, AST_DATA_STRING)		\
146
	MEMBER(ast_callerid, cid_dnid, AST_DATA_STRING)		\
147
	MEMBER(ast_callerid, cid_num, AST_DATA_STRING)		\
147
	MEMBER(ast_callerid, cid_num, AST_DATA_STRING)		\
148
	MEMBER(ast_callerid, cid_name, AST_DATA_STRING)		\
148
	MEMBER(ast_callerid, cid_name, AST_DATA_STRING)		\
149
	MEMBER(ast_callerid, cid_ani, AST_DATA_STRING)		\
149
	MEMBER(ast_callerid, cid_ani, AST_DATA_STRING)		\
150
	MEMBER(ast_callerid, cid_pres, AST_DATA_INTEGER)	\
150
	MEMBER(ast_callerid, cid_pres, AST_DATA_INTEGER)	\
151
	MEMBER(ast_callerid, cid_ani2, AST_DATA_INTEGER)	\
151
	MEMBER(ast_callerid, cid_ani2, AST_DATA_INTEGER)	\
152
	MEMBER(ast_callerid, cid_tag, AST_DATA_STRING)
152
	MEMBER(ast_callerid, cid_tag, AST_DATA_STRING)
153

    
   
153

   
154
AST_DATA_STRUCTURE(ast_callerid, DATA_EXPORT_CALLERID);
154
AST_DATA_STRUCTURE(ast_callerid, DATA_EXPORT_CALLERID);
155
#endif
155
#endif
156

    
   
156

   
157
#define DATA_EXPORT_CHANNEL(MEMBER)						\
157
#define DATA_EXPORT_CHANNEL(MEMBER)						\
158
	MEMBER(ast_channel, blockproc, AST_DATA_STRING)				\
158
	MEMBER(ast_channel, blockproc, AST_DATA_STRING)				\
159
	MEMBER(ast_channel, appl, AST_DATA_STRING)				\
159
	MEMBER(ast_channel, appl, AST_DATA_STRING)				\
160
	MEMBER(ast_channel, data, AST_DATA_STRING)				\
160
	MEMBER(ast_channel, data, AST_DATA_STRING)				\
161
	MEMBER(ast_channel, name, AST_DATA_STRING)				\
161
	MEMBER(ast_channel, name, AST_DATA_STRING)				\
162
	MEMBER(ast_channel, language, AST_DATA_STRING)				\
162
	MEMBER(ast_channel, language, AST_DATA_STRING)				\
163
	MEMBER(ast_channel, musicclass, AST_DATA_STRING)			\
163
	MEMBER(ast_channel, musicclass, AST_DATA_STRING)			\
164
	MEMBER(ast_channel, accountcode, AST_DATA_STRING)			\
164
	MEMBER(ast_channel, accountcode, AST_DATA_STRING)			\
165
	MEMBER(ast_channel, peeraccount, AST_DATA_STRING)			\
165
	MEMBER(ast_channel, peeraccount, AST_DATA_STRING)			\
166
	MEMBER(ast_channel, userfield, AST_DATA_STRING)				\
166
	MEMBER(ast_channel, userfield, AST_DATA_STRING)				\
167
	MEMBER(ast_channel, call_forward, AST_DATA_STRING)			\
167
	MEMBER(ast_channel, call_forward, AST_DATA_STRING)			\
168
	MEMBER(ast_channel, uniqueid, AST_DATA_STRING)				\
168
	MEMBER(ast_channel, uniqueid, AST_DATA_STRING)				\
169
	MEMBER(ast_channel, linkedid, AST_DATA_STRING)				\
169
	MEMBER(ast_channel, linkedid, AST_DATA_STRING)				\
170
	MEMBER(ast_channel, parkinglot, AST_DATA_STRING)			\
170
	MEMBER(ast_channel, parkinglot, AST_DATA_STRING)			\
171
	MEMBER(ast_channel, hangupsource, AST_DATA_STRING)			\
171
	MEMBER(ast_channel, hangupsource, AST_DATA_STRING)			\
172
	MEMBER(ast_channel, dialcontext, AST_DATA_STRING)			\
172
	MEMBER(ast_channel, dialcontext, AST_DATA_STRING)			\
173
	MEMBER(ast_channel, rings, AST_DATA_INTEGER)				\
173
	MEMBER(ast_channel, rings, AST_DATA_INTEGER)				\
174
	MEMBER(ast_channel, priority, AST_DATA_INTEGER)				\
174
	MEMBER(ast_channel, priority, AST_DATA_INTEGER)				\
175
	MEMBER(ast_channel, macropriority, AST_DATA_INTEGER)			\
175
	MEMBER(ast_channel, macropriority, AST_DATA_INTEGER)			\
176
	MEMBER(ast_channel, adsicpe, AST_DATA_INTEGER)				\
176
	MEMBER(ast_channel, adsicpe, AST_DATA_INTEGER)				\
177
	MEMBER(ast_channel, fin, AST_DATA_UNSIGNED_INTEGER)			\
177
	MEMBER(ast_channel, fin, AST_DATA_UNSIGNED_INTEGER)			\
178
	MEMBER(ast_channel, fout, AST_DATA_UNSIGNED_INTEGER)			\
178
	MEMBER(ast_channel, fout, AST_DATA_UNSIGNED_INTEGER)			\
179
	MEMBER(ast_channel, emulate_dtmf_duration, AST_DATA_UNSIGNED_INTEGER)	\
179
	MEMBER(ast_channel, emulate_dtmf_duration, AST_DATA_UNSIGNED_INTEGER)	\
180
	MEMBER(ast_channel, visible_indication, AST_DATA_INTEGER)		\
180
	MEMBER(ast_channel, visible_indication, AST_DATA_INTEGER)		\
181
	MEMBER(ast_channel, context, AST_DATA_STRING)				\
181
	MEMBER(ast_channel, context, AST_DATA_STRING)				\
182
	MEMBER(ast_channel, exten, AST_DATA_STRING)				\
182
	MEMBER(ast_channel, exten, AST_DATA_STRING)				\
183
	MEMBER(ast_channel, macrocontext, AST_DATA_STRING)			\
183
	MEMBER(ast_channel, macrocontext, AST_DATA_STRING)			\
184
	MEMBER(ast_channel, macroexten, AST_DATA_STRING)
184
	MEMBER(ast_channel, macroexten, AST_DATA_STRING)
185

    
   
185

   
186
AST_DATA_STRUCTURE(ast_channel, DATA_EXPORT_CHANNEL);
186
AST_DATA_STRUCTURE(ast_channel, DATA_EXPORT_CHANNEL);
187

    
   
187

   
188

    
   
188

   
189
/*! \brief All active channels on the system */
189
/*! \brief All active channels on the system */
190
static struct ao2_container *channels;
190
static struct ao2_container *channels;
191

    
   
191

   
192
/*! \brief map AST_CAUSE's to readable string representations 
192
/*! \brief map AST_CAUSE's to readable string representations 
193
 *
193
 *
194
 * \ref causes.h
194
 * \ref causes.h
195
*/
195
*/
196
static const struct {
196
static const struct {
197
	int cause;
197
	int cause;
198
	const char *name;
198
	const char *name;
199
	const char *desc;
199
	const char *desc;
200
} causes[] = {
200
} causes[] = {
201
	{ AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
201
	{ AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
202
	{ AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
202
	{ AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
203
	{ AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
203
	{ AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
204
	{ AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
204
	{ AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
205
	{ AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
205
	{ AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
206
	{ AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
206
	{ AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
207
	{ AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
207
	{ AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
208
	{ AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
208
	{ AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
209
	{ AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
209
	{ AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
210
	{ AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
210
	{ AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
211
	{ AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
211
	{ AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
212
	{ AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
212
	{ AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
213
	{ AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
213
	{ AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
214
	{ AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
214
	{ AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
215
	{ AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
215
	{ AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
216
	{ AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
216
	{ AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
217
	{ AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
217
	{ AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
218
	{ AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
218
	{ AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
219
	{ AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
219
	{ AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
220
	{ AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
220
	{ AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
221
	{ AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
221
	{ AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
222
	{ AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
222
	{ AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
223
	{ AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
223
	{ AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
224
	{ AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
224
	{ AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
225
	{ AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
225
	{ AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
226
	{ AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
226
	{ AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
227
	{ AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
227
	{ AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
228
	{ AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
228
	{ AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
229
	{ AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
229
	{ AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
230
	{ AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
230
	{ AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
231
	{ AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
231
	{ AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
232
	{ AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
232
	{ AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
233
	{ AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
233
	{ AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
234
	{ AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
234
	{ AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
235
	{ AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
235
	{ AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
236
	{ AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
236
	{ AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
237
	{ AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
237
	{ AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
238
	{ AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
238
	{ AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
239
	{ AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
239
	{ AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
240
	{ AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
240
	{ AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
241
	{ AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
241
	{ AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
242
	{ AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
242
	{ AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
243
	{ AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
243
	{ AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
244
	{ AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
244
	{ AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
245
};
245
};
246

    
   
246

   
247
struct ast_variable *ast_channeltype_list(void)
247
struct ast_variable *ast_channeltype_list(void)
248
{
248
{
249
	struct chanlist *cl;
249
	struct chanlist *cl;
250
	struct ast_variable *var = NULL, *prev = NULL;
250
	struct ast_variable *var = NULL, *prev = NULL;
251

    
   
251

   
252
	AST_RWLIST_RDLOCK(&backends);
252
	AST_RWLIST_RDLOCK(&backends);
253
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
253
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
254
		if (prev)  {
254
		if (prev)  {
255
			if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
255
			if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
256
				prev = prev->next;
256
				prev = prev->next;
257
		} else {
257
		} else {
258
			var = ast_variable_new(cl->tech->type, cl->tech->description, "");
258
			var = ast_variable_new(cl->tech->type, cl->tech->description, "");
259
			prev = var;
259
			prev = var;
260
		}
260
		}
261
	}
261
	}
262
	AST_RWLIST_UNLOCK(&backends);
262
	AST_RWLIST_UNLOCK(&backends);
263

    
   
263

   
264
	return var;
264
	return var;
265
}
265
}
266

    
   
266

   
267
static void channel_data_add_flags(struct ast_data *tree,
267
static void channel_data_add_flags(struct ast_data *tree,
268
	struct ast_channel *chan)
268
	struct ast_channel *chan)
269
{
269
{
270
	ast_data_add_bool(tree, "DEFER_DTMF", ast_test_flag(chan, AST_FLAG_DEFER_DTMF));
270
	ast_data_add_bool(tree, "DEFER_DTMF", ast_test_flag(chan, AST_FLAG_DEFER_DTMF));
271
	ast_data_add_bool(tree, "WRITE_INT", ast_test_flag(chan, AST_FLAG_WRITE_INT));
271
	ast_data_add_bool(tree, "WRITE_INT", ast_test_flag(chan, AST_FLAG_WRITE_INT));
272
	ast_data_add_bool(tree, "BLOCKING", ast_test_flag(chan, AST_FLAG_BLOCKING));
272
	ast_data_add_bool(tree, "BLOCKING", ast_test_flag(chan, AST_FLAG_BLOCKING));
273
	ast_data_add_bool(tree, "ZOMBIE", ast_test_flag(chan, AST_FLAG_ZOMBIE));
273
	ast_data_add_bool(tree, "ZOMBIE", ast_test_flag(chan, AST_FLAG_ZOMBIE));
274
	ast_data_add_bool(tree, "EXCEPTION", ast_test_flag(chan, AST_FLAG_EXCEPTION));
274
	ast_data_add_bool(tree, "EXCEPTION", ast_test_flag(chan, AST_FLAG_EXCEPTION));
275
	ast_data_add_bool(tree, "MOH", ast_test_flag(chan, AST_FLAG_MOH));
275
	ast_data_add_bool(tree, "MOH", ast_test_flag(chan, AST_FLAG_MOH));
276
	ast_data_add_bool(tree, "SPYING", ast_test_flag(chan, AST_FLAG_SPYING));
276
	ast_data_add_bool(tree, "SPYING", ast_test_flag(chan, AST_FLAG_SPYING));
277
	ast_data_add_bool(tree, "NBRIDGE", ast_test_flag(chan, AST_FLAG_NBRIDGE));
277
	ast_data_add_bool(tree, "NBRIDGE", ast_test_flag(chan, AST_FLAG_NBRIDGE));
278
	ast_data_add_bool(tree, "IN_AUTOLOOP", ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP));
278
	ast_data_add_bool(tree, "IN_AUTOLOOP", ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP));
279
	ast_data_add_bool(tree, "OUTGOING", ast_test_flag(chan, AST_FLAG_OUTGOING));
279
	ast_data_add_bool(tree, "OUTGOING", ast_test_flag(chan, AST_FLAG_OUTGOING));
280
	ast_data_add_bool(tree, "IN_DTMF", ast_test_flag(chan, AST_FLAG_IN_DTMF));
280
	ast_data_add_bool(tree, "IN_DTMF", ast_test_flag(chan, AST_FLAG_IN_DTMF));
281
	ast_data_add_bool(tree, "EMULATE_DTMF", ast_test_flag(chan, AST_FLAG_EMULATE_DTMF));
281
	ast_data_add_bool(tree, "EMULATE_DTMF", ast_test_flag(chan, AST_FLAG_EMULATE_DTMF));
282
	ast_data_add_bool(tree, "END_DTMF_ONLY", ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY));
282
	ast_data_add_bool(tree, "END_DTMF_ONLY", ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY));
283
	ast_data_add_bool(tree, "ANSWERED_ELSEWHERE", ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE));
283
	ast_data_add_bool(tree, "ANSWERED_ELSEWHERE", ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE));
284
	ast_data_add_bool(tree, "MASQ_NOSTREAM", ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM));
284
	ast_data_add_bool(tree, "MASQ_NOSTREAM", ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM));
285
	ast_data_add_bool(tree, "BRIDGE_HANGUP_RUN", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN));
285
	ast_data_add_bool(tree, "BRIDGE_HANGUP_RUN", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN));
286
	ast_data_add_bool(tree, "BRIDGE_HANGUP_DONT", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT));
286
	ast_data_add_bool(tree, "BRIDGE_HANGUP_DONT", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT));
287
	ast_data_add_bool(tree, "DISABLE_WORKAROUNDS", ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS));
287
	ast_data_add_bool(tree, "DISABLE_WORKAROUNDS", ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS));
288
}
288
}
289

    
   
289

   
290
#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
290
#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
291
static const char *party_number_ton2str(int ton)
291
static const char *party_number_ton2str(int ton)
292
{
292
{
293
#if defined(HAVE_PRI)
293
#if defined(HAVE_PRI)
294
	switch ((ton >> 4) & 0x07) {
294
	switch ((ton >> 4) & 0x07) {
295
	case PRI_TON_INTERNATIONAL:
295
	case PRI_TON_INTERNATIONAL:
296
		return "International";
296
		return "International";
297
	case PRI_TON_NATIONAL:
297
	case PRI_TON_NATIONAL:
298
		return "National";
298
		return "National";
299
	case PRI_TON_NET_SPECIFIC:
299
	case PRI_TON_NET_SPECIFIC:
300
		return "Network Specific";
300
		return "Network Specific";
301
	case PRI_TON_SUBSCRIBER:
301
	case PRI_TON_SUBSCRIBER:
302
		return "Subscriber";
302
		return "Subscriber";
303
	case PRI_TON_ABBREVIATED:
303
	case PRI_TON_ABBREVIATED:
304
		return "Abbreviated";
304
		return "Abbreviated";
305
	case PRI_TON_RESERVED:
305
	case PRI_TON_RESERVED:
306
		return "Reserved";
306
		return "Reserved";
307
	case PRI_TON_UNKNOWN:
307
	case PRI_TON_UNKNOWN:
308
	default:
308
	default:
309
		break;
309
		break;
310
	}
310
	}
311
#endif	/* defined(HAVE_PRI) */
311
#endif	/* defined(HAVE_PRI) */
312
	return "Unknown";
312
	return "Unknown";
313
}
313
}
314
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
314
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
315

    
   
315

   
316
#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
316
#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
317
static const char *party_number_plan2str(int plan)
317
static const char *party_number_plan2str(int plan)
318
{
318
{
319
#if defined(HAVE_PRI)
319
#if defined(HAVE_PRI)
320
	switch (plan & 0x0F) {
320
	switch (plan & 0x0F) {
321
	default:
321
	default:
322
	case PRI_NPI_UNKNOWN:
322
	case PRI_NPI_UNKNOWN:
323
		break;
323
		break;
324
	case PRI_NPI_E163_E164:
324
	case PRI_NPI_E163_E164:
325
		return "Public (E.163/E.164)";
325
		return "Public (E.163/E.164)";
326
	case PRI_NPI_X121:
326
	case PRI_NPI_X121:
327
		return "Data (X.121)";
327
		return "Data (X.121)";
328
	case PRI_NPI_F69:
328
	case PRI_NPI_F69:
329
		return "Telex (F.69)";
329
		return "Telex (F.69)";
330
	case PRI_NPI_NATIONAL:
330
	case PRI_NPI_NATIONAL:
331
		return "National Standard";
331
		return "National Standard";
332
	case PRI_NPI_PRIVATE:
332
	case PRI_NPI_PRIVATE:
333
		return "Private";
333
		return "Private";
334
	case PRI_NPI_RESERVED:
334
	case PRI_NPI_RESERVED:
335
		return "Reserved";
335
		return "Reserved";
336
	}
336
	}
337
#endif	/* defined(HAVE_PRI) */
337
#endif	/* defined(HAVE_PRI) */
338
	return "Unknown";
338
	return "Unknown";
339
}
339
}
340
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
340
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
341

    
   
341

   
342
int ast_channel_data_add_structure(struct ast_data *tree,
342
int ast_channel_data_add_structure(struct ast_data *tree,
343
	struct ast_channel *chan, int add_bridged)
343
	struct ast_channel *chan, int add_bridged)
344
{
344
{
345
	struct ast_channel *bc;
345
	struct ast_channel *bc;
346
	struct ast_data *data_bridged;
346
	struct ast_data *data_bridged;
347
	struct ast_data *data_cdr;
347
	struct ast_data *data_cdr;
348
	struct ast_data *data_flags;
348
	struct ast_data *data_flags;
349
	struct ast_data *data_zones;
349
	struct ast_data *data_zones;
350
	struct ast_data *enum_node;
350
	struct ast_data *enum_node;
351
	struct ast_data *data_softhangup;
351
	struct ast_data *data_softhangup;
352
#if 0	/* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
352
#if 0	/* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
353
	struct ast_data *data_callerid;
353
	struct ast_data *data_callerid;
354
	char value_str[100];
354
	char value_str[100];
355
#endif
355
#endif
356

    
   
356

   
357
	if (!tree) {
357
	if (!tree) {
358
		return -1;
358
		return -1;
359
	}
359
	}
360

    
   
360

   
361
	ast_data_add_structure(ast_channel, tree, chan);
361
	ast_data_add_structure(ast_channel, tree, chan);
362

    
   
362

   
363
	if (add_bridged) {
363
	if (add_bridged) {
364
		bc = ast_bridged_channel(chan);
364
		bc = ast_bridged_channel(chan);
365
		if (bc) {
365
		if (bc) {
366
			data_bridged = ast_data_add_node(tree, "bridged");
366
			data_bridged = ast_data_add_node(tree, "bridged");
367
			if (!data_bridged) {
367
			if (!data_bridged) {
368
				return -1;
368
				return -1;
369
			}
369
			}
370
			ast_channel_data_add_structure(data_bridged, bc, 0);
370
			ast_channel_data_add_structure(data_bridged, bc, 0);
371
		}
371
		}
372
	}
372
	}
373

    
   
373

   
374
	ast_data_add_codecs(tree, "oldwriteformat", chan->oldwriteformat);
374
	ast_data_add_codecs(tree, "oldwriteformat", chan->oldwriteformat);
375
	ast_data_add_codecs(tree, "nativeformats", chan->nativeformats);
375
	ast_data_add_codecs(tree, "nativeformats", chan->nativeformats);
376
	ast_data_add_codecs(tree, "readformat", chan->readformat);
376
	ast_data_add_codecs(tree, "readformat", chan->readformat);
377
	ast_data_add_codecs(tree, "writeformat", chan->writeformat);
377
	ast_data_add_codecs(tree, "writeformat", chan->writeformat);
378
	ast_data_add_codecs(tree, "rawreadformat", chan->rawreadformat);
378
	ast_data_add_codecs(tree, "rawreadformat", chan->rawreadformat);
379
	ast_data_add_codecs(tree, "rawwriteformat", chan->rawwriteformat);
379
	ast_data_add_codecs(tree, "rawwriteformat", chan->rawwriteformat);
380

    
   
380

   
381
	/* state */
381
	/* state */
382
	enum_node = ast_data_add_node(tree, "state");
382
	enum_node = ast_data_add_node(tree, "state");
383
	if (!enum_node) {
383
	if (!enum_node) {
384
		return -1;
384
		return -1;
385
	}
385
	}
386
	ast_data_add_str(enum_node, "text", ast_state2str(chan->_state));
386
	ast_data_add_str(enum_node, "text", ast_state2str(chan->_state));
387
	ast_data_add_int(enum_node, "value", chan->_state);
387
	ast_data_add_int(enum_node, "value", chan->_state);
388

    
   
388

   
389
	/* hangupcause */
389
	/* hangupcause */
390
	enum_node = ast_data_add_node(tree, "hangupcause");
390
	enum_node = ast_data_add_node(tree, "hangupcause");
391
	if (!enum_node) {
391
	if (!enum_node) {
392
		return -1;
392
		return -1;
393
	}
393
	}
394
	ast_data_add_str(enum_node, "text", ast_cause2str(chan->hangupcause));
394
	ast_data_add_str(enum_node, "text", ast_cause2str(chan->hangupcause));
395
	ast_data_add_int(enum_node, "value", chan->hangupcause);
395
	ast_data_add_int(enum_node, "value", chan->hangupcause);
396

    
   
396

   
397
	/* amaflags */
397
	/* amaflags */
398
	enum_node = ast_data_add_node(tree, "amaflags");
398
	enum_node = ast_data_add_node(tree, "amaflags");
399
	if (!enum_node) {
399
	if (!enum_node) {
400
		return -1;
400
		return -1;
401
	}
401
	}
402
	ast_data_add_str(enum_node, "text", ast_cdr_flags2str(chan->amaflags));
402
	ast_data_add_str(enum_node, "text", ast_cdr_flags2str(chan->amaflags));
403
	ast_data_add_int(enum_node, "value", chan->amaflags);
403
	ast_data_add_int(enum_node, "value", chan->amaflags);
404

    
   
404

   
405
	/* transfercapability */
405
	/* transfercapability */
406
	enum_node = ast_data_add_node(tree, "transfercapability");
406
	enum_node = ast_data_add_node(tree, "transfercapability");
407
	if (!enum_node) {
407
	if (!enum_node) {
408
		return -1;
408
		return -1;
409
	}
409
	}
410
	ast_data_add_str(enum_node, "text", ast_transfercapability2str(chan->transfercapability));
410
	ast_data_add_str(enum_node, "text", ast_transfercapability2str(chan->transfercapability));
411
	ast_data_add_int(enum_node, "value", chan->transfercapability);
411
	ast_data_add_int(enum_node, "value", chan->transfercapability);
412

    
   
412

   
413
	/* _softphangup */
413
	/* _softphangup */
414
	data_softhangup = ast_data_add_node(tree, "softhangup");
414
	data_softhangup = ast_data_add_node(tree, "softhangup");
415
	if (!data_softhangup) {
415
	if (!data_softhangup) {
416
		return -1;
416
		return -1;
417
	}
417
	}
418
	ast_data_add_bool(data_softhangup, "dev", chan->_softhangup & AST_SOFTHANGUP_DEV);
418
	ast_data_add_bool(data_softhangup, "dev", chan->_softhangup & AST_SOFTHANGUP_DEV);
419
	ast_data_add_bool(data_softhangup, "asyncgoto", chan->_softhangup & AST_SOFTHANGUP_ASYNCGOTO);
419
	ast_data_add_bool(data_softhangup, "asyncgoto", chan->_softhangup & AST_SOFTHANGUP_ASYNCGOTO);
420
	ast_data_add_bool(data_softhangup, "shutdown", chan->_softhangup & AST_SOFTHANGUP_SHUTDOWN);
420
	ast_data_add_bool(data_softhangup, "shutdown", chan->_softhangup & AST_SOFTHANGUP_SHUTDOWN);
421
	ast_data_add_bool(data_softhangup, "timeout", chan->_softhangup & AST_SOFTHANGUP_TIMEOUT);
421
	ast_data_add_bool(data_softhangup, "timeout", chan->_softhangup & AST_SOFTHANGUP_TIMEOUT);
422
	ast_data_add_bool(data_softhangup, "appunload", chan->_softhangup & AST_SOFTHANGUP_APPUNLOAD);
422
	ast_data_add_bool(data_softhangup, "appunload", chan->_softhangup & AST_SOFTHANGUP_APPUNLOAD);
423
	ast_data_add_bool(data_softhangup, "explicit", chan->_softhangup & AST_SOFTHANGUP_EXPLICIT);
423
	ast_data_add_bool(data_softhangup, "explicit", chan->_softhangup & AST_SOFTHANGUP_EXPLICIT);
424
	ast_data_add_bool(data_softhangup, "unbridge", chan->_softhangup & AST_SOFTHANGUP_UNBRIDGE);
424
	ast_data_add_bool(data_softhangup, "unbridge", chan->_softhangup & AST_SOFTHANGUP_UNBRIDGE);
425

    
   
425

   
426
	/* channel flags */
426
	/* channel flags */
427
	data_flags = ast_data_add_node(tree, "flags");
427
	data_flags = ast_data_add_node(tree, "flags");
428
	if (!data_flags) {
428
	if (!data_flags) {
429
		return -1;
429
		return -1;
430
	}
430
	}
431
	channel_data_add_flags(data_flags, chan);
431
	channel_data_add_flags(data_flags, chan);
432

    
   
432

   
433
	ast_data_add_uint(tree, "timetohangup", chan->whentohangup.tv_sec);
433
	ast_data_add_uint(tree, "timetohangup", chan->whentohangup.tv_sec);
434

    
   
434

   
435
#if 0	/* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
435
#if 0	/* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
436
	/* callerid */
436
	/* callerid */
437
	data_callerid = ast_data_add_node(tree, "callerid");
437
	data_callerid = ast_data_add_node(tree, "callerid");
438
	if (!data_callerid) {
438
	if (!data_callerid) {
439
		return -1;
439
		return -1;
440
	}
440
	}
441
	ast_data_add_structure(ast_callerid, data_callerid, &(chan->cid));
441
	ast_data_add_structure(ast_callerid, data_callerid, &(chan->cid));
442
	/* insert the callerid ton */
442
	/* insert the callerid ton */
443
	enum_node = ast_data_add_node(data_callerid, "cid_ton");
443
	enum_node = ast_data_add_node(data_callerid, "cid_ton");
444
	if (!enum_node) {
444
	if (!enum_node) {
445
		return -1;
445
		return -1;
446
	}
446
	}
447
	ast_data_add_int(enum_node, "value", chan->cid.cid_ton);
447
	ast_data_add_int(enum_node, "value", chan->cid.cid_ton);
448
	snprintf(value_str, sizeof(value_str), "TON: %s/Plan: %s",
448
	snprintf(value_str, sizeof(value_str), "TON: %s/Plan: %s",
449
		party_number_ton2str(chan->cid.cid_ton),
449
		party_number_ton2str(chan->cid.cid_ton),
450
		party_number_plan2str(chan->cid.cid_ton));
450
		party_number_plan2str(chan->cid.cid_ton));
451
	ast_data_add_str(enum_node, "text", value_str);
451
	ast_data_add_str(enum_node, "text", value_str);
452
#endif
452
#endif
453

    
   
453

   
454
	/* tone zone */
454
	/* tone zone */
455
	if (chan->zone) {
455
	if (chan->zone) {
456
		data_zones = ast_data_add_node(tree, "zone");
456
		data_zones = ast_data_add_node(tree, "zone");
457
		if (!data_zones) {
457
		if (!data_zones) {
458
			return -1;
458
			return -1;
459
		}
459
		}
460
		ast_tone_zone_data_add_structure(data_zones, chan->zone);
460
		ast_tone_zone_data_add_structure(data_zones, chan->zone);
461
	}
461
	}
462

    
   
462

   
463
	/* insert cdr */
463
	/* insert cdr */
464
	data_cdr = ast_data_add_node(tree, "cdr");
464
	data_cdr = ast_data_add_node(tree, "cdr");
465
	if (!data_cdr) {
465
	if (!data_cdr) {
466
		return -1;
466
		return -1;
467
	}
467
	}
468

    
   
468

   
469
	ast_cdr_data_add_structure(data_cdr, chan->cdr, 1);
469
	ast_cdr_data_add_structure(data_cdr, chan->cdr, 1);
470

    
   
470

   
471
	return 0;
471
	return 0;
472
}
472
}
473

    
   
473

   
474
int ast_channel_data_cmp_structure(const struct ast_data_search *tree,
474
int ast_channel_data_cmp_structure(const struct ast_data_search *tree,
475
	struct ast_channel *chan, const char *structure_name)
475
	struct ast_channel *chan, const char *structure_name)
476
{
476
{
477
	return ast_data_search_cmp_structure(tree, ast_channel, chan, structure_name);
477
	return ast_data_search_cmp_structure(tree, ast_channel, chan, structure_name);
478
}
478
}
479

    
   
479

   
480
/*! \brief Show channel types - CLI command */
480
/*! \brief Show channel types - CLI command */
481
static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
481
static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
482
{
482
{
483
#define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
483
#define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
484
	struct chanlist *cl;
484
	struct chanlist *cl;
485
	int count_chan = 0;
485
	int count_chan = 0;
486

    
   
486

   
487
	switch (cmd) {
487
	switch (cmd) {
488
	case CLI_INIT:
488
	case CLI_INIT:
489
		e->command = "core show channeltypes";
489
		e->command = "core show channeltypes";
490
		e->usage =
490
		e->usage =
491
			"Usage: core show channeltypes\n"
491
			"Usage: core show channeltypes\n"
492
			"       Lists available channel types registered in your\n"
492
			"       Lists available channel types registered in your\n"
493
			"       Asterisk server.\n";
493
			"       Asterisk server.\n";
494
		return NULL;
494
		return NULL;
495
	case CLI_GENERATE:
495
	case CLI_GENERATE:
496
		return NULL;
496
		return NULL;
497
	}
497
	}
498

    
   
498

   
499
	if (a->argc != 3)
499
	if (a->argc != 3)
500
		return CLI_SHOWUSAGE;
500
		return CLI_SHOWUSAGE;
501

    
   
501

   
502
	ast_cli(a->fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
502
	ast_cli(a->fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
503
	ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
503
	ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
504

    
   
504

   
505
	AST_RWLIST_RDLOCK(&backends);
505
	AST_RWLIST_RDLOCK(&backends);
506
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
506
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
507
		ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
507
		ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
508
			(cl->tech->devicestate) ? "yes" : "no",
508
			(cl->tech->devicestate) ? "yes" : "no",
509
			(cl->tech->indicate) ? "yes" : "no",
509
			(cl->tech->indicate) ? "yes" : "no",
510
			(cl->tech->transfer) ? "yes" : "no");
510
			(cl->tech->transfer) ? "yes" : "no");
511
		count_chan++;
511
		count_chan++;
512
	}
512
	}
513
	AST_RWLIST_UNLOCK(&backends);
513
	AST_RWLIST_UNLOCK(&backends);
514

    
   
514

   
515
	ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
515
	ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
516

    
   
516

   
517
	return CLI_SUCCESS;
517
	return CLI_SUCCESS;
518

    
   
518

   
519
#undef FORMAT
519
#undef FORMAT
520
}
520
}
521

    
   
521

   
522
static char *complete_channeltypes(struct ast_cli_args *a)
522
static char *complete_channeltypes(struct ast_cli_args *a)
523
{
523
{
524
	struct chanlist *cl;
524
	struct chanlist *cl;
525
	int which = 0;
525
	int which = 0;
526
	int wordlen;
526
	int wordlen;
527
	char *ret = NULL;
527
	char *ret = NULL;
528

    
   
528

   
529
	if (a->pos != 3)
529
	if (a->pos != 3)
530
		return NULL;
530
		return NULL;
531

    
   
531

   
532
	wordlen = strlen(a->word);
532
	wordlen = strlen(a->word);
533

    
   
533

   
534
	AST_RWLIST_RDLOCK(&backends);
534
	AST_RWLIST_RDLOCK(&backends);
535
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
535
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
536
		if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
536
		if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
537
			ret = ast_strdup(cl->tech->type);
537
			ret = ast_strdup(cl->tech->type);
538
			break;
538
			break;
539
		}
539
		}
540
	}
540
	}
541
	AST_RWLIST_UNLOCK(&backends);
541
	AST_RWLIST_UNLOCK(&backends);
542
	
542
	
543
	return ret;
543
	return ret;
544
}
544
}
545

    
   
545

   
546
/*! \brief Show details about a channel driver - CLI command */
546
/*! \brief Show details about a channel driver - CLI command */
547
static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
547
static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
548
{
548
{
549
	struct chanlist *cl = NULL;
549
	struct chanlist *cl = NULL;
550
	char buf[512];
550
	char buf[512];
551

    
   
551

   
552
	switch (cmd) {
552
	switch (cmd) {
553
	case CLI_INIT:
553
	case CLI_INIT:
554
		e->command = "core show channeltype";
554
		e->command = "core show channeltype";
555
		e->usage =
555
		e->usage =
556
			"Usage: core show channeltype <name>\n"
556
			"Usage: core show channeltype <name>\n"
557
			"	Show details about the specified channel type, <name>.\n";
557
			"	Show details about the specified channel type, <name>.\n";
558
		return NULL;
558
		return NULL;
559
	case CLI_GENERATE:
559
	case CLI_GENERATE:
560
		return complete_channeltypes(a);
560
		return complete_channeltypes(a);
561
	}
561
	}
562

    
   
562

   
563
	if (a->argc != 4)
563
	if (a->argc != 4)
564
		return CLI_SHOWUSAGE;
564
		return CLI_SHOWUSAGE;
565
	
565
	
566
	AST_RWLIST_RDLOCK(&backends);
566
	AST_RWLIST_RDLOCK(&backends);
567

    
   
567

   
568
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
568
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
569
		if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
569
		if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
570
			break;
570
			break;
571
	}
571
	}
572

    
   
572

   
573

    
   
573

   
574
	if (!cl) {
574
	if (!cl) {
575
		ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
575
		ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
576
		AST_RWLIST_UNLOCK(&backends);
576
		AST_RWLIST_UNLOCK(&backends);
577
		return CLI_FAILURE;
577
		return CLI_FAILURE;
578
	}
578
	}
579

    
   
579

   
580
	ast_cli(a->fd,
580
	ast_cli(a->fd,
581
		"-- Info about channel driver: %s --\n"
581
		"-- Info about channel driver: %s --\n"
582
		"  Device State: %s\n"
582
		"  Device State: %s\n"
583
		"    Indication: %s\n"
583
		"    Indication: %s\n"
584
		"     Transfer : %s\n"
584
		"     Transfer : %s\n"
585
		"  Capabilities: %s\n"
585
		"  Capabilities: %s\n"
586
		"   Digit Begin: %s\n"
586
		"   Digit Begin: %s\n"
587
		"     Digit End: %s\n"
587
		"     Digit End: %s\n"
588
		"    Send HTML : %s\n"
588
		"    Send HTML : %s\n"
589
		" Image Support: %s\n"
589
		" Image Support: %s\n"
590
		"  Text Support: %s\n",
590
		"  Text Support: %s\n",
591
		cl->tech->type,
591
		cl->tech->type,
592
		(cl->tech->devicestate) ? "yes" : "no",
592
		(cl->tech->devicestate) ? "yes" : "no",
593
		(cl->tech->indicate) ? "yes" : "no",
593
		(cl->tech->indicate) ? "yes" : "no",
594
		(cl->tech->transfer) ? "yes" : "no",
594
		(cl->tech->transfer) ? "yes" : "no",
595
		ast_getformatname_multiple(buf, sizeof(buf), (cl->tech->capabilities) ? cl->tech->capabilities : -1),
595
		ast_getformatname_multiple(buf, sizeof(buf), (cl->tech->capabilities) ? cl->tech->capabilities : -1),
596
		(cl->tech->send_digit_begin) ? "yes" : "no",
596
		(cl->tech->send_digit_begin) ? "yes" : "no",
597
		(cl->tech->send_digit_end) ? "yes" : "no",
597
		(cl->tech->send_digit_end) ? "yes" : "no",
598
		(cl->tech->send_html) ? "yes" : "no",
598
		(cl->tech->send_html) ? "yes" : "no",
599
		(cl->tech->send_image) ? "yes" : "no",
599
		(cl->tech->send_image) ? "yes" : "no",
600
		(cl->tech->send_text) ? "yes" : "no"
600
		(cl->tech->send_text) ? "yes" : "no"
601
		
601
		
602
	);
602
	);
603

    
   
603

   
604
	AST_RWLIST_UNLOCK(&backends);
604
	AST_RWLIST_UNLOCK(&backends);
605

    
   
605

   
606
	return CLI_SUCCESS;
606
	return CLI_SUCCESS;
607
}
607
}
608

    
   
608

   
609
static struct ast_cli_entry cli_channel[] = {
609
static struct ast_cli_entry cli_channel[] = {
610
	AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
610
	AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
611
	AST_CLI_DEFINE(handle_cli_core_show_channeltype,  "Give more details on that channel type")
611
	AST_CLI_DEFINE(handle_cli_core_show_channeltype,  "Give more details on that channel type")
612
};
612
};
613

    
   
613

   
614
#ifdef CHANNEL_TRACE
614
#ifdef CHANNEL_TRACE
615
/*! \brief Destructor for the channel trace datastore */
615
/*! \brief Destructor for the channel trace datastore */
616
static void ast_chan_trace_destroy_cb(void *data)
616
static void ast_chan_trace_destroy_cb(void *data)
617
{
617
{
618
	struct ast_chan_trace *trace;
618
	struct ast_chan_trace *trace;
619
	struct ast_chan_trace_data *traced = data;
619
	struct ast_chan_trace_data *traced = data;
620
	while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
620
	while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
621
		ast_free(trace);
621
		ast_free(trace);
622
	}
622
	}
623
	ast_free(traced);
623
	ast_free(traced);
624
}
624
}
625

    
   
625

   
626
/*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
626
/*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
627
static const struct ast_datastore_info ast_chan_trace_datastore_info = {
627
static const struct ast_datastore_info ast_chan_trace_datastore_info = {
628
	.type = "ChanTrace",
628
	.type = "ChanTrace",
629
	.destroy = ast_chan_trace_destroy_cb
629
	.destroy = ast_chan_trace_destroy_cb
630
};
630
};
631

    
   
631

   
632
/*! \brief Put the channel backtrace in a string */
632
/*! \brief Put the channel backtrace in a string */
633
int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
633
int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
634
{
634
{
635
	int total = 0;
635
	int total = 0;
636
	struct ast_chan_trace *trace;
636
	struct ast_chan_trace *trace;
637
	struct ast_chan_trace_data *traced;
637
	struct ast_chan_trace_data *traced;
638
	struct ast_datastore *store;
638
	struct ast_datastore *store;
639

    
   
639

   
640
	ast_channel_lock(chan);
640
	ast_channel_lock(chan);
641
	store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
641
	store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
642
	if (!store) {
642
	if (!store) {
643
		ast_channel_unlock(chan);
643
		ast_channel_unlock(chan);
644
		return total;
644
		return total;
645
	}
645
	}
646
	traced = store->data;
646
	traced = store->data;
647
	ast_str_reset(*buf);
647
	ast_str_reset(*buf);
648
	AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
648
	AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
649
		if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
649
		if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
650
			ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
650
			ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
651
			total = -1;
651
			total = -1;
652
			break;
652
			break;
653
		}
653
		}
654
		total++;
654
		total++;
655
	}
655
	}
656
	ast_channel_unlock(chan);
656
	ast_channel_unlock(chan);
657
	return total;
657
	return total;
658
}
658
}
659

    
   
659

   
660
/* !\brief Whether or not context tracing is enabled */
660
/* !\brief Whether or not context tracing is enabled */
661
int ast_channel_trace_is_enabled(struct ast_channel *chan)
661
int ast_channel_trace_is_enabled(struct ast_channel *chan)
662
{
662
{
663
	struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
663
	struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
664
	if (!store)
664
	if (!store)
665
		return 0;
665
		return 0;
666
	return ((struct ast_chan_trace_data *)store->data)->enabled;
666
	return ((struct ast_chan_trace_data *)store->data)->enabled;
667
}
667
}
668

    
   
668

   
669
/*! \brief Update the context backtrace data if tracing is enabled */
669
/*! \brief Update the context backtrace data if tracing is enabled */
670
static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
670
static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
671
{
671
{
672
	struct ast_chan_trace *trace;
672
	struct ast_chan_trace *trace;
673
	if (!traced->enabled)
673
	if (!traced->enabled)
674
		return 0;
674
		return 0;
675
	/* If the last saved context does not match the current one
675
	/* If the last saved context does not match the current one
676
	   OR we have not saved any context so far, then save the current context */
676
	   OR we have not saved any context so far, then save the current context */
677
	if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) || 
677
	if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) || 
678
	    (AST_LIST_EMPTY(&traced->trace))) {
678
	    (AST_LIST_EMPTY(&traced->trace))) {
679
		/* Just do some debug logging */
679
		/* Just do some debug logging */
680
		if (AST_LIST_EMPTY(&traced->trace))
680
		if (AST_LIST_EMPTY(&traced->trace))
681
			ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
681
			ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
682
		else
682
		else
683
			ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
683
			ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
684
		/* alloc or bail out */
684
		/* alloc or bail out */
685
		trace = ast_malloc(sizeof(*trace));
685
		trace = ast_malloc(sizeof(*trace));
686
		if (!trace) 
686
		if (!trace) 
687
			return -1;
687
			return -1;
688
		/* save the current location and store it in the trace list */
688
		/* save the current location and store it in the trace list */
689
		ast_copy_string(trace->context, chan->context, sizeof(trace->context));
689
		ast_copy_string(trace->context, chan->context, sizeof(trace->context));
690
		ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
690
		ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
691
		trace->priority = chan->priority;
691
		trace->priority = chan->priority;
692
		AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
692
		AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
693
	}
693
	}
694
	return 0;
694
	return 0;
695
}
695
}
696

    
   
696

   
697
/*! \brief Update the context backtrace if tracing is enabled */
697
/*! \brief Update the context backtrace if tracing is enabled */
698
int ast_channel_trace_update(struct ast_channel *chan)
698
int ast_channel_trace_update(struct ast_channel *chan)
699
{
699
{
700
	struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
700
	struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
701
	if (!store)
701
	if (!store)
702
		return 0;
702
		return 0;
703
	return ast_channel_trace_data_update(chan, store->data);
703
	return ast_channel_trace_data_update(chan, store->data);
704
}
704
}
705

    
   
705

   
706
/*! \brief Enable context tracing in the channel */
706
/*! \brief Enable context tracing in the channel */
707
int ast_channel_trace_enable(struct ast_channel *chan)
707
int ast_channel_trace_enable(struct ast_channel *chan)
708
{
708
{
709
	struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
709
	struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
710
	struct ast_chan_trace_data *traced;
710
	struct ast_chan_trace_data *traced;
711
	if (!store) {
711
	if (!store) {
712
		store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
712
		store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
713
		if (!store) 
713
		if (!store) 
714
			return -1;
714
			return -1;
715
		traced = ast_calloc(1, sizeof(*traced));
715
		traced = ast_calloc(1, sizeof(*traced));
716
		if (!traced) {
716
		if (!traced) {
717
			ast_datastore_free(store);
717
			ast_datastore_free(store);
718
			return -1;
718
			return -1;
719
		}	
719
		}	
720
		store->data = traced;
720
		store->data = traced;
721
		AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
721
		AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
722
		ast_channel_datastore_add(chan, store);
722
		ast_channel_datastore_add(chan, store);
723
	}	
723
	}	
724
	((struct ast_chan_trace_data *)store->data)->enabled = 1;
724
	((struct ast_chan_trace_data *)store->data)->enabled = 1;
725
	ast_channel_trace_data_update(chan, store->data);
725
	ast_channel_trace_data_update(chan, store->data);
726
	return 0;
726
	return 0;
727
}
727
}
728

    
   
728

   
729
/*! \brief Disable context tracing in the channel */
729
/*! \brief Disable context tracing in the channel */
730
int ast_channel_trace_disable(struct ast_channel *chan)
730
int ast_channel_trace_disable(struct ast_channel *chan)
731
{
731
{
732
	struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
732
	struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
733
	if (!store)
733
	if (!store)
734
		return 0;
734
		return 0;
735
	((struct ast_chan_trace_data *)store->data)->enabled = 0;
735
	((struct ast_chan_trace_data *)store->data)->enabled = 0;
736
	return 0;
736
	return 0;
737
}
737
}
738
#endif /* CHANNEL_TRACE */
738
#endif /* CHANNEL_TRACE */
739

    
   
739

   
740
/*! \brief Checks to see if a channel is needing hang up */
740
/*! \brief Checks to see if a channel is needing hang up */
741
int ast_check_hangup(struct ast_channel *chan)
741
int ast_check_hangup(struct ast_channel *chan)
742
{
742
{
743
	if (chan->_softhangup)		/* yes if soft hangup flag set */
743
	if (chan->_softhangup)		/* yes if soft hangup flag set */
744
		return 1;
744
		return 1;
745
	if (ast_tvzero(chan->whentohangup))	/* no if no hangup scheduled */
745
	if (ast_tvzero(chan->whentohangup))	/* no if no hangup scheduled */
746
		return 0;
746
		return 0;
747
	if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) 	/* no if hangup time has not come yet. */
747
	if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) 	/* no if hangup time has not come yet. */
748
		return 0;
748
		return 0;
749
	ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(chan->whentohangup, ast_tvnow()));
749
	ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(chan->whentohangup, ast_tvnow()));
750
	chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;	/* record event */
750
	chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;	/* record event */
751
	return 1;
751
	return 1;
752
}
752
}
753

    
   
753

   
754
int ast_check_hangup_locked(struct ast_channel *chan)
754
int ast_check_hangup_locked(struct ast_channel *chan)
755
{
755
{
756
	int res;
756
	int res;
757
	ast_channel_lock(chan);
757
	ast_channel_lock(chan);
758
	res = ast_check_hangup(chan);
758
	res = ast_check_hangup(chan);
759
	ast_channel_unlock(chan);
759
	ast_channel_unlock(chan);
760
	return res;
760
	return res;
761
}
761
}
762

    
   
762

   
763
static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
763
static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
764
{
764
{
765
	struct ast_channel *chan = obj;
765
	struct ast_channel *chan = obj;
766

    
   
766

   
767
	ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
767
	ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
768

    
   
768

   
769
	return 0;
769
	return 0;
770
}
770
}
771

    
   
771

   
772
void ast_begin_shutdown(int hangup)
772
void ast_begin_shutdown(int hangup)
773
{
773
{
774
	shutting_down = 1;
774
	shutting_down = 1;
775

    
   
775

   
776
	if (hangup) {
776
	if (hangup) {
777
		ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
777
		ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
778
	}
778
	}
779
}
779
}
780

    
   
780

   
781
/*! \brief returns number of active/allocated channels */
781
/*! \brief returns number of active/allocated channels */
782
int ast_active_channels(void)
782
int ast_active_channels(void)
783
{
783
{
784
	return channels ? ao2_container_count(channels) : 0;
784
	return channels ? ao2_container_count(channels) : 0;
785
}
785
}
786

    
   
786

   
787
/*! \brief Cancel a shutdown in progress */
787
/*! \brief Cancel a shutdown in progress */
788
void ast_cancel_shutdown(void)
788
void ast_cancel_shutdown(void)
789
{
789
{
790
	shutting_down = 0;
790
	shutting_down = 0;
791
}
791
}
792

    
   
792

   
793
/*! \brief Returns non-zero if Asterisk is being shut down */
793
/*! \brief Returns non-zero if Asterisk is being shut down */
794
int ast_shutting_down(void)
794
int ast_shutting_down(void)
795
{
795
{
796
	return shutting_down;
796
	return shutting_down;
797
}
797
}
798

    
   
798

   
799
/*! \brief Set when to hangup channel */
799
/*! \brief Set when to hangup channel */
800
void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
800
void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
801
{
801
{
802
	chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
802
	chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
803
	ast_queue_frame(chan, &ast_null_frame);
803
	ast_queue_frame(chan, &ast_null_frame);
804
	return;
804
	return;
805
}
805
}
806

    
   
806

   
807
void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
807
void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
808
{
808
{
809
	struct timeval when = { offset, };
809
	struct timeval when = { offset, };
810
	ast_channel_setwhentohangup_tv(chan, when);
810
	ast_channel_setwhentohangup_tv(chan, when);
811
}
811
}
812

    
   
812

   
813
/*! \brief Compare a offset with when to hangup channel */
813
/*! \brief Compare a offset with when to hangup channel */
814
int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
814
int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
815
{
815
{
816
	struct timeval whentohangup;
816
	struct timeval whentohangup;
817

    
   
817

   
818
	if (ast_tvzero(chan->whentohangup))
818
	if (ast_tvzero(chan->whentohangup))
819
		return ast_tvzero(offset) ? 0 : -1;
819
		return ast_tvzero(offset) ? 0 : -1;
820

    
   
820

   
821
	if (ast_tvzero(offset))
821
	if (ast_tvzero(offset))
822
		return 1;
822
		return 1;
823

    
   
823

   
824
	whentohangup = ast_tvadd(offset, ast_tvnow());
824
	whentohangup = ast_tvadd(offset, ast_tvnow());
825

    
   
825

   
826
	return ast_tvdiff_ms(whentohangup, chan->whentohangup);
826
	return ast_tvdiff_ms(whentohangup, chan->whentohangup);
827
}
827
}
828

    
   
828

   
829
int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
829
int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
830
{
830
{
831
	struct timeval when = { offset, };
831
	struct timeval when = { offset, };
832
	return ast_channel_cmpwhentohangup_tv(chan, when);
832
	return ast_channel_cmpwhentohangup_tv(chan, when);
833
}
833
}
834

    
   
834

   
835
/*! \brief Register a new telephony channel in Asterisk */
835
/*! \brief Register a new telephony channel in Asterisk */
836
int ast_channel_register(const struct ast_channel_tech *tech)
836
int ast_channel_register(const struct ast_channel_tech *tech)
837
{
837
{
838
	struct chanlist *chan;
838
	struct chanlist *chan;
839

    
   
839

   
840
	AST_RWLIST_WRLOCK(&backends);
840
	AST_RWLIST_WRLOCK(&backends);
841

    
   
841

   
842
	AST_RWLIST_TRAVERSE(&backends, chan, list) {
842
	AST_RWLIST_TRAVERSE(&backends, chan, list) {
843
		if (!strcasecmp(tech->type, chan->tech->type)) {
843
		if (!strcasecmp(tech->type, chan->tech->type)) {
844
			ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
844
			ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
845
			AST_RWLIST_UNLOCK(&backends);
845
			AST_RWLIST_UNLOCK(&backends);
846
			return -1;
846
			return -1;
847
		}
847
		}
848
	}
848
	}
849
	
849
	
850
	if (!(chan = ast_calloc(1, sizeof(*chan)))) {
850
	if (!(chan = ast_calloc(1, sizeof(*chan)))) {
851
		AST_RWLIST_UNLOCK(&backends);
851
		AST_RWLIST_UNLOCK(&backends);
852
		return -1;
852
		return -1;
853
	}
853
	}
854
	chan->tech = tech;
854
	chan->tech = tech;
855
	AST_RWLIST_INSERT_HEAD(&backends, chan, list);
855
	AST_RWLIST_INSERT_HEAD(&backends, chan, list);
856

    
   
856

   
857
	ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
857
	ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
858

    
   
858

   
859
	ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
859
	ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
860

    
   
860

   
861
	AST_RWLIST_UNLOCK(&backends);
861
	AST_RWLIST_UNLOCK(&backends);
862

    
   
862

   
863
	return 0;
863
	return 0;
864
}
864
}
865

    
   
865

   
866
/*! \brief Unregister channel driver */
866
/*! \brief Unregister channel driver */
867
void ast_channel_unregister(const struct ast_channel_tech *tech)
867
void ast_channel_unregister(const struct ast_channel_tech *tech)
868
{
868
{
869
	struct chanlist *chan;
869
	struct chanlist *chan;
870

    
   
870

   
871
	ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
871
	ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
872

    
   
872

   
873
	AST_RWLIST_WRLOCK(&backends);
873
	AST_RWLIST_WRLOCK(&backends);
874

    
   
874

   
875
	AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
875
	AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
876
		if (chan->tech == tech) {
876
		if (chan->tech == tech) {
877
			AST_LIST_REMOVE_CURRENT(list);
877
			AST_LIST_REMOVE_CURRENT(list);
878
			ast_free(chan);
878
			ast_free(chan);
879
			ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
879
			ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
880
			break;	
880
			break;	
881
		}
881
		}
882
	}
882
	}
883
	AST_LIST_TRAVERSE_SAFE_END;
883
	AST_LIST_TRAVERSE_SAFE_END;
884

    
   
884

   
885
	AST_RWLIST_UNLOCK(&backends);
885
	AST_RWLIST_UNLOCK(&backends);
886
}
886
}
887

    
   
887

   
888
/*! \brief Get handle to channel driver based on name */
888
/*! \brief Get handle to channel driver based on name */
889
const struct ast_channel_tech *ast_get_channel_tech(const char *name)
889
const struct ast_channel_tech *ast_get_channel_tech(const char *name)
890
{
890
{
891
	struct chanlist *chanls;
891
	struct chanlist *chanls;
892
	const struct ast_channel_tech *ret = NULL;
892
	const struct ast_channel_tech *ret = NULL;
893

    
   
893

   
894
	AST_RWLIST_RDLOCK(&backends);
894
	AST_RWLIST_RDLOCK(&backends);
895

    
   
895

   
896
	AST_RWLIST_TRAVERSE(&backends, chanls, list) {
896
	AST_RWLIST_TRAVERSE(&backends, chanls, list) {
897
		if (!strcasecmp(name, chanls->tech->type)) {
897
		if (!strcasecmp(name, chanls->tech->type)) {
898
			ret = chanls->tech;
898
			ret = chanls->tech;
899
			break;
899
			break;
900
		}
900
		}
901
	}
901
	}
902

    
   
902

   
903
	AST_RWLIST_UNLOCK(&backends);
903
	AST_RWLIST_UNLOCK(&backends);
904
	
904
	
905
	return ret;
905
	return ret;
906
}
906
}
907

    
   
907

   
908
/*! \brief Gives the string form of a given hangup cause */
908
/*! \brief Gives the string form of a given hangup cause */
909
const char *ast_cause2str(int cause)
909
const char *ast_cause2str(int cause)
910
{
910
{
911
	int x;
911
	int x;
912

    
   
912

   
913
	for (x = 0; x < ARRAY_LEN(causes); x++) {
913
	for (x = 0; x < ARRAY_LEN(causes); x++) {
914
		if (causes[x].cause == cause)
914
		if (causes[x].cause == cause)
915
			return causes[x].desc;
915
			return causes[x].desc;
916
	}
916
	}
917

    
   
917

   
918
	return "Unknown";
918
	return "Unknown";
919
}
919
}
920

    
   
920

   
921
/*! \brief Convert a symbolic hangup cause to number */
921
/*! \brief Convert a symbolic hangup cause to number */
922
int ast_str2cause(const char *name)
922
int ast_str2cause(const char *name)
923
{
923
{
924
	int x;
924
	int x;
925

    
   
925

   
926
	for (x = 0; x < ARRAY_LEN(causes); x++)
926
	for (x = 0; x < ARRAY_LEN(causes); x++)
927
		if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
927
		if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
928
			return causes[x].cause;
928
			return causes[x].cause;
929

    
   
929

   
930
	return -1;
930
	return -1;
931
}
931
}
932

    
   
932

   
933
/*! \brief Gives the string form of a given channel state.
933
/*! \brief Gives the string form of a given channel state.
934
	\note This function is not reentrant.
934
	\note This function is not reentrant.
935
 */
935
 */
936
const char *ast_state2str(enum ast_channel_state state)
936
const char *ast_state2str(enum ast_channel_state state)
937
{
937
{
938
	char *buf;
938
	char *buf;
939

    
   
939

   
940
	switch (state) {
940
	switch (state) {
941
	case AST_STATE_DOWN:
941
	case AST_STATE_DOWN:
942
		return "Down";
942
		return "Down";
943
	case AST_STATE_RESERVED:
943
	case AST_STATE_RESERVED:
944
		return "Rsrvd";
944
		return "Rsrvd";
945
	case AST_STATE_OFFHOOK:
945
	case AST_STATE_OFFHOOK:
946
		return "OffHook";
946
		return "OffHook";
947
	case AST_STATE_DIALING:
947
	case AST_STATE_DIALING:
948
		return "Dialing";
948
		return "Dialing";
949
	case AST_STATE_RING:
949
	case AST_STATE_RING:
950
		return "Ring";
950
		return "Ring";
951
	case AST_STATE_RINGING:
951
	case AST_STATE_RINGING:
952
		return "Ringing";
952
		return "Ringing";
953
	case AST_STATE_UP:
953
	case AST_STATE_UP:
954
		return "Up";
954
		return "Up";
955
	case AST_STATE_BUSY:
955
	case AST_STATE_BUSY:
956
		return "Busy";
956
		return "Busy";
957
	case AST_STATE_DIALING_OFFHOOK:
957
	case AST_STATE_DIALING_OFFHOOK:
958
		return "Dialing Offhook";
958
		return "Dialing Offhook";
959
	case AST_STATE_PRERING:
959
	case AST_STATE_PRERING:
960
		return "Pre-ring";
960
		return "Pre-ring";
961
	default:
961
	default:
962
		if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
962
		if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
963
			return "Unknown";
963
			return "Unknown";
964
		snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
964
		snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
965
		return buf;
965
		return buf;
966
	}
966
	}
967
}
967
}
968

    
   
968

   
969
/*! \brief Gives the string form of a given transfer capability */
969
/*! \brief Gives the string form of a given transfer capability */
970
char *ast_transfercapability2str(int transfercapability)
970
char *ast_transfercapability2str(int transfercapability)
971
{
971
{
972
	switch (transfercapability) {
972
	switch (transfercapability) {
973
	case AST_TRANS_CAP_SPEECH:
973
	case AST_TRANS_CAP_SPEECH:
974
		return "SPEECH";
974
		return "SPEECH";
975
	case AST_TRANS_CAP_DIGITAL:
975
	case AST_TRANS_CAP_DIGITAL:
976
		return "DIGITAL";
976
		return "DIGITAL";
977
	case AST_TRANS_CAP_RESTRICTED_DIGITAL:
977
	case AST_TRANS_CAP_RESTRICTED_DIGITAL:
978
		return "RESTRICTED_DIGITAL";
978
		return "RESTRICTED_DIGITAL";
979
	case AST_TRANS_CAP_3_1K_AUDIO:
979
	case AST_TRANS_CAP_3_1K_AUDIO:
980
		return "3K1AUDIO";
980
		return "3K1AUDIO";
981
	case AST_TRANS_CAP_DIGITAL_W_TONES:
981
	case AST_TRANS_CAP_DIGITAL_W_TONES:
982
		return "DIGITAL_W_TONES";
982
		return "DIGITAL_W_TONES";
983
	case AST_TRANS_CAP_VIDEO:
983
	case AST_TRANS_CAP_VIDEO:
984
		return "VIDEO";
984
		return "VIDEO";
985
	default:
985
	default:
986
		return "UNKNOWN";
986
		return "UNKNOWN";
987
	}
987
	}
988
}
988
}
989

    
   
989

   
990
/*! \brief Pick the best audio codec */
990
/*! \brief Pick the best audio codec */
991
format_t ast_best_codec(format_t fmts)
991
format_t ast_best_codec(format_t fmts)
992
{
992
{
993
	/* This just our opinion, expressed in code.  We are asked to choose
993
	/* This just our opinion, expressed in code.  We are asked to choose
994
	   the best codec to use, given no information */
994
	   the best codec to use, given no information */
995
	int x;
995
	int x;
996
	static const format_t prefs[] =
996
	static const format_t prefs[] =
997
	{
997
	{
998
		/*! Okay, ulaw is used by all telephony equipment, so start with it */
998
		/*! Okay, ulaw is used by all telephony equipment, so start with it */
999
		AST_FORMAT_ULAW,
999
		AST_FORMAT_ULAW,
1000
		/*! Unless of course, you're a silly European, so then prefer ALAW */
1000
		/*! Unless of course, you're a silly European, so then prefer ALAW */
1001
		AST_FORMAT_ALAW,
1001
		AST_FORMAT_ALAW,
1002
		AST_FORMAT_G719,
1002
		AST_FORMAT_G719,
1003
		AST_FORMAT_SIREN14,
1003
		AST_FORMAT_SIREN14,
1004
		AST_FORMAT_SIREN7,
1004
		AST_FORMAT_SIREN7,
1005
		AST_FORMAT_TESTLAW,
1005
		AST_FORMAT_TESTLAW,
1006
		/*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
1006
		/*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
1007
		AST_FORMAT_G722,
1007
		AST_FORMAT_G722,
1008
		/*! Okay, well, signed linear is easy to translate into other stuff */
1008
		/*! Okay, well, signed linear is easy to translate into other stuff */
1009
		AST_FORMAT_SLINEAR16,
1009
		AST_FORMAT_SLINEAR16,
1010
		AST_FORMAT_SLINEAR,
1010
		AST_FORMAT_SLINEAR,
1011
		/*! G.726 is standard ADPCM, in RFC3551 packing order */
1011
		/*! G.726 is standard ADPCM, in RFC3551 packing order */
1012
		AST_FORMAT_G726,
1012
		AST_FORMAT_G726,
1013
		/*! G.726 is standard ADPCM, in AAL2 packing order */
1013
		/*! G.726 is standard ADPCM, in AAL2 packing order */
1014
		AST_FORMAT_G726_AAL2,
1014
		AST_FORMAT_G726_AAL2,
1015
		/*! ADPCM has great sound quality and is still pretty easy to translate */
1015
		/*! ADPCM has great sound quality and is still pretty easy to translate */
1016
		AST_FORMAT_ADPCM,
1016
		AST_FORMAT_ADPCM,
1017
		/*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
1017
		/*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
1018
		    translate and sounds pretty good */
1018
		    translate and sounds pretty good */
1019
		AST_FORMAT_GSM,
1019
		AST_FORMAT_GSM,
1020
		/*! iLBC is not too bad */
1020
		/*! iLBC is not too bad */
1021
		AST_FORMAT_ILBC,
1021
		AST_FORMAT_ILBC,
1022
		/*! Speex is free, but computationally more expensive than GSM */
1022
		/*! Speex is free, but computationally more expensive than GSM */
1023
		AST_FORMAT_SPEEX16,
1023
		AST_FORMAT_SPEEX16,
1024
		AST_FORMAT_SPEEX,
1024
		AST_FORMAT_SPEEX,
1025
		/*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
1025
		/*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
1026
		    to use it */
1026
		    to use it */
1027
		AST_FORMAT_LPC10,
1027
		AST_FORMAT_LPC10,
1028
		/*! G.729a is faster than 723 and slightly less expensive */
1028
		/*! G.729a is faster than 723 and slightly less expensive */
1029
		AST_FORMAT_G729A,
1029
		AST_FORMAT_G729A,
1030
		/*! Down to G.723.1 which is proprietary but at least designed for voice */
1030
		/*! Down to G.723.1 which is proprietary but at least designed for voice */
1031
		AST_FORMAT_G723_1,
1031
		AST_FORMAT_G723_1,
1032
	};
1032
	};
1033
	char buf[512];
1033
	char buf[512];
1034

    
   
1034

   
1035
	/* Strip out video */
1035
	/* Strip out video */
1036
	fmts &= AST_FORMAT_AUDIO_MASK;
1036
	fmts &= AST_FORMAT_AUDIO_MASK;
1037
	
1037
	
1038
	/* Find the first preferred codec in the format given */
1038
	/* Find the first preferred codec in the format given */
1039
	for (x = 0; x < ARRAY_LEN(prefs); x++) {
1039
	for (x = 0; x < ARRAY_LEN(prefs); x++) {
1040
		if (fmts & prefs[x])
1040
		if (fmts & prefs[x])
1041
			return prefs[x];
1041
			return prefs[x];
1042
	}
1042
	}
1043

    
   
1043

   
1044
	ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), fmts));
1044
	ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), fmts));
1045

    
   
1045

   
1046
	return 0;
1046
	return 0;
1047
}
1047
}
1048

    
   
1048

   
1049
static const struct ast_channel_tech null_tech = {
1049
static const struct ast_channel_tech null_tech = {
1050
	.type = "NULL",
1050
	.type = "NULL",
1051
	.description = "Null channel (should not see this)",
1051
	.description = "Null channel (should not see this)",
1052
};
1052
};
1053

    
   
1053

   
1054
static void ast_channel_destructor(void *obj);
1054
static void ast_channel_destructor(void *obj);
1055
static void ast_dummy_channel_destructor(void *obj);
1055
static void ast_dummy_channel_destructor(void *obj);
1056

    
   
1056

   
1057
/*! \brief Create a new channel structure */
1057
/*! \brief Create a new channel structure */
1058
static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
1058
static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
1059
__ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
1059
__ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
1060
		       const char *acctcode, const char *exten, const char *context,
1060
		       const char *acctcode, const char *exten, const char *context,
1061
		       const char *linkedid, const int amaflag, const char *file, int line,
1061
		       const char *linkedid, const int amaflag, const char *file, int line,
1062
		       const char *function, const char *name_fmt, va_list ap1, va_list ap2)
1062
		       const char *function, const char *name_fmt, va_list ap1, va_list ap2)
1063
{
1063
{
1064
	struct ast_channel *tmp;
1064
	struct ast_channel *tmp;
1065
	int x;
1065
	int x;
1066
	int flags;
1066
	int flags;
1067
	struct varshead *headp;
1067
	struct varshead *headp;
1068
	char *tech = "";
1068
	char *tech = "";
1069

    
   
1069

   
1070
	/* If shutting down, don't allocate any new channels */
1070
	/* If shutting down, don't allocate any new channels */
1071
	if (shutting_down) {
1071
	if (shutting_down) {
1072
		ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
1072
		ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
1073
		return NULL;
1073
		return NULL;
1074
	}
1074
	}
1075

    
   
1075

   
1076
#if defined(REF_DEBUG)
1076
#if defined(REF_DEBUG)
1077
	tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1077
	tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1078
		function, 1);
1078
		function, 1);
1079
#elif defined(__AST_DEBUG_MALLOC)
1079
#elif defined(__AST_DEBUG_MALLOC)
1080
	tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1080
	tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1081
		function, 0);
1081
		function, 0);
1082
#else
1082
#else
1083
	tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor);
1083
	tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor);
1084
#endif
1084
#endif
1085
	if (!tmp) {
1085
	if (!tmp) {
1086
		/* Channel structure allocation failure. */
1086
		/* Channel structure allocation failure. */
1087
		return NULL;
1087
		return NULL;
1088
	}
1088
	}
1089

    
   
1089

   
1090
	/*
1090
	/*
1091
	 * Init file descriptors to unopened state so
1091
	 * Init file descriptors to unopened state so
1092
	 * the destructor can know not to close them.
1092
	 * the destructor can know not to close them.
1093
	 */
1093
	 */
1094
	tmp->timingfd = -1;
1094
	tmp->timingfd = -1;
1095
	for (x = 0; x < ARRAY_LEN(tmp->alertpipe); ++x) {
1095
	for (x = 0; x < ARRAY_LEN(tmp->alertpipe); ++x) {
1096
		tmp->alertpipe[x] = -1;
1096
		tmp->alertpipe[x] = -1;
1097
	}
1097
	}
1098
	for (x = 0; x < ARRAY_LEN(tmp->fds); ++x) {
1098
	for (x = 0; x < ARRAY_LEN(tmp->fds); ++x) {
1099
		tmp->fds[x] = -1;
1099
		tmp->fds[x] = -1;
1100
	}
1100
	}
1101
#ifdef HAVE_EPOLL
1101
#ifdef HAVE_EPOLL
1102
	tmp->epfd = epoll_create(25);
1102
	tmp->epfd = epoll_create(25);
1103
#endif
1103
#endif
1104

    
   
1104

   
1105
	if (!(tmp->sched = sched_context_create())) {
1105
	if (!(tmp->sched = sched_context_create())) {
1106
		ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
1106
		ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
1107
		return ast_channel_unref(tmp);
1107
		return ast_channel_unref(tmp);
1108
	}
1108
	}
1109
	
1109
	
1110
	ast_party_dialed_init(&tmp->dialed);
1110
	ast_party_dialed_init(&tmp->dialed);
1111
	ast_party_caller_init(&tmp->caller);
1111
	ast_party_caller_init(&tmp->caller);
1112
	ast_party_connected_line_init(&tmp->connected);
1112
	ast_party_connected_line_init(&tmp->connected);
1113
	ast_party_redirecting_init(&tmp->redirecting);
1113
	ast_party_redirecting_init(&tmp->redirecting);
1114

    
   
1114

   
1115
	if (cid_name) {
1115
	if (cid_name) {
1116
		tmp->caller.id.name.valid = 1;
1116
		tmp->caller.id.name.valid = 1;
1117
		tmp->caller.id.name.str = ast_strdup(cid_name);
1117
		tmp->caller.id.name.str = ast_strdup(cid_name);
1118
		if (!tmp->caller.id.name.str) {
1118
		if (!tmp->caller.id.name.str) {
1119
			return ast_channel_unref(tmp);
1119
			return ast_channel_unref(tmp);
1120
		}
1120
		}
1121
	}
1121
	}
1122
	if (cid_num) {
1122
	if (cid_num) {
1123
		tmp->caller.id.number.valid = 1;
1123
		tmp->caller.id.number.valid = 1;
1124
		tmp->caller.id.number.str = ast_strdup(cid_num);
1124
		tmp->caller.id.number.str = ast_strdup(cid_num);
1125
		if (!tmp->caller.id.number.str) {
1125
		if (!tmp->caller.id.number.str) {
1126
			return ast_channel_unref(tmp);
1126
			return ast_channel_unref(tmp);
1127
		}
1127
		}
1128
	}
1128
	}
1129

    
   
1129

   
1130
	if ((tmp->timer = ast_timer_open())) {
1130
	if ((tmp->timer = ast_timer_open())) {
1131
		needqueue = 0;
1131
		needqueue = 0;
1132
		tmp->timingfd = ast_timer_fd(tmp->timer);
1132
		tmp->timingfd = ast_timer_fd(tmp->timer);
1133
	}
1133
	}
1134

    
   
1134

   
1135
	if (needqueue) {
1135
	if (needqueue) {
1136
		if (pipe(tmp->alertpipe)) {
1136
		if (pipe(tmp->alertpipe)) {
1137
			ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
1137
			ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
1138
			return ast_channel_unref(tmp);
1138
			return ast_channel_unref(tmp);
1139
		} else {
1139
		} else {
1140
			flags = fcntl(tmp->alertpipe[0], F_GETFL);
1140
			flags = fcntl(tmp->alertpipe[0], F_GETFL);
1141
			if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
1141
			if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
1142
				ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1142
				ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1143
				return ast_channel_unref(tmp);
1143
				return ast_channel_unref(tmp);
1144
			}
1144
			}
1145
			flags = fcntl(tmp->alertpipe[1], F_GETFL);
1145
			flags = fcntl(tmp->alertpipe[1], F_GETFL);
1146
			if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
1146
			if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
1147
				ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1147
				ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1148
				return ast_channel_unref(tmp);
1148
				return ast_channel_unref(tmp);
1149
			}
1149
			}
1150
		}
1150
		}
1151
	}
1151
	}
1152

    
   
1152

   
1153
	/*
1153
	/*
1154
	 * This is the last place the channel constructor can fail.
1154
	 * This is the last place the channel constructor can fail.
1155
	 *
1155
	 *
1156
	 * The destructor takes advantage of this fact to ensure that the
1156
	 * The destructor takes advantage of this fact to ensure that the
1157
	 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1157
	 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1158
	 * AST_CEL_CHANNEL_START yet.
1158
	 * AST_CEL_CHANNEL_START yet.
1159
	 */
1159
	 */
1160
	if ((ast_string_field_init(tmp, 128))) {
1160
	if ((ast_string_field_init(tmp, 128))) {
1161
		return ast_channel_unref(tmp);
1161
		return ast_channel_unref(tmp);
1162
	}
1162
	}
1163

    
   
1163

   
1164
	/* Always watch the alertpipe */
1164
	/* Always watch the alertpipe */
1165
	ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
1165
	ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
1166
	/* And timing pipe */
1166
	/* And timing pipe */
1167
	ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
1167
	ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
1168

    
   
1168

   
1169
	/* Initial state */
1169
	/* Initial state */
1170
	tmp->_state = state;
1170
	tmp->_state = state;
1171

    
   
1171

   
1172
	tmp->streamid = -1;
1172
	tmp->streamid = -1;
1173
	
1173
	
1174
	tmp->fin = global_fin;
1174
	tmp->fin = global_fin;
1175
	tmp->fout = global_fout;
1175
	tmp->fout = global_fout;
1176

    
   
1176

   
1177
	if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1177
	if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1178
		ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
1178
		ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
1179
			ast_atomic_fetchadd_int(&uniqueint, 1));
1179
			ast_atomic_fetchadd_int(&uniqueint, 1));
1180
	} else {
1180
	} else {
1181
		ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
1181
		ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
1182
			(long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1182
			(long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1183
	}
1183
	}
1184

    
   
1184

   
1185
	if (!ast_strlen_zero(linkedid)) {
1185
	if (!ast_strlen_zero(linkedid)) {
1186
		ast_string_field_set(tmp, linkedid, linkedid);
1186
		ast_string_field_set(tmp, linkedid, linkedid);
1187
	} else {
1187
	} else {
1188
		ast_string_field_set(tmp, linkedid, tmp->uniqueid);
1188
		ast_string_field_set(tmp, linkedid, tmp->uniqueid);
1189
	}
1189
	}
1190

    
   
1190

   
1191
	if (!ast_strlen_zero(name_fmt)) {
1191
	if (!ast_strlen_zero(name_fmt)) {
1192
		char *slash;
1192
		char *slash;
1193
		/* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1193
		/* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1194
		 * And they all use slightly different formats for their name string.
1194
		 * And they all use slightly different formats for their name string.
1195
		 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1195
		 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1196
		 * This means, that the stringfields must have a routine that takes the va_lists directly, and 
1196
		 * This means, that the stringfields must have a routine that takes the va_lists directly, and 
1197
		 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1197
		 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1198
		 * This new function was written so this can be accomplished.
1198
		 * This new function was written so this can be accomplished.
1199
		 */
1199
		 */
1200
		ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
1200
		ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
1201
		tech = ast_strdupa(tmp->name);
1201
		tech = ast_strdupa(tmp->name);
1202
		if ((slash = strchr(tech, '/'))) {
1202
		if ((slash = strchr(tech, '/'))) {
1203
			*slash = '\0';
1203
			*slash = '\0';
1204
		}
1204
		}
1205
	} else {
1205
	} else {
1206
		/*
1206
		/*
1207
		 * Start the string with '-' so it becomes an empty string
1207
		 * Start the string with '-' so it becomes an empty string
1208
		 * in the destructor.
1208
		 * in the destructor.
1209
		 */
1209
		 */
1210
		ast_string_field_set(tmp, name, "-**Unknown**");
1210
		ast_string_field_set(tmp, name, "-**Unknown**");
1211
	}
1211
	}
1212

    
   
1212

   
1213
	/* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1213
	/* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1214

    
   
1214

   
1215
	/* These 4 variables need to be set up for the cdr_init() to work right */
1215
	/* These 4 variables need to be set up for the cdr_init() to work right */
1216
	if (amaflag)
1216
	if (amaflag)
1217
		tmp->amaflags = amaflag;
1217
		tmp->amaflags = amaflag;
1218
	else
1218
	else
1219
		tmp->amaflags = ast_default_amaflags;
1219
		tmp->amaflags = ast_default_amaflags;
1220
	
1220
	
1221
	if (!ast_strlen_zero(acctcode))
1221
	if (!ast_strlen_zero(acctcode))
1222
		ast_string_field_set(tmp, accountcode, acctcode);
1222
		ast_string_field_set(tmp, accountcode, acctcode);
1223
	else
1223
	else
1224
		ast_string_field_set(tmp, accountcode, ast_default_accountcode);
1224
		ast_string_field_set(tmp, accountcode, ast_default_accountcode);
1225
		
1225
		
1226
	if (!ast_strlen_zero(context))
1226
	if (!ast_strlen_zero(context))
1227
		ast_copy_string(tmp->context, context, sizeof(tmp->context));
1227
		ast_copy_string(tmp->context, context, sizeof(tmp->context));
1228
	else
1228
	else
1229
		strcpy(tmp->context, "default");
1229
		strcpy(tmp->context, "default");
1230

    
   
1230

   
1231
	if (!ast_strlen_zero(exten))
1231
	if (!ast_strlen_zero(exten))
1232
		ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1232
		ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1233
	else
1233
	else
1234
		strcpy(tmp->exten, "s");
1234
		strcpy(tmp->exten, "s");
1235

    
   
1235

   
1236
	tmp->priority = 1;
1236
	tmp->priority = 1;
1237

    
   
1237

   
1238
	tmp->cdr = ast_cdr_alloc();
1238
	tmp->cdr = ast_cdr_alloc();
1239
	ast_cdr_init(tmp->cdr, tmp);
1239
	ast_cdr_init(tmp->cdr, tmp);
1240
	ast_cdr_start(tmp->cdr);
1240
	ast_cdr_start(tmp->cdr);
1241

    
   
1241

   
1242
	ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1242
	ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1243

    
   
1243

   
1244
	headp = &tmp->varshead;
1244
	headp = &tmp->varshead;
1245
	AST_LIST_HEAD_INIT_NOLOCK(headp);
1245
	AST_LIST_HEAD_INIT_NOLOCK(headp);
1246
	
1246
	
1247
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1247
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1248

    
   
1248

   
1249
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1249
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1250
	
1250
	
1251
	ast_string_field_set(tmp, language, defaultlanguage);
1251
	ast_string_field_set(tmp, language, defaultlanguage);
1252

    
   
1252

   
1253
	tmp->tech = &null_tech;
1253
	tmp->tech = &null_tech;
1254

    
   
1254

   
1255
	ao2_link(channels, tmp);
1255
	ao2_link(channels, tmp);
1256

    
   
1256

   
1257
	/*
1257
	/*
1258
	 * And now, since the channel structure is built, and has its name, let's
1258
	 * And now, since the channel structure is built, and has its name, let's
1259
	 * call the manager event generator with this Newchannel event. This is the
1259
	 * call the manager event generator with this Newchannel event. This is the
1260
	 * proper and correct place to make this call, but you sure do have to pass
1260
	 * proper and correct place to make this call, but you sure do have to pass
1261
	 * a lot of data into this func to do it here!
1261
	 * a lot of data into this func to do it here!
1262
	 */
1262
	 */
1263
	if (ast_get_channel_tech(tech)) {
1263
	if (ast_get_channel_tech(tech)) {
1264
		ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1264
		ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1265
			"Channel: %s\r\n"
1265
			"Channel: %s\r\n"
1266
			"ChannelState: %d\r\n"
1266
			"ChannelState: %d\r\n"
1267
			"ChannelStateDesc: %s\r\n"
1267
			"ChannelStateDesc: %s\r\n"
1268
			"CallerIDNum: %s\r\n"
1268
			"CallerIDNum: %s\r\n"
1269
			"CallerIDName: %s\r\n"
1269
			"CallerIDName: %s\r\n"
1270
			"AccountCode: %s\r\n"
1270
			"AccountCode: %s\r\n"
1271
			"Exten: %s\r\n"
1271
			"Exten: %s\r\n"
1272
			"Context: %s\r\n"
1272
			"Context: %s\r\n"
1273
			"Uniqueid: %s\r\n",
1273
			"Uniqueid: %s\r\n",
1274
			tmp->name, 
1274
			tmp->name, 
1275
			state, 
1275
			state, 
1276
			ast_state2str(state),
1276
			ast_state2str(state),
1277
			S_OR(cid_num, ""),
1277
			S_OR(cid_num, ""),
1278
			S_OR(cid_name, ""),
1278
			S_OR(cid_name, ""),
1279
			tmp->accountcode,
1279
			tmp->accountcode,
1280
			S_OR(exten, ""),
1280
			S_OR(exten, ""),
1281
			S_OR(context, ""),
1281
			S_OR(context, ""),
1282
			tmp->uniqueid);
1282
			tmp->uniqueid);
1283
	}
1283
	}
1284

    
   
1284

   
1285
	return tmp;
1285
	return tmp;
1286
}
1286
}
1287

    
   
1287

   
1288
struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1288
struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1289
					const char *cid_name, const char *acctcode,
1289
					const char *cid_name, const char *acctcode,
1290
					const char *exten, const char *context,
1290
					const char *exten, const char *context,
1291
					const char *linkedid, const int amaflag,
1291
					const char *linkedid, const int amaflag,
1292
					const char *file, int line, const char *function,
1292
					const char *file, int line, const char *function,
1293
					const char *name_fmt, ...)
1293
					const char *name_fmt, ...)
1294
{
1294
{
1295
	va_list ap1, ap2;
1295
	va_list ap1, ap2;
1296
	struct ast_channel *result;
1296
	struct ast_channel *result;
1297

    
   
1297

   
1298
	va_start(ap1, name_fmt);
1298
	va_start(ap1, name_fmt);
1299
	va_start(ap2, name_fmt);
1299
	va_start(ap2, name_fmt);
1300
	result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1300
	result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1301
					linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
1301
					linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
1302
	va_end(ap1);
1302
	va_end(ap1);
1303
	va_end(ap2);
1303
	va_end(ap2);
1304

    
   
1304

   
1305
	return result;
1305
	return result;
1306
}
1306
}
1307

    
   
1307

   
1308
/* only do the minimum amount of work needed here to make a channel
1308
/* only do the minimum amount of work needed here to make a channel
1309
 * structure that can be used to expand channel vars */
1309
 * structure that can be used to expand channel vars */
1310
#if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1310
#if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1311
struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1311
struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1312
#else
1312
#else
1313
struct ast_channel *ast_dummy_channel_alloc(void)
1313
struct ast_channel *ast_dummy_channel_alloc(void)
1314
#endif
1314
#endif
1315
{
1315
{
1316
	struct ast_channel *tmp;
1316
	struct ast_channel *tmp;
1317
	struct varshead *headp;
1317
	struct varshead *headp;
1318

    
   
1318

   
1319
#if defined(REF_DEBUG)
1319
#if defined(REF_DEBUG)
1320
	tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1320
	tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1321
		file, line, function, 1);
1321
		file, line, function, 1);
1322
#elif defined(__AST_DEBUG_MALLOC)
1322
#elif defined(__AST_DEBUG_MALLOC)
1323
	tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1323
	tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1324
		file, line, function, 0);
1324
		file, line, function, 0);
1325
#else
1325
#else
1326
	tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1326
	tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1327
#endif
1327
#endif
1328
	if (!tmp) {
1328
	if (!tmp) {
1329
		/* Dummy channel structure allocation failure. */
1329
		/* Dummy channel structure allocation failure. */
1330
		return NULL;
1330
		return NULL;
1331
	}
1331
	}
1332

    
   
1332

   
1333
	if ((ast_string_field_init(tmp, 128))) {
1333
	if ((ast_string_field_init(tmp, 128))) {
1334
		return ast_channel_unref(tmp);
1334
		return ast_channel_unref(tmp);
1335
	}
1335
	}
1336

    
   
1336

   
1337
	headp = &tmp->varshead;
1337
	headp = &tmp->varshead;
1338
	AST_LIST_HEAD_INIT_NOLOCK(headp);
1338
	AST_LIST_HEAD_INIT_NOLOCK(headp);
1339

    
   
1339

   
1340
	return tmp;
1340
	return tmp;
1341
}
1341
}
1342

    
   
1342

   
1343
static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1343
static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1344
{
1344
{
1345
	struct ast_frame *f;
1345
	struct ast_frame *f;
1346
	struct ast_frame *cur;
1346
	struct ast_frame *cur;
1347
	int blah = 1;
1347
	int blah = 1;
1348
	unsigned int new_frames = 0;
1348
	unsigned int new_frames = 0;
1349
	unsigned int new_voice_frames = 0;
1349
	unsigned int new_voice_frames = 0;
1350
	unsigned int queued_frames = 0;
1350
	unsigned int queued_frames = 0;
1351
	unsigned int queued_voice_frames = 0;
1351
	unsigned int queued_voice_frames = 0;
1352
	AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1352
	AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1353

    
   
1353

   
1354
	ast_channel_lock(chan);
1354
	ast_channel_lock(chan);
1355

    
   
1355

   
1356
	/* See if the last frame on the queue is a hangup, if so don't queue anything */
1356
	/* See if the last frame on the queue is a hangup, if so don't queue anything */
1357
	if ((cur = AST_LIST_LAST(&chan->readq)) &&
1357
	if ((cur = AST_LIST_LAST(&chan->readq)) &&
1358
	    (cur->frametype == AST_FRAME_CONTROL) &&
1358
	    (cur->frametype == AST_FRAME_CONTROL) &&
1359
	    (cur->subclass.integer == AST_CONTROL_HANGUP)) {
1359
	    (cur->subclass.integer == AST_CONTROL_HANGUP)) {
1360
		ast_channel_unlock(chan);
1360
		ast_channel_unlock(chan);
1361
		return 0;
1361
		return 0;
1362
	}
1362
	}
1363

    
   
1363

   
1364
	/* Build copies of all the frames and count them */
1364
	/* Build copies of all the frames and count them */
1365
	AST_LIST_HEAD_INIT_NOLOCK(&frames);
1365
	AST_LIST_HEAD_INIT_NOLOCK(&frames);
1366
	for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1366
	for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1367
		if (!(f = ast_frdup(cur))) {
1367
		if (!(f = ast_frdup(cur))) {
1368
			ast_frfree(AST_LIST_FIRST(&frames));
1368
			ast_frfree(AST_LIST_FIRST(&frames));
1369
			ast_channel_unlock(chan);
1369
			ast_channel_unlock(chan);
1370
			return -1;
1370
			return -1;
1371
		}
1371
		}
1372

    
   
1372

   
1373
		AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1373
		AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1374
		new_frames++;
1374
		new_frames++;
1375
		if (f->frametype == AST_FRAME_VOICE) {
1375
		if (f->frametype == AST_FRAME_VOICE) {
1376
			new_voice_frames++;
1376
			new_voice_frames++;
1377
		}
1377
		}
1378
	}
1378
	}
1379

    
   
1379

   
1380
	/* Count how many frames exist on the queue */
1380
	/* Count how many frames exist on the queue */
1381
	AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1381
	AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1382
		queued_frames++;
1382
		queued_frames++;
1383
		if (cur->frametype == AST_FRAME_VOICE) {
1383
		if (cur->frametype == AST_FRAME_VOICE) {
1384
			queued_voice_frames++;
1384
			queued_voice_frames++;
1385
		}
1385
		}
1386
	}
1386
	}
1387

    
   
1387

   
1388
	if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1388
	if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1389
		int count = 0;
1389
		int count = 0;
1390
		ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
1390
		ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
1391
		AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1391
		AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1392
			/* Save the most recent frame */
1392
			/* Save the most recent frame */
1393
			if (!AST_LIST_NEXT(cur, frame_list)) {
1393
			if (!AST_LIST_NEXT(cur, frame_list)) {
1394
				break;
1394
				break;
1395
			} else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1395
			} else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1396
				if (++count > 64) {
1396
				if (++count > 64) {
1397
					break;
1397
					break;
1398
				}
1398
				}
1399
				AST_LIST_REMOVE_CURRENT(frame_list);
1399
				AST_LIST_REMOVE_CURRENT(frame_list);
1400
				ast_frfree(cur);
1400
				ast_frfree(cur);
1401
			}
1401
			}
1402
		}
1402
		}
1403
		AST_LIST_TRAVERSE_SAFE_END;
1403
		AST_LIST_TRAVERSE_SAFE_END;
1404
	}
1404
	}
1405

    
   
1405

   
1406
	if (after) {
1406
	if (after) {
1407
		AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1407
		AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1408
	} else {
1408
	} else {
1409
		if (head) {
1409
		if (head) {
1410
			AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1410
			AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1411
			AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1411
			AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1412
		}
1412
		}
1413
		AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1413
		AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1414
	}
1414
	}
1415

    
   
1415

   
1416
	if (chan->alertpipe[1] > -1) {
1416
	if (chan->alertpipe[1] > -1) {
1417
		if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1417
		if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1418
			ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1418
			ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1419
				chan->name, queued_frames, strerror(errno));
1419
				chan->name, queued_frames, strerror(errno));
1420
		}
1420
		}
1421
	} else if (chan->timingfd > -1) {
1421
	} else if (chan->timingfd > -1) {
1422
		ast_timer_enable_continuous(chan->timer);
1422
		ast_timer_enable_continuous(chan->timer);
1423
	} else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1423
	} else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1424
		pthread_kill(chan->blocker, SIGURG);
1424
		pthread_kill(chan->blocker, SIGURG);
1425
	}
1425
	}
1426

    
   
1426

   
1427
	ast_channel_unlock(chan);
1427
	ast_channel_unlock(chan);
1428

    
   
1428

   
1429
	return 0;
1429
	return 0;
1430
}
1430
}
1431

    
   
1431

   
1432
int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1432
int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1433
{
1433
{
1434
	return __ast_queue_frame(chan, fin, 0, NULL);
1434
	return __ast_queue_frame(chan, fin, 0, NULL);
1435
}
1435
}
1436

    
   
1436

   
1437
int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1437
int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1438
{
1438
{
1439
	return __ast_queue_frame(chan, fin, 1, NULL);
1439
	return __ast_queue_frame(chan, fin, 1, NULL);
1440
}
1440
}
1441

    
   
1441

   
1442
/*! \brief Queue a hangup frame for channel */
1442
/*! \brief Queue a hangup frame for channel */
1443
int ast_queue_hangup(struct ast_channel *chan)
1443
int ast_queue_hangup(struct ast_channel *chan)
1444
{
1444
{
1445
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1445
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1446
	/* Yeah, let's not change a lock-critical value without locking */
1446
	/* Yeah, let's not change a lock-critical value without locking */
1447
	if (!ast_channel_trylock(chan)) {
1447
	if (!ast_channel_trylock(chan)) {
1448
		chan->_softhangup |= AST_SOFTHANGUP_DEV;
1448
		chan->_softhangup |= AST_SOFTHANGUP_DEV;
1449
		ast_channel_unlock(chan);
1449
		ast_channel_unlock(chan);
1450
	}
1450
	}
1451
	return ast_queue_frame(chan, &f);
1451
	return ast_queue_frame(chan, &f);
1452
}
1452
}
1453

    
   
1453

   
1454
/*! \brief Queue a hangup frame for channel */
1454
/*! \brief Queue a hangup frame for channel */
1455
int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1455
int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1456
{
1456
{
1457
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1457
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1458

    
   
1458

   
1459
	if (cause >= 0)
1459
	if (cause >= 0)
1460
		f.data.uint32 = cause;
1460
		f.data.uint32 = cause;
1461

    
   
1461

   
1462
	/* Yeah, let's not change a lock-critical value without locking */
1462
	/* Yeah, let's not change a lock-critical value without locking */
1463
	if (!ast_channel_trylock(chan)) {
1463
	if (!ast_channel_trylock(chan)) {
1464
		chan->_softhangup |= AST_SOFTHANGUP_DEV;
1464
		chan->_softhangup |= AST_SOFTHANGUP_DEV;
1465
		if (cause < 0)
1465
		if (cause < 0)
1466
			f.data.uint32 = chan->hangupcause;
1466
			f.data.uint32 = chan->hangupcause;
1467

    
   
1467

   
1468
		ast_channel_unlock(chan);
1468
		ast_channel_unlock(chan);
1469
	}
1469
	}
1470

    
   
1470

   
1471
	return ast_queue_frame(chan, &f);
1471
	return ast_queue_frame(chan, &f);
1472
}
1472
}
1473

    
   
1473

   
1474
/*! \brief Queue a control frame */
1474
/*! \brief Queue a control frame */
1475
int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1475
int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1476
{
1476
{
1477
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1477
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1478
	return ast_queue_frame(chan, &f);
1478
	return ast_queue_frame(chan, &f);
1479
}
1479
}
1480

    
   
1480

   
1481
/*! \brief Queue a control frame with payload */
1481
/*! \brief Queue a control frame with payload */
1482
int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1482
int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1483
			   const void *data, size_t datalen)
1483
			   const void *data, size_t datalen)
1484
{
1484
{
1485
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1485
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1486
	return ast_queue_frame(chan, &f);
1486
	return ast_queue_frame(chan, &f);
1487
}
1487
}
1488

    
   
1488

   
1489
/*! \brief Set defer DTMF flag on channel */
1489
/*! \brief Set defer DTMF flag on channel */
1490
int ast_channel_defer_dtmf(struct ast_channel *chan)
1490
int ast_channel_defer_dtmf(struct ast_channel *chan)
1491
{
1491
{
1492
	int pre = 0;
1492
	int pre = 0;
1493

    
   
1493

   
1494
	if (chan) {
1494
	if (chan) {
1495
		pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1495
		pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1496
		ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1496
		ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1497
	}
1497
	}
1498
	return pre;
1498
	return pre;
1499
}
1499
}
1500

    
   
1500

   
1501
/*! \brief Unset defer DTMF flag on channel */
1501
/*! \brief Unset defer DTMF flag on channel */
1502
void ast_channel_undefer_dtmf(struct ast_channel *chan)
1502
void ast_channel_undefer_dtmf(struct ast_channel *chan)
1503
{
1503
{
1504
	if (chan)
1504
	if (chan)
1505
		ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1505
		ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1506
}
1506
}
1507

    
   
1507

   
1508
struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1508
struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1509
		void *data, int ao2_flags)
1509
		void *data, int ao2_flags)
1510
{
1510
{
1511
	return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1511
	return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1512
}
1512
}
1513

    
   
1513

   
1514
struct ast_channel_iterator {
1514
struct ast_channel_iterator {
1515
	/* storage for non-dynamically allocated iterator */
1515
	/* storage for non-dynamically allocated iterator */
1516
	struct ao2_iterator simple_iterator;
1516
	struct ao2_iterator simple_iterator;
1517
	/* pointer to the actual iterator (simple_iterator or a dynamically
1517
	/* pointer to the actual iterator (simple_iterator or a dynamically
1518
	 * allocated iterator)
1518
	 * allocated iterator)
1519
	 */
1519
	 */
1520
	struct ao2_iterator *active_iterator;
1520
	struct ao2_iterator *active_iterator;
1521
};
1521
};
1522

    
   
1522

   
1523
struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1523
struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1524
{
1524
{
1525
	ao2_iterator_destroy(i->active_iterator);
1525
	ao2_iterator_destroy(i->active_iterator);
1526
	ast_free(i);
1526
	ast_free(i);
1527

    
   
1527

   
1528
	return NULL;
1528
	return NULL;
1529
}
1529
}
1530

    
   
1530

   
1531
static struct ast_channel_iterator *channel_iterator_search(const char *name,
1531
static struct ast_channel_iterator *channel_iterator_search(const char *name,
1532
							    size_t name_len, const char *exten,
1532
							    size_t name_len, const char *exten,
1533
							    const char *context)
1533
							    const char *context)
1534
{
1534
{
1535
	struct ast_channel_iterator *i;
1535
	struct ast_channel_iterator *i;
1536
	struct ast_channel tmp_chan = {
1536
	struct ast_channel tmp_chan = {
1537
		.name = name,
1537
		.name = name,
1538
		/* This is sort of a hack.  Basically, we're using an arbitrary field
1538
		/* This is sort of a hack.  Basically, we're using an arbitrary field
1539
		 * in ast_channel to pass the name_len for a prefix match.  If this
1539
		 * in ast_channel to pass the name_len for a prefix match.  If this
1540
		 * gets changed, then the compare callback must be changed, too. */
1540
		 * gets changed, then the compare callback must be changed, too. */
1541
		.rings = name_len,
1541
		.rings = name_len,
1542
	};
1542
	};
1543

    
   
1543

   
1544
	if (!(i = ast_calloc(1, sizeof(*i)))) {
1544
	if (!(i = ast_calloc(1, sizeof(*i)))) {
1545
		return NULL;
1545
		return NULL;
1546
	}
1546
	}
1547

    
   
1547

   
1548
	if (exten) {
1548
	if (exten) {
1549
		ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1549
		ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1550
	}
1550
	}
1551

    
   
1551

   
1552
	if (context) {
1552
	if (context) {
1553
		ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1553
		ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1554
	}
1554
	}
1555

    
   
1555

   
1556
	if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1556
	if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1557
					    OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1557
					    OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1558
		    ast_free(i);
1558
		    ast_free(i);
1559
		    return NULL;
1559
		    return NULL;
1560
	}
1560
	}
1561

    
   
1561

   
1562
	return i;
1562
	return i;
1563
}
1563
}
1564

    
   
1564

   
1565
struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1565
struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1566
{
1566
{
1567
	return channel_iterator_search(NULL, 0, exten, context);
1567
	return channel_iterator_search(NULL, 0, exten, context);
1568
}
1568
}
1569

    
   
1569

   
1570
struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1570
struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1571
{
1571
{
1572
	return channel_iterator_search(name, name_len, NULL, NULL);
1572
	return channel_iterator_search(name, name_len, NULL, NULL);
1573
}
1573
}
1574

    
   
1574

   
1575
struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1575
struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1576
{
1576
{
1577
	struct ast_channel_iterator *i;
1577
	struct ast_channel_iterator *i;
1578

    
   
1578

   
1579
	if (!(i = ast_calloc(1, sizeof(*i)))) {
1579
	if (!(i = ast_calloc(1, sizeof(*i)))) {
1580
		return NULL;
1580
		return NULL;
1581
	}
1581
	}
1582

    
   
1582

   
1583
	i->simple_iterator = ao2_iterator_init(channels, 0);
1583
	i->simple_iterator = ao2_iterator_init(channels, 0);
1584
	i->active_iterator = &i->simple_iterator;
1584
	i->active_iterator = &i->simple_iterator;
1585

    
   
1585

   
1586
	return i;
1586
	return i;
1587
}
1587
}
1588

    
   
1588

   
1589
struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1589
struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1590
{
1590
{
1591
	return ao2_iterator_next(i->active_iterator);
1591
	return ao2_iterator_next(i->active_iterator);
1592
}
1592
}
1593

    
   
1593

   
1594
static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1594
static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1595
{
1595
{
1596
	struct ast_channel *chan = obj, *cmp_args = arg;
1596
	struct ast_channel *chan = obj, *cmp_args = arg;
1597
	size_t name_len;
1597
	size_t name_len;
1598
	int ret = CMP_MATCH;
1598
	int ret = CMP_MATCH;
1599

    
   
1599

   
1600
	/* This is sort of a hack.  Basically, we're using an arbitrary field
1600
	/* This is sort of a hack.  Basically, we're using an arbitrary field
1601
	 * in ast_channel to pass the name_len for a prefix match.  If this
1601
	 * in ast_channel to pass the name_len for a prefix match.  If this
1602
	 * gets changed, then the uses of ao2_find() must be changed, too. */
1602
	 * gets changed, then the uses of ao2_find() must be changed, too. */
1603
	name_len = cmp_args->rings;
1603
	name_len = cmp_args->rings;
1604

    
   
1604

   
1605
	ast_channel_lock(chan);
1605
	ast_channel_lock(chan);
1606

    
   
1606

   
1607
	if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1607
	if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1608
		if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1608
		if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1609
				(name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1609
				(name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1610
			ret = 0; /* name match failed */
1610
			ret = 0; /* name match failed */
1611
		}
1611
		}
1612
	} else if (!ast_strlen_zero(cmp_args->exten)) {
1612
	} else if (!ast_strlen_zero(cmp_args->exten)) {
1613
		if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1613
		if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1614
				strcasecmp(chan->macrocontext, cmp_args->context)) {
1614
				strcasecmp(chan->macrocontext, cmp_args->context)) {
1615
			ret = 0; /* context match failed */
1615
			ret = 0; /* context match failed */
1616
		}
1616
		}
1617
		if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1617
		if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1618
				strcasecmp(chan->macroexten, cmp_args->exten)) {
1618
				strcasecmp(chan->macroexten, cmp_args->exten)) {
1619
			ret = 0; /* exten match failed */
1619
			ret = 0; /* exten match failed */
1620
		}
1620
		}
1621
	} else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1621
	} else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1622
		if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1622
		if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1623
				(name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1623
				(name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1624
			ret = 0; /* uniqueid match failed */
1624
			ret = 0; /* uniqueid match failed */
1625
		}
1625
		}
1626
	} else {
1626
	} else {
1627
		ret = 0;
1627
		ret = 0;
1628
	}
1628
	}
1629

    
   
1629

   
1630
	ast_channel_unlock(chan);
1630
	ast_channel_unlock(chan);
1631

    
   
1631

   
1632
	return ret;
1632
	return ret;
1633
}
1633
}
1634

    
   
1634

   
1635
static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1635
static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1636
						const char *exten, const char *context)
1636
						const char *exten, const char *context)
1637
{
1637
{
1638
	struct ast_channel tmp_chan = {
1638
	struct ast_channel tmp_chan = {
1639
		.name = name,
1639
		.name = name,
1640
		/* This is sort of a hack.  Basically, we're using an arbitrary field
1640
		/* This is sort of a hack.  Basically, we're using an arbitrary field
1641
		 * in ast_channel to pass the name_len for a prefix match.  If this
1641
		 * in ast_channel to pass the name_len for a prefix match.  If this
1642
		 * gets changed, then the compare callback must be changed, too. */
1642
		 * gets changed, then the compare callback must be changed, too. */
1643
		.rings = name_len,
1643
		.rings = name_len,
1644
	};
1644
	};
1645
	struct ast_channel *chan;
1645
	struct ast_channel *chan;
1646

    
   
1646

   
1647
	if (exten) {
1647
	if (exten) {
1648
		ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1648
		ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1649
	}
1649
	}
1650

    
   
1650

   
1651
	if (context) {
1651
	if (context) {
1652
		ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1652
		ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1653
	}
1653
	}
1654

    
   
1654

   
1655
	if ((chan = ao2_find(channels, &tmp_chan,
1655
	if ((chan = ao2_find(channels, &tmp_chan,
1656
			     (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1656
			     (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1657
		return chan;
1657
		return chan;
1658
	}
1658
	}
1659

    
   
1659

   
1660
	if (!name) {
1660
	if (!name) {
1661
		return NULL;
1661
		return NULL;
1662
	}
1662
	}
1663

    
   
1663

   
1664
	/* If name was specified, but the result was NULL, 
1664
	/* If name was specified, but the result was NULL, 
1665
	 * try a search on uniqueid, instead. */
1665
	 * try a search on uniqueid, instead. */
1666

    
   
1666

   
1667
	{
1667
	{
1668
		struct ast_channel tmp_chan2 = {
1668
		struct ast_channel tmp_chan2 = {
1669
			.uniqueid = name,
1669
			.uniqueid = name,
1670
			.rings = name_len,
1670
			.rings = name_len,
1671
		};
1671
		};
1672

    
   
1672

   
1673
		return ao2_find(channels, &tmp_chan2, 0);
1673
		return ao2_find(channels, &tmp_chan2, 0);
1674
	}
1674
	}
1675
}
1675
}
1676

    
   
1676

   
1677
struct ast_channel *ast_channel_get_by_name(const char *name)
1677
struct ast_channel *ast_channel_get_by_name(const char *name)
1678
{
1678
{
1679
	return ast_channel_get_full(name, 0, NULL, NULL);
1679
	return ast_channel_get_full(name, 0, NULL, NULL);
1680
}
1680
}
1681

    
   
1681

   
1682
struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1682
struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1683
{
1683
{
1684
	return ast_channel_get_full(name, name_len, NULL, NULL);
1684
	return ast_channel_get_full(name, name_len, NULL, NULL);
1685
}
1685
}
1686

    
   
1686

   
1687
struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1687
struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1688
{
1688
{
1689
	return ast_channel_get_full(NULL, 0, exten, context);
1689
	return ast_channel_get_full(NULL, 0, exten, context);
1690
}
1690
}
1691

    
   
1691

   
1692
int ast_is_deferrable_frame(const struct ast_frame *frame)
1692
int ast_is_deferrable_frame(const struct ast_frame *frame)
1693
{
1693
{
1694
	/* Do not add a default entry in this switch statement.  Each new
1694
	/* Do not add a default entry in this switch statement.  Each new
1695
	 * frame type should be addressed directly as to whether it should
1695
	 * frame type should be addressed directly as to whether it should
1696
	 * be queued up or not.
1696
	 * be queued up or not.
1697
	 */
1697
	 */
1698
	switch (frame->frametype) {
1698
	switch (frame->frametype) {
1699
	case AST_FRAME_DTMF_END:
1699
	case AST_FRAME_DTMF_END:
1700
	case AST_FRAME_CONTROL:
1700
	case AST_FRAME_CONTROL:
1701
	case AST_FRAME_TEXT:
1701
	case AST_FRAME_TEXT:
1702
	case AST_FRAME_IMAGE:
1702
	case AST_FRAME_IMAGE:
1703
	case AST_FRAME_HTML:
1703
	case AST_FRAME_HTML:
1704
		return 1;
1704
		return 1;
1705

    
   
1705

   
1706
	case AST_FRAME_DTMF_BEGIN:
1706
	case AST_FRAME_DTMF_BEGIN:
1707
	case AST_FRAME_VOICE:
1707
	case AST_FRAME_VOICE:
1708
	case AST_FRAME_VIDEO:
1708
	case AST_FRAME_VIDEO:
1709
	case AST_FRAME_NULL:
1709
	case AST_FRAME_NULL:
1710
	case AST_FRAME_IAX:
1710
	case AST_FRAME_IAX:
1711
	case AST_FRAME_CNG:
1711
	case AST_FRAME_CNG:
1712
	case AST_FRAME_MODEM:
1712
	case AST_FRAME_MODEM:
1713
		return 0;
1713
		return 0;
1714
	}
1714
	}
1715
	return 0;
1715
	return 0;
1716
}
1716
}
1717

    
   
1717

   
1718
/*! \brief Wait, look for hangups and condition arg */
1718
/*! \brief Wait, look for hangups and condition arg */
1719
int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1719
int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1720
{
1720
{
1721
	struct ast_frame *f;
1721
	struct ast_frame *f;
1722
	struct ast_silence_generator *silgen = NULL;
1722
	struct ast_silence_generator *silgen = NULL;
1723
	int res = 0;
1723
	int res = 0;
1724
	AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1724
	AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1725

    
   
1725

   
1726
	AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1726
	AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1727

    
   
1727

   
1728
	/* If no other generator is present, start silencegen while waiting */
1728
	/* If no other generator is present, start silencegen while waiting */
1729
	if (ast_opt_transmit_silence && !chan->generatordata) {
1729
	if (ast_opt_transmit_silence && !chan->generatordata) {
1730
		silgen = ast_channel_start_silence_generator(chan);
1730
		silgen = ast_channel_start_silence_generator(chan);
1731
	}
1731
	}
1732

    
   
1732

   
1733
	while (ms > 0) {
1733
	while (ms > 0) {
1734
		struct ast_frame *dup_f = NULL;
1734
		struct ast_frame *dup_f = NULL;
1735
		if (cond && ((*cond)(data) == 0)) {
1735
		if (cond && ((*cond)(data) == 0)) {
1736
			break;
1736
			break;
1737
		}
1737
		}
1738
		ms = ast_waitfor(chan, ms);
1738
		ms = ast_waitfor(chan, ms);
1739
		if (ms < 0) {
1739
		if (ms < 0) {
1740
			res = -1;
1740
			res = -1;
1741
			break;
1741
			break;
1742
		}
1742
		}
1743
		if (ms > 0) {
1743
		if (ms > 0) {
1744
			f = ast_read(chan);
1744
			f = ast_read(chan);
1745
			if (!f) {
1745
			if (!f) {
1746
				res = -1;
1746
				res = -1;
1747
				break;
1747
				break;
1748
			}
1748
			}
1749

    
   
1749

   
1750
			if (!ast_is_deferrable_frame(f)) {
1750
			if (!ast_is_deferrable_frame(f)) {
1751
				ast_frfree(f);
1751
				ast_frfree(f);
1752
				continue;
1752
				continue;
1753
			}
1753
			}
1754
			
1754
			
1755
			if ((dup_f = ast_frisolate(f))) {
1755
			if ((dup_f = ast_frisolate(f))) {
1756
				if (dup_f != f) {
1756
				if (dup_f != f) {
1757
					ast_frfree(f);
1757
					ast_frfree(f);
1758
				}
1758
				}
1759
				AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1759
				AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1760
			}
1760
			}
1761
		}
1761
		}
1762
	}
1762
	}
1763

    
   
1763

   
1764
	/* stop silgen if present */
1764
	/* stop silgen if present */
1765
	if (silgen) {
1765
	if (silgen) {
1766
		ast_channel_stop_silence_generator(chan, silgen);
1766
		ast_channel_stop_silence_generator(chan, silgen);
1767
	}
1767
	}
1768

    
   
1768

   
1769
	/* We need to free all the deferred frames, but we only need to
1769
	/* We need to free all the deferred frames, but we only need to
1770
	 * queue the deferred frames if there was no error and no
1770
	 * queue the deferred frames if there was no error and no
1771
	 * hangup was received
1771
	 * hangup was received
1772
	 */
1772
	 */
1773
	ast_channel_lock(chan);
1773
	ast_channel_lock(chan);
1774
	while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1774
	while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1775
		if (!res) {
1775
		if (!res) {
1776
			ast_queue_frame_head(chan, f);
1776
			ast_queue_frame_head(chan, f);
1777
		}
1777
		}
1778
		ast_frfree(f);
1778
		ast_frfree(f);
1779
	}
1779
	}
1780
	ast_channel_unlock(chan);
1780
	ast_channel_unlock(chan);
1781

    
   
1781

   
1782
	return res;
1782
	return res;
1783
}
1783
}
1784

    
   
1784

   
1785
/*! \brief Wait, look for hangups */
1785
/*! \brief Wait, look for hangups */
1786
int ast_safe_sleep(struct ast_channel *chan, int ms)
1786
int ast_safe_sleep(struct ast_channel *chan, int ms)
1787
{
1787
{
1788
	return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1788
	return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1789
}
1789
}
1790

    
   
1790

   
1791
struct ast_channel *ast_channel_release(struct ast_channel *chan)
1791
struct ast_channel *ast_channel_release(struct ast_channel *chan)
1792
{
1792
{
1793
	/* Safe, even if already unlinked. */
1793
	/* Safe, even if already unlinked. */
1794
	ao2_unlink(channels, chan);
1794
	ao2_unlink(channels, chan);
1795
	return ast_channel_unref(chan);
1795
	return ast_channel_unref(chan);
1796
}
1796
}
1797

    
   
1797

   
1798
void ast_party_name_init(struct ast_party_name *init)
1798
void ast_party_name_init(struct ast_party_name *init)
1799
{
1799
{
1800
	init->str = NULL;
1800
	init->str = NULL;
1801
	init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1801
	init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1802
	init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1802
	init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1803
	init->valid = 0;
1803
	init->valid = 0;
1804
}
1804
}
1805

    
   
1805

   
1806
void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1806
void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1807
{
1807
{
1808
	if (dest == src) {
1808
	if (dest == src) {
1809
		/* Don't copy to self */
1809
		/* Don't copy to self */
1810
		return;
1810
		return;
1811
	}
1811
	}
1812

    
   
1812

   
1813
	ast_free(dest->str);
1813
	ast_free(dest->str);
1814
	dest->str = ast_strdup(src->str);
1814
	dest->str = ast_strdup(src->str);
1815
	dest->char_set = src->char_set;
1815
	dest->char_set = src->char_set;
1816
	dest->presentation = src->presentation;
1816
	dest->presentation = src->presentation;
1817
	dest->valid = src->valid;
1817
	dest->valid = src->valid;
1818
}
1818
}
1819

    
   
1819

   
1820
void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1820
void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1821
{
1821
{
1822
	init->str = NULL;
1822
	init->str = NULL;
1823
	init->char_set = guide->char_set;
1823
	init->char_set = guide->char_set;
1824
	init->presentation = guide->presentation;
1824
	init->presentation = guide->presentation;
1825
	init->valid = guide->valid;
1825
	init->valid = guide->valid;
1826
}
1826
}
1827

    
   
1827

   
1828
void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1828
void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1829
{
1829
{
1830
	if (dest == src) {
1830
	if (dest == src) {
1831
		/* Don't set to self */
1831
		/* Don't set to self */
1832
		return;
1832
		return;
1833
	}
1833
	}
1834

    
   
1834

   
1835
	if (src->str && src->str != dest->str) {
1835
	if (src->str && src->str != dest->str) {
1836
		ast_free(dest->str);
1836
		ast_free(dest->str);
1837
		dest->str = ast_strdup(src->str);
1837
		dest->str = ast_strdup(src->str);
1838
	}
1838
	}
1839

    
   
1839

   
1840
	dest->char_set = src->char_set;
1840
	dest->char_set = src->char_set;
1841
	dest->presentation = src->presentation;
1841
	dest->presentation = src->presentation;
1842
	dest->valid = src->valid;
1842
	dest->valid = src->valid;
1843
}
1843
}
1844

    
   
1844

   
1845
void ast_party_name_free(struct ast_party_name *doomed)
1845
void ast_party_name_free(struct ast_party_name *doomed)
1846
{
1846
{
1847
	ast_free(doomed->str);
1847
	ast_free(doomed->str);
1848
	doomed->str = NULL;
1848
	doomed->str = NULL;
1849
}
1849
}
1850

    
   
1850

   
1851
void ast_party_number_init(struct ast_party_number *init)
1851
void ast_party_number_init(struct ast_party_number *init)
1852
{
1852
{
1853
	init->str = NULL;
1853
	init->str = NULL;
1854
	init->plan = 0;/* Unknown */
1854
	init->plan = 0;/* Unknown */
1855
	init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1855
	init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1856
	init->valid = 0;
1856
	init->valid = 0;
1857
}
1857
}
1858

    
   
1858

   
1859
void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1859
void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1860
{
1860
{
1861
	if (dest == src) {
1861
	if (dest == src) {
1862
		/* Don't copy to self */
1862
		/* Don't copy to self */
1863
		return;
1863
		return;
1864
	}
1864
	}
1865

    
   
1865

   
1866
	ast_free(dest->str);
1866
	ast_free(dest->str);
1867
	dest->str = ast_strdup(src->str);
1867
	dest->str = ast_strdup(src->str);
1868
	dest->plan = src->plan;
1868
	dest->plan = src->plan;
1869
	dest->presentation = src->presentation;
1869
	dest->presentation = src->presentation;
1870
	dest->valid = src->valid;
1870
	dest->valid = src->valid;
1871
}
1871
}
1872

    
   
1872

   
1873
void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1873
void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1874
{
1874
{
1875
	init->str = NULL;
1875
	init->str = NULL;
1876
	init->plan = guide->plan;
1876
	init->plan = guide->plan;
1877
	init->presentation = guide->presentation;
1877
	init->presentation = guide->presentation;
1878
	init->valid = guide->valid;
1878
	init->valid = guide->valid;
1879
}
1879
}
1880

    
   
1880

   
1881
void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1881
void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1882
{
1882
{
1883
	if (dest == src) {
1883
	if (dest == src) {
1884
		/* Don't set to self */
1884
		/* Don't set to self */
1885
		return;
1885
		return;
1886
	}
1886
	}
1887

    
   
1887

   
1888
	if (src->str && src->str != dest->str) {
1888
	if (src->str && src->str != dest->str) {
1889
		ast_free(dest->str);
1889
		ast_free(dest->str);
1890
		dest->str = ast_strdup(src->str);
1890
		dest->str = ast_strdup(src->str);
1891
	}
1891
	}
1892

    
   
1892

   
1893
	dest->plan = src->plan;
1893
	dest->plan = src->plan;
1894
	dest->presentation = src->presentation;
1894
	dest->presentation = src->presentation;
1895
	dest->valid = src->valid;
1895
	dest->valid = src->valid;
1896
}
1896
}
1897

    
   
1897

   
1898
void ast_party_number_free(struct ast_party_number *doomed)
1898
void ast_party_number_free(struct ast_party_number *doomed)
1899
{
1899
{
1900
	ast_free(doomed->str);
1900
	ast_free(doomed->str);
1901
	doomed->str = NULL;
1901
	doomed->str = NULL;
1902
}
1902
}
1903

    
   
1903

   
1904
void ast_party_subaddress_init(struct ast_party_subaddress *init)
1904
void ast_party_subaddress_init(struct ast_party_subaddress *init)
1905
{
1905
{
1906
	init->str = NULL;
1906
	init->str = NULL;
1907
	init->type = 0;
1907
	init->type = 0;
1908
	init->odd_even_indicator = 0;
1908
	init->odd_even_indicator = 0;
1909
	init->valid = 0;
1909
	init->valid = 0;
1910
}
1910
}
1911

    
   
1911

   
1912
void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1912
void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1913
{
1913
{
1914
	if (dest == src) {
1914
	if (dest == src) {
1915
		/* Don't copy to self */
1915
		/* Don't copy to self */
1916
		return;
1916
		return;
1917
	}
1917
	}
1918

    
   
1918

   
1919
	ast_free(dest->str);
1919
	ast_free(dest->str);
1920
	dest->str = ast_strdup(src->str);
1920
	dest->str = ast_strdup(src->str);
1921
	dest->type = src->type;
1921
	dest->type = src->type;
1922
	dest->odd_even_indicator = src->odd_even_indicator;
1922
	dest->odd_even_indicator = src->odd_even_indicator;
1923
	dest->valid = src->valid;
1923
	dest->valid = src->valid;
1924
}
1924
}
1925

    
   
1925

   
1926
void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1926
void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1927
{
1927
{
1928
	init->str = NULL;
1928
	init->str = NULL;
1929
	init->type = guide->type;
1929
	init->type = guide->type;
1930
	init->odd_even_indicator = guide->odd_even_indicator;
1930
	init->odd_even_indicator = guide->odd_even_indicator;
1931
	init->valid = guide->valid;
1931
	init->valid = guide->valid;
1932
}
1932
}
1933

    
   
1933

   
1934
void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1934
void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1935
{
1935
{
1936
	if (dest == src) {
1936
	if (dest == src) {
1937
		/* Don't set to self */
1937
		/* Don't set to self */
1938
		return;
1938
		return;
1939
	}
1939
	}
1940

    
   
1940

   
1941
	if (src->str && src->str != dest->str) {
1941
	if (src->str && src->str != dest->str) {
1942
		ast_free(dest->str);
1942
		ast_free(dest->str);
1943
		dest->str = ast_strdup(src->str);
1943
		dest->str = ast_strdup(src->str);
1944
	}
1944
	}
1945

    
   
1945

   
1946
	dest->type = src->type;
1946
	dest->type = src->type;
1947
	dest->odd_even_indicator = src->odd_even_indicator;
1947
	dest->odd_even_indicator = src->odd_even_indicator;
1948
	dest->valid = src->valid;
1948
	dest->valid = src->valid;
1949
}
1949
}
1950

    
   
1950

   
1951
void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1951
void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1952
{
1952
{
1953
	ast_free(doomed->str);
1953
	ast_free(doomed->str);
1954
	doomed->str = NULL;
1954
	doomed->str = NULL;
1955
}
1955
}
1956

    
   
1956

   
1957
void ast_party_id_init(struct ast_party_id *init)
1957
void ast_party_id_init(struct ast_party_id *init)
1958
{
1958
{
1959
	ast_party_name_init(&init->name);
1959
	ast_party_name_init(&init->name);
1960
	ast_party_number_init(&init->number);
1960
	ast_party_number_init(&init->number);
1961
	ast_party_subaddress_init(&init->subaddress);
1961
	ast_party_subaddress_init(&init->subaddress);
1962
	init->tag = NULL;
1962
	init->tag = NULL;
1963
}
1963
}
1964

    
   
1964

   
1965
void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1965
void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1966
{
1966
{
1967
	if (dest == src) {
1967
	if (dest == src) {
1968
		/* Don't copy to self */
1968
		/* Don't copy to self */
1969
		return;
1969
		return;
1970
	}
1970
	}
1971

    
   
1971

   
1972
	ast_party_name_copy(&dest->name, &src->name);
1972
	ast_party_name_copy(&dest->name, &src->name);
1973
	ast_party_number_copy(&dest->number, &src->number);
1973
	ast_party_number_copy(&dest->number, &src->number);
1974
	ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1974
	ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1975

    
   
1975

   
1976
	ast_free(dest->tag);
1976
	ast_free(dest->tag);
1977
	dest->tag = ast_strdup(src->tag);
1977
	dest->tag = ast_strdup(src->tag);
1978
}
1978
}
1979

    
   
1979

   
1980
void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1980
void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1981
{
1981
{
1982
	ast_party_name_set_init(&init->name, &guide->name);
1982
	ast_party_name_set_init(&init->name, &guide->name);
1983
	ast_party_number_set_init(&init->number, &guide->number);
1983
	ast_party_number_set_init(&init->number, &guide->number);
1984
	ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1984
	ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1985
	init->tag = NULL;
1985
	init->tag = NULL;
1986
}
1986
}
1987

    
   
1987

   
1988
void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1988
void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1989
{
1989
{
1990
	if (dest == src) {
1990
	if (dest == src) {
1991
		/* Don't set to self */
1991
		/* Don't set to self */
1992
		return;
1992
		return;
1993
	}
1993
	}
1994

    
   
1994

   
1995
	if (!update || update->name) {
1995
	if (!update || update->name) {
1996
		ast_party_name_set(&dest->name, &src->name);
1996
		ast_party_name_set(&dest->name, &src->name);
1997
	}
1997
	}
1998
	if (!update || update->number) {
1998
	if (!update || update->number) {
1999
		ast_party_number_set(&dest->number, &src->number);
1999
		ast_party_number_set(&dest->number, &src->number);
2000
	}
2000
	}
2001
	if (!update || update->subaddress) {
2001
	if (!update || update->subaddress) {
2002
		ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2002
		ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2003
	}
2003
	}
2004

    
   
2004

   
2005
	if (src->tag && src->tag != dest->tag) {
2005
	if (src->tag && src->tag != dest->tag) {
2006
		ast_free(dest->tag);
2006
		ast_free(dest->tag);
2007
		dest->tag = ast_strdup(src->tag);
2007
		dest->tag = ast_strdup(src->tag);
2008
	}
2008
	}
2009
}
2009
}
2010

    
   
2010

   
2011
void ast_party_id_free(struct ast_party_id *doomed)
2011
void ast_party_id_free(struct ast_party_id *doomed)
2012
{
2012
{
2013
	ast_party_name_free(&doomed->name);
2013
	ast_party_name_free(&doomed->name);
2014
	ast_party_number_free(&doomed->number);
2014
	ast_party_number_free(&doomed->number);
2015
	ast_party_subaddress_free(&doomed->subaddress);
2015
	ast_party_subaddress_free(&doomed->subaddress);
2016

    
   
2016

   
2017
	ast_free(doomed->tag);
2017
	ast_free(doomed->tag);
2018
	doomed->tag = NULL;
2018
	doomed->tag = NULL;
2019
}
2019
}
2020

    
   
2020

   
2021
int ast_party_id_presentation(const struct ast_party_id *id)
2021
int ast_party_id_presentation(const struct ast_party_id *id)
2022
{
2022
{
2023
	int number_priority;
2023
	int number_priority;
2024
	int number_value;
2024
	int number_value;
2025
	int number_screening;
2025
	int number_screening;
2026
	int name_priority;
2026
	int name_priority;
2027
	int name_value;
2027
	int name_value;
2028

    
   
2028

   
2029
	/* Determine name presentation priority. */
2029
	/* Determine name presentation priority. */
2030
	if (!id->name.valid) {
2030
	if (!id->name.valid) {
2031
		name_value = AST_PRES_UNAVAILABLE;
2031
		name_value = AST_PRES_UNAVAILABLE;
2032
		name_priority = 3;
2032
		name_priority = 3;
2033
	} else {
2033
	} else {
2034
		name_value = id->name.presentation & AST_PRES_RESTRICTION;
2034
		name_value = id->name.presentation & AST_PRES_RESTRICTION;
2035
		switch (name_value) {
2035
		switch (name_value) {
2036
		case AST_PRES_RESTRICTED:
2036
		case AST_PRES_RESTRICTED:
2037
			name_priority = 0;
2037
			name_priority = 0;
2038
			break;
2038
			break;
2039
		case AST_PRES_ALLOWED:
2039
		case AST_PRES_ALLOWED:
2040
			name_priority = 1;
2040
			name_priority = 1;
2041
			break;
2041
			break;
2042
		case AST_PRES_UNAVAILABLE:
2042
		case AST_PRES_UNAVAILABLE:
2043
			name_priority = 2;
2043
			name_priority = 2;
2044
			break;
2044
			break;
2045
		default:
2045
		default:
2046
			name_value = AST_PRES_UNAVAILABLE;
2046
			name_value = AST_PRES_UNAVAILABLE;
2047
			name_priority = 3;
2047
			name_priority = 3;
2048
			break;
2048
			break;
2049
		}
2049
		}
2050
	}
2050
	}
2051

    
   
2051

   
2052
	/* Determine number presentation priority. */
2052
	/* Determine number presentation priority. */
2053
	if (!id->number.valid) {
2053
	if (!id->number.valid) {
2054
		number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2054
		number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2055
		number_value = AST_PRES_UNAVAILABLE;
2055
		number_value = AST_PRES_UNAVAILABLE;
2056
		number_priority = 3;
2056
		number_priority = 3;
2057
	} else {
2057
	} else {
2058
		number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2058
		number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2059
		number_value = id->number.presentation & AST_PRES_RESTRICTION;
2059
		number_value = id->number.presentation & AST_PRES_RESTRICTION;
2060
		switch (number_value) {
2060
		switch (number_value) {
2061
		case AST_PRES_RESTRICTED:
2061
		case AST_PRES_RESTRICTED:
2062
			number_priority = 0;
2062
			number_priority = 0;
2063
			break;
2063
			break;
2064
		case AST_PRES_ALLOWED:
2064
		case AST_PRES_ALLOWED:
2065
			number_priority = 1;
2065
			number_priority = 1;
2066
			break;
2066
			break;
2067
		case AST_PRES_UNAVAILABLE:
2067
		case AST_PRES_UNAVAILABLE:
2068
			number_priority = 2;
2068
			number_priority = 2;
2069
			break;
2069
			break;
2070
		default:
2070
		default:
2071
			number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2071
			number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2072
			number_value = AST_PRES_UNAVAILABLE;
2072
			number_value = AST_PRES_UNAVAILABLE;
2073
			number_priority = 3;
2073
			number_priority = 3;
2074
			break;
2074
			break;
2075
		}
2075
		}
2076
	}
2076
	}
2077

    
   
2077

   
2078
	/* Select the wining presentation value. */
2078
	/* Select the wining presentation value. */
2079
	if (name_priority < number_priority) {
2079
	if (name_priority < number_priority) {
2080
		number_value = name_value;
2080
		number_value = name_value;
2081
	}
2081
	}
2082

    
   
2082

   
2083
	return number_value | number_screening;
2083
	return number_value | number_screening;
2084
}
2084
}
2085

    
   
2085

   
2086
void ast_party_dialed_init(struct ast_party_dialed *init)
2086
void ast_party_dialed_init(struct ast_party_dialed *init)
2087
{
2087
{
2088
	init->number.str = NULL;
2088
	init->number.str = NULL;
2089
	init->number.plan = 0;/* Unknown */
2089
	init->number.plan = 0;/* Unknown */
2090
	ast_party_subaddress_init(&init->subaddress);
2090
	ast_party_subaddress_init(&init->subaddress);
2091
	init->transit_network_select = 0;
2091
	init->transit_network_select = 0;
2092
}
2092
}
2093

    
   
2093

   
2094
void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2094
void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2095
{
2095
{
2096
	if (dest == src) {
2096
	if (dest == src) {
2097
		/* Don't copy to self */
2097
		/* Don't copy to self */
2098
		return;
2098
		return;
2099
	}
2099
	}
2100

    
   
2100

   
2101
	ast_free(dest->number.str);
2101
	ast_free(dest->number.str);
2102
	dest->number.str = ast_strdup(src->number.str);
2102
	dest->number.str = ast_strdup(src->number.str);
2103
	dest->number.plan = src->number.plan;
2103
	dest->number.plan = src->number.plan;
2104
	ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2104
	ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2105
	dest->transit_network_select = src->transit_network_select;
2105
	dest->transit_network_select = src->transit_network_select;
2106
}
2106
}
2107

    
   
2107

   
2108
void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2108
void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2109
{
2109
{
2110
	init->number.str = NULL;
2110
	init->number.str = NULL;
2111
	init->number.plan = guide->number.plan;
2111
	init->number.plan = guide->number.plan;
2112
	ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2112
	ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2113
	init->transit_network_select = guide->transit_network_select;
2113
	init->transit_network_select = guide->transit_network_select;
2114
}
2114
}
2115

    
   
2115

   
2116
void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2116
void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2117
{
2117
{
2118
	if (src->number.str && src->number.str != dest->number.str) {
2118
	if (src->number.str && src->number.str != dest->number.str) {
2119
		ast_free(dest->number.str);
2119
		ast_free(dest->number.str);
2120
		dest->number.str = ast_strdup(src->number.str);
2120
		dest->number.str = ast_strdup(src->number.str);
2121
	}
2121
	}
2122
	dest->number.plan = src->number.plan;
2122
	dest->number.plan = src->number.plan;
2123

    
   
2123

   
2124
	ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2124
	ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2125

    
   
2125

   
2126
	dest->transit_network_select = src->transit_network_select;
2126
	dest->transit_network_select = src->transit_network_select;
2127
}
2127
}
2128

    
   
2128

   
2129
void ast_party_dialed_free(struct ast_party_dialed *doomed)
2129
void ast_party_dialed_free(struct ast_party_dialed *doomed)
2130
{
2130
{
2131
	ast_free(doomed->number.str);
2131
	ast_free(doomed->number.str);
2132
	doomed->number.str = NULL;
2132
	doomed->number.str = NULL;
2133
	ast_party_subaddress_free(&doomed->subaddress);
2133
	ast_party_subaddress_free(&doomed->subaddress);
2134
}
2134
}
2135

    
   
2135

   
2136
void ast_party_caller_init(struct ast_party_caller *init)
2136
void ast_party_caller_init(struct ast_party_caller *init)
2137
{
2137
{
2138
	ast_party_id_init(&init->id);
2138
	ast_party_id_init(&init->id);
2139
	ast_party_id_init(&init->ani);
2139
	ast_party_id_init(&init->ani);
2140
	init->ani2 = 0;
2140
	init->ani2 = 0;
2141
}
2141
}
2142

    
   
2142

   
2143
void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2143
void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2144
{
2144
{
2145
	if (dest == src) {
2145
	if (dest == src) {
2146
		/* Don't copy to self */
2146
		/* Don't copy to self */
2147
		return;
2147
		return;
2148
	}
2148
	}
2149

    
   
2149

   
2150
	ast_party_id_copy(&dest->id, &src->id);
2150
	ast_party_id_copy(&dest->id, &src->id);
2151
	ast_party_id_copy(&dest->ani, &src->ani);
2151
	ast_party_id_copy(&dest->ani, &src->ani);
2152
	dest->ani2 = src->ani2;
2152
	dest->ani2 = src->ani2;
2153
}
2153
}
2154

    
   
2154

   
2155
void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2155
void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2156
{
2156
{
2157
	ast_party_id_set_init(&init->id, &guide->id);
2157
	ast_party_id_set_init(&init->id, &guide->id);
2158
	ast_party_id_set_init(&init->ani, &guide->ani);
2158
	ast_party_id_set_init(&init->ani, &guide->ani);
2159
	init->ani2 = guide->ani2;
2159
	init->ani2 = guide->ani2;
2160
}
2160
}
2161

    
   
2161

   
2162
void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2162
void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2163
{
2163
{
2164
	ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2164
	ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2165
	ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2165
	ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2166
	dest->ani2 = src->ani2;
2166
	dest->ani2 = src->ani2;
2167
}
2167
}
2168

    
   
2168

   
2169
void ast_party_caller_free(struct ast_party_caller *doomed)
2169
void ast_party_caller_free(struct ast_party_caller *doomed)
2170
{
2170
{
2171
	ast_party_id_free(&doomed->id);
2171
	ast_party_id_free(&doomed->id);
2172
	ast_party_id_free(&doomed->ani);
2172
	ast_party_id_free(&doomed->ani);
2173
}
2173
}
2174

    
   
2174

   
2175
void ast_party_connected_line_init(struct ast_party_connected_line *init)
2175
void ast_party_connected_line_init(struct ast_party_connected_line *init)
2176
{
2176
{
2177
	ast_party_id_init(&init->id);
2177
	ast_party_id_init(&init->id);
2178
	ast_party_id_init(&init->ani);
2178
	ast_party_id_init(&init->ani);
2179
	init->ani2 = 0;
2179
	init->ani2 = 0;
2180
	init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2180
	init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2181
}
2181
}
2182

    
   
2182

   
2183
void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2183
void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2184
{
2184
{
2185
	if (dest == src) {
2185
	if (dest == src) {
2186
		/* Don't copy to self */
2186
		/* Don't copy to self */
2187
		return;
2187
		return;
2188
	}
2188
	}
2189

    
   
2189

   
2190
	ast_party_id_copy(&dest->id, &src->id);
2190
	ast_party_id_copy(&dest->id, &src->id);
2191
	ast_party_id_copy(&dest->ani, &src->ani);
2191
	ast_party_id_copy(&dest->ani, &src->ani);
2192
	dest->ani2 = src->ani2;
2192
	dest->ani2 = src->ani2;
2193
	dest->source = src->source;
2193
	dest->source = src->source;
2194
}
2194
}
2195

    
   
2195

   
2196
void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2196
void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2197
{
2197
{
2198
	ast_party_id_set_init(&init->id, &guide->id);
2198
	ast_party_id_set_init(&init->id, &guide->id);
2199
	ast_party_id_set_init(&init->ani, &guide->ani);
2199
	ast_party_id_set_init(&init->ani, &guide->ani);
2200
	init->ani2 = guide->ani2;
2200
	init->ani2 = guide->ani2;
2201
	init->source = guide->source;
2201
	init->source = guide->source;
2202
}
2202
}
2203

    
   
2203

   
2204
void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src, const struct ast_set_party_connected_line *update)
2204
void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src, const struct ast_set_party_connected_line *update)
2205
{
2205
{
2206
	ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2206
	ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2207
	ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2207
	ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2208
	dest->ani2 = src->ani2;
2208
	dest->ani2 = src->ani2;
2209
	dest->source = src->source;
2209
	dest->source = src->source;
2210
}
2210
}
2211

    
   
2211

   
2212
void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2212
void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2213
{
2213
{
2214
	connected->id = caller->id;
2214
	connected->id = caller->id;
2215
	connected->ani = caller->ani;
2215
	connected->ani = caller->ani;
2216
	connected->ani2 = caller->ani2;
2216
	connected->ani2 = caller->ani2;
2217
	connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2217
	connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2218
}
2218
}
2219

    
   
2219

   
2220
void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2220
void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2221
{
2221
{
2222
	ast_party_id_free(&doomed->id);
2222
	ast_party_id_free(&doomed->id);
2223
	ast_party_id_free(&doomed->ani);
2223
	ast_party_id_free(&doomed->ani);
2224
}
2224
}
2225

    
   
2225

   
2226
void ast_party_redirecting_init(struct ast_party_redirecting *init)
2226
void ast_party_redirecting_init(struct ast_party_redirecting *init)
2227
{
2227
{
2228
	ast_party_id_init(&init->from);
2228
	ast_party_id_init(&init->from);
2229
	ast_party_id_init(&init->to);
2229
	ast_party_id_init(&init->to);
2230
	init->count = 0;
2230
	init->count = 0;
2231
	init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2231
	init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2232
}
2232
}
2233

    
   
2233

   
2234
void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2234
void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2235
{
2235
{
2236
	if (dest == src) {
2236
	if (dest == src) {
2237
		/* Don't copy to self */
2237
		/* Don't copy to self */
2238
		return;
2238
		return;
2239
	}
2239
	}
2240

    
   
2240

   
2241
	ast_party_id_copy(&dest->from, &src->from);
2241
	ast_party_id_copy(&dest->from, &src->from);
2242
	ast_party_id_copy(&dest->to, &src->to);
2242
	ast_party_id_copy(&dest->to, &src->to);
2243
	dest->count = src->count;
2243
	dest->count = src->count;
2244
	dest->reason = src->reason;
2244
	dest->reason = src->reason;
2245
}
2245
}
2246

    
   
2246

   
2247
void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2247
void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2248
{
2248
{
2249
	ast_party_id_set_init(&init->from, &guide->from);
2249
	ast_party_id_set_init(&init->from, &guide->from);
2250
	ast_party_id_set_init(&init->to, &guide->to);
2250
	ast_party_id_set_init(&init->to, &guide->to);
2251
	init->count = guide->count;
2251
	init->count = guide->count;
2252
	init->reason = guide->reason;
2252
	init->reason = guide->reason;
2253
}
2253
}
2254

    
   
2254

   
2255
void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2255
void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2256
{
2256
{
2257
	ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2257
	ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2258
	ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2258
	ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2259
	dest->reason = src->reason;
2259
	dest->reason = src->reason;
2260
	dest->count = src->count;
2260
	dest->count = src->count;
2261
}
2261
}
2262

    
   
2262

   
2263
void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2263
void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2264
{
2264
{
2265
	ast_party_id_free(&doomed->from);
2265
	ast_party_id_free(&doomed->from);
2266
	ast_party_id_free(&doomed->to);
2266
	ast_party_id_free(&doomed->to);
2267
}
2267
}
2268

    
   
2268

   
2269
/*! \brief Free a channel structure */
2269
/*! \brief Free a channel structure */
2270
static void ast_channel_destructor(void *obj)
2270
static void ast_channel_destructor(void *obj)
2271
{
2271
{
2272
	struct ast_channel *chan = obj;
2272
	struct ast_channel *chan = obj;
2273
	int fd;
2273
	int fd;
2274
#ifdef HAVE_EPOLL
2274
#ifdef HAVE_EPOLL
2275
	int i;
2275
	int i;
2276
#endif
2276
#endif
2277
	struct ast_var_t *vardata;
2277
	struct ast_var_t *vardata;
2278
	struct ast_frame *f;
2278
	struct ast_frame *f;
2279
	struct varshead *headp;
2279
	struct varshead *headp;
2280
	struct ast_datastore *datastore;
2280
	struct ast_datastore *datastore;
2281
	char device_name[AST_CHANNEL_NAME];
2281
	char device_name[AST_CHANNEL_NAME];
2282

    
   
2282

   
2283
	if (chan->name) {
2283
	if (chan->name) {
2284
		/* The string fields were initialized. */
2284
		/* The string fields were initialized. */
2285
		ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2285
		ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2286
		ast_cel_check_retire_linkedid(chan);
2286
		ast_cel_check_retire_linkedid(chan);
2287
	}
2287
	}
2288

    
   
2288

   
2289
	/* Get rid of each of the data stores on the channel */
2289
	/* Get rid of each of the data stores on the channel */
2290
	ast_channel_lock(chan);
2290
	ast_channel_lock(chan);
2291
	while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2291
	while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2292
		/* Free the data store */
2292
		/* Free the data store */
2293
		ast_datastore_free(datastore);
2293
		ast_datastore_free(datastore);
2294
	ast_channel_unlock(chan);
2294
	ast_channel_unlock(chan);
2295

    
   
2295

   
2296
	/* Lock and unlock the channel just to be sure nobody has it locked still
2296
	/* Lock and unlock the channel just to be sure nobody has it locked still
2297
	   due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2297
	   due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2298
	ast_channel_lock(chan);
2298
	ast_channel_lock(chan);
2299
	ast_channel_unlock(chan);
2299
	ast_channel_unlock(chan);
2300

    
   
2300

   
2301
	if (chan->tech_pvt) {
2301
	if (chan->tech_pvt) {
2302
		ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
2302
		ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
2303
		ast_free(chan->tech_pvt);
2303
		ast_free(chan->tech_pvt);
2304
	}
2304
	}
2305

    
   
2305

   
2306
	if (chan->sched)
2306
	if (chan->sched)
2307
		sched_context_destroy(chan->sched);
2307
		sched_context_destroy(chan->sched);
2308

    
   
2308

   
2309
	if (chan->name) {
2309
	if (chan->name) {
2310
		char *dashptr;
2310
		char *dashptr;
2311

    
   
2311

   
2312
		/* The string fields were initialized. */
2312
		/* The string fields were initialized. */
2313
		ast_copy_string(device_name, chan->name, sizeof(device_name));
2313
		ast_copy_string(device_name, chan->name, sizeof(device_name));
2314
		if ((dashptr = strrchr(device_name, '-'))) {
2314
		if ((dashptr = strrchr(device_name, '-'))) {
2315
			*dashptr = '\0';
2315
			*dashptr = '\0';
2316
		}
2316
		}
2317
	} else {
2317
	} else {
2318
		device_name[0] = '\0';
2318
		device_name[0] = '\0';
2319
	}
2319
	}
2320

    
   
2320

   
2321
	/* Stop monitoring */
2321
	/* Stop monitoring */
2322
	if (chan->monitor)
2322
	if (chan->monitor)
2323
		chan->monitor->stop( chan, 0 );
2323
		chan->monitor->stop( chan, 0 );
2324

    
   
2324

   
2325
	/* If there is native format music-on-hold state, free it */
2325
	/* If there is native format music-on-hold state, free it */
2326
	if (chan->music_state)
2326
	if (chan->music_state)
2327
		ast_moh_cleanup(chan);
2327
		ast_moh_cleanup(chan);
2328

    
   
2328

   
2329
	/* Free translators */
2329
	/* Free translators */
2330
	if (chan->readtrans)
2330
	if (chan->readtrans)
2331
		ast_translator_free_path(chan->readtrans);
2331
		ast_translator_free_path(chan->readtrans);
2332
	if (chan->writetrans)
2332
	if (chan->writetrans)
2333
		ast_translator_free_path(chan->writetrans);
2333
		ast_translator_free_path(chan->writetrans);
2334
	if (chan->pbx)
2334
	if (chan->pbx)
2335
		ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
2335
		ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
2336

    
   
2336

   
2337
	ast_party_dialed_free(&chan->dialed);
2337
	ast_party_dialed_free(&chan->dialed);
2338
	ast_party_caller_free(&chan->caller);
2338
	ast_party_caller_free(&chan->caller);
2339
	ast_party_connected_line_free(&chan->connected);
2339
	ast_party_connected_line_free(&chan->connected);
2340
	ast_party_redirecting_free(&chan->redirecting);
2340
	ast_party_redirecting_free(&chan->redirecting);
2341

    
   
2341

   
2342
	/* Close pipes if appropriate */
2342
	/* Close pipes if appropriate */
2343
	if ((fd = chan->alertpipe[0]) > -1)
2343
	if ((fd = chan->alertpipe[0]) > -1)
2344
		close(fd);
2344
		close(fd);
2345
	if ((fd = chan->alertpipe[1]) > -1)
2345
	if ((fd = chan->alertpipe[1]) > -1)
2346
		close(fd);
2346
		close(fd);
2347
	if (chan->timer) {
2347
	if (chan->timer) {
2348
		ast_timer_close(chan->timer);
2348
		ast_timer_close(chan->timer);
2349
	}
2349
	}
2350
#ifdef HAVE_EPOLL
2350
#ifdef HAVE_EPOLL
2351
	for (i = 0; i < AST_MAX_FDS; i++) {
2351
	for (i = 0; i < AST_MAX_FDS; i++) {
2352
		if (chan->epfd_data[i])
2352
		if (chan->epfd_data[i])
2353
			free(chan->epfd_data[i]);
2353
			free(chan->epfd_data[i]);
2354
	}
2354
	}
2355
	close(chan->epfd);
2355
	close(chan->epfd);
2356
#endif
2356
#endif
2357
	while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2357
	while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2358
		ast_frfree(f);
2358
		ast_frfree(f);
2359
	
2359
	
2360
	/* loop over the variables list, freeing all data and deleting list items */
2360
	/* loop over the variables list, freeing all data and deleting list items */
2361
	/* no need to lock the list, as the channel is already locked */
2361
	/* no need to lock the list, as the channel is already locked */
2362
	headp = &chan->varshead;
2362
	headp = &chan->varshead;
2363
	while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2363
	while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2364
		ast_var_delete(vardata);
2364
		ast_var_delete(vardata);
2365

    
   
2365

   
2366
	ast_app_group_discard(chan);
2366
	ast_app_group_discard(chan);
2367

    
   
2367

   
2368
	/* Destroy the jitterbuffer */
2368
	/* Destroy the jitterbuffer */
2369
	ast_jb_destroy(chan);
2369
	ast_jb_destroy(chan);
2370

    
   
2370

   
2371
	if (chan->cdr) {
2371
	if (chan->cdr) {
2372
		ast_cdr_discard(chan->cdr);
2372
		ast_cdr_discard(chan->cdr);
2373
		chan->cdr = NULL;
2373
		chan->cdr = NULL;
2374
	}
2374
	}
2375

    
   
2375

   
2376
	if (chan->zone) {
2376
	if (chan->zone) {
2377
		chan->zone = ast_tone_zone_unref(chan->zone);
2377
		chan->zone = ast_tone_zone_unref(chan->zone);
2378
	}
2378
	}
2379

    
   
2379

   
2380
	ast_string_field_free_memory(chan);
2380
	ast_string_field_free_memory(chan);
2381

    
   
2381

   
2382
	if (device_name[0]) {
2382
	if (device_name[0]) {
2383
		/*
2383
		/*
2384
		 * We have a device name to notify of a new state.
2384
		 * We have a device name to notify of a new state.
2385
		 *
2385
		 *
2386
		 * Queue an unknown state, because, while we know that this particular
2386
		 * Queue an unknown state, because, while we know that this particular
2387
		 * instance is dead, we don't know the state of all other possible
2387
		 * instance is dead, we don't know the state of all other possible
2388
		 * instances.
2388
		 * instances.
2389
		 */
2389
		 */
2390
		ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2390
		ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2391
	}
2391
	}
2392
}
2392
}
2393

    
   
2393

   
2394
/*! \brief Free a dummy channel structure */
2394
/*! \brief Free a dummy channel structure */
2395
static void ast_dummy_channel_destructor(void *obj)
2395
static void ast_dummy_channel_destructor(void *obj)
2396
{
2396
{
2397
	struct ast_channel *chan = obj;
2397
	struct ast_channel *chan = obj;
2398
	struct ast_var_t *vardata;
2398
	struct ast_var_t *vardata;
2399
	struct varshead *headp;
2399
	struct varshead *headp;
2400

    
   
2400

   
2401
	headp = &chan->varshead;
2401
	headp = &chan->varshead;
2402

    
   
2402

   
2403
	ast_party_dialed_free(&chan->dialed);
2403
	ast_party_dialed_free(&chan->dialed);
2404
	ast_party_caller_free(&chan->caller);
2404
	ast_party_caller_free(&chan->caller);
2405
	ast_party_connected_line_free(&chan->connected);
2405
	ast_party_connected_line_free(&chan->connected);
2406
	ast_party_redirecting_free(&chan->redirecting);
2406
	ast_party_redirecting_free(&chan->redirecting);
2407

    
   
2407

   
2408
	/* loop over the variables list, freeing all data and deleting list items */
2408
	/* loop over the variables list, freeing all data and deleting list items */
2409
	/* no need to lock the list, as the channel is already locked */
2409
	/* no need to lock the list, as the channel is already locked */
2410
	while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2410
	while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2411
		ast_var_delete(vardata);
2411
		ast_var_delete(vardata);
2412

    
   
2412

   
2413
	if (chan->cdr) {
2413
	if (chan->cdr) {
2414
		ast_cdr_discard(chan->cdr);
2414
		ast_cdr_discard(chan->cdr);
2415
		chan->cdr = NULL;
2415
		chan->cdr = NULL;
2416
	}
2416
	}
2417

    
   
2417

   
2418
	ast_string_field_free_memory(chan);
2418
	ast_string_field_free_memory(chan);
2419
}
2419
}
2420

    
   
2420

   
2421
struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2421
struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2422
{
2422
{
2423
	return ast_datastore_alloc(info, uid);
2423
	return ast_datastore_alloc(info, uid);
2424
}
2424
}
2425

    
   
2425

   
2426
int ast_channel_datastore_free(struct ast_datastore *datastore)
2426
int ast_channel_datastore_free(struct ast_datastore *datastore)
2427
{
2427
{
2428
	return ast_datastore_free(datastore);
2428
	return ast_datastore_free(datastore);
2429
}
2429
}
2430

    
   
2430

   
2431
int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2431
int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2432
{
2432
{
2433
	struct ast_datastore *datastore = NULL, *datastore2;
2433
	struct ast_datastore *datastore = NULL, *datastore2;
2434

    
   
2434

   
2435
	AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2435
	AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2436
		if (datastore->inheritance > 0) {
2436
		if (datastore->inheritance > 0) {
2437
			datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2437
			datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2438
			if (datastore2) {
2438
			if (datastore2) {
2439
				datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2439
				datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2440
				datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2440
				datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2441
				AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2441
				AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2442
			}
2442
			}
2443
		}
2443
		}
2444
	}
2444
	}
2445
	return 0;
2445
	return 0;
2446
}
2446
}
2447

    
   
2447

   
2448
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2448
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2449
{
2449
{
2450
	int res = 0;
2450
	int res = 0;
2451

    
   
2451

   
2452
	AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2452
	AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2453

    
   
2453

   
2454
	return res;
2454
	return res;
2455
}
2455
}
2456

    
   
2456

   
2457
int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2457
int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2458
{
2458
{
2459
	return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2459
	return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2460
}
2460
}
2461

    
   
2461

   
2462
struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2462
struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2463
{
2463
{
2464
	struct ast_datastore *datastore = NULL;
2464
	struct ast_datastore *datastore = NULL;
2465
	
2465
	
2466
	if (info == NULL)
2466
	if (info == NULL)
2467
		return NULL;
2467
		return NULL;
2468

    
   
2468

   
2469
	AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
2469
	AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
2470
		if (datastore->info != info) {
2470
		if (datastore->info != info) {
2471
			continue;
2471
			continue;
2472
		}
2472
		}
2473

    
   
2473

   
2474
		if (uid == NULL) {
2474
		if (uid == NULL) {
2475
			/* matched by type only */
2475
			/* matched by type only */
2476
			break;
2476
			break;
2477
		}
2477
		}
2478

    
   
2478

   
2479
		if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2479
		if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2480
			/* Matched by type AND uid */
2480
			/* Matched by type AND uid */
2481
			break;
2481
			break;
2482
		}
2482
		}
2483
	}
2483
	}
2484
	AST_LIST_TRAVERSE_SAFE_END;
2484
	AST_LIST_TRAVERSE_SAFE_END;
2485

    
   
2485

   
2486
	return datastore;
2486
	return datastore;
2487
}
2487
}
2488

    
   
2488

   
2489
/*! Set the file descriptor on the channel */
2489
/*! Set the file descriptor on the channel */
2490
void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2490
void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2491
{
2491
{
2492
#ifdef HAVE_EPOLL
2492
#ifdef HAVE_EPOLL
2493
	struct epoll_event ev;
2493
	struct epoll_event ev;
2494
	struct ast_epoll_data *aed = NULL;
2494
	struct ast_epoll_data *aed = NULL;
2495

    
   
2495

   
2496
	if (chan->fds[which] > -1) {
2496
	if (chan->fds[which] > -1) {
2497
		epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2497
		epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2498
		aed = chan->epfd_data[which];
2498
		aed = chan->epfd_data[which];
2499
	}
2499
	}
2500

    
   
2500

   
2501
	/* If this new fd is valid, add it to the epoll */
2501
	/* If this new fd is valid, add it to the epoll */
2502
	if (fd > -1) {
2502
	if (fd > -1) {
2503
		if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2503
		if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2504
			return;
2504
			return;
2505
		
2505
		
2506
		chan->epfd_data[which] = aed;
2506
		chan->epfd_data[which] = aed;
2507
		aed->chan = chan;
2507
		aed->chan = chan;
2508
		aed->which = which;
2508
		aed->which = which;
2509
		
2509
		
2510
		ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2510
		ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2511
		ev.data.ptr = aed;
2511
		ev.data.ptr = aed;
2512
		epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2512
		epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2513
	} else if (aed) {
2513
	} else if (aed) {
2514
		/* We don't have to keep around this epoll data structure now */
2514
		/* We don't have to keep around this epoll data structure now */
2515
		free(aed);
2515
		free(aed);
2516
		chan->epfd_data[which] = NULL;
2516
		chan->epfd_data[which] = NULL;
2517
	}
2517
	}
2518
#endif
2518
#endif
2519
	chan->fds[which] = fd;
2519
	chan->fds[which] = fd;
2520
	return;
2520
	return;
2521
}
2521
}
2522

    
   
2522

   
2523
/*! Add a channel to an optimized waitfor */
2523
/*! Add a channel to an optimized waitfor */
2524
void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2524
void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2525
{
2525
{
2526
#ifdef HAVE_EPOLL
2526
#ifdef HAVE_EPOLL
2527
	struct epoll_event ev;
2527
	struct epoll_event ev;
2528
	int i = 0;
2528
	int i = 0;
2529

    
   
2529

   
2530
	if (chan0->epfd == -1)
2530
	if (chan0->epfd == -1)
2531
		return;
2531
		return;
2532

    
   
2532

   
2533
	/* Iterate through the file descriptors on chan1, adding them to chan0 */
2533
	/* Iterate through the file descriptors on chan1, adding them to chan0 */
2534
	for (i = 0; i < AST_MAX_FDS; i++) {
2534
	for (i = 0; i < AST_MAX_FDS; i++) {
2535
		if (chan1->fds[i] == -1)
2535
		if (chan1->fds[i] == -1)
2536
			continue;
2536
			continue;
2537
		ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2537
		ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2538
		ev.data.ptr = chan1->epfd_data[i];
2538
		ev.data.ptr = chan1->epfd_data[i];
2539
		epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2539
		epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2540
	}
2540
	}
2541

    
   
2541

   
2542
#endif
2542
#endif
2543
	return;
2543
	return;
2544
}
2544
}
2545

    
   
2545

   
2546
/*! Delete a channel from an optimized waitfor */
2546
/*! Delete a channel from an optimized waitfor */
2547
void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2547
void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2548
{
2548
{
2549
#ifdef HAVE_EPOLL
2549
#ifdef HAVE_EPOLL
2550
	struct epoll_event ev;
2550
	struct epoll_event ev;
2551
	int i = 0;
2551
	int i = 0;
2552

    
   
2552

   
2553
	if (chan0->epfd == -1)
2553
	if (chan0->epfd == -1)
2554
		return;
2554
		return;
2555

    
   
2555

   
2556
	for (i = 0; i < AST_MAX_FDS; i++) {
2556
	for (i = 0; i < AST_MAX_FDS; i++) {
2557
		if (chan1->fds[i] == -1)
2557
		if (chan1->fds[i] == -1)
2558
			continue;
2558
			continue;
2559
		epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2559
		epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2560
	}
2560
	}
2561

    
   
2561

   
2562
#endif
2562
#endif
2563
	return;
2563
	return;
2564
}
2564
}
2565

    
   
2565

   
2566
/*! \brief Softly hangup a channel, don't lock */
2566
/*! \brief Softly hangup a channel, don't lock */
2567
int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2567
int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2568
{
2568
{
2569
	ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2569
	ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2570
	/* Inform channel driver that we need to be hung up, if it cares */
2570
	/* Inform channel driver that we need to be hung up, if it cares */
2571
	chan->_softhangup |= cause;
2571
	chan->_softhangup |= cause;
2572
	ast_queue_frame(chan, &ast_null_frame);
2572
	ast_queue_frame(chan, &ast_null_frame);
2573
	/* Interrupt any poll call or such */
2573
	/* Interrupt any poll call or such */
2574
	if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2574
	if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2575
		pthread_kill(chan->blocker, SIGURG);
2575
		pthread_kill(chan->blocker, SIGURG);
2576
	return 0;
2576
	return 0;
2577
}
2577
}
2578

    
   
2578

   
2579
/*! \brief Softly hangup a channel, lock */
2579
/*! \brief Softly hangup a channel, lock */
2580
int ast_softhangup(struct ast_channel *chan, int cause)
2580
int ast_softhangup(struct ast_channel *chan, int cause)
2581
{
2581
{
2582
	int res;
2582
	int res;
2583

    
   
2583

   
2584
	ast_channel_lock(chan);
2584
	ast_channel_lock(chan);
2585
	res = ast_softhangup_nolock(chan, cause);
2585
	res = ast_softhangup_nolock(chan, cause);
2586
	ast_channel_unlock(chan);
2586
	ast_channel_unlock(chan);
2587

    
   
2587

   
2588
	return res;
2588
	return res;
2589
}
2589
}
2590

    
   
2590

   
2591
static void free_translation(struct ast_channel *clonechan)
2591
static void free_translation(struct ast_channel *clonechan)
2592
{
2592
{
2593
	if (clonechan->writetrans)
2593
	if (clonechan->writetrans)
2594
		ast_translator_free_path(clonechan->writetrans);
2594
		ast_translator_free_path(clonechan->writetrans);
2595
	if (clonechan->readtrans)
2595
	if (clonechan->readtrans)
2596
		ast_translator_free_path(clonechan->readtrans);
2596
		ast_translator_free_path(clonechan->readtrans);
2597
	clonechan->writetrans = NULL;
2597
	clonechan->writetrans = NULL;
2598
	clonechan->readtrans = NULL;
2598
	clonechan->readtrans = NULL;
2599
	clonechan->rawwriteformat = clonechan->nativeformats;
2599
	clonechan->rawwriteformat = clonechan->nativeformats;
2600
	clonechan->rawreadformat = clonechan->nativeformats;
2600
	clonechan->rawreadformat = clonechan->nativeformats;
2601
}
2601
}
2602

    
   
2602

   
2603
void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2603
void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2604
{
2604
{
2605
	struct ast_channel *bridge;
2605
	struct ast_channel *bridge;
2606

    
   
2606

   
2607
	ast_channel_lock(chan);
2607
	ast_channel_lock(chan);
2608
	if (force || ast_strlen_zero(chan->hangupsource)) {
2608
	if (force || ast_strlen_zero(chan->hangupsource)) {
2609
		ast_string_field_set(chan, hangupsource, source);
2609
		ast_string_field_set(chan, hangupsource, source);
2610
	}
2610
	}
2611
	bridge = ast_bridged_channel(chan);
2611
	bridge = ast_bridged_channel(chan);
2612
	ast_channel_unlock(chan);
2612
	ast_channel_unlock(chan);
2613

    
   
2613

   
2614
	if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2614
	if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2615
		ast_channel_lock(bridge);
2615
		ast_channel_lock(bridge);
2616
		ast_string_field_set(chan, hangupsource, source);
2616
		ast_string_field_set(chan, hangupsource, source);
2617
		ast_channel_unlock(bridge);
2617
		ast_channel_unlock(bridge);
2618
	}
2618
	}
2619
}
2619
}
2620

    
   
2620

   
2621
/*! \brief Hangup a channel */
2621
/*! \brief Hangup a channel */
2622
int ast_hangup(struct ast_channel *chan)
2622
int ast_hangup(struct ast_channel *chan)
2623
{
2623
{
2624
	int res = 0;
2624
	int res = 0;
2625
	char extra_str[64]; /* used for cel logging below */
2625
	char extra_str[64]; /* used for cel logging below */
2626

    
   
2626

   
2627
	/* Don't actually hang up a channel that will masquerade as someone else, or
2627
	/* Don't actually hang up a channel that will masquerade as someone else, or
2628
	   if someone is going to masquerade as us */
2628
	   if someone is going to masquerade as us */
2629
	ast_channel_lock(chan);
2629
	ast_channel_lock(chan);
2630

    
   
2630

   
2631
	if (chan->audiohooks) {
2631
	if (chan->audiohooks) {
2632
		ast_audiohook_detach_list(chan->audiohooks);
2632
		ast_audiohook_detach_list(chan->audiohooks);
2633
		chan->audiohooks = NULL;
2633
		chan->audiohooks = NULL;
2634
	}
2634
	}
2635

    
   
2635

   
2636
	ast_autoservice_stop(chan);
2636
	ast_autoservice_stop(chan);
2637

    
   
2637

   
2638
	if (chan->masq) {
2638
	if (chan->masq) {
2639
		ast_channel_unlock(chan);
2639
		ast_channel_unlock(chan);
2640
		if (ast_do_masquerade(chan)) {
2640
		if (ast_do_masquerade(chan)) {
2641
			ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2641
			ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2642
		}
2642
		}
2643
		ast_channel_lock(chan);
2643
		ast_channel_lock(chan);
2644
	}
2644
	}
2645

    
   
2645

   
2646
	if (chan->masq) {
2646
	if (chan->masq) {
2647
		ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2647
		ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2648
		ast_channel_unlock(chan);
2648
		ast_channel_unlock(chan);
2649
		return 0;
2649
		return 0;
2650
	}
2650
	}
2651
	/* If this channel is one which will be masqueraded into something,
2651
	/* If this channel is one which will be masqueraded into something,
2652
	   mark it as a zombie already, so we know to free it later */
2652
	   mark it as a zombie already, so we know to free it later */
2653
	if (chan->masqr) {
2653
	if (chan->masqr) {
2654
		ast_set_flag(chan, AST_FLAG_ZOMBIE);
2654
		ast_set_flag(chan, AST_FLAG_ZOMBIE);
2655
		ast_channel_unlock(chan);
2655
		ast_channel_unlock(chan);
2656
		return 0;
2656
		return 0;
2657
	}
2657
	}
2658
	ast_channel_unlock(chan);
2658
	ast_channel_unlock(chan);
2659

    
   
2659

   
2660
	ao2_unlink(channels, chan);
2660
	ao2_unlink(channels, chan);
2661

    
   
2661

   
2662
	ast_channel_lock(chan);
2662
	ast_channel_lock(chan);
2663
	free_translation(chan);
2663
	free_translation(chan);
2664
	/* Close audio stream */
2664
	/* Close audio stream */
2665
	if (chan->stream) {
2665
	if (chan->stream) {
2666
		ast_closestream(chan->stream);
2666
		ast_closestream(chan->stream);
2667
		chan->stream = NULL;
2667
		chan->stream = NULL;
2668
	}
2668
	}
2669
	/* Close video stream */
2669
	/* Close video stream */
2670
	if (chan->vstream) {
2670
	if (chan->vstream) {
2671
		ast_closestream(chan->vstream);
2671
		ast_closestream(chan->vstream);
2672
		chan->vstream = NULL;
2672
		chan->vstream = NULL;
2673
	}
2673
	}
2674
	if (chan->sched) {
2674
	if (chan->sched) {
2675
		sched_context_destroy(chan->sched);
2675
		sched_context_destroy(chan->sched);
2676
		chan->sched = NULL;
2676
		chan->sched = NULL;
2677
	}
2677
	}
2678

    
   
2678

   
2679
	if (chan->generatordata)	/* Clear any tone stuff remaining */
2679
	if (chan->generatordata)	/* Clear any tone stuff remaining */
2680
		if (chan->generator && chan->generator->release)
2680
		if (chan->generator && chan->generator->release)
2681
			chan->generator->release(chan, chan->generatordata);
2681
			chan->generator->release(chan, chan->generatordata);
2682
	chan->generatordata = NULL;
2682
	chan->generatordata = NULL;
2683
	chan->generator = NULL;
2683
	chan->generator = NULL;
2684

    
   
2684

   
2685
	snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2685
	snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2686
	ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2686
	ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2687

    
   
2687

   
2688
	if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2688
	if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2689
		ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2689
		ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2690
					"is blocked by thread %ld in procedure %s!  Expect a failure\n",
2690
					"is blocked by thread %ld in procedure %s!  Expect a failure\n",
2691
					(long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2691
					(long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2692
		ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2692
		ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2693
	}
2693
	}
2694
	if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2694
	if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2695
		ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2695
		ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2696
		if (chan->tech->hangup)
2696
		if (chan->tech->hangup)
2697
			res = chan->tech->hangup(chan);
2697
			res = chan->tech->hangup(chan);
2698
	} else {
2698
	} else {
2699
		ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2699
		ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2700
	}
2700
	}
2701
			
2701
			
2702
	ast_channel_unlock(chan);
2702
	ast_channel_unlock(chan);
2703
	ast_cc_offer(chan);
2703
	ast_cc_offer(chan);
2704
	ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2704
	ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2705
		"Channel: %s\r\n"
2705
		"Channel: %s\r\n"
2706
		"Uniqueid: %s\r\n"
2706
		"Uniqueid: %s\r\n"
2707
		"CallerIDNum: %s\r\n"
2707
		"CallerIDNum: %s\r\n"
2708
		"CallerIDName: %s\r\n"
2708
		"CallerIDName: %s\r\n"
2709
		"Cause: %d\r\n"
2709
		"Cause: %d\r\n"
2710
		"Cause-txt: %s\r\n",
2710
		"Cause-txt: %s\r\n",
2711
		chan->name,
2711
		chan->name,
2712
		chan->uniqueid,
2712
		chan->uniqueid,
2713
		S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
2713
		S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
2714
		S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
2714
		S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
2715
		chan->hangupcause,
2715
		chan->hangupcause,
2716
		ast_cause2str(chan->hangupcause)
2716
		ast_cause2str(chan->hangupcause)
2717
		);
2717
		);
2718

    
   
2718

   
2719
	if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && 
2719
	if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && 
2720
		!ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && 
2720
		!ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && 
2721
	    (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2721
	    (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2722
		ast_channel_lock(chan);
2722
		ast_channel_lock(chan);
2723
			
2723
			
2724
		ast_cdr_end(chan->cdr);
2724
		ast_cdr_end(chan->cdr);
2725
		ast_cdr_detach(chan->cdr);
2725
		ast_cdr_detach(chan->cdr);
2726
		chan->cdr = NULL;
2726
		chan->cdr = NULL;
2727
		ast_channel_unlock(chan);
2727
		ast_channel_unlock(chan);
2728
	}
2728
	}
2729

    
   
2729

   
2730
	chan = ast_channel_release(chan);
2730
	chan = ast_channel_release(chan);
2731

    
   
2731

   
2732
	return res;
2732
	return res;
2733
}
2733
}
2734

    
   
2734

   
2735
int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2735
int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2736
{
2736
{
2737
	int res = 0;
2737
	int res = 0;
2738

    
   
2738

   
2739
	ast_channel_lock(chan);
2739
	ast_channel_lock(chan);
2740

    
   
2740

   
2741
	/* You can't answer an outbound call */
2741
	/* You can't answer an outbound call */
2742
	if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2742
	if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2743
		ast_channel_unlock(chan);
2743
		ast_channel_unlock(chan);
2744
		return 0;
2744
		return 0;
2745
	}
2745
	}
2746

    
   
2746

   
2747
	/* Stop if we're a zombie or need a soft hangup */
2747
	/* Stop if we're a zombie or need a soft hangup */
2748
	if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2748
	if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2749
		ast_channel_unlock(chan);
2749
		ast_channel_unlock(chan);
2750
		return -1;
2750
		return -1;
2751
	}
2751
	}
2752

    
   
2752

   
2753
	ast_channel_unlock(chan);
2753
	ast_channel_unlock(chan);
2754

    
   
2754

   
2755
	switch (chan->_state) {
2755
	switch (chan->_state) {
2756
	case AST_STATE_RINGING:
2756
	case AST_STATE_RINGING:
2757
	case AST_STATE_RING:
2757
	case AST_STATE_RING:
2758
		ast_channel_lock(chan);
2758
		ast_channel_lock(chan);
2759
		if (chan->tech->answer) {
2759
		if (chan->tech->answer) {
2760
			res = chan->tech->answer(chan);
2760
			res = chan->tech->answer(chan);
2761
		}
2761
		}
2762
		ast_setstate(chan, AST_STATE_UP);
2762
		ast_setstate(chan, AST_STATE_UP);
2763
		if (cdr_answer) {
2763
		if (cdr_answer) {
2764
			ast_cdr_answer(chan->cdr);
2764
			ast_cdr_answer(chan->cdr);
2765
		}
2765
		}
2766
		ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2766
		ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2767
		ast_channel_unlock(chan);
2767
		ast_channel_unlock(chan);
2768
		break;
2768
		break;
2769
	case AST_STATE_UP:
2769
	case AST_STATE_UP:
2770
		ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2770
		ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2771
		/* Calling ast_cdr_answer when it it has previously been called
2771
		/* Calling ast_cdr_answer when it it has previously been called
2772
		 * is essentially a no-op, so it is safe.
2772
		 * is essentially a no-op, so it is safe.
2773
		 */
2773
		 */
2774
		if (cdr_answer) {
2774
		if (cdr_answer) {
2775
			ast_cdr_answer(chan->cdr);
2775
			ast_cdr_answer(chan->cdr);
2776
		}
2776
		}
2777
		break;
2777
		break;
2778
	default:
2778
	default:
2779
		break;
2779
		break;
2780
	}
2780
	}
2781

    
   
2781

   
2782
	ast_indicate(chan, -1);
2782
	ast_indicate(chan, -1);
2783
	chan->visible_indication = 0;
2783
	chan->visible_indication = 0;
2784

    
   
2784

   
2785
	return res;
2785
	return res;
2786
}
2786
}
2787

    
   
2787

   
2788
int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2788
int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2789
{
2789
{
2790
	int res = 0;
2790
	int res = 0;
2791
	enum ast_channel_state old_state;
2791
	enum ast_channel_state old_state;
2792

    
   
2792

   
2793
	old_state = chan->_state;
2793
	old_state = chan->_state;
2794
	if ((res = ast_raw_answer(chan, cdr_answer))) {
2794
	if ((res = ast_raw_answer(chan, cdr_answer))) {
2795
		return res;
2795
		return res;
2796
	}
2796
	}
2797

    
   
2797

   
2798
	switch (old_state) {
2798
	switch (old_state) {
2799
	case AST_STATE_RINGING:
2799
	case AST_STATE_RINGING:
2800
	case AST_STATE_RING:
2800
	case AST_STATE_RING:
2801
		/* wait for media to start flowing, but don't wait any longer
2801
		/* wait for media to start flowing, but don't wait any longer
2802
		 * than 'delay' or 500 milliseconds, whichever is longer
2802
		 * than 'delay' or 500 milliseconds, whichever is longer
2803
		 */
2803
		 */
2804
		do {
2804
		do {
2805
			AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2805
			AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2806
			struct ast_frame *cur, *new;
2806
			struct ast_frame *cur, *new;
2807
			int ms = MAX(delay, 500);
2807
			int ms = MAX(delay, 500);
2808
			unsigned int done = 0;
2808
			unsigned int done = 0;
2809

    
   
2809

   
2810
			AST_LIST_HEAD_INIT_NOLOCK(&frames);
2810
			AST_LIST_HEAD_INIT_NOLOCK(&frames);
2811

    
   
2811

   
2812
			for (;;) {
2812
			for (;;) {
2813
				ms = ast_waitfor(chan, ms);
2813
				ms = ast_waitfor(chan, ms);
2814
				if (ms < 0) {
2814
				if (ms < 0) {
2815
					ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2815
					ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2816
					res = -1;
2816
					res = -1;
2817
					break;
2817
					break;
2818
				}
2818
				}
2819
				if (ms == 0) {
2819
				if (ms == 0) {
2820
					ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2820
					ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2821
					break;
2821
					break;
2822
				}
2822
				}
2823
				cur = ast_read(chan);
2823
				cur = ast_read(chan);
2824
				if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2824
				if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2825
					     (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2825
					     (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2826
					if (cur) {
2826
					if (cur) {
2827
						ast_frfree(cur);
2827
						ast_frfree(cur);
2828
					}
2828
					}
2829
					res = -1;
2829
					res = -1;
2830
					ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2830
					ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2831
					break;
2831
					break;
2832
				}
2832
				}
2833

    
   
2833

   
2834
				if ((new = ast_frisolate(cur)) != cur) {
2834
				if ((new = ast_frisolate(cur)) != cur) {
2835
					ast_frfree(cur);
2835
					ast_frfree(cur);
2836
				}
2836
				}
2837

    
   
2837

   
2838
				AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2838
				AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2839

    
   
2839

   
2840
				/* if a specific delay period was requested, continue
2840
				/* if a specific delay period was requested, continue
2841
				 * until that delay has passed. don't stop just because
2841
				 * until that delay has passed. don't stop just because
2842
				 * incoming media has arrived.
2842
				 * incoming media has arrived.
2843
				 */
2843
				 */
2844
				if (delay) {
2844
				if (delay) {
2845
					continue;
2845
					continue;
2846
				}
2846
				}
2847

    
   
2847

   
2848
				switch (new->frametype) {
2848
				switch (new->frametype) {
2849
					/* all of these frametypes qualify as 'media' */
2849
					/* all of these frametypes qualify as 'media' */
2850
				case AST_FRAME_VOICE:
2850
				case AST_FRAME_VOICE:
2851
				case AST_FRAME_VIDEO:
2851
				case AST_FRAME_VIDEO:
2852
				case AST_FRAME_TEXT:
2852
				case AST_FRAME_TEXT:
2853
				case AST_FRAME_DTMF_BEGIN:
2853
				case AST_FRAME_DTMF_BEGIN:
2854
				case AST_FRAME_DTMF_END:
2854
				case AST_FRAME_DTMF_END:
2855
				case AST_FRAME_IMAGE:
2855
				case AST_FRAME_IMAGE:
2856
				case AST_FRAME_HTML:
2856
				case AST_FRAME_HTML:
2857
				case AST_FRAME_MODEM:
2857
				case AST_FRAME_MODEM:
2858
					done = 1;
2858
					done = 1;
2859
					break;
2859
					break;
2860
				case AST_FRAME_CONTROL:
2860
				case AST_FRAME_CONTROL:
2861
				case AST_FRAME_IAX:
2861
				case AST_FRAME_IAX:
2862
				case AST_FRAME_NULL:
2862
				case AST_FRAME_NULL:
2863
				case AST_FRAME_CNG:
2863
				case AST_FRAME_CNG:
2864
					break;
2864
					break;
2865
				}
2865
				}
2866

    
   
2866

   
2867
				if (done) {
2867
				if (done) {
2868
					break;
2868
					break;
2869
				}
2869
				}
2870
			}
2870
			}
2871

    
   
2871

   
2872
			if (res == 0) {
2872
			if (res == 0) {
2873
				ast_channel_lock(chan);
2873
				ast_channel_lock(chan);
2874
				while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2874
				while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2875
					ast_queue_frame_head(chan, cur);
2875
					ast_queue_frame_head(chan, cur);
2876
					ast_frfree(cur);
2876
					ast_frfree(cur);
2877
				}
2877
				}
2878
				ast_channel_unlock(chan);
2878
				ast_channel_unlock(chan);
2879
			}
2879
			}
2880
		} while (0);
2880
		} while (0);
2881
		break;
2881
		break;
2882
	default:
2882
	default:
2883
		break;
2883
		break;
2884
	}
2884
	}
2885

    
   
2885

   
2886
	return res;
2886
	return res;
2887
}
2887
}
2888

    
   
2888

   
2889
int ast_answer(struct ast_channel *chan)
2889
int ast_answer(struct ast_channel *chan)
2890
{
2890
{
2891
	return __ast_answer(chan, 0, 1);
2891
	return __ast_answer(chan, 0, 1);
2892
}
2892
}
2893

    
   
2893

   
2894
void ast_deactivate_generator(struct ast_channel *chan)
2894
void ast_deactivate_generator(struct ast_channel *chan)
2895
{
2895
{
2896
	ast_channel_lock(chan);
2896
	ast_channel_lock(chan);
2897
	if (chan->generatordata) {
2897
	if (chan->generatordata) {
2898
		if (chan->generator && chan->generator->release)
2898
		if (chan->generator && chan->generator->release)
2899
			chan->generator->release(chan, chan->generatordata);
2899
			chan->generator->release(chan, chan->generatordata);
2900
		chan->generatordata = NULL;
2900
		chan->generatordata = NULL;
2901
		chan->generator = NULL;
2901
		chan->generator = NULL;
2902
		ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2902
		ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2903
		ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2903
		ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2904
		ast_settimeout(chan, 0, NULL, NULL);
2904
		ast_settimeout(chan, 0, NULL, NULL);
2905
	}
2905
	}
2906
	ast_channel_unlock(chan);
2906
	ast_channel_unlock(chan);
2907
}
2907
}
2908

    
   
2908

   
2909
static int generator_force(const void *data)
2909
static int generator_force(const void *data)
2910
{
2910
{
2911
	/* Called if generator doesn't have data */
2911
	/* Called if generator doesn't have data */
2912
	void *tmp;
2912
	void *tmp;
2913
	int res;
2913
	int res;
2914
	int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2914
	int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2915
	struct ast_channel *chan = (struct ast_channel *)data;
2915
	struct ast_channel *chan = (struct ast_channel *)data;
2916

    
   
2916

   
2917
	ast_channel_lock(chan);
2917
	ast_channel_lock(chan);
2918
	tmp = chan->generatordata;
2918
	tmp = chan->generatordata;
2919
	chan->generatordata = NULL;
2919
	chan->generatordata = NULL;
2920
	if (chan->generator)
2920
	if (chan->generator)
2921
		generate = chan->generator->generate;
2921
		generate = chan->generator->generate;
2922
	ast_channel_unlock(chan);
2922
	ast_channel_unlock(chan);
2923

    
   
2923

   
2924
	if (!tmp || !generate)
2924
	if (!tmp || !generate)
2925
		return 0;
2925
		return 0;
2926

    
   
2926

   
2927
	res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2927
	res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2928

    
   
2928

   
2929
	chan->generatordata = tmp;
2929
	chan->generatordata = tmp;
2930

    
   
2930

   
2931
	if (res) {
2931
	if (res) {
2932
		ast_debug(1, "Auto-deactivating generator\n");
2932
		ast_debug(1, "Auto-deactivating generator\n");
2933
		ast_deactivate_generator(chan);
2933
		ast_deactivate_generator(chan);
2934
	}
2934
	}
2935

    
   
2935

   
2936
	return 0;
2936
	return 0;
2937
}
2937
}
2938

    
   
2938

   
2939
int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2939
int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2940
{
2940
{
2941
	int res = 0;
2941
	int res = 0;
2942

    
   
2942

   
2943
	ast_channel_lock(chan);
2943
	ast_channel_lock(chan);
2944
	if (chan->generatordata) {
2944
	if (chan->generatordata) {
2945
		if (chan->generator && chan->generator->release)
2945
		if (chan->generator && chan->generator->release)
2946
			chan->generator->release(chan, chan->generatordata);
2946
			chan->generator->release(chan, chan->generatordata);
2947
		chan->generatordata = NULL;
2947
		chan->generatordata = NULL;
2948
	}
2948
	}
2949
	if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2949
	if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2950
		res = -1;
2950
		res = -1;
2951
	}
2951
	}
2952
	if (!res) {
2952
	if (!res) {
2953
		ast_settimeout(chan, 50, generator_force, chan);
2953
		ast_settimeout(chan, 50, generator_force, chan);
2954
		chan->generator = gen;
2954
		chan->generator = gen;
2955
	}
2955
	}
2956
	ast_channel_unlock(chan);
2956
	ast_channel_unlock(chan);
2957

    
   
2957

   
2958
	ast_prod(chan);
2958
	ast_prod(chan);
2959

    
   
2959

   
2960
	return res;
2960
	return res;
2961
}
2961
}
2962

    
   
2962

   
2963
/*! \brief Wait for x amount of time on a file descriptor to have input.  */
2963
/*! \brief Wait for x amount of time on a file descriptor to have input.  */
2964
int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2964
int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2965
{
2965
{
2966
	int winner = -1;
2966
	int winner = -1;
2967
	ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2967
	ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2968
	return winner;
2968
	return winner;
2969
}
2969
}
2970

    
   
2970

   
2971
/*! \brief Wait for x amount of time on a file descriptor to have input.  */
2971
/*! \brief Wait for x amount of time on a file descriptor to have input.  */
2972
#ifdef HAVE_EPOLL
2972
#ifdef HAVE_EPOLL
2973
static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2973
static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2974
					int *exception, int *outfd, int *ms)
2974
					int *exception, int *outfd, int *ms)
2975
#else
2975
#else
2976
struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2976
struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2977
					int *exception, int *outfd, int *ms)
2977
					int *exception, int *outfd, int *ms)
2978
#endif
2978
#endif
2979
{
2979
{
2980
	struct timeval start = { 0 , 0 };
2980
	struct timeval start = { 0 , 0 };
2981
	struct pollfd *pfds = NULL;
2981
	struct pollfd *pfds = NULL;
2982
	int res;
2982
	int res;
2983
	long rms;
2983
	long rms;
2984
	int x, y, max;
2984
	int x, y, max;
2985
	int sz;
2985
	int sz;
2986
	struct timeval now = { 0, 0 };
2986
	struct timeval now = { 0, 0 };
2987
	struct timeval whentohangup = { 0, 0 }, diff;
2987
	struct timeval whentohangup = { 0, 0 }, diff;
2988
	struct ast_channel *winner = NULL;
2988
	struct ast_channel *winner = NULL;
2989
	struct fdmap {
2989
	struct fdmap {
2990
		int chan;
2990
		int chan;
2991
		int fdno;
2991
		int fdno;
2992
	} *fdmap = NULL;
2992
	} *fdmap = NULL;
2993

    
   
2993

   
2994
	if ((sz = n * AST_MAX_FDS + nfds)) {
2994
	if ((sz = n * AST_MAX_FDS + nfds)) {
2995
		pfds = alloca(sizeof(*pfds) * sz);
2995
		pfds = alloca(sizeof(*pfds) * sz);
2996
		fdmap = alloca(sizeof(*fdmap) * sz);
2996
		fdmap = alloca(sizeof(*fdmap) * sz);
2997
	}
2997
	}
2998

    
   
2998

   
2999
	if (outfd)
2999
	if (outfd)
3000
		*outfd = -99999;
3000
		*outfd = -99999;
3001
	if (exception)
3001
	if (exception)
3002
		*exception = 0;
3002
		*exception = 0;
3003
	
3003
	
3004
	/* Perform any pending masquerades */
3004
	/* Perform any pending masquerades */
3005
	for (x = 0; x < n; x++) {
3005
	for (x = 0; x < n; x++) {
3006
		if (c[x]->masq && ast_do_masquerade(c[x])) {
3006
		if (c[x]->masq && ast_do_masquerade(c[x])) {
3007
			ast_log(LOG_WARNING, "Masquerade failed\n");
3007
			ast_log(LOG_WARNING, "Masquerade failed\n");
3008
			*ms = -1;
3008
			*ms = -1;
3009
			return NULL;
3009
			return NULL;
3010
		}
3010
		}
3011

    
   
3011

   
3012
		ast_channel_lock(c[x]);
3012
		ast_channel_lock(c[x]);
3013
		if (!ast_tvzero(c[x]->whentohangup)) {
3013
		if (!ast_tvzero(c[x]->whentohangup)) {
3014
			if (ast_tvzero(whentohangup))
3014
			if (ast_tvzero(whentohangup))
3015
				now = ast_tvnow();
3015
				now = ast_tvnow();
3016
			diff = ast_tvsub(c[x]->whentohangup, now);
3016
			diff = ast_tvsub(c[x]->whentohangup, now);
3017
			if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3017
			if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3018
				/* Should already be hungup */
3018
				/* Should already be hungup */
3019
				c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3019
				c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3020
				ast_channel_unlock(c[x]);
3020
				ast_channel_unlock(c[x]);
3021
				return c[x];
3021
				return c[x];
3022
			}
3022
			}
3023
			if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3023
			if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3024
				whentohangup = diff;
3024
				whentohangup = diff;
3025
		}
3025
		}
3026
		ast_channel_unlock(c[x]);
3026
		ast_channel_unlock(c[x]);
3027
	}
3027
	}
3028
	/* Wait full interval */
3028
	/* Wait full interval */
3029
	rms = *ms;
3029
	rms = *ms;
3030
	/* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3030
	/* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3031
	if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3031
	if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3032
		rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3032
		rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3033
		if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3033
		if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3034
			rms =  *ms;
3034
			rms =  *ms;
3035
		}
3035
		}
3036
	} else if (!ast_tvzero(whentohangup) && rms < 0) {
3036
	} else if (!ast_tvzero(whentohangup) && rms < 0) {
3037
		/* Tiny corner case... call would need to last >24 days */
3037
		/* Tiny corner case... call would need to last >24 days */
3038
		rms = INT_MAX;
3038
		rms = INT_MAX;
3039
	}
3039
	}
3040
	/*
3040
	/*
3041
	 * Build the pollfd array, putting the channels' fds first,
3041
	 * Build the pollfd array, putting the channels' fds first,
3042
	 * followed by individual fds. Order is important because
3042
	 * followed by individual fds. Order is important because
3043
	 * individual fd's must have priority over channel fds.
3043
	 * individual fd's must have priority over channel fds.
3044
	 */
3044
	 */
3045
	max = 0;
3045
	max = 0;
3046
	for (x = 0; x < n; x++) {
3046
	for (x = 0; x < n; x++) {
3047
		for (y = 0; y < AST_MAX_FDS; y++) {
3047
		for (y = 0; y < AST_MAX_FDS; y++) {
3048
			fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3048
			fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3049
			fdmap[max].chan = x;  /* channel x is linked to this pfds */
3049
			fdmap[max].chan = x;  /* channel x is linked to this pfds */
3050
			max += ast_add_fd(&pfds[max], c[x]->fds[y]);
3050
			max += ast_add_fd(&pfds[max], c[x]->fds[y]);
3051
		}
3051
		}
3052
		CHECK_BLOCKING(c[x]);
3052
		CHECK_BLOCKING(c[x]);
3053
	}
3053
	}
3054
	/* Add the individual fds */
3054
	/* Add the individual fds */
3055
	for (x = 0; x < nfds; x++) {
3055
	for (x = 0; x < nfds; x++) {
3056
		fdmap[max].chan = -1;
3056
		fdmap[max].chan = -1;
3057
		max += ast_add_fd(&pfds[max], fds[x]);
3057
		max += ast_add_fd(&pfds[max], fds[x]);
3058
	}
3058
	}
3059

    
   
3059

   
3060
	if (*ms > 0)
3060
	if (*ms > 0)
3061
		start = ast_tvnow();
3061
		start = ast_tvnow();
3062
	
3062
	
3063
	if (sizeof(int) == 4) {	/* XXX fix timeout > 600000 on linux x86-32 */
3063
	if (sizeof(int) == 4) {	/* XXX fix timeout > 600000 on linux x86-32 */
3064
		do {
3064
		do {
3065
			int kbrms = rms;
3065
			int kbrms = rms;
3066
			if (kbrms > 600000)
3066
			if (kbrms > 600000)
3067
				kbrms = 600000;
3067
				kbrms = 600000;
3068
			res = ast_poll(pfds, max, kbrms);
3068
			res = ast_poll(pfds, max, kbrms);
3069
			if (!res)
3069
			if (!res)
3070
				rms -= kbrms;
3070
				rms -= kbrms;
3071
		} while (!res && (rms > 0));
3071
		} while (!res && (rms > 0));
3072
	} else {
3072
	} else {
3073
		res = ast_poll(pfds, max, rms);
3073
		res = ast_poll(pfds, max, rms);
3074
	}
3074
	}
3075
	for (x = 0; x < n; x++)
3075
	for (x = 0; x < n; x++)
3076
		ast_clear_flag(c[x], AST_FLAG_BLOCKING);
3076
		ast_clear_flag(c[x], AST_FLAG_BLOCKING);
3077
	if (res < 0) { /* Simulate a timeout if we were interrupted */
3077
	if (res < 0) { /* Simulate a timeout if we were interrupted */
3078
		if (errno != EINTR)
3078
		if (errno != EINTR)
3079
			*ms = -1;
3079
			*ms = -1;
3080
		return NULL;
3080
		return NULL;
3081
	}
3081
	}
3082
	if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3082
	if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3083
		now = ast_tvnow();
3083
		now = ast_tvnow();
3084
		for (x = 0; x < n; x++) {
3084
		for (x = 0; x < n; x++) {
3085
			if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
3085
			if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
3086
				c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3086
				c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3087
				if (winner == NULL)
3087
				if (winner == NULL)
3088
					winner = c[x];
3088
					winner = c[x];
3089
			}
3089
			}
3090
		}
3090
		}
3091
	}
3091
	}
3092
	if (res == 0) { /* no fd ready, reset timeout and done */
3092
	if (res == 0) { /* no fd ready, reset timeout and done */
3093
		*ms = 0;	/* XXX use 0 since we may not have an exact timeout. */
3093
		*ms = 0;	/* XXX use 0 since we may not have an exact timeout. */
3094
		return winner;
3094
		return winner;
3095
	}
3095
	}
3096
	/*
3096
	/*
3097
	 * Then check if any channel or fd has a pending event.
3097
	 * Then check if any channel or fd has a pending event.
3098
	 * Remember to check channels first and fds last, as they
3098
	 * Remember to check channels first and fds last, as they
3099
	 * must have priority on setting 'winner'
3099
	 * must have priority on setting 'winner'
3100
	 */
3100
	 */
3101
	for (x = 0; x < max; x++) {
3101
	for (x = 0; x < max; x++) {
3102
		res = pfds[x].revents;
3102
		res = pfds[x].revents;
3103
		if (res == 0)
3103
		if (res == 0)
3104
			continue;
3104
			continue;
3105
		if (fdmap[x].chan >= 0) {	/* this is a channel */
3105
		if (fdmap[x].chan >= 0) {	/* this is a channel */
3106
			winner = c[fdmap[x].chan];	/* override previous winners */
3106
			winner = c[fdmap[x].chan];	/* override previous winners */
3107
			if (res & POLLPRI)
3107
			if (res & POLLPRI)
3108
				ast_set_flag(winner, AST_FLAG_EXCEPTION);
3108
				ast_set_flag(winner, AST_FLAG_EXCEPTION);
3109
			else
3109
			else
3110
				ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3110
				ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3111
			winner->fdno = fdmap[x].fdno;
3111
			winner->fdno = fdmap[x].fdno;
3112
		} else {			/* this is an fd */
3112
		} else {			/* this is an fd */
3113
			if (outfd)
3113
			if (outfd)
3114
				*outfd = pfds[x].fd;
3114
				*outfd = pfds[x].fd;
3115
			if (exception)
3115
			if (exception)
3116
				*exception = (res & POLLPRI) ? -1 : 0;
3116
				*exception = (res & POLLPRI) ? -1 : 0;
3117
			winner = NULL;
3117
			winner = NULL;
3118
		}
3118
		}
3119
	}
3119
	}
3120
	if (*ms > 0) {
3120
	if (*ms > 0) {
3121
		*ms -= ast_tvdiff_ms(ast_tvnow(), start);
3121
		*ms -= ast_tvdiff_ms(ast_tvnow(), start);
3122
		if (*ms < 0)
3122
		if (*ms < 0)
3123
			*ms = 0;
3123
			*ms = 0;
3124
	}
3124
	}
3125
	return winner;
3125
	return winner;
3126
}
3126
}
3127

    
   
3127

   
3128
#ifdef HAVE_EPOLL
3128
#ifdef HAVE_EPOLL
3129
static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3129
static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3130
{
3130
{
3131
	struct timeval start = { 0 , 0 };
3131
	struct timeval start = { 0 , 0 };
3132
	int res = 0;
3132
	int res = 0;
3133
	struct epoll_event ev[1];
3133
	struct epoll_event ev[1];
3134
	long diff, rms = *ms;
3134
	long diff, rms = *ms;
3135
	struct ast_channel *winner = NULL;
3135
	struct ast_channel *winner = NULL;
3136
	struct ast_epoll_data *aed = NULL;
3136
	struct ast_epoll_data *aed = NULL;
3137

    
   
3137

   
3138

    
   
3138

   
3139
	/* See if this channel needs to be masqueraded */
3139
	/* See if this channel needs to be masqueraded */
3140
	if (chan->masq && ast_do_masquerade(chan)) {
3140
	if (chan->masq && ast_do_masquerade(chan)) {
3141
		ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
3141
		ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
3142
		*ms = -1;
3142
		*ms = -1;
3143
		return NULL;
3143
		return NULL;
3144
	}
3144
	}
3145

    
   
3145

   
3146
	ast_channel_lock(chan);
3146
	ast_channel_lock(chan);
3147
	/* Figure out their timeout */
3147
	/* Figure out their timeout */
3148
	if (!ast_tvzero(chan->whentohangup)) {
3148
	if (!ast_tvzero(chan->whentohangup)) {
3149
		if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
3149
		if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
3150
			/* They should already be hungup! */
3150
			/* They should already be hungup! */
3151
			chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3151
			chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3152
			ast_channel_unlock(chan);
3152
			ast_channel_unlock(chan);
3153
			return NULL;
3153
			return NULL;
3154
		}
3154
		}
3155
		/* If this value is smaller then the current one... make it priority */
3155
		/* If this value is smaller then the current one... make it priority */
3156
		if (rms > diff)
3156
		if (rms > diff)
3157
			rms = diff;
3157
			rms = diff;
3158
	}
3158
	}
3159

    
   
3159

   
3160
	ast_channel_unlock(chan);
3160
	ast_channel_unlock(chan);
3161

    
   
3161

   
3162
	/* Time to make this channel block... */
3162
	/* Time to make this channel block... */
3163
	CHECK_BLOCKING(chan);
3163
	CHECK_BLOCKING(chan);
3164

    
   
3164

   
3165
	if (*ms > 0)
3165
	if (*ms > 0)
3166
		start = ast_tvnow();
3166
		start = ast_tvnow();
3167

    
   
3167

   
3168
	/* We don't have to add any file descriptors... they are already added, we just have to wait! */
3168
	/* We don't have to add any file descriptors... they are already added, we just have to wait! */
3169
	res = epoll_wait(chan->epfd, ev, 1, rms);
3169
	res = epoll_wait(chan->epfd, ev, 1, rms);
3170

    
   
3170

   
3171
	/* Stop blocking */
3171
	/* Stop blocking */
3172
	ast_clear_flag(chan, AST_FLAG_BLOCKING);
3172
	ast_clear_flag(chan, AST_FLAG_BLOCKING);
3173

    
   
3173

   
3174
	/* Simulate a timeout if we were interrupted */
3174
	/* Simulate a timeout if we were interrupted */
3175
	if (res < 0) {
3175
	if (res < 0) {
3176
		if (errno != EINTR)
3176
		if (errno != EINTR)
3177
			*ms = -1;
3177
			*ms = -1;
3178
		return NULL;
3178
		return NULL;
3179
	}
3179
	}
3180

    
   
3180

   
3181
	/* If this channel has a timeout see if it expired */
3181
	/* If this channel has a timeout see if it expired */
3182
	if (!ast_tvzero(chan->whentohangup)) {
3182
	if (!ast_tvzero(chan->whentohangup)) {
3183
		if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
3183
		if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
3184
			chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3184
			chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3185
			winner = chan;
3185
			winner = chan;
3186
		}
3186
		}
3187
	}
3187
	}
3188

    
   
3188

   
3189
	/* No fd ready, reset timeout and be done for now */
3189
	/* No fd ready, reset timeout and be done for now */
3190
	if (!res) {
3190
	if (!res) {
3191
		*ms = 0;
3191
		*ms = 0;
3192
		return winner;
3192
		return winner;
3193
	}
3193
	}
3194

    
   
3194

   
3195
	/* See what events are pending */
3195
	/* See what events are pending */
3196
	aed = ev[0].data.ptr;
3196
	aed = ev[0].data.ptr;
3197
	chan->fdno = aed->which;
3197
	chan->fdno = aed->which;
3198
	if (ev[0].events & EPOLLPRI)
3198
	if (ev[0].events & EPOLLPRI)
3199
		ast_set_flag(chan, AST_FLAG_EXCEPTION);
3199
		ast_set_flag(chan, AST_FLAG_EXCEPTION);
3200
	else
3200
	else
3201
		ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3201
		ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3202

    
   
3202

   
3203
	if (*ms > 0) {
3203
	if (*ms > 0) {
3204
		*ms -= ast_tvdiff_ms(ast_tvnow(), start);
3204
		*ms -= ast_tvdiff_ms(ast_tvnow(), start);
3205
		if (*ms < 0)
3205
		if (*ms < 0)
3206
			*ms = 0;
3206
			*ms = 0;
3207
	}
3207
	}
3208

    
   
3208

   
3209
	return chan;
3209
	return chan;
3210
}
3210
}
3211

    
   
3211

   
3212
static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3212
static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3213
{
3213
{
3214
	struct timeval start = { 0 , 0 };
3214
	struct timeval start = { 0 , 0 };
3215
	int res = 0, i;
3215
	int res = 0, i;
3216
	struct epoll_event ev[25] = { { 0, } };
3216
	struct epoll_event ev[25] = { { 0, } };
3217
	struct timeval now = { 0, 0 };
3217
	struct timeval now = { 0, 0 };
3218
	long whentohangup = 0, diff = 0, rms = *ms;
3218
	long whentohangup = 0, diff = 0, rms = *ms;
3219
	struct ast_channel *winner = NULL;
3219
	struct ast_channel *winner = NULL;
3220

    
   
3220

   
3221
	for (i = 0; i < n; i++) {
3221
	for (i = 0; i < n; i++) {
3222
		if (c[i]->masq && ast_do_masquerade(c[i])) {
3222
		if (c[i]->masq && ast_do_masquerade(c[i])) {
3223
			ast_log(LOG_WARNING, "Masquerade failed\n");
3223
			ast_log(LOG_WARNING, "Masquerade failed\n");
3224
			*ms = -1;
3224
			*ms = -1;
3225
			return NULL;
3225
			return NULL;
3226
		}
3226
		}
3227

    
   
3227

   
3228
		ast_channel_lock(c[i]);
3228
		ast_channel_lock(c[i]);
3229
		if (!ast_tvzero(c[i]->whentohangup)) {
3229
		if (!ast_tvzero(c[i]->whentohangup)) {
3230
			if (whentohangup == 0)
3230
			if (whentohangup == 0)
3231
				now = ast_tvnow();
3231
				now = ast_tvnow();
3232
			if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
3232
			if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
3233
				c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3233
				c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3234
				ast_channel_unlock(c[i]);
3234
				ast_channel_unlock(c[i]);
3235
				return c[i];
3235
				return c[i];
3236
			}
3236
			}
3237
			if (!whentohangup || whentohangup > diff)
3237
			if (!whentohangup || whentohangup > diff)
3238
				whentohangup = diff;
3238
				whentohangup = diff;
3239
		}
3239
		}
3240
		ast_channel_unlock(c[i]);
3240
		ast_channel_unlock(c[i]);
3241
		CHECK_BLOCKING(c[i]);
3241
		CHECK_BLOCKING(c[i]);
3242
	}
3242
	}
3243

    
   
3243

   
3244
	rms = *ms;
3244
	rms = *ms;
3245
	if (whentohangup) {
3245
	if (whentohangup) {
3246
		rms = whentohangup;
3246
		rms = whentohangup;
3247
		if (*ms >= 0 && *ms < rms)
3247
		if (*ms >= 0 && *ms < rms)
3248
			rms = *ms;
3248
			rms = *ms;
3249
	}
3249
	}
3250

    
   
3250

   
3251
	if (*ms > 0)
3251
	if (*ms > 0)
3252
		start = ast_tvnow();
3252
		start = ast_tvnow();
3253

    
   
3253

   
3254
	res = epoll_wait(c[0]->epfd, ev, 25, rms);
3254
	res = epoll_wait(c[0]->epfd, ev, 25, rms);
3255

    
   
3255

   
3256
	for (i = 0; i < n; i++)
3256
	for (i = 0; i < n; i++)
3257
		ast_clear_flag(c[i], AST_FLAG_BLOCKING);
3257
		ast_clear_flag(c[i], AST_FLAG_BLOCKING);
3258

    
   
3258

   
3259
	if (res < 0) {
3259
	if (res < 0) {
3260
		if (errno != EINTR)
3260
		if (errno != EINTR)
3261
			*ms = -1;
3261
			*ms = -1;
3262
		return NULL;
3262
		return NULL;
3263
	}
3263
	}
3264

    
   
3264

   
3265
	if (whentohangup) {
3265
	if (whentohangup) {
3266
		now = ast_tvnow();
3266
		now = ast_tvnow();
3267
		for (i = 0; i < n; i++) {
3267
		for (i = 0; i < n; i++) {
3268
			if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
3268
			if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
3269
				c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3269
				c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3270
				if (!winner)
3270
				if (!winner)
3271
					winner = c[i];
3271
					winner = c[i];
3272
			}
3272
			}
3273
		}
3273
		}
3274
	}
3274
	}
3275

    
   
3275

   
3276
	if (!res) {
3276
	if (!res) {
3277
		*ms = 0;
3277
		*ms = 0;
3278
		return winner;
3278
		return winner;
3279
	}
3279
	}
3280

    
   
3280

   
3281
	for (i = 0; i < res; i++) {
3281
	for (i = 0; i < res; i++) {
3282
		struct ast_epoll_data *aed = ev[i].data.ptr;
3282
		struct ast_epoll_data *aed = ev[i].data.ptr;
3283

    
   
3283

   
3284
		if (!ev[i].events || !aed)
3284
		if (!ev[i].events || !aed)
3285
			continue;
3285
			continue;
3286

    
   
3286

   
3287
		winner = aed->chan;
3287
		winner = aed->chan;
3288
		if (ev[i].events & EPOLLPRI)
3288
		if (ev[i].events & EPOLLPRI)
3289
			ast_set_flag(winner, AST_FLAG_EXCEPTION);
3289
			ast_set_flag(winner, AST_FLAG_EXCEPTION);
3290
		else
3290
		else
3291
			ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3291
			ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3292
		winner->fdno = aed->which;
3292
		winner->fdno = aed->which;
3293
	}
3293
	}
3294

    
   
3294

   
3295
	if (*ms > 0) {
3295
	if (*ms > 0) {
3296
		*ms -= ast_tvdiff_ms(ast_tvnow(), start);
3296
		*ms -= ast_tvdiff_ms(ast_tvnow(), start);
3297
		if (*ms < 0)
3297
		if (*ms < 0)
3298
			*ms = 0;
3298
			*ms = 0;
3299
	}
3299
	}
3300

    
   
3300

   
3301
	return winner;
3301
	return winner;
3302
}
3302
}
3303

    
   
3303

   
3304
struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3304
struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3305
					int *exception, int *outfd, int *ms)
3305
					int *exception, int *outfd, int *ms)
3306
{
3306
{
3307
	/* Clear all provided values in one place. */
3307
	/* Clear all provided values in one place. */
3308
	if (outfd)
3308
	if (outfd)
3309
		*outfd = -99999;
3309
		*outfd = -99999;
3310
	if (exception)
3310
	if (exception)
3311
		*exception = 0;
3311
		*exception = 0;
3312

    
   
3312

   
3313
	/* If no epoll file descriptor is available resort to classic nandfds */
3313
	/* If no epoll file descriptor is available resort to classic nandfds */
3314
	if (!n || nfds || c[0]->epfd == -1)
3314
	if (!n || nfds || c[0]->epfd == -1)
3315
		return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3315
		return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3316
	else if (!nfds && n == 1)
3316
	else if (!nfds && n == 1)
3317
		return ast_waitfor_nandfds_simple(c[0], ms);
3317
		return ast_waitfor_nandfds_simple(c[0], ms);
3318
	else
3318
	else
3319
		return ast_waitfor_nandfds_complex(c, n, ms);
3319
		return ast_waitfor_nandfds_complex(c, n, ms);
3320
}
3320
}
3321
#endif
3321
#endif
3322

    
   
3322

   
3323
struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3323
struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3324
{
3324
{
3325
	return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3325
	return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3326
}
3326
}
3327

    
   
3327

   
3328
int ast_waitfor(struct ast_channel *c, int ms)
3328
int ast_waitfor(struct ast_channel *c, int ms)
3329
{
3329
{
3330
	int oldms = ms;	/* -1 if no timeout */
3330
	int oldms = ms;	/* -1 if no timeout */
3331

    
   
3331

   
3332
	ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3332
	ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3333
	if ((ms < 0) && (oldms < 0))
3333
	if ((ms < 0) && (oldms < 0))
3334
		ms = 0;
3334
		ms = 0;
3335
	return ms;
3335
	return ms;
3336
}
3336
}
3337

    
   
3337

   
3338
/* XXX never to be called with ms = -1 */
3338
/* XXX never to be called with ms = -1 */
3339
int ast_waitfordigit(struct ast_channel *c, int ms)
3339
int ast_waitfordigit(struct ast_channel *c, int ms)
3340
{
3340
{
3341
	return ast_waitfordigit_full(c, ms, -1, -1);
3341
	return ast_waitfordigit_full(c, ms, -1, -1);
3342
}
3342
}
3343

    
   
3343

   
3344
int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3344
int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3345
{
3345
{
3346
	int res;
3346
	int res;
3347
	unsigned int real_rate = rate, max_rate;
3347
	unsigned int real_rate = rate, max_rate;
3348

    
   
3348

   
3349
	ast_channel_lock(c);
3349
	ast_channel_lock(c);
3350

    
   
3350

   
3351
	if (c->timingfd == -1) {
3351
	if (c->timingfd == -1) {
3352
		ast_channel_unlock(c);
3352
		ast_channel_unlock(c);
3353
		return -1;
3353
		return -1;
3354
	}
3354
	}
3355

    
   
3355

   
3356
	if (!func) {
3356
	if (!func) {
3357
		rate = 0;
3357
		rate = 0;
3358
		data = NULL;
3358
		data = NULL;
3359
	}
3359
	}
3360

    
   
3360

   
3361
	if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
3361
	if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
3362
		real_rate = max_rate;
3362
		real_rate = max_rate;
3363
	}
3363
	}
3364

    
   
3364

   
3365
	ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3365
	ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3366

    
   
3366

   
3367
	res = ast_timer_set_rate(c->timer, real_rate);
3367
	res = ast_timer_set_rate(c->timer, real_rate);
3368

    
   
3368

   
3369
	c->timingfunc = func;
3369
	c->timingfunc = func;
3370
	c->timingdata = data;
3370
	c->timingdata = data;
3371

    
   
3371

   
3372
	ast_channel_unlock(c);
3372
	ast_channel_unlock(c);
3373

    
   
3373

   
3374
	return res;
3374
	return res;
3375
}
3375
}
3376

    
   
3376

   
3377
int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
3377
int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
3378
{
3378
{
3379
	/* Stop if we're a zombie or need a soft hangup */
3379
	/* Stop if we're a zombie or need a soft hangup */
3380
	if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3380
	if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3381
		return -1;
3381
		return -1;
3382

    
   
3382

   
3383
	/* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3383
	/* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3384
	ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
3384
	ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
3385

    
   
3385

   
3386
	/* Wait for a digit, no more than ms milliseconds total. */
3386
	/* Wait for a digit, no more than ms milliseconds total. */
3387
	
3387
	
3388
	while (ms) {
3388
	while (ms) {
3389
		struct ast_channel *rchan;
3389
		struct ast_channel *rchan;
3390
		int outfd=-1;
3390
		int outfd=-1;
3391

    
   
3391

   
3392
		errno = 0;
3392
		errno = 0;
3393
		rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3393
		rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3394
		
3394
		
3395
		if (!rchan && outfd < 0 && ms) {
3395
		if (!rchan && outfd < 0 && ms) {
3396
			if (errno == 0 || errno == EINTR)
3396
			if (errno == 0 || errno == EINTR)
3397
				continue;
3397
				continue;
3398
			ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3398
			ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3399
			ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3399
			ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3400
			return -1;
3400
			return -1;
3401
		} else if (outfd > -1) {
3401
		} else if (outfd > -1) {
3402
			/* The FD we were watching has something waiting */
3402
			/* The FD we were watching has something waiting */
3403
			ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3403
			ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3404
			ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3404
			ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3405
			return 1;
3405
			return 1;
3406
		} else if (rchan) {
3406
		} else if (rchan) {
3407
			int res;
3407
			int res;
3408
			struct ast_frame *f = ast_read(c);
3408
			struct ast_frame *f = ast_read(c);
3409
			if (!f)
3409
			if (!f)
3410
				return -1;
3410
				return -1;
3411

    
   
3411

   
3412
			switch (f->frametype) {
3412
			switch (f->frametype) {
3413
			case AST_FRAME_DTMF_BEGIN:
3413
			case AST_FRAME_DTMF_BEGIN:
3414
				break;
3414
				break;
3415
			case AST_FRAME_DTMF_END:
3415
			case AST_FRAME_DTMF_END:
3416
				res = f->subclass.integer;
3416
				res = f->subclass.integer;
3417
				ast_frfree(f);
3417
				ast_frfree(f);
3418
				ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3418
				ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3419
				return res;
3419
				return res;
3420
			case AST_FRAME_CONTROL:
3420
			case AST_FRAME_CONTROL:
3421
				switch (f->subclass.integer) {
3421
				switch (f->subclass.integer) {
3422
				case AST_CONTROL_HANGUP:
3422
				case AST_CONTROL_HANGUP:
3423
					ast_frfree(f);
3423
					ast_frfree(f);
3424
					ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3424
					ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3425
					return -1;
3425
					return -1;
3426
				case AST_CONTROL_RINGING:
3426
				case AST_CONTROL_RINGING:
3427
				case AST_CONTROL_ANSWER:
3427
				case AST_CONTROL_ANSWER:
3428
				case AST_CONTROL_SRCUPDATE:
3428
				case AST_CONTROL_SRCUPDATE:
3429
				case AST_CONTROL_SRCCHANGE:
3429
				case AST_CONTROL_SRCCHANGE:
3430
				case AST_CONTROL_CONNECTED_LINE:
3430
				case AST_CONTROL_CONNECTED_LINE:
3431
				case AST_CONTROL_REDIRECTING:
3431
				case AST_CONTROL_REDIRECTING:
3432
				case -1:
3432
				case -1:
3433
					/* Unimportant */
3433
					/* Unimportant */
3434
					break;
3434
					break;
3435
				default:
3435
				default:
3436
					ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3436
					ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3437
					break;
3437
					break;
3438
				}
3438
				}
3439
				break;
3439
				break;
3440
			case AST_FRAME_VOICE:
3440
			case AST_FRAME_VOICE:
3441
				/* Write audio if appropriate */
3441
				/* Write audio if appropriate */
3442
				if (audiofd > -1) {
3442
				if (audiofd > -1) {
3443
					if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3443
					if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3444
						ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3444
						ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3445
					}
3445
					}
3446
				}
3446
				}
3447
			default:
3447
			default:
3448
				/* Ignore */
3448
				/* Ignore */
3449
				break;
3449
				break;
3450
			}
3450
			}
3451
			ast_frfree(f);
3451
			ast_frfree(f);
3452
		}
3452
		}
3453
	}
3453
	}
3454

    
   
3454

   
3455
	ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3455
	ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3456

    
   
3456

   
3457
	return 0; /* Time is up */
3457
	return 0; /* Time is up */
3458
}
3458
}
3459

    
   
3459

   
3460
static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
3460
static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
3461
{
3461
{
3462
	ast_manager_event(chan, EVENT_FLAG_DTMF,
3462
	ast_manager_event(chan, EVENT_FLAG_DTMF,
3463
			"DTMF",
3463
			"DTMF",
3464
			"Channel: %s\r\n"
3464
			"Channel: %s\r\n"
3465
			"Uniqueid: %s\r\n"
3465
			"Uniqueid: %s\r\n"
3466
			"Digit: %c\r\n"
3466
			"Digit: %c\r\n"
3467
			"Direction: %s\r\n"
3467
			"Direction: %s\r\n"
3468
			"Begin: %s\r\n"
3468
			"Begin: %s\r\n"
3469
			"End: %s\r\n",
3469
			"End: %s\r\n",
3470
			chan->name, chan->uniqueid, digit, direction, begin, end);
3470
			chan->name, chan->uniqueid, digit, direction, begin, end);
3471
}
3471
}
3472

    
   
3472

   
3473
static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3473
static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3474
{
3474
{
3475
	if (chan->generator && chan->generator->generate && chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
3475
	if (chan->generator && chan->generator->generate && chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
3476
		void *tmp = chan->generatordata;
3476
		void *tmp = chan->generatordata;
3477
		int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
3477
		int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
3478
		int res;
3478
		int res;
3479
		int samples;
3479
		int samples;
3480

    
   
3480

   
3481
		if (chan->timingfunc) {
3481
		if (chan->timingfunc) {
3482
			ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3482
			ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3483
			ast_settimeout(chan, 0, NULL, NULL);
3483
			ast_settimeout(chan, 0, NULL, NULL);
3484
		}
3484
		}
3485

    
   
3485

   
3486
		chan->generatordata = NULL;     /* reset, to let writes go through */
3486
		chan->generatordata = NULL;     /* reset, to let writes go through */
3487

    
   
3487

   
3488
		if (f->subclass.codec != chan->writeformat) {
3488
		if (f->subclass.codec != chan->writeformat) {
3489
			float factor;
3489
			float factor;
3490
			factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
3490
			factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
3491
			samples = (int) ( ((float) f->samples) * factor );
3491
			samples = (int) ( ((float) f->samples) * factor );
3492
		} else {
3492
		} else {
3493
			samples = f->samples;
3493
			samples = f->samples;
3494
		}
3494
		}
3495
		
3495
		
3496
		/* This unlock is here based on two assumptions that hold true at this point in the
3496
		/* This unlock is here based on two assumptions that hold true at this point in the
3497
		 * code. 1) this function is only called from within __ast_read() and 2) all generators
3497
		 * code. 1) this function is only called from within __ast_read() and 2) all generators
3498
		 * call ast_write() in their generate callback.
3498
		 * call ast_write() in their generate callback.
3499
		 *
3499
		 *
3500
		 * The reason this is added is so that when ast_write is called, the lock that occurs 
3500
		 * The reason this is added is so that when ast_write is called, the lock that occurs 
3501
		 * there will not recursively lock the channel. Doing this will cause intended deadlock 
3501
		 * there will not recursively lock the channel. Doing this will cause intended deadlock 
3502
		 * avoidance not to work in deeper functions
3502
		 * avoidance not to work in deeper functions
3503
		 */
3503
		 */
3504
		ast_channel_unlock(chan);
3504
		ast_channel_unlock(chan);
3505
		res = generate(chan, tmp, f->datalen, samples);
3505
		res = generate(chan, tmp, f->datalen, samples);
3506
		ast_channel_lock(chan);
3506
		ast_channel_lock(chan);
3507
		chan->generatordata = tmp;
3507
		chan->generatordata = tmp;
3508
		if (res) {
3508
		if (res) {
3509
			ast_debug(1, "Auto-deactivating generator\n");
3509
			ast_debug(1, "Auto-deactivating generator\n");
3510
			ast_deactivate_generator(chan);
3510
			ast_deactivate_generator(chan);
3511
		}
3511
		}
3512

    
   
3512

   
3513
	} else if (f->frametype == AST_FRAME_CNG) {
3513
	} else if (f->frametype == AST_FRAME_CNG) {
3514
		if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3514
		if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3515
			ast_debug(1, "Generator got CNG, switching to timed mode\n");
3515
			ast_debug(1, "Generator got CNG, switching to timed mode\n");
3516
			ast_settimeout(chan, 50, generator_force, chan);
3516
			ast_settimeout(chan, 50, generator_force, chan);
3517
		}
3517
		}
3518
	}
3518
	}
3519
}
3519
}
3520

    
   
3520

   
3521
static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3521
static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3522
{
3522
{
3523
	struct ast_frame *fr = &chan->dtmff;
3523
	struct ast_frame *fr = &chan->dtmff;
3524

    
   
3524

   
3525
	fr->frametype = AST_FRAME_DTMF_END;
3525
	fr->frametype = AST_FRAME_DTMF_END;
3526
	fr->subclass.integer = f->subclass.integer;
3526
	fr->subclass.integer = f->subclass.integer;
3527
	fr->len = f->len;
3527
	fr->len = f->len;
3528

    
   
3528

   
3529
	/* The only time this function will be called is for a frame that just came
3529
	/* The only time this function will be called is for a frame that just came
3530
	 * out of the channel driver.  So, we want to stick it on the tail of the
3530
	 * out of the channel driver.  So, we want to stick it on the tail of the
3531
	 * readq. */
3531
	 * readq. */
3532

    
   
3532

   
3533
	ast_queue_frame(chan, fr);
3533
	ast_queue_frame(chan, fr);
3534
}
3534
}
3535

    
   
3535

   
3536
/*!
3536
/*!
3537
 * \brief Determine whether or not we should ignore DTMF in the readq
3537
 * \brief Determine whether or not we should ignore DTMF in the readq
3538
 */
3538
 */
3539
static inline int should_skip_dtmf(struct ast_channel *chan)
3539
static inline int should_skip_dtmf(struct ast_channel *chan)
3540
{
3540
{
3541
	if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3541
	if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3542
		/* We're in the middle of emulating a digit, or DTMF has been
3542
		/* We're in the middle of emulating a digit, or DTMF has been
3543
		 * explicitly deferred.  Skip this digit, then. */
3543
		 * explicitly deferred.  Skip this digit, then. */
3544
		return 1;
3544
		return 1;
3545
	}
3545
	}
3546
			
3546
			
3547
	if (!ast_tvzero(chan->dtmf_tv) && 
3547
	if (!ast_tvzero(chan->dtmf_tv) && 
3548
			ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3548
			ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3549
		/* We're not in the middle of a digit, but it hasn't been long enough
3549
		/* We're not in the middle of a digit, but it hasn't been long enough
3550
		 * since the last digit, so we'll have to skip DTMF for now. */
3550
		 * since the last digit, so we'll have to skip DTMF for now. */
3551
		return 1;
3551
		return 1;
3552
	}
3552
	}
3553

    
   
3553

   
3554
	return 0;
3554
	return 0;
3555
}
3555
}
3556

    
   
3556

   
3557
/*!
3557
/*!
3558
 * \brief calculates the number of samples to jump forward with in a monitor stream.
3558
 * \brief calculates the number of samples to jump forward with in a monitor stream.
3559
 
3559
 
3560
 * \note When using ast_seekstream() with the read and write streams of a monitor,
3560
 * \note When using ast_seekstream() with the read and write streams of a monitor,
3561
 * the number of samples to seek forward must be of the same sample rate as the stream
3561
 * the number of samples to seek forward must be of the same sample rate as the stream
3562
 * or else the jump will not be calculated correctly.
3562
 * or else the jump will not be calculated correctly.
3563
 *
3563
 *
3564
 * \retval number of samples to seek forward after rate conversion.
3564
 * \retval number of samples to seek forward after rate conversion.
3565
 */
3565
 */
3566
static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3566
static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3567
{
3567
{
3568
	int diff = sample_rate - seek_rate;
3568
	int diff = sample_rate - seek_rate;
3569

    
   
3569

   
3570
	if (diff > 0) {
3570
	if (diff > 0) {
3571
		samples = samples / (float) (sample_rate / seek_rate);
3571
		samples = samples / (float) (sample_rate / seek_rate);
3572
	} else if (diff < 0) {
3572
	} else if (diff < 0) {
3573
		samples = samples * (float) (seek_rate / sample_rate);
3573
		samples = samples * (float) (seek_rate / sample_rate);
3574
	}
3574
	}
3575

    
   
3575

   
3576
	return samples;
3576
	return samples;
3577
}
3577
}
3578

    
   
3578

   
3579
static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3579
static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3580
{
3580
{
3581
	struct ast_frame *f = NULL;	/* the return value */
3581
	struct ast_frame *f = NULL;	/* the return value */
3582
	int blah;
3582
	int blah;
3583
	int prestate;
3583
	int prestate;
3584
	int cause = 0;
3584
	int cause = 0;
3585

    
   
3585

   
3586
	/* this function is very long so make sure there is only one return
3586
	/* this function is very long so make sure there is only one return
3587
	 * point at the end (there are only two exceptions to this).
3587
	 * point at the end (there are only two exceptions to this).
3588
	 */
3588
	 */
3589

    
   
3589

   
3590
	if (chan->masq) {
3590
	if (chan->masq) {
3591
		if (ast_do_masquerade(chan))
3591
		if (ast_do_masquerade(chan))
3592
			ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3592
			ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3593
		else
3593
		else
3594
			f =  &ast_null_frame;
3594
			f =  &ast_null_frame;
3595
		return f;
3595
		return f;
3596
	}
3596
	}
3597

    
   
3597

   
3598
	/* if here, no masq has happened, lock the channel and proceed */
3598
	/* if here, no masq has happened, lock the channel and proceed */
3599
	ast_channel_lock(chan);
3599
	ast_channel_lock(chan);
3600

    
   
3600

   
3601
	/* Stop if we're a zombie or need a soft hangup */
3601
	/* Stop if we're a zombie or need a soft hangup */
3602
	if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3602
	if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3603
		if (chan->generator)
3603
		if (chan->generator)
3604
			ast_deactivate_generator(chan);
3604
			ast_deactivate_generator(chan);
3605
		goto done;
3605
		goto done;
3606
	}
3606
	}
3607

    
   
3607

   
3608
#ifdef AST_DEVMODE
3608
#ifdef AST_DEVMODE
3609
	/* 
3609
	/* 
3610
	 * The ast_waitfor() code records which of the channel's file descriptors reported that
3610
	 * The ast_waitfor() code records which of the channel's file descriptors reported that
3611
	 * data is available.  In theory, ast_read() should only be called after ast_waitfor()
3611
	 * data is available.  In theory, ast_read() should only be called after ast_waitfor()
3612
	 * reports that a channel has data available for reading.  However, there still may be
3612
	 * reports that a channel has data available for reading.  However, there still may be
3613
	 * some edge cases throughout the code where ast_read() is called improperly.  This can
3613
	 * some edge cases throughout the code where ast_read() is called improperly.  This can
3614
	 * potentially cause problems, so if this is a developer build, make a lot of noise if
3614
	 * potentially cause problems, so if this is a developer build, make a lot of noise if
3615
	 * this happens so that it can be addressed. 
3615
	 * this happens so that it can be addressed. 
3616
	 */
3616
	 */
3617
	if (chan->fdno == -1) {
3617
	if (chan->fdno == -1) {
3618
		ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
3618
		ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
3619
	}
3619
	}
3620
#endif
3620
#endif
3621

    
   
3621

   
3622
	prestate = chan->_state;
3622
	prestate = chan->_state;
3623

    
   
3623

   
3624
	/* Read and ignore anything on the alertpipe, but read only
3624
	/* Read and ignore anything on the alertpipe, but read only
3625
	   one sizeof(blah) per frame that we send from it */
3625
	   one sizeof(blah) per frame that we send from it */
3626
	if (chan->alertpipe[0] > -1) {
3626
	if (chan->alertpipe[0] > -1) {
3627
		int flags = fcntl(chan->alertpipe[0], F_GETFL);
3627
		int flags = fcntl(chan->alertpipe[0], F_GETFL);
3628
		/* For some odd reason, the alertpipe occasionally loses nonblocking status,
3628
		/* For some odd reason, the alertpipe occasionally loses nonblocking status,
3629
		 * which immediately causes a deadlock scenario.  Detect and prevent this. */
3629
		 * which immediately causes a deadlock scenario.  Detect and prevent this. */
3630
		if ((flags & O_NONBLOCK) == 0) {
3630
		if ((flags & O_NONBLOCK) == 0) {
3631
			ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
3631
			ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
3632
			if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3632
			if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3633
				ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3633
				ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3634
				f = &ast_null_frame;
3634
				f = &ast_null_frame;
3635
				goto done;
3635
				goto done;
3636
			}
3636
			}
3637
		}
3637
		}
3638
		if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3638
		if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3639
			if (errno != EINTR && errno != EAGAIN)
3639
			if (errno != EINTR && errno != EAGAIN)
3640
				ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3640
				ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3641
		}
3641
		}
3642
	}
3642
	}
3643

    
   
3643

   
3644
	if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3644
	if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3645
		enum ast_timer_event res;
3645
		enum ast_timer_event res;
3646

    
   
3646

   
3647
		ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3647
		ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3648

    
   
3648

   
3649
		res = ast_timer_get_event(chan->timer);
3649
		res = ast_timer_get_event(chan->timer);
3650

    
   
3650

   
3651
		switch (res) {
3651
		switch (res) {
3652
		case AST_TIMING_EVENT_EXPIRED:
3652
		case AST_TIMING_EVENT_EXPIRED:
3653
			ast_timer_ack(chan->timer, 1);
3653
			ast_timer_ack(chan->timer, 1);
3654

    
   
3654

   
3655
			if (chan->timingfunc) {
3655
			if (chan->timingfunc) {
3656
				/* save a copy of func/data before unlocking the channel */
3656
				/* save a copy of func/data before unlocking the channel */
3657
				int (*func)(const void *) = chan->timingfunc;
3657
				int (*func)(const void *) = chan->timingfunc;
3658
				void *data = chan->timingdata;
3658
				void *data = chan->timingdata;
3659
				chan->fdno = -1;
3659
				chan->fdno = -1;
3660
				ast_channel_unlock(chan);
3660
				ast_channel_unlock(chan);
3661
				func(data);
3661
				func(data);
3662
			} else {
3662
			} else {
3663
				ast_timer_set_rate(chan->timer, 0);
3663
				ast_timer_set_rate(chan->timer, 0);
3664
				chan->fdno = -1;
3664
				chan->fdno = -1;
3665
				ast_channel_unlock(chan);
3665
				ast_channel_unlock(chan);
3666
			}
3666
			}
3667

    
   
3667

   
3668
			/* cannot 'goto done' because the channel is already unlocked */
3668
			/* cannot 'goto done' because the channel is already unlocked */
3669
			return &ast_null_frame;
3669
			return &ast_null_frame;
3670

    
   
3670

   
3671
		case AST_TIMING_EVENT_CONTINUOUS:
3671
		case AST_TIMING_EVENT_CONTINUOUS:
3672
			if (AST_LIST_EMPTY(&chan->readq) || 
3672
			if (AST_LIST_EMPTY(&chan->readq) || 
3673
				!AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3673
				!AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3674
				ast_timer_disable_continuous(chan->timer);
3674
				ast_timer_disable_continuous(chan->timer);
3675
			}
3675
			}
3676
			break;
3676
			break;
3677
		}
3677
		}
3678

    
   
3678

   
3679
	} else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3679
	} else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3680
		/* if the AST_GENERATOR_FD is set, call the generator with args
3680
		/* if the AST_GENERATOR_FD is set, call the generator with args
3681
		 * set to -1 so it can do whatever it needs to.
3681
		 * set to -1 so it can do whatever it needs to.
3682
		 */
3682
		 */
3683
		void *tmp = chan->generatordata;
3683
		void *tmp = chan->generatordata;
3684
		chan->generatordata = NULL;     /* reset to let ast_write get through */
3684
		chan->generatordata = NULL;     /* reset to let ast_write get through */
3685
		chan->generator->generate(chan, tmp, -1, -1);
3685
		chan->generator->generate(chan, tmp, -1, -1);
3686
		chan->generatordata = tmp;
3686
		chan->generatordata = tmp;
3687
		f = &ast_null_frame;
3687
		f = &ast_null_frame;
3688
		chan->fdno = -1;
3688
		chan->fdno = -1;
3689
		goto done;
3689
		goto done;
3690
	}
3690
	}
3691

    
   
3691

   
3692
	/* Check for pending read queue */
3692
	/* Check for pending read queue */
3693
	if (!AST_LIST_EMPTY(&chan->readq)) {
3693
	if (!AST_LIST_EMPTY(&chan->readq)) {
3694
		int skip_dtmf = should_skip_dtmf(chan);
3694
		int skip_dtmf = should_skip_dtmf(chan);
3695

    
   
3695

   
3696
		AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3696
		AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3697
			/* We have to be picky about which frame we pull off of the readq because
3697
			/* We have to be picky about which frame we pull off of the readq because
3698
			 * there are cases where we want to leave DTMF frames on the queue until
3698
			 * there are cases where we want to leave DTMF frames on the queue until
3699
			 * some later time. */
3699
			 * some later time. */
3700

    
   
3700

   
3701
			if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3701
			if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3702
				continue;
3702
				continue;
3703
			}
3703
			}
3704

    
   
3704

   
3705
			AST_LIST_REMOVE_CURRENT(frame_list);
3705
			AST_LIST_REMOVE_CURRENT(frame_list);
3706
			break;
3706
			break;
3707
		}
3707
		}
3708
		AST_LIST_TRAVERSE_SAFE_END;
3708
		AST_LIST_TRAVERSE_SAFE_END;
3709
		
3709
		
3710
		if (!f) {
3710
		if (!f) {
3711
			/* There were no acceptable frames on the readq. */
3711
			/* There were no acceptable frames on the readq. */
3712
			f = &ast_null_frame;
3712
			f = &ast_null_frame;
3713
			if (chan->alertpipe[0] > -1) {
3713
			if (chan->alertpipe[0] > -1) {
3714
				int poke = 0;
3714
				int poke = 0;
3715
				/* Restore the state of the alertpipe since we aren't ready for any
3715
				/* Restore the state of the alertpipe since we aren't ready for any
3716
				 * of the frames in the readq. */
3716
				 * of the frames in the readq. */
3717
				if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3717
				if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3718
					ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3718
					ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3719
				}
3719
				}
3720
			}
3720
			}
3721
		}
3721
		}
3722

    
   
3722

   
3723
		/* Interpret hangup and return NULL */
3723
		/* Interpret hangup and return NULL */
3724
		/* XXX why not the same for frames from the channel ? */
3724
		/* XXX why not the same for frames from the channel ? */
3725
		if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
3725
		if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
3726
			cause = f->data.uint32;
3726
			cause = f->data.uint32;
3727
			ast_frfree(f);
3727
			ast_frfree(f);
3728
			f = NULL;
3728
			f = NULL;
3729
		}
3729
		}
3730
	} else {
3730
	} else {
3731
		chan->blocker = pthread_self();
3731
		chan->blocker = pthread_self();
3732
		if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3732
		if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3733
			if (chan->tech->exception)
3733
			if (chan->tech->exception)
3734
				f = chan->tech->exception(chan);
3734
				f = chan->tech->exception(chan);
3735
			else {
3735
			else {
3736
				ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
3736
				ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
3737
				f = &ast_null_frame;
3737
				f = &ast_null_frame;
3738
			}
3738
			}
3739
			/* Clear the exception flag */
3739
			/* Clear the exception flag */
3740
			ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3740
			ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3741
		} else if (chan->tech->read)
3741
		} else if (chan->tech->read)
3742
			f = chan->tech->read(chan);
3742
			f = chan->tech->read(chan);
3743
		else
3743
		else
3744
			ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
3744
			ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
3745
	}
3745
	}
3746

    
   
3746

   
3747
	/*
3747
	/*
3748
	 * Reset the recorded file descriptor that triggered this read so that we can
3748
	 * Reset the recorded file descriptor that triggered this read so that we can
3749
	 * easily detect when ast_read() is called without properly using ast_waitfor().
3749
	 * easily detect when ast_read() is called without properly using ast_waitfor().
3750
	 */
3750
	 */
3751
	chan->fdno = -1;
3751
	chan->fdno = -1;
3752

    
   
3752

   
3753
	if (f) {
3753
	if (f) {
3754
		struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3754
		struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3755
		struct ast_control_read_action_payload *read_action_payload;
3755
		struct ast_control_read_action_payload *read_action_payload;
3756
		struct ast_party_connected_line connected;
3756
		struct ast_party_connected_line connected;
3757

    
   
3757

   
3758
		/* if the channel driver returned more than one frame, stuff the excess
3758
		/* if the channel driver returned more than one frame, stuff the excess
3759
		   into the readq for the next ast_read call
3759
		   into the readq for the next ast_read call
3760
		*/
3760
		*/
3761
		if (AST_LIST_NEXT(f, frame_list)) {
3761
		if (AST_LIST_NEXT(f, frame_list)) {
3762
			ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3762
			ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3763
			ast_frfree(AST_LIST_NEXT(f, frame_list));
3763
			ast_frfree(AST_LIST_NEXT(f, frame_list));
3764
			AST_LIST_NEXT(f, frame_list) = NULL;
3764
			AST_LIST_NEXT(f, frame_list) = NULL;
3765
		}
3765
		}
3766

    
   
3766

   
3767
		switch (f->frametype) {
3767
		switch (f->frametype) {
3768
		case AST_FRAME_CONTROL:
3768
		case AST_FRAME_CONTROL:
3769
			if (f->subclass.integer == AST_CONTROL_ANSWER) {
3769
			if (f->subclass.integer == AST_CONTROL_ANSWER) {
3770
				if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3770
				if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3771
					ast_debug(1, "Ignoring answer on an inbound call!\n");
3771
					ast_debug(1, "Ignoring answer on an inbound call!\n");
3772
					ast_frfree(f);
3772
					ast_frfree(f);
3773
					f = &ast_null_frame;
3773
					f = &ast_null_frame;
3774
				} else if (prestate == AST_STATE_UP && ast_bridged_channel(chan)) {
3774
				} else if (prestate == AST_STATE_UP && ast_bridged_channel(chan)) {
3775
					ast_debug(1, "Dropping duplicate answer!\n");
3775
					ast_debug(1, "Dropping duplicate answer!\n");
3776
					ast_frfree(f);
3776
					ast_frfree(f);
3777
					f = &ast_null_frame;
3777
					f = &ast_null_frame;
3778
				} else {
3778
				} else {
3779
					/* Answer the CDR */
3779
					/* Answer the CDR */
3780
					ast_setstate(chan, AST_STATE_UP);
3780
					ast_setstate(chan, AST_STATE_UP);
3781
					/* removed a call to ast_cdr_answer(chan->cdr) from here. */
3781
					/* removed a call to ast_cdr_answer(chan->cdr) from here. */
3782
					ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
3782
					ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
3783
				}
3783
				}
3784
			} else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
3784
			} else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
3785
				read_action_payload = f->data.ptr;
3785
				read_action_payload = f->data.ptr;
3786
				switch (read_action_payload->action) {
3786
				switch (read_action_payload->action) {
3787
				case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
3787
				case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
3788
					ast_party_connected_line_init(&connected);
3788
					ast_party_connected_line_init(&connected);
3789
					ast_party_connected_line_copy(&connected, &chan->connected);
3789
					ast_party_connected_line_copy(&connected, &chan->connected);
3790
					if (ast_connected_line_parse_data(read_action_payload->payload,
3790
					if (ast_connected_line_parse_data(read_action_payload->payload,
3791
						read_action_payload->payload_size, &connected)) {
3791
						read_action_payload->payload_size, &connected)) {
3792
						ast_party_connected_line_free(&connected);
3792
						ast_party_connected_line_free(&connected);
3793
						break;
3793
						break;
3794
					}
3794
					}
3795
					if (ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
3795
					if (ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
3796
						ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE,
3796
						ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE,
3797
							read_action_payload->payload,
3797
							read_action_payload->payload,
3798
							read_action_payload->payload_size);
3798
							read_action_payload->payload_size);
3799
					}
3799
					}
3800
					ast_party_connected_line_free(&connected);
3800
					ast_party_connected_line_free(&connected);
3801
					break;
3801
					break;
3802
				}
3802
				}
3803
				ast_frfree(f);
3803
				ast_frfree(f);
3804
				f = &ast_null_frame;
3804
				f = &ast_null_frame;
3805
			}
3805
			}
3806
			break;
3806
			break;
3807
		case AST_FRAME_DTMF_END:
3807
		case AST_FRAME_DTMF_END:
3808
			send_dtmf_event(chan, "Received", f->subclass.integer, "No", "Yes");
3808
			send_dtmf_event(chan, "Received", f->subclass.integer, "No", "Yes");
3809
			ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, chan->name, f->len);
3809
			ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, chan->name, f->len);
3810
			/* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3810
			/* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3811
			if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3811
			if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3812
				queue_dtmf_readq(chan, f);
3812
				queue_dtmf_readq(chan, f);
3813
				ast_frfree(f);
3813
				ast_frfree(f);
3814
				f = &ast_null_frame;
3814
				f = &ast_null_frame;
3815
			} else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
3815
			} else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
3816
				if (!ast_tvzero(chan->dtmf_tv) && 
3816
				if (!ast_tvzero(chan->dtmf_tv) && 
3817
				    ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3817
				    ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3818
					/* If it hasn't been long enough, defer this digit */
3818
					/* If it hasn't been long enough, defer this digit */
3819
					queue_dtmf_readq(chan, f);
3819
					queue_dtmf_readq(chan, f);
3820
					ast_frfree(f);
3820
					ast_frfree(f);
3821
					f = &ast_null_frame;
3821
					f = &ast_null_frame;
3822
				} else {
3822
				} else {
3823
					/* There was no begin, turn this into a begin and send the end later */
3823
					/* There was no begin, turn this into a begin and send the end later */
3824
					f->frametype = AST_FRAME_DTMF_BEGIN;
3824
					f->frametype = AST_FRAME_DTMF_BEGIN;
3825
					ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3825
					ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3826
					chan->emulate_dtmf_digit = f->subclass.integer;
3826
					chan->emulate_dtmf_digit = f->subclass.integer;
3827
					chan->dtmf_tv = ast_tvnow();
3827
					chan->dtmf_tv = ast_tvnow();
3828
					if (f->len) {
3828
					if (f->len) {
3829
						if (f->len > AST_MIN_DTMF_DURATION)
3829
						if (f->len > AST_MIN_DTMF_DURATION)
3830
							chan->emulate_dtmf_duration = f->len;
3830
							chan->emulate_dtmf_duration = f->len;
3831
						else 
3831
						else 
3832
							chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
3832
							chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
3833
					} else
3833
					} else
3834
						chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
3834
						chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
3835
					ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass.integer, chan->emulate_dtmf_duration, chan->name);
3835
					ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass.integer, chan->emulate_dtmf_duration, chan->name);
3836
				}
3836
				}
3837
				if (chan->audiohooks) {
3837
				if (chan->audiohooks) {
3838
					struct ast_frame *old_frame = f;
3838
					struct ast_frame *old_frame = f;
3839
					/*!
3839
					/*!
3840
					 * \todo XXX It is possible to write a digit to the audiohook twice
3840
					 * \todo XXX It is possible to write a digit to the audiohook twice
3841
					 * if the digit was originally read while the channel was in autoservice. */
3841
					 * if the digit was originally read while the channel was in autoservice. */
3842
					f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3842
					f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3843
					if (old_frame != f)
3843
					if (old_frame != f)
3844
						ast_frfree(old_frame);
3844
						ast_frfree(old_frame);
3845
				}
3845
				}
3846
			} else {
3846
			} else {
3847
				struct timeval now = ast_tvnow();
3847
				struct timeval now = ast_tvnow();
3848
				if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3848
				if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3849
					ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, chan->name);
3849
					ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, chan->name);
3850
					ast_clear_flag(chan, AST_FLAG_IN_DTMF);
3850
					ast_clear_flag(chan, AST_FLAG_IN_DTMF);
3851
					if (!f->len)
3851
					if (!f->len)
3852
						f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3852
						f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3853

    
   
3853

   
3854
					/* detect tones that were received on
3854
					/* detect tones that were received on
3855
					 * the wire with durations shorter than
3855
					 * the wire with durations shorter than
3856
					 * AST_MIN_DTMF_DURATION and set f->len
3856
					 * AST_MIN_DTMF_DURATION and set f->len
3857
					 * to the actual duration of the DTMF
3857
					 * to the actual duration of the DTMF
3858
					 * frames on the wire.  This will cause
3858
					 * frames on the wire.  This will cause
3859
					 * dtmf emulation to be triggered later
3859
					 * dtmf emulation to be triggered later
3860
					 * on.
3860
					 * on.
3861
					 */
3861
					 */
3862
					if (ast_tvdiff_ms(now, chan->dtmf_tv) < AST_MIN_DTMF_DURATION) {
3862
					if (ast_tvdiff_ms(now, chan->dtmf_tv) < AST_MIN_DTMF_DURATION) {
3863
						f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3863
						f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3864
						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, chan->name);
3864
						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, chan->name);
3865
					}
3865
					}
3866
				} else if (!f->len) {
3866
				} else if (!f->len) {
3867
					ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, chan->name);
3867
					ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, chan->name);
3868
					f->len = AST_MIN_DTMF_DURATION;
3868
					f->len = AST_MIN_DTMF_DURATION;
3869
				}
3869
				}
3870
				if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
3870
				if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
3871
					ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass.integer, f->len, AST_MIN_DTMF_DURATION, chan->name);
3871
					ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass.integer, f->len, AST_MIN_DTMF_DURATION, chan->name);
3872
					ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3872
					ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3873
					chan->emulate_dtmf_digit = f->subclass.integer;
3873
					chan->emulate_dtmf_digit = f->subclass.integer;
3874
					chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
3874
					chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
3875
					ast_frfree(f);
3875
					ast_frfree(f);
3876
					f = &ast_null_frame;
3876
					f = &ast_null_frame;
3877
				} else {
3877
				} else {
3878
					ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, chan->name);
3878
					ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, chan->name);
3879
					if (f->len < AST_MIN_DTMF_DURATION) {
3879
					if (f->len < AST_MIN_DTMF_DURATION) {
3880
						f->len = AST_MIN_DTMF_DURATION;
3880
						f->len = AST_MIN_DTMF_DURATION;
3881
					}
3881
					}
3882
					chan->dtmf_tv = now;
3882
					chan->dtmf_tv = now;
3883
				}
3883
				}
3884
				if (chan->audiohooks) {
3884
				if (chan->audiohooks) {
3885
					struct ast_frame *old_frame = f;
3885
					struct ast_frame *old_frame = f;
3886
					f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3886
					f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3887
					if (old_frame != f)
3887
					if (old_frame != f)
3888
						ast_frfree(old_frame);
3888
						ast_frfree(old_frame);
3889
				}
3889
				}
3890
			}
3890
			}
3891
			break;
3891
			break;
3892
		case AST_FRAME_DTMF_BEGIN:
3892
		case AST_FRAME_DTMF_BEGIN:
3893
			send_dtmf_event(chan, "Received", f->subclass.integer, "Yes", "No");
3893
			send_dtmf_event(chan, "Received", f->subclass.integer, "Yes", "No");
3894
			ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, chan->name);
3894
			ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, chan->name);
3895
			if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
3895
			if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
3896
			    (!ast_tvzero(chan->dtmf_tv) && 
3896
			    (!ast_tvzero(chan->dtmf_tv) && 
3897
			      ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
3897
			      ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
3898
				ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, chan->name);
3898
				ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, chan->name);
3899
				ast_frfree(f);
3899
				ast_frfree(f);
3900
				f = &ast_null_frame;
3900
				f = &ast_null_frame;
3901
			} else {
3901
			} else {
3902
				ast_set_flag(chan, AST_FLAG_IN_DTMF);
3902
				ast_set_flag(chan, AST_FLAG_IN_DTMF);
3903
				chan->dtmf_tv = ast_tvnow();
3903
				chan->dtmf_tv = ast_tvnow();
3904
				ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, chan->name);
3904
				ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, chan->name);
3905
			}
3905
			}
3906
			break;
3906
			break;
3907
		case AST_FRAME_NULL:
3907
		case AST_FRAME_NULL:
3908
			/* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3908
			/* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3909
			 * is reached , because we want to make sure we pass at least one
3909
			 * is reached , because we want to make sure we pass at least one
3910
			 * voice frame through before starting the next digit, to ensure a gap
3910
			 * voice frame through before starting the next digit, to ensure a gap
3911
			 * between DTMF digits. */
3911
			 * between DTMF digits. */
3912
			if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3912
			if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3913
				struct timeval now = ast_tvnow();
3913
				struct timeval now = ast_tvnow();
3914
				if (!chan->emulate_dtmf_duration) {
3914
				if (!chan->emulate_dtmf_duration) {
3915
					ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3915
					ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3916
					chan->emulate_dtmf_digit = 0;
3916
					chan->emulate_dtmf_digit = 0;
3917
				} else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
3917
				} else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
3918
					chan->emulate_dtmf_duration = 0;
3918
					chan->emulate_dtmf_duration = 0;
3919
					ast_frfree(f);
3919
					ast_frfree(f);
3920
					f = &chan->dtmff;
3920
					f = &chan->dtmff;
3921
					f->frametype = AST_FRAME_DTMF_END;
3921
					f->frametype = AST_FRAME_DTMF_END;
3922
					f->subclass.integer = chan->emulate_dtmf_digit;
3922
					f->