Wed Jan 8 2020 09:49:43

Asterisk developer's documentation


chan_iax2.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18 
19 /*! \file
20  *
21  * \brief Implementation of Inter-Asterisk eXchange Version 2
22  * as specified in RFC 5456
23  *
24  * \author Mark Spencer <markster@digium.com>
25  *
26  * \par See also
27  * \arg \ref Config_iax
28  *
29  * \ingroup channel_drivers
30  *
31  * \todo Implement musicclass settings for IAX2 devices
32  */
33 
34 /*** MODULEINFO
35  <use>crypto</use>
36  <support_level>core</support_level>
37  ***/
38 
39 #include "asterisk.h"
40 
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 413586 $")
42 
43 #include <sys/mman.h>
44 #include <dirent.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
50 #include <sys/time.h>
51 #include <sys/signal.h>
52 #include <signal.h>
53 #include <strings.h>
54 #include <netdb.h>
55 #include <fcntl.h>
56 #include <sys/stat.h>
57 #include <regex.h>
58 
59 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
60 
61 #include "asterisk/lock.h"
62 #include "asterisk/frame.h"
63 #include "asterisk/channel.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/sched.h"
67 #include "asterisk/io.h"
68 #include "asterisk/config.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/translate.h"
71 #include "asterisk/md5.h"
72 #include "asterisk/cdr.h"
73 #include "asterisk/crypto.h"
74 #include "asterisk/acl.h"
75 #include "asterisk/manager.h"
76 #include "asterisk/callerid.h"
77 #include "asterisk/app.h"
78 #include "asterisk/astdb.h"
79 #include "asterisk/musiconhold.h"
80 #include "asterisk/features.h"
81 #include "asterisk/utils.h"
82 #include "asterisk/causes.h"
83 #include "asterisk/localtime.h"
84 #include "asterisk/dnsmgr.h"
85 #include "asterisk/devicestate.h"
86 #include "asterisk/netsock.h"
87 #include "asterisk/stringfields.h"
88 #include "asterisk/linkedlists.h"
89 #include "asterisk/event.h"
90 #include "asterisk/astobj2.h"
91 #include "asterisk/timing.h"
92 #include "asterisk/taskprocessor.h"
93 #include "asterisk/test.h"
94 #include "asterisk/data.h"
95 #include "asterisk/netsock2.h"
96 
97 #include "iax2.h"
98 #include "iax2-parser.h"
99 #include "iax2-provision.h"
100 #include "jitterbuf.h"
101 
102 /*** DOCUMENTATION
103  <application name="IAX2Provision" language="en_US">
104  <synopsis>
105  Provision a calling IAXy with a given template.
106  </synopsis>
107  <syntax>
108  <parameter name="template">
109  <para>If not specified, defaults to <literal>default</literal>.</para>
110  </parameter>
111  </syntax>
112  <description>
113  <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
114  given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
115  or <literal>0</literal> on success.</para>
116  </description>
117  </application>
118  <function name="IAXPEER" language="en_US">
119  <synopsis>
120  Gets IAX peer information.
121  </synopsis>
122  <syntax>
123  <parameter name="peername" required="true">
124  <enumlist>
125  <enum name="CURRENTCHANNEL">
126  <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
127  endpoint of the current channel</para>
128  </enum>
129  </enumlist>
130  </parameter>
131  <parameter name="item">
132  <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
133  <enumlist>
134  <enum name="ip">
135  <para>(default) The IP address.</para>
136  </enum>
137  <enum name="status">
138  <para>The peer's status (if <literal>qualify=yes</literal>)</para>
139  </enum>
140  <enum name="mailbox">
141  <para>The configured mailbox.</para>
142  </enum>
143  <enum name="context">
144  <para>The configured context.</para>
145  </enum>
146  <enum name="expire">
147  <para>The epoch time of the next expire.</para>
148  </enum>
149  <enum name="dynamic">
150  <para>Is it dynamic? (yes/no).</para>
151  </enum>
152  <enum name="callerid_name">
153  <para>The configured Caller ID name.</para>
154  </enum>
155  <enum name="callerid_num">
156  <para>The configured Caller ID number.</para>
157  </enum>
158  <enum name="codecs">
159  <para>The configured codecs.</para>
160  </enum>
161  <enum name="codec[x]">
162  <para>Preferred codec index number <replaceable>x</replaceable> (beginning
163  with <literal>0</literal>)</para>
164  </enum>
165  </enumlist>
166  </parameter>
167  </syntax>
168  <description>
169  <para>Gets information associated with the specified IAX2 peer.</para>
170  </description>
171  <see-also>
172  <ref type="function">SIPPEER</ref>
173  </see-also>
174  </function>
175  <function name="IAXVAR" language="en_US">
176  <synopsis>
177  Sets or retrieves a remote variable.
178  </synopsis>
179  <syntax>
180  <parameter name="varname" required="true" />
181  </syntax>
182  <description>
183  <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
184  </description>
185  </function>
186  <manager name="IAXpeers" language="en_US">
187  <synopsis>
188  List IAX peers.
189  </synopsis>
190  <syntax>
191  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
192  </syntax>
193  <description>
194  </description>
195  </manager>
196  <manager name="IAXpeerlist" language="en_US">
197  <synopsis>
198  List IAX Peers.
199  </synopsis>
200  <syntax>
201  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
202  </syntax>
203  <description>
204  <para>List all the IAX peers.</para>
205  </description>
206  </manager>
207  <manager name="IAXnetstats" language="en_US">
208  <synopsis>
209  Show IAX Netstats.
210  </synopsis>
211  <syntax />
212  <description>
213  <para>Show IAX channels network statistics.</para>
214  </description>
215  </manager>
216  <manager name="IAXregistry" language="en_US">
217  <synopsis>
218  Show IAX registrations.
219  </synopsis>
220  <syntax>
221  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
222  </syntax>
223  <description>
224  <para>Show IAX registrations.</para>
225  </description>
226  </manager>
227  ***/
228 
229 /* Define SCHED_MULTITHREADED to run the scheduler in a special
230  multithreaded mode. */
231 #define SCHED_MULTITHREADED
232 
233 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
234  thread is actually doing. */
235 #define DEBUG_SCHED_MULTITHREAD
236 
237 
238 #ifdef SO_NO_CHECK
239 static int nochecksums = 0;
240 #endif
241 
242 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
243 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
244 
245 #define DEFAULT_THREAD_COUNT 10
246 #define DEFAULT_MAX_THREAD_COUNT 100
247 #define DEFAULT_RETRY_TIME 1000
248 #define MEMORY_SIZE 100
249 #define DEFAULT_DROP 3
250 
251 #define DEBUG_SUPPORT
252 
253 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
254 
255 /* Sample over last 100 units to determine historic jitter */
256 #define GAMMA (0.01)
257 
258 static struct ast_codec_pref prefs;
259 
260 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
261 
262 
263 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
264  fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
265 #define MAX_TRUNK_MTU 1240
266 
267 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
268 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
269 
270 #define DEFAULT_CONTEXT "default"
271 
273 
274 static char language[MAX_LANGUAGE] = "";
275 static char regcontext[AST_MAX_CONTEXT] = "";
276 
277 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
279 
280 static int maxauthreq = 3;
281 static int max_retries = 4;
282 static int ping_time = 21;
283 static int lagrq_time = 10;
284 static int maxjitterbuffer=1000;
285 static int resyncthreshold=1000;
286 static int maxjitterinterps=10;
287 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
288 
289 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
290 
291 static int trunkfreq = 20;
293 
294 static int authdebug = 1;
295 static int autokill = 0;
296 static int iaxcompat = 0;
297 static int last_authmethod = 0;
298 
299 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
300 
301 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
302 
303 static struct {
304  unsigned int tos;
305  unsigned int cos;
306 } qos = { 0, 0 };
307 
308 static int min_reg_expire;
309 static int max_reg_expire;
310 
311 static int srvlookup = 0;
312 
313 static struct ast_timer *timer; /* Timer for trunking */
314 
315 static struct ast_netsock_list *netsock;
316 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
317 static int defaultsockfd = -1;
318 
319 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
320 
321 /* Ethernet, etc */
322 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
323 /* T1, maybe ISDN */
324 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
325  ~AST_FORMAT_SLINEAR & \
326  ~AST_FORMAT_SLINEAR16 & \
327  ~AST_FORMAT_SIREN7 & \
328  ~AST_FORMAT_SIREN14 & \
329  ~AST_FORMAT_G719 & \
330  ~AST_FORMAT_ULAW & \
331  ~AST_FORMAT_ALAW & \
332  ~AST_FORMAT_G722)
333 /* A modem */
334 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
335  ~AST_FORMAT_G726 & \
336  ~AST_FORMAT_G726_AAL2 & \
337  ~AST_FORMAT_ADPCM)
338 
339 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
340  ~AST_FORMAT_G723_1)
341 
342 
343 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
344 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
345 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
346 
347 /* if a pvt has encryption setup done and is running on the call */
348 #define IAX_CALLENCRYPTED(pvt) \
349  (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
350 
351 #define IAX_DEBUGDIGEST(msg, key) do { \
352  int idx; \
353  char digest[33] = ""; \
354  \
355  if (!iaxdebug) \
356  break; \
357  \
358  for (idx = 0; idx < 16; idx++) \
359  sprintf(digest + (idx << 1), "%2.2x", (unsigned) key[idx]); \
360  \
361  ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
362  } while(0)
363 
364 static struct io_context *io;
365 static struct ast_sched_thread *sched;
366 
367 #define DONT_RESCHEDULE -2
368 
370 
371 static int iaxdebug = 0;
372 
373 static int iaxtrunkdebug = 0;
374 
375 static int test_losspct = 0;
376 #ifdef IAXTESTS
377 static int test_late = 0;
378 static int test_resync = 0;
379 static int test_jit = 0;
380 static int test_jitpct = 0;
381 #endif /* IAXTESTS */
382 
386 static int amaflags = 0;
387 static int adsi = 0;
388 static int delayreject = 0;
389 static int iax2_encryption = 0;
390 
391 static struct ast_flags64 globalflags = { 0 };
392 
393 static pthread_t netthreadid = AST_PTHREADT_NULL;
394 
396  IAX_STATE_STARTED = (1 << 0),
398  IAX_STATE_TBD = (1 << 2),
399 };
400 
401 struct iax2_context {
404 };
405 
406 
407 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
408 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
409 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
410 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
411 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
412 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
413 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
414 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
415 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
416 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
417 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
418 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
419 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
420 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
421 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
422 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
423 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
424 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
425 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
426 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
427 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
428 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
429 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
430 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
431 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
432 #define IAX_DELAYPBXSTART (uint64_t)(1 << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
433 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
434 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
435 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
436 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
437 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
438 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
439 static int global_rtautoclear = 120;
440 
441 static int reload_config(void);
442 
443 /*!
444  * \brief Call token validation settings.
445  */
447  /*! \brief Default calltoken required unless the ip is in the ignorelist */
449  /*! \brief Require call token validation. */
451  /*! \brief Require call token validation after a successful registration
452  * using call token validation occurs. */
454  /*! \brief Do not require call token validation. */
456 };
457 
458 struct iax2_user {
463  AST_STRING_FIELD(accountcode);
464  AST_STRING_FIELD(mohinterpret);
465  AST_STRING_FIELD(mohsuggest);
466  AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
467  AST_STRING_FIELD(language);
470  AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
471  );
472 
475  int amaflags;
476  int adsi;
477  uint64_t flags;
479  int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
480  int curauthreq; /*!< Current number of outstanding AUTHREQs */
482  struct ast_ha *ha;
485  enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
486 };
487 
488 struct iax2_peer {
491  AST_STRING_FIELD(username);
494  AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
495 
496  AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
497  AST_STRING_FIELD(context); /*!< For transfers only */
498  AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
499  AST_STRING_FIELD(mailbox); /*!< Mailbox */
500  AST_STRING_FIELD(mohinterpret);
501  AST_STRING_FIELD(mohsuggest);
502  AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
503  /* Suggested caller id if registering */
504  AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
505  AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
506  AST_STRING_FIELD(zonetag); /*!< Time Zone */
507  AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
508  );
510  struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
512  int formats;
513  int sockfd; /*!< Socket to use for transmission */
514  struct in_addr mask;
515  int adsi;
516  uint64_t flags;
517 
518  /* Dynamic Registration fields */
519  struct sockaddr_in defaddr; /*!< Default address if there is one */
520  int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
521  int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
522 
523  int expire; /*!< Schedule entry for expiry */
524  int expiry; /*!< How soon to expire */
525  format_t capability; /*!< Capability */
526 
527  /* Qualification */
528  int callno; /*!< Call number of POKE request */
529  int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
530  int lastms; /*!< How long last response took (in ms), or -1 for no response */
531  int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
532 
533  int pokefreqok; /*!< How often to check if the host is up */
534  int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
535  int historicms; /*!< How long recent average responses took */
536  int smoothing; /*!< Sample over how many units to determine historic ms */
537  uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
538 
540 
541  struct ast_ha *ha;
542  enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
543 };
544 
545 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
546 
549  int sockfd;
550  struct sockaddr_in addr;
551  struct timeval txtrunktime; /*!< Transmit trunktime */
552  struct timeval rxtrunktime; /*!< Receive trunktime */
553  struct timeval lasttxtime; /*!< Last transmitted trunktime */
554  struct timeval trunkact; /*!< Last trunk activity */
555  unsigned int lastsent; /*!< Last sent time */
556  /* Trunk data and length */
557  unsigned char *trunkdata;
558  unsigned int trunkdatalen;
559  unsigned int trunkdataalloc;
562  int calls;
564 };
565 
567 
568 struct iax_firmware {
569  AST_LIST_ENTRY(iax_firmware) list;
570  int fd;
571  int mmaplen;
572  int dead;
574  unsigned char *buf;
575 };
576 
585 };
586 
599 };
600 
602  struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
603  char username[80];
604  char secret[80]; /*!< Password or key name in []'s */
605  int expire; /*!< Sched ID of expiration */
606  int refresh; /*!< How often to refresh */
607  enum iax_reg_state regstate;
608  int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
609  int callno; /*!< Associated call number if applicable */
610  struct sockaddr_in us; /*!< Who the server thinks we are */
611  struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
613 };
614 
616 
617 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
618 #define MIN_RETRY_TIME 100
619 #define MAX_RETRY_TIME 10000
620 
621 #define MAX_JITTER_BUFFER 50
622 #define MIN_JITTER_BUFFER 10
623 
624 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
625 
626 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
627 
628 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
629 #define TS_GAP_FOR_JB_RESYNC 5000
630 
631 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
632 #define MARK_IAX_SUBCLASS_TX 0x8000
633 
636 static int iaxdynamicthreadcount = 0;
637 static int iaxdynamicthreadnum = 0;
638 static int iaxactivethreadcount = 0;
639 
640 struct iax_rr {
641  int jitter;
642  int losspct;
643  int losscnt;
644  int packets;
645  int delay;
646  int dropped;
647  int ooo;
648 };
649 
650 struct iax2_pvt_ref;
651 
653  /*! Socket to send/receive on for this call */
654  int sockfd;
655  /*! Last received voice format */
657  /*! Last received video format */
659  /*! Last sent voice format */
661  /*! Last sent video format */
663  /*! What we are capable of sending */
665  /*! Last received timestamp */
666  unsigned int last;
667  /*! Last sent timestamp - never send the same timestamp twice in a single call */
668  unsigned int lastsent;
669  /*! Timestamp of the last video frame sent */
670  unsigned int lastvsent;
671  /*! Next outgoing timestamp if everything is good */
672  unsigned int nextpred;
673  /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
675  /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
677  /*! True if the last voice we transmitted was not silence/CNG */
678  unsigned int notsilenttx:1;
679  /*! Ping time */
680  unsigned int pingtime;
681  /*! Max time for initial response */
682  int maxtime;
683  /*! Peer Address */
684  struct sockaddr_in addr;
685  /*! Actual used codec preferences */
687  /*! Requested codec preferences */
688  struct ast_codec_pref rprefs;
689  /*! Our call number */
690  unsigned short callno;
691  /*! Our callno_entry entry */
693  /*! Peer callno */
694  unsigned short peercallno;
695  /*! Negotiated format, this is only used to remember what format was
696  chosen for an unauthenticated call so that the channel can get
697  created later using the right format */
699  /*! Peer selected format */
701  /*! Peer capability */
703  /*! timeval that we base our transmission on */
704  struct timeval offset;
705  /*! timeval that we base our delivery on */
706  struct timeval rxcore;
707  /*! The jitterbuffer */
709  /*! active jb read scheduler id */
710  int jbid;
711  /*! LAG */
712  int lag;
713  /*! Error, as discovered by the manager */
714  int error;
715  /*! Owner if we have one */
717  /*! What's our state? */
718  struct ast_flags state;
719  /*! Expiry (optional) */
720  int expiry;
721  /*! Next outgoing sequence number */
722  unsigned char oseqno;
723  /*! Next sequence number they have not yet acknowledged */
724  unsigned char rseqno;
725  /*! Next incoming sequence number */
726  unsigned char iseqno;
727  /*! Last incoming sequence number we have acknowledged */
728  unsigned char aseqno;
729 
731  /*! Peer name */
732  AST_STRING_FIELD(peer);
733  /*! Default Context */
735  /*! Caller ID if available */
738  /*! Hidden Caller ID (i.e. ANI) if appropriate */
739  AST_STRING_FIELD(ani);
740  /*! DNID */
741  AST_STRING_FIELD(dnid);
742  /*! RDNIS */
743  AST_STRING_FIELD(rdnis);
744  /*! Requested Extension */
746  /*! Expected Username */
747  AST_STRING_FIELD(username);
748  /*! Expected Secret */
750  /*! MD5 challenge */
751  AST_STRING_FIELD(challenge);
752  /*! Public keys permitted keys for incoming authentication */
753  AST_STRING_FIELD(inkeys);
754  /*! Private key for outgoing authentication */
755  AST_STRING_FIELD(outkey);
756  /*! Preferred language */
757  AST_STRING_FIELD(language);
758  /*! Hostname/peername for naming purposes */
759  AST_STRING_FIELD(host);
760 
761  AST_STRING_FIELD(dproot);
762  AST_STRING_FIELD(accountcode);
763  AST_STRING_FIELD(mohinterpret);
764  AST_STRING_FIELD(mohsuggest);
765  /*! received OSP token */
766  AST_STRING_FIELD(osptoken);
767  /*! Default parkinglot */
769  );
770  /*! AUTHREJ all AUTHREP frames */
771  int authrej;
772  /*! permitted authentication methods */
774  /*! permitted encryption methods */
776  /*! Encryption AES-128 Key */
778  /*! Decryption AES-128 Key corresponding to ecx */
780  /*! Decryption AES-128 Key used to decrypt peer frames */
782  /*! scheduler id associated with iax_key_rotate
783  * for encrypted calls*/
785  /*! 32 bytes of semi-random data */
786  unsigned char semirand[32];
787  /*! Associated registry */
788  struct iax2_registry *reg;
789  /*! Associated peer for poking */
791  /*! IAX_ flags */
792  uint64_t flags;
793  int adsi;
794 
795  /*! Transferring status */
796  enum iax_transfer_state transferring;
797  /*! Transfer identifier */
799  /*! Who we are IAX transferring to */
800  struct sockaddr_in transfer;
801  /*! What's the new call number for the transfer */
802  unsigned short transfercallno;
803  /*! Transfer encrypt AES-128 Key */
805 
806  /*! Status of knowledge of peer ADSI capability */
808 
809  /*! Callno of native bridge peer. (Valid if nonzero) */
810  unsigned short bridgecallno;
811 
812  int pingid; /*!< Transmit PING request */
813  int lagid; /*!< Retransmit lag request */
814  int autoid; /*!< Auto hangup for Dialplan requestor */
815  int authid; /*!< Authentication rejection ID */
816  int authfail; /*!< Reason to report failure */
817  int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
821  int amaflags;
823  /*! variables inherited from the user definition */
824  struct ast_variable *vars;
825  /*! variables transmitted in a NEW packet */
826  struct ast_variable *iaxvars;
827  /*! last received remote rr */
828  struct iax_rr remote_rr;
829  /*! Current base time: (just for stats) */
830  int min;
831  /*! Dropped frame count: (just for stats) */
832  int frames_dropped;
833  /*! received frame count: (just for stats) */
834  int frames_received;
835  /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
836  unsigned char calltoken_ie_len;
837  /*! hold all signaling frames from the pbx thread until we have a destination callno */
838  char hold_signaling;
839  /*! frame queue for signaling frames from pbx thread waiting for destination callno */
841 };
842 
844  struct ast_frame f;
845  AST_LIST_ENTRY(signaling_queue_entry) next;
846 };
847 
848 /*! table of available call numbers */
849 static struct ao2_container *callno_pool;
850 
851 /*! table of available trunk call numbers */
853 
854 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
855 
856 /*!
857  * \brief a list of frames that may need to be retransmitted
858  *
859  * \note The contents of this list do not need to be explicitly destroyed
860  * on module unload. This is because all active calls are destroyed, and
861  * all frames in this queue will get destroyed as a part of that process.
862  *
863  * \note Contents protected by the iaxsl[] locks
864  */
866 
868 
870 
871 static const time_t MAX_CALLTOKEN_DELAY = 10;
872 
873 /*!
874  * This module will get much higher performance when doing a lot of
875  * user and peer lookups if the number of buckets is increased from 1.
876  * However, to maintain old behavior for Asterisk 1.4, these are set to
877  * 1 by default. When using multiple buckets, search order through these
878  * containers is considered random, so you will not be able to depend on
879  * the order the entires are specified in iax.conf for matching order. */
880 #ifdef LOW_MEMORY
881 #define MAX_PEER_BUCKETS 17
882 #else
883 #define MAX_PEER_BUCKETS 563
884 #endif
885 static struct ao2_container *peers;
886 
887 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
888 static struct ao2_container *users;
889 
890 /*! Table containing peercnt objects for every ip address consuming a callno */
891 static struct ao2_container *peercnts;
892 
893 /*! Table containing custom callno limit rules for a range of ip addresses. */
895 
896 /*! Table containing ip addresses not requiring calltoken validation */
898 
899 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
900 
901 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
902 
903 static uint16_t global_maxcallno;
904 
905 /*! Total num of call numbers allowed to be allocated without calltoken validation */
906 static uint16_t global_maxcallno_nonval;
907 
908 static uint16_t total_nonval_callno_used = 0;
909 
910 /*! peer connection private, keeps track of all the call numbers
911  * consumed by a single ip address */
912 struct peercnt {
913  /*! ip address consuming call numbers */
914  unsigned long addr;
915  /*! Number of call numbers currently used by this ip address */
916  uint16_t cur;
917  /*! Max call numbers allowed for this ip address */
918  uint16_t limit;
919  /*! Specifies whether limit is set by a registration or not, if so normal
920  * limit setting rules do not apply to this address. */
921  unsigned char reg;
922 };
923 
924 /*! used by both callno_limits and calltoken_ignores containers */
925 struct addr_range {
926  /*! ip address range for custom callno limit rule */
927  struct ast_ha ha;
928  /*! callno limit for this ip address range, only used in callno_limits container */
929  uint16_t limit;
930  /*! delete me marker for reloads */
931  unsigned char delme;
932 };
933 
934 struct callno_entry {
935  /*! callno used for this entry */
936  uint16_t callno;
937  /*! was this callno calltoken validated or not */
938  unsigned char validated;
939 };
940 
941 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
942 
943 enum {
944  /*! Extension exists */
945  CACHE_FLAG_EXISTS = (1 << 0),
946  /*! Extension is nonexistent */
948  /*! Extension can exist */
950  /*! Waiting to hear back response */
951  CACHE_FLAG_PENDING = (1 << 3),
952  /*! Timed out */
953  CACHE_FLAG_TIMEOUT = (1 << 4),
954  /*! Request transmitted */
956  /*! Timeout */
957  CACHE_FLAG_UNKNOWN = (1 << 6),
958  /*! Matchmore */
960 };
961 
962 struct iax2_dpcache {
963  char peercontext[AST_MAX_CONTEXT];
965  struct timeval orig;
966  struct timeval expiry;
967  int flags;
968  unsigned short callno;
969  int waiters[256];
971  AST_LIST_ENTRY(iax2_dpcache) peer_list;
972 };
973 
975 
976 static void reg_source_db(struct iax2_peer *p);
977 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
978 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
979 
980 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
981 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
982 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
983 
989 };
990 
994 };
995 
996 struct iax2_pkt_buf {
998  size_t len;
999  unsigned char buf[1];
1000 };
1001 
1002 struct iax2_thread {
1003  AST_LIST_ENTRY(iax2_thread) list;
1005  enum iax2_thread_iostate iostate;
1006 #ifdef SCHED_MULTITHREADED
1007  void (*schedfunc)(const void *);
1008  const void *scheddata;
1009 #endif
1010 #ifdef DEBUG_SCHED_MULTITHREAD
1011  char curfunc[80];
1012 #endif
1013  int actions;
1014  pthread_t threadid;
1016  struct sockaddr_in iosin;
1017  unsigned char readbuf[4096];
1018  unsigned char *buf;
1019  ssize_t buf_len;
1020  size_t buf_size;
1021  int iofd;
1022  time_t checktime;
1027  /*! if this thread is processing a full frame,
1028  some information about that frame will be stored
1029  here, so we can avoid dispatching any more full
1030  frames for that callno to other threads */
1031  struct {
1032  unsigned short callno;
1033  struct sockaddr_in sin;
1034  unsigned char type;
1035  unsigned char csub;
1036  } ffinfo;
1037  /*! Queued up full frames for processing. If more full frames arrive for
1038  * a call which this thread is already processing a full frame for, they
1039  * are queued up here. */
1041  unsigned char stop;
1042 };
1043 
1044 /* Thread lists */
1045 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1046 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1047 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1048 
1049 static void *iax2_process_thread(void *data);
1050 static void iax2_destroy(int callno);
1051 
1052 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1053 {
1054  ast_mutex_lock(lock);
1055  ast_cond_signal(cond);
1056  ast_mutex_unlock(lock);
1057 }
1058 
1059 /*!
1060  * \brief an array of iax2 pvt structures
1061  *
1062  * The container for active chan_iax2_pvt structures is implemented as an
1063  * array for extremely quick direct access to the correct pvt structure
1064  * based on the local call number. The local call number is used as the
1065  * index into the array where the associated pvt structure is stored.
1066  */
1068 
1069 /*!
1070  * \brief Another container of iax2_pvt structures
1071  *
1072  * Active IAX2 pvt structs are also stored in this container, if they are a part
1073  * of an active call where we know the remote side's call number. The reason
1074  * for this is that incoming media frames do not contain our call number. So,
1075  * instead of having to iterate the entire iaxs array, we use this container to
1076  * look up calls where the remote side is using a given call number.
1077  */
1079 
1080 /*!
1081  * \brief chan_iax2_pvt structure locks
1082  *
1083  * These locks are used when accessing a pvt structure in the iaxs array.
1084  * The index used here is the same as used in the iaxs array. It is the
1085  * local call number for the associated pvt struct.
1086  */
1088 
1089 /*!
1090  * * \brief Another container of iax2_pvt structures
1091  *
1092  * Active IAX2 pvt stucts used during transfering a call are stored here.
1093  */
1095 
1096 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1097  but keeps the division between trunked and non-trunked better. */
1098 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1099 
1100 /* Debug routines... */
1101 static struct sockaddr_in debugaddr;
1102 
1103 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1104 {
1105  if (iaxdebug ||
1106  (sin && debugaddr.sin_addr.s_addr &&
1107  (!ntohs(debugaddr.sin_port) ||
1108  debugaddr.sin_port == sin->sin_port) &&
1109  debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1110  if (iaxdebug) {
1111  iax_showframe(f, fhi, rx, sin, datalen);
1112  } else {
1113  iaxdebug = 1;
1114  iax_showframe(f, fhi, rx, sin, datalen);
1115  iaxdebug = 0;
1116  }
1117  }
1118 }
1119 
1120 static void iax_debug_output(const char *data)
1121 {
1122  if (iaxdebug)
1123  ast_verbose("%s", data);
1124 }
1125 
1126 static void iax_error_output(const char *data)
1127 {
1128  ast_log(LOG_WARNING, "%s", data);
1129 }
1130 
1131 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1132 {
1133  va_list args;
1134  char buf[1024];
1135 
1136  va_start(args, fmt);
1137  vsnprintf(buf, sizeof(buf), fmt, args);
1138  va_end(args);
1139 
1140  ast_log(LOG_ERROR, "%s", buf);
1141 }
1142 
1143 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1144 {
1145  va_list args;
1146  char buf[1024];
1147 
1148  va_start(args, fmt);
1149  vsnprintf(buf, sizeof(buf), fmt, args);
1150  va_end(args);
1151 
1152  ast_log(LOG_WARNING, "%s", buf);
1153 }
1154 
1155 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1156 {
1157  va_list args;
1158  char buf[1024];
1159 
1160  va_start(args, fmt);
1161  vsnprintf(buf, sizeof(buf), fmt, args);
1162  va_end(args);
1163 
1164  ast_verbose("%s", buf);
1165 }
1166 
1167 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
1168 static int expire_registry(const void *data);
1169 static int iax2_answer(struct ast_channel *c);
1170 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
1171 static int iax2_devicestate(void *data);
1172 static int iax2_digit_begin(struct ast_channel *c, char digit);
1173 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1174 static int iax2_do_register(struct iax2_registry *reg);
1175 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1176 static int iax2_hangup(struct ast_channel *c);
1177 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1178 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1179 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1180 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1181 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1182 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1183 static int iax2_sendtext(struct ast_channel *c, const char *text);
1184 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1185 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1186 static int iax2_transfer(struct ast_channel *c, const char *dest);
1187 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1188 static int iax2_sched_add(struct ast_sched_thread *st, int when, ast_sched_cb callback, const void *data);
1189 
1190 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1191 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1192 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1193 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1194 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1195 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1196 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1197 static struct ast_frame *iax2_read(struct ast_channel *c);
1198 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1199 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1200 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1201 static void *iax2_dup_variable_datastore(void *);
1202 static void prune_peers(void);
1203 static void prune_users(void);
1204 static void iax2_free_variable_datastore(void *);
1205 
1206 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1207 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1208 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1209 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1210 static void build_rand_pad(unsigned char *buf, ssize_t len);
1211 static struct callno_entry *get_unused_callno(int trunk, int validated);
1212 static int replace_callno(const void *obj);
1213 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1214 static void network_change_event_cb(const struct ast_event *, void *);
1215 
1216 static const struct ast_channel_tech iax2_tech = {
1217  .type = "IAX2",
1218  .description = tdesc,
1219  .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
1220  .properties = AST_CHAN_TP_WANTSJITTER,
1221  .requester = iax2_request,
1222  .devicestate = iax2_devicestate,
1223  .send_digit_begin = iax2_digit_begin,
1224  .send_digit_end = iax2_digit_end,
1225  .send_text = iax2_sendtext,
1226  .send_image = iax2_sendimage,
1227  .send_html = iax2_sendhtml,
1228  .call = iax2_call,
1229  .hangup = iax2_hangup,
1230  .answer = iax2_answer,
1231  .read = iax2_read,
1232  .write = iax2_write,
1233  .write_video = iax2_write,
1234  .indicate = iax2_indicate,
1235  .setoption = iax2_setoption,
1236  .queryoption = iax2_queryoption,
1237  .bridge = iax2_bridge,
1238  .transfer = iax2_transfer,
1239  .fixup = iax2_fixup,
1240  .func_channel_read = acf_channel_read,
1241 };
1242 
1243 /*!
1244  * \internal
1245  * \brief Obtain the owner channel lock if the owner exists.
1246  *
1247  * \param callno IAX2 call id.
1248  *
1249  * \note Assumes the iaxsl[callno] lock is already obtained.
1250  *
1251  * \note
1252  * IMPORTANT NOTE!!! Any time this function is used, even if
1253  * iaxs[callno] was valid before calling it, it may no longer be
1254  * valid after calling it. This function may unlock and lock
1255  * the mutex associated with this callno, meaning that another
1256  * thread may grab it and destroy the call.
1257  *
1258  * \return Nothing
1259  */
1260 static void iax2_lock_owner(int callno)
1261 {
1262  for (;;) {
1263  if (!iaxs[callno] || !iaxs[callno]->owner) {
1264  /* There is no owner lock to get. */
1265  break;
1266  }
1267  if (!ast_channel_trylock(iaxs[callno]->owner)) {
1268  /* We got the lock */
1269  break;
1270  }
1271  /* Avoid deadlock by pausing and trying again */
1272  DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1273  }
1274 }
1275 
1276 /*!
1277  * \internal
1278  * \brief Check if a control subtype is allowed on the wire.
1279  *
1280  * \param subtype Control frame subtype to check if allowed to/from the wire.
1281  *
1282  * \retval non-zero if allowed.
1283  */
1284 static int iax2_is_control_frame_allowed(int subtype)
1285 {
1286  enum ast_control_frame_type control = subtype;
1287  int is_allowed;
1288 
1289  /*
1290  * Note: If we compare the enumeration type, which does not have any
1291  * negative constants, the compiler may optimize this code away.
1292  * Therefore, we must perform an integer comparison here.
1293  */
1294  if (subtype == -1) {
1295  return -1;
1296  }
1297 
1298  /* Default to not allowing control frames to pass. */
1299  is_allowed = 0;
1300 
1301  /*
1302  * The switch default is not present in order to take advantage
1303  * of the compiler complaining of a missing enum case.
1304  */
1305  switch (control) {
1306  /*
1307  * These control frames make sense to send/receive across the link.
1308  */
1309  case AST_CONTROL_HANGUP:
1310  case AST_CONTROL_RING:
1311  case AST_CONTROL_RINGING:
1312  case AST_CONTROL_ANSWER:
1313  case AST_CONTROL_BUSY:
1315  case AST_CONTROL_OFFHOOK:
1317  case AST_CONTROL_FLASH:
1318  case AST_CONTROL_WINK:
1319  case AST_CONTROL_OPTION:
1320  case AST_CONTROL_RADIO_KEY:
1322  case AST_CONTROL_PROGRESS:
1324  case AST_CONTROL_HOLD:
1325  case AST_CONTROL_UNHOLD:
1326  case AST_CONTROL_VIDUPDATE:
1330  case AST_CONTROL_AOC:
1332  is_allowed = -1;
1333  break;
1334 
1335  /*
1336  * These control frames do not make sense to send/receive across the link.
1337  */
1338  case _XXX_AST_CONTROL_T38:
1339  /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1340  case AST_CONTROL_SRCUPDATE:
1341  /* Across an IAX link the source is still the same. */
1342  case AST_CONTROL_TRANSFER:
1343  /* A success/fail status report from calling ast_transfer() on this machine. */
1344  case AST_CONTROL_CC:
1345  /* The payload contains pointers that are valid for the sending machine only. */
1346  case AST_CONTROL_SRCCHANGE:
1347  /* Across an IAX link the source is still the same. */
1349  /* The action can only be done by the sending machine. */
1350  case AST_CONTROL_END_OF_Q:
1351  /* This frame would cause the call to unexpectedly hangup. */
1353  /* Only meaningful across a bridge on this machine for direct-media exchange. */
1354  break;
1355  }
1356  return is_allowed;
1357 }
1358 
1359 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1360 {
1361  /* The MWI subscriptions exist just so the core knows we care about those
1362  * mailboxes. However, we just grab the events out of the cache when it
1363  * is time to send MWI, since it is only sent with a REGACK. */
1364 }
1365 
1367 {
1368  if (!network_change_event_subscription) {
1369  network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1370  network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1371  }
1372 }
1373 
1375 {
1376  if (network_change_event_subscription) {
1377  network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1378  }
1379 }
1380 
1381 static int network_change_event_sched_cb(const void *data)
1382 {
1383  struct iax2_registry *reg;
1384  network_change_event_sched_id = -1;
1385  AST_LIST_LOCK(&registrations);
1386  AST_LIST_TRAVERSE(&registrations, reg, entry) {
1387  iax2_do_register(reg);
1388  }
1389  AST_LIST_UNLOCK(&registrations);
1390 
1391  return 0;
1392 }
1393 
1394 static void network_change_event_cb(const struct ast_event *event, void *userdata)
1395 {
1396  ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1397  if (network_change_event_sched_id == -1) {
1398  network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1399  }
1400 
1401 }
1402 
1403 
1404 /*! \brief Send manager event at call setup to link between Asterisk channel name
1405  and IAX2 call identifiers */
1406 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1407 {
1408  manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1409  "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1410  pvt->owner ? pvt->owner->name : "",
1411  pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1412 }
1413 
1415  .type = "IAX2_VARIABLE",
1416  .duplicate = iax2_dup_variable_datastore,
1417  .destroy = iax2_free_variable_datastore,
1418 };
1419 
1420 static void *iax2_dup_variable_datastore(void *old)
1421 {
1422  AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1423  struct ast_var_t *oldvar, *newvar;
1424 
1425  newlist = ast_calloc(sizeof(*newlist), 1);
1426  if (!newlist) {
1427  ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1428  return NULL;
1429  }
1430 
1431  AST_LIST_HEAD_INIT(newlist);
1432  AST_LIST_LOCK(oldlist);
1433  AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1434  newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1435  if (newvar)
1436  AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1437  else
1438  ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1439  }
1440  AST_LIST_UNLOCK(oldlist);
1441  return newlist;
1442 }
1443 
1444 static void iax2_free_variable_datastore(void *old)
1445 {
1446  AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1447  struct ast_var_t *oldvar;
1448 
1449  AST_LIST_LOCK(oldlist);
1450  while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1451  ast_free(oldvar);
1452  }
1453  AST_LIST_UNLOCK(oldlist);
1454  AST_LIST_HEAD_DESTROY(oldlist);
1455  ast_free(oldlist);
1456 }
1457 
1458 
1459 /* WARNING: insert_idle_thread should only ever be called within the
1460  * context of an iax2_process_thread() thread.
1461  */
1462 static void insert_idle_thread(struct iax2_thread *thread)
1463 {
1464  if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1466  AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1468  } else {
1470  AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1472  }
1473 
1474  return;
1475 }
1476 
1477 static struct iax2_thread *find_idle_thread(void)
1478 {
1479  struct iax2_thread *thread = NULL;
1480 
1481  /* Pop the head of the idle list off */
1483  thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1485 
1486  /* If we popped a thread off the idle list, just return it */
1487  if (thread) {
1488  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1489  return thread;
1490  }
1491 
1492  /* Pop the head of the dynamic list off */
1494  thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1496 
1497  /* If we popped a thread off the dynamic list, just return it */
1498  if (thread) {
1499  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1500  return thread;
1501  }
1502 
1503  /* If we can't create a new dynamic thread for any reason, return no thread at all */
1504  if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1505  return NULL;
1506 
1507  /* Set default values */
1510  thread->type = IAX_THREAD_TYPE_DYNAMIC;
1511 
1512  /* Initialize lock and condition */
1513  ast_mutex_init(&thread->lock);
1514  ast_cond_init(&thread->cond, NULL);
1515  ast_mutex_init(&thread->init_lock);
1516  ast_cond_init(&thread->init_cond, NULL);
1517  ast_mutex_lock(&thread->init_lock);
1518 
1519  /* Create thread and send it on it's way */
1520  if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1521  ast_cond_destroy(&thread->cond);
1522  ast_mutex_destroy(&thread->lock);
1523  ast_mutex_unlock(&thread->init_lock);
1524  ast_cond_destroy(&thread->init_cond);
1525  ast_mutex_destroy(&thread->init_lock);
1526  ast_free(thread);
1527  return NULL;
1528  }
1529 
1530  /* this thread is not processing a full frame (since it is idle),
1531  so ensure that the field for the full frame call number is empty */
1532  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1533 
1534  /* Wait for the thread to be ready before returning it to the caller */
1535  ast_cond_wait(&thread->init_cond, &thread->init_lock);
1536 
1537  /* Done with init_lock */
1538  ast_mutex_unlock(&thread->init_lock);
1539 
1540  return thread;
1541 }
1542 
1543 #ifdef SCHED_MULTITHREADED
1544 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1545 {
1546  struct iax2_thread *thread;
1547  static time_t lasterror;
1548  time_t t;
1549 
1550  thread = find_idle_thread();
1551  if (thread != NULL) {
1552  thread->schedfunc = func;
1553  thread->scheddata = data;
1554  thread->iostate = IAX_IOSTATE_SCHEDREADY;
1555 #ifdef DEBUG_SCHED_MULTITHREAD
1556  ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1557 #endif
1558  signal_condition(&thread->lock, &thread->cond);
1559  return 0;
1560  }
1561  time(&t);
1562  if (t != lasterror) {
1563  lasterror = t;
1564  ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1565  }
1566 
1567  return -1;
1568 }
1569 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1570 #endif
1571 
1572 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when,
1573  ast_sched_cb callback, const void *data)
1574 {
1575  ast_sched_thread_del(st, id);
1576 
1577  return ast_sched_thread_add(st, when, callback, data);
1578 }
1579 
1580 static int iax2_sched_add(struct ast_sched_thread *st, int when,
1581  ast_sched_cb callback, const void *data)
1582 {
1583  return ast_sched_thread_add(st, when, callback, data);
1584 }
1585 
1586 static int send_ping(const void *data);
1587 
1588 static void __send_ping(const void *data)
1589 {
1590  int callno = (long) data;
1591 
1592  ast_mutex_lock(&iaxsl[callno]);
1593 
1594  if (iaxs[callno]) {
1595  if (iaxs[callno]->peercallno) {
1596  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1597  if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1598  iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1599  }
1600  }
1601  } else {
1602  ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1603  }
1604 
1605  ast_mutex_unlock(&iaxsl[callno]);
1606 }
1607 
1608 static int send_ping(const void *data)
1609 {
1610  int callno = (long) data;
1611  ast_mutex_lock(&iaxsl[callno]);
1612  if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1613  iaxs[callno]->pingid = -1;
1614  }
1615  ast_mutex_unlock(&iaxsl[callno]);
1616 
1617 #ifdef SCHED_MULTITHREADED
1618  if (schedule_action(__send_ping, data))
1619 #endif
1620  __send_ping(data);
1621 
1622  return 0;
1623 }
1624 
1625 static void encmethods_to_str(int e, struct ast_str **buf)
1626 {
1627  ast_str_set(buf, 0, "(");
1628  if (e & IAX_ENCRYPT_AES128) {
1629  ast_str_append(buf, 0, "aes128");
1630  }
1631  if (e & IAX_ENCRYPT_KEYROTATE) {
1632  ast_str_append(buf, 0, ",keyrotate");
1633  }
1634  if (ast_str_strlen(*buf) > 1) {
1635  ast_str_append(buf, 0, ")");
1636  } else {
1637  ast_str_set(buf, 0, "No");
1638  }
1639 }
1640 
1641 static int get_encrypt_methods(const char *s)
1642 {
1643  int e;
1644  if (!strcasecmp(s, "aes128"))
1646  else if (ast_true(s))
1648  else
1649  e = 0;
1650  return e;
1651 }
1652 
1653 static int send_lagrq(const void *data);
1654 
1655 static void __send_lagrq(const void *data)
1656 {
1657  int callno = (long) data;
1658 
1659  ast_mutex_lock(&iaxsl[callno]);
1660 
1661  if (iaxs[callno]) {
1662  if (iaxs[callno]->peercallno) {
1663  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1664  if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1665  iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1666  }
1667  }
1668  } else {
1669  ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1670  }
1671 
1672  ast_mutex_unlock(&iaxsl[callno]);
1673 }
1674 
1675 static int send_lagrq(const void *data)
1676 {
1677  int callno = (long) data;
1678  ast_mutex_lock(&iaxsl[callno]);
1679  if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1680  iaxs[callno]->lagid = -1;
1681  }
1682  ast_mutex_unlock(&iaxsl[callno]);
1683 
1684 #ifdef SCHED_MULTITHREADED
1685  if (schedule_action(__send_lagrq, data))
1686 #endif
1687  __send_lagrq(data);
1688  return 0;
1689 }
1690 
1691 static unsigned char compress_subclass(format_t subclass)
1692 {
1693  int x;
1694  int power=-1;
1695  /* If it's 64 or smaller, just return it */
1696  if (subclass < IAX_FLAG_SC_LOG)
1697  return subclass;
1698  /* Otherwise find its power */
1699  for (x = 0; x < IAX_MAX_SHIFT; x++) {
1700  if (subclass & (1LL << x)) {
1701  if (power > -1) {
1702  ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1703  return 0;
1704  } else
1705  power = x;
1706  }
1707  }
1708  return power | IAX_FLAG_SC_LOG;
1709 }
1710 
1711 static format_t uncompress_subclass(unsigned char csub)
1712 {
1713  /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1714  if (csub & IAX_FLAG_SC_LOG) {
1715  /* special case for 'compressed' -1 */
1716  if (csub == 0xff)
1717  return -1;
1718  else
1719  return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1720  }
1721  else
1722  return csub;
1723 }
1724 
1725 /*!
1726  * \note The only member of the peer passed here guaranteed to be set is the name field
1727  */
1728 static int peer_hash_cb(const void *obj, const int flags)
1729 {
1730  const struct iax2_peer *peer = obj;
1731 
1732  return ast_str_hash(peer->name);
1733 }
1734 
1735 /*!
1736  * \note The only member of the peer passed here guaranteed to be set is the name field
1737  */
1738 static int peer_cmp_cb(void *obj, void *arg, int flags)
1739 {
1740  struct iax2_peer *peer = obj, *peer2 = arg;
1741 
1742  return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
1743 }
1744 
1745 /*!
1746  * \note The only member of the user passed here guaranteed to be set is the name field
1747  */
1748 static int user_hash_cb(const void *obj, const int flags)
1749 {
1750  const struct iax2_user *user = obj;
1751 
1752  return ast_str_hash(user->name);
1753 }
1754 
1755 /*!
1756  * \note The only member of the user passed here guaranteed to be set is the name field
1757  */
1758 static int user_cmp_cb(void *obj, void *arg, int flags)
1759 {
1760  struct iax2_user *user = obj, *user2 = arg;
1761 
1762  return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
1763 }
1764 
1765 /*!
1766  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1767  * so do not call it with a pvt lock held.
1768  */
1769 static struct iax2_peer *find_peer(const char *name, int realtime)
1770 {
1771  struct iax2_peer *peer = NULL;
1772  struct iax2_peer tmp_peer = {
1773  .name = name,
1774  };
1775 
1776  peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1777 
1778  /* Now go for realtime if applicable */
1779  if(!peer && realtime)
1780  peer = realtime_peer(name, NULL);
1781 
1782  return peer;
1783 }
1784 
1785 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1786 {
1787  ao2_ref(peer, +1);
1788  return peer;
1789 }
1790 
1791 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1792 {
1793  ao2_ref(peer, -1);
1794  return NULL;
1795 }
1796 
1797 static struct iax2_user *find_user(const char *name)
1798 {
1799  struct iax2_user tmp_user = {
1800  .name = name,
1801  };
1802 
1803  return ao2_find(users, &tmp_user, OBJ_POINTER);
1804 }
1805 static inline struct iax2_user *user_ref(struct iax2_user *user)
1806 {
1807  ao2_ref(user, +1);
1808  return user;
1809 }
1810 
1811 static inline struct iax2_user *user_unref(struct iax2_user *user)
1812 {
1813  ao2_ref(user, -1);
1814  return NULL;
1815 }
1816 
1817 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1818 {
1819  struct iax2_peer *peer = NULL;
1820  int res = 0;
1821  struct ao2_iterator i;
1822 
1823  i = ao2_iterator_init(peers, 0);
1824  while ((peer = ao2_iterator_next(&i))) {
1825  struct sockaddr_in peer_addr;
1826 
1827  ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1828 
1829  if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1830  (peer_addr.sin_port == sin.sin_port)) {
1831  ast_copy_string(host, peer->name, len);
1832  peer_unref(peer);
1833  res = 1;
1834  break;
1835  }
1836  peer_unref(peer);
1837  }
1839 
1840  if (!peer) {
1841  peer = realtime_peer(NULL, &sin);
1842  if (peer) {
1843  ast_copy_string(host, peer->name, len);
1844  peer_unref(peer);
1845  res = 1;
1846  }
1847  }
1848 
1849  return res;
1850 }
1851 
1852 /*!\note Assumes the lock on the pvt is already held, when
1853  * iax2_destroy_helper() is called. */
1854 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1855 {
1856  /* Decrement AUTHREQ count if needed */
1857  if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1858  struct iax2_user *user;
1859  struct iax2_user tmp_user = {
1860  .name = pvt->username,
1861  };
1862 
1863  user = ao2_find(users, &tmp_user, OBJ_POINTER);
1864  if (user) {
1865  ast_atomic_fetchadd_int(&user->curauthreq, -1);
1866  user_unref(user);
1867  }
1868 
1870  }
1871  /* No more pings or lagrq's */
1873  pvt->pingid = DONT_RESCHEDULE;
1875  pvt->lagid = DONT_RESCHEDULE;
1876  ast_sched_thread_del(sched, pvt->autoid);
1877  ast_sched_thread_del(sched, pvt->authid);
1878  ast_sched_thread_del(sched, pvt->initid);
1879  ast_sched_thread_del(sched, pvt->jbid);
1880  ast_sched_thread_del(sched, pvt->keyrotateid);
1881 }
1882 
1883 static void iax2_frame_free(struct iax_frame *fr)
1884 {
1885  ast_sched_thread_del(sched, fr->retrans);
1886  iax_frame_free(fr);
1887 }
1888 
1889 static int scheduled_destroy(const void *vid)
1890 {
1891  unsigned short callno = PTR_TO_CALLNO(vid);
1892  ast_mutex_lock(&iaxsl[callno]);
1893  if (iaxs[callno]) {
1894  if (option_debug) {
1895  ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
1896  }
1897  iax2_destroy(callno);
1898  }
1899  ast_mutex_unlock(&iaxsl[callno]);
1900  return 0;
1901 }
1902 
1903 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1904 {
1905  if (s->f.datalen) {
1906  ast_free(s->f.data.ptr);
1907  }
1908  ast_free(s);
1909 }
1910 
1911 /*! \brief This function must be called once we are sure the other side has
1912  * given us a call number. All signaling is held here until that point. */
1913 static void send_signaling(struct chan_iax2_pvt *pvt)
1914 {
1915  struct signaling_queue_entry *s = NULL;
1916 
1917  while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1918  iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1920  }
1921  pvt->hold_signaling = 0;
1922 }
1923 
1924 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1925  * we have received a destination call number. */
1926 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1927 {
1928  struct signaling_queue_entry *qe;
1929 
1930  if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1931  return 1; /* do not queue this frame */
1932  } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1933  return -1; /* out of memory */
1934  }
1935 
1936  /* copy ast_frame into our queue entry */
1937  qe->f = *f;
1938  if (qe->f.datalen) {
1939  /* if there is data in this frame copy it over as well */
1940  if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
1942  return -1;
1943  }
1944  memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
1945  }
1946  AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
1947 
1948  return 0;
1949 }
1950 
1951 static void pvt_destructor(void *obj)
1952 {
1953  struct chan_iax2_pvt *pvt = obj;
1954  struct iax_frame *cur = NULL;
1955  struct signaling_queue_entry *s = NULL;
1956 
1957  ast_mutex_lock(&iaxsl[pvt->callno]);
1958 
1959  iax2_destroy_helper(pvt);
1960 
1961  sched_delay_remove(&pvt->addr, pvt->callno_entry);
1962  pvt->callno_entry = NULL;
1963 
1964  /* Already gone */
1966 
1967  AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
1968  /* Cancel any pending transmissions */
1969  cur->retries = -1;
1970  }
1971 
1972  ast_mutex_unlock(&iaxsl[pvt->callno]);
1973 
1974  while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1976  }
1977 
1978  if (pvt->reg) {
1979  pvt->reg->callno = 0;
1980  }
1981 
1982  if (!pvt->owner) {
1983  jb_frame frame;
1984  if (pvt->vars) {
1986  pvt->vars = NULL;
1987  }
1988 
1989  while (jb_getall(pvt->jb, &frame) == JB_OK) {
1990  iax2_frame_free(frame.data);
1991  }
1992 
1993  jb_destroy(pvt->jb);
1995  }
1996 }
1997 
1998 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1999 {
2000  struct chan_iax2_pvt *tmp;
2001  jb_conf jbconf;
2002 
2003  if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2004  return NULL;
2005  }
2006 
2007  if (ast_string_field_init(tmp, 32)) {
2008  ao2_ref(tmp, -1);
2009  tmp = NULL;
2010  return NULL;
2011  }
2012 
2013  tmp->prefs = prefs;
2014  tmp->pingid = -1;
2015  tmp->lagid = -1;
2016  tmp->autoid = -1;
2017  tmp->authid = -1;
2018  tmp->initid = -1;
2019  tmp->keyrotateid = -1;
2020 
2021  ast_string_field_set(tmp,exten, "s");
2022  ast_string_field_set(tmp,host, host);
2023 
2024  tmp->jb = jb_new();
2025  tmp->jbid = -1;
2026  jbconf.max_jitterbuf = maxjitterbuffer;
2030  jb_setconf(tmp->jb,&jbconf);
2031 
2033 
2034  tmp->hold_signaling = 1;
2036 
2037  return tmp;
2038 }
2039 
2040 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2041 {
2042  struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2043  if (new) {
2044  size_t afdatalen = new->afdatalen;
2045  memcpy(new, fr, sizeof(*new));
2046  iax_frame_wrap(new, &fr->af);
2047  new->afdatalen = afdatalen;
2048  new->data = NULL;
2049  new->datalen = 0;
2050  new->direction = DIRECTION_INGRESS;
2051  new->retrans = -1;
2052  }
2053  return new;
2054 }
2055 /* keep these defined in this order. They are used in find_callno to
2056  * determine whether or not a new call number should be allowed. */
2057 enum {
2058  /* do not allow a new call number, only search ones in use for match */
2060  /* search for match first, then allow a new one to be allocated */
2062  /* do not search for match, force a new call number */
2064  /* do not search for match, force a new call number. Signifies call number
2065  * has been calltoken validated */
2067 };
2068 
2069 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2070 {
2071  if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2072  (cur->addr.sin_port == sin->sin_port)) {
2073  /* This is the main host */
2074  if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2075  (check_dcallno ? dcallno == cur->callno : 1) ) {
2076  /* That's us. Be sure we keep track of the peer call number */
2077  return 1;
2078  }
2079  }
2080  if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2081  (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2082  /* We're transferring */
2083  if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2084  return 1;
2085  }
2086  return 0;
2087 }
2088 
2089 #ifdef IAX_OLD_FIND
2090 
2091 static int maxtrunkcall = TRUNK_CALL_START;
2092 static int maxnontrunkcall = 1;
2093 
2094 #define update_max_trunk() __update_max_trunk()
2095 #define update_max_nontrunk() __update_max_nontrunk()
2096 
2097 static void __update_max_trunk(void)
2098 {
2099  int max = TRUNK_CALL_START;
2100  int x;
2101 
2102  /* XXX Prolly don't need locks here XXX */
2103  for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
2104  if (iaxs[x]) {
2105  max = x + 1;
2106  }
2107  }
2108 
2109  maxtrunkcall = max;
2110  if (iaxdebug)
2111  ast_debug(1, "New max trunk callno is %d\n", max);
2112 }
2113 
2114 static void __update_max_nontrunk(void)
2115 {
2116  int max = 1;
2117  int x;
2118  /* XXX Prolly don't need locks here XXX */
2119  for (x=1;x<TRUNK_CALL_START - 1; x++) {
2120  if (iaxs[x])
2121  max = x + 1;
2122  }
2123  maxnontrunkcall = max;
2124  if (iaxdebug)
2125  ast_debug(1, "New max nontrunk callno is %d\n", max);
2126 }
2127 
2128 #else
2129 
2130 #define update_max_trunk() do { } while (0)
2131 #define update_max_nontrunk() do { } while (0)
2132 
2133 #endif
2134 
2135 static int make_trunk(unsigned short callno, int locked)
2136 {
2137  int x;
2138  int res= 0;
2139  struct callno_entry *callno_entry;
2140  if (iaxs[callno]->oseqno) {
2141  ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2142  return -1;
2143  }
2144  if (callno >= TRUNK_CALL_START) {
2145  ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2146  return -1;
2147  }
2148 
2149  if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
2150  ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2151  return -1;
2152  }
2153 
2154  x = callno_entry->callno;
2155  ast_mutex_lock(&iaxsl[x]);
2156 
2157  /*!
2158  * \note We delete these before switching the slot, because if
2159  * they fire in the meantime, they will generate a warning.
2160  */
2161  ast_sched_thread_del(sched, iaxs[callno]->pingid);
2162  ast_sched_thread_del(sched, iaxs[callno]->lagid);
2163  iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2164  iaxs[x] = iaxs[callno];
2165  iaxs[x]->callno = x;
2166 
2167  /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2168  * before assigning the new one */
2169  if (iaxs[x]->callno_entry) {
2170  iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
2171  }
2172  iaxs[x]->callno_entry = callno_entry;
2173 
2174  iaxs[callno] = NULL;
2175  /* Update the two timers that should have been started */
2176  iaxs[x]->pingid = iax2_sched_add(sched,
2177  ping_time * 1000, send_ping, (void *)(long)x);
2178  iaxs[x]->lagid = iax2_sched_add(sched,
2179  lagrq_time * 1000, send_lagrq, (void *)(long)x);
2180 
2181  if (locked)
2182  ast_mutex_unlock(&iaxsl[callno]);
2183  res = x;
2184  if (!locked)
2185  ast_mutex_unlock(&iaxsl[x]);
2186 
2187  ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2188  /* We move this call from a non-trunked to a trunked call */
2189  update_max_trunk();
2191  return res;
2192 }
2193 
2194 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2195 {
2196  if (!pvt->transfercallno) {
2197  ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2198  return;
2199  }
2200 
2201  ao2_link(iax_transfercallno_pvts, pvt);
2202 }
2203 
2204 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2205 {
2206  if (!pvt->transfercallno) {
2207  ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2208  return;
2209  }
2210 
2211  ao2_unlink(iax_transfercallno_pvts, pvt);
2212 }
2213 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2214 {
2215  if (!pvt->peercallno) {
2216  ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2217  return;
2218  }
2219 
2220  ao2_link(iax_peercallno_pvts, pvt);
2221 }
2222 
2223 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2224 {
2225  if (!pvt->peercallno) {
2226  ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2227  return;
2228  }
2229 
2230  ao2_unlink(iax_peercallno_pvts, pvt);
2231 }
2232 
2233 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2234 {
2235  struct addr_range *lim = obj;
2236  lim->delme = 1;
2237  return 0;
2238 }
2239 
2240 static int addr_range_hash_cb(const void *obj, const int flags)
2241 {
2242  const struct addr_range *lim = obj;
2243  struct sockaddr_in sin;
2244  ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2245  return abs((int) sin.sin_addr.s_addr);
2246 }
2247 
2248 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2249 {
2250  struct addr_range *lim1 = obj, *lim2 = arg;
2251  return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2252  !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2253  CMP_MATCH | CMP_STOP : 0;
2254 }
2255 
2256 static int peercnt_hash_cb(const void *obj, const int flags)
2257 {
2258  const struct peercnt *peercnt = obj;
2259  return abs((int) peercnt->addr);
2260 }
2261 
2262 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2263 {
2264  struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2265  return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2266 }
2267 
2268 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2269 {
2270  struct addr_range *addr_range = obj;
2271  struct sockaddr_in *sin = arg;
2272  struct sockaddr_in ha_netmask_sin;
2273  struct sockaddr_in ha_addr_sin;
2274 
2275  ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2276  ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2277 
2278  if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2279  return CMP_MATCH | CMP_STOP;
2280  }
2281  return 0;
2282 }
2283 
2284 /*!
2285  * \internal
2286  *
2287  * \brief compares sin to calltoken_ignores table to determine if validation is required.
2288  */
2289 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2290 {
2291  struct addr_range *addr_range;
2292  struct iax2_peer *peer = NULL;
2293  struct iax2_user *user = NULL;
2294  /* if no username is given, check for guest accounts */
2295  const char *find = S_OR(name, "guest");
2296  int res = 1; /* required by default */
2297  int optional = 0;
2299  /* There are only two cases in which calltoken validation is not required.
2300  * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2301  * the peer definition has not set the requirecalltoken option.
2302  * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2303  */
2304 
2305  /* ----- Case 1 ----- */
2306  if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2307  ao2_ref(addr_range, -1);
2308  optional = 1;
2309  }
2310 
2311  /* ----- Case 2 ----- */
2312  if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2313  calltoken_required = user->calltoken_required;
2314  } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2315  calltoken_required = user->calltoken_required;
2316  } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2317  calltoken_required = peer->calltoken_required;
2318  } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2319  calltoken_required = peer->calltoken_required;
2320  }
2321 
2322  if (peer) {
2323  peer_unref(peer);
2324  }
2325  if (user) {
2326  user_unref(user);
2327  }
2328 
2329  ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %u\n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
2330  if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2331  (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2332  res = 0;
2333  }
2334 
2335  return res;
2336 }
2337 
2338 /*!
2339  * \internal
2340  *
2341  * \brief set peercnt callno limit.
2342  *
2343  * \details
2344  * First looks in custom definitions. If not found, global limit
2345  * is used. Entries marked as reg already have
2346  * a custom limit set by a registration and are not modified.
2347  */
2348 static void set_peercnt_limit(struct peercnt *peercnt)
2349 {
2350  uint16_t limit = global_maxcallno;
2351  struct addr_range *addr_range;
2352  struct sockaddr_in sin = {
2353  .sin_addr.s_addr = peercnt->addr,
2354  };
2355 
2356 
2357  if (peercnt->reg && peercnt->limit) {
2358  return; /* this peercnt has a custom limit set by a registration */
2359  }
2360 
2361  if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2362  limit = addr_range->limit;
2363  ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2364  ao2_ref(addr_range, -1);
2365  }
2366 
2367  peercnt->limit = limit;
2368 }
2369 
2370 /*!
2371  * \internal
2372  * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2373  */
2374 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2375 {
2376  struct peercnt *peercnt = obj;
2377 
2378  set_peercnt_limit(peercnt);
2379  ast_debug(1, "Reset limits for peercnts table\n");
2380 
2381  return 0;
2382 }
2383 
2384 /*!
2385  * \internal
2386  * \brief returns match if delme is set.
2387  */
2388 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2389 {
2390  struct addr_range *addr_range = obj;
2391 
2392  return addr_range->delme ? CMP_MATCH : 0;
2393 }
2394 
2395 /*!
2396  * \internal
2397  * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2398  */
2399 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2400 {
2401  /* this function turns off and on custom callno limits set by peer registration */
2402  struct peercnt *peercnt;
2403  struct peercnt tmp = {
2404  .addr = 0,
2405  };
2406  struct sockaddr_in sin;
2407 
2408  ast_sockaddr_to_sin(sockaddr, &sin);
2409 
2410  tmp.addr = sin.sin_addr.s_addr;
2411 
2412  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2413  peercnt->reg = reg;
2414  if (limit) {
2415  peercnt->limit = limit;
2416  } else {
2417  set_peercnt_limit(peercnt);
2418  }
2419  ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2420  ao2_ref(peercnt, -1); /* decrement ref from find */
2421  }
2422 }
2423 
2424 /*!
2425  * \internal
2426  * \brief adds an ip to the peercnts table, increments connection count if it already exists
2427  *
2428  * \details First searches for the address in the peercnts table. If found
2429  * the current count is incremented. If not found a new peercnt is allocated
2430  * and linked into the peercnts table with a call number count of 1.
2431  */
2432 static int peercnt_add(struct sockaddr_in *sin)
2433 {
2434  struct peercnt *peercnt;
2435  unsigned long addr = sin->sin_addr.s_addr;
2436  int res = 0;
2437  struct peercnt tmp = {
2438  .addr = addr,
2439  };
2440 
2441  /* Reasoning for peercnts container lock: Two identical ip addresses
2442  * could be added by different threads at the "same time". Without the container
2443  * lock, both threads could alloc space for the same object and attempt
2444  * to link to table. With the lock, one would create the object and link
2445  * to table while the other would find the already created peercnt object
2446  * rather than creating a new one. */
2447  ao2_lock(peercnts);
2448  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2449  ao2_lock(peercnt);
2450  } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2451  ao2_lock(peercnt);
2452  /* create and set defaults */
2453  peercnt->addr = addr;
2454  set_peercnt_limit(peercnt);
2455  /* guarantees it does not go away after unlocking table
2456  * ao2_find automatically adds this */
2457  ao2_link(peercnts, peercnt);
2458  } else {
2459  ao2_unlock(peercnts);
2460  return -1;
2461  }
2462 
2463  /* check to see if the address has hit its callno limit. If not increment cur. */
2464  if (peercnt->limit > peercnt->cur) {
2465  peercnt->cur++;
2466  ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2467  } else { /* max num call numbers for this peer has been reached! */
2468  ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2469  res = -1;
2470  }
2471 
2472  /* clean up locks and ref count */
2473  ao2_unlock(peercnt);
2474  ao2_unlock(peercnts);
2475  ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2476 
2477  return res;
2478 }
2479 
2480 /*!
2481  * \internal
2482  * \brief decrements a peercnts table entry
2483  */
2484 static void peercnt_remove(struct peercnt *peercnt)
2485 {
2486  struct sockaddr_in sin = {
2487  .sin_addr.s_addr = peercnt->addr,
2488  };
2489 
2490  /*
2491  * Container locked here since peercnt may be unlinked from
2492  * list. If left unlocked, peercnt_add could try and grab this
2493  * entry from the table and modify it at the "same time" this
2494  * thread attemps to unlink it.
2495  */
2496  ao2_lock(peercnts);
2497  peercnt->cur--;
2498  ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2499  /* if this was the last connection from the peer remove it from table */
2500  if (peercnt->cur == 0) {
2501  ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2502  }
2503  ao2_unlock(peercnts);
2504 }
2505 
2506 /*!
2507  * \internal
2508  * \brief called by scheduler to decrement object
2509  */
2510 static int peercnt_remove_cb(const void *obj)
2511 {
2512  struct peercnt *peercnt = (struct peercnt *) obj;
2513 
2514  peercnt_remove(peercnt);
2515  ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2516 
2517  return 0;
2518 }
2519 
2520 /*!
2521  * \internal
2522  * \brief decrements peercnts connection count, finds by addr
2523  */
2524 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2525 {
2526  struct peercnt *peercnt;
2527  struct peercnt tmp = {
2528  .addr = sin->sin_addr.s_addr,
2529  };
2530 
2531  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2532  peercnt_remove(peercnt);
2533  ao2_ref(peercnt, -1); /* decrement ref from find */
2534  }
2535  return 0;
2536 }
2537 
2538 /*!
2539  * \internal
2540  * \brief Create callno_limit entry based on configuration
2541  */
2542 static void build_callno_limits(struct ast_variable *v)
2543 {
2544  struct addr_range *addr_range = NULL;
2545  struct addr_range tmp;
2546  struct ast_ha *ha;
2547  int limit;
2548  int error;
2549  int found;
2550 
2551  for (; v; v = v->next) {
2552  limit = -1;
2553  error = 0;
2554  found = 0;
2555  ha = ast_append_ha("permit", v->name, NULL, &error);
2556 
2557  /* check for valid config information */
2558  if (error) {
2559  ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2560  continue;
2561  } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2562  ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2563  ast_free_ha(ha);
2564  continue;
2565  }
2566 
2567  ast_copy_ha(ha, &tmp.ha);
2568  /* find or create the addr_range */
2569  if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2570  ao2_lock(addr_range);
2571  found = 1;
2572  } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2573  ast_free_ha(ha);
2574  return; /* out of memory */
2575  }
2576 
2577  /* copy over config data into addr_range object */
2578  ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2579  ast_free_ha(ha); /* cleanup the tmp ha */
2580  addr_range->limit = limit;
2581  addr_range->delme = 0;
2582 
2583  /* cleanup */
2584  if (found) {
2585  ao2_unlock(addr_range);
2586  } else {
2587  ao2_link(callno_limits, addr_range);
2588  }
2589  ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2590  }
2591 }
2592 
2593 /*!
2594  * \internal
2595  * \brief Create calltoken_ignores entry based on configuration
2596  */
2597 static int add_calltoken_ignore(const char *addr)
2598 {
2599  struct addr_range tmp;
2600  struct addr_range *addr_range = NULL;
2601  struct ast_ha *ha = NULL;
2602  int error = 0;
2603 
2604  if (ast_strlen_zero(addr)) {
2605  ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2606  return -1;
2607  }
2608 
2609  ha = ast_append_ha("permit", addr, NULL, &error);
2610 
2611  /* check for valid config information */
2612  if (error) {
2613  ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2614  return -1;
2615  }
2616 
2617  ast_copy_ha(ha, &tmp.ha);
2618  /* find or create the addr_range */
2619  if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2620  ao2_lock(addr_range);
2621  addr_range->delme = 0;
2622  ao2_unlock(addr_range);
2623  } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2624  /* copy over config data into addr_range object */
2625  ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2626  ao2_link(calltoken_ignores, addr_range);
2627  } else {
2628  ast_free_ha(ha);
2629  return -1;
2630  }
2631 
2632  ast_free_ha(ha);
2633  ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2634 
2635  return 0;
2636 }
2637 
2638 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2639 {
2640  struct ao2_iterator i;
2641  struct peercnt *peercnt;
2642  struct sockaddr_in sin;
2643  int found = 0;
2644 
2645  switch (cmd) {
2646  case CLI_INIT:
2647  e->command = "iax2 show callnumber usage";
2648  e->usage =
2649  "Usage: iax2 show callnumber usage [IP address]\n"
2650  " Shows current IP addresses which are consuming iax2 call numbers\n";
2651  return NULL;
2652  case CLI_GENERATE:
2653  return NULL;
2654  case CLI_HANDLER:
2655  if (a->argc < 4 || a->argc > 5)
2656  return CLI_SHOWUSAGE;
2657 
2658  if (a->argc == 4) {
2659  ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2660  }
2661 
2662  i = ao2_iterator_init(peercnts, 0);
2663  while ((peercnt = ao2_iterator_next(&i))) {
2664  sin.sin_addr.s_addr = peercnt->addr;
2665  if (a->argc == 5) {
2666  if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2667  ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2668  ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2669  ao2_ref(peercnt, -1);
2670  found = 1;
2671  break;
2672  }
2673  } else {
2674  ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2675  }
2676  ao2_ref(peercnt, -1);
2677  }
2679 
2680  if (a->argc == 4) {
2681  ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2682  "Non-CallToken Validated Callno Used: %d\n",
2683  global_maxcallno_nonval,
2684  total_nonval_callno_used);
2685 
2686  ast_cli(a->fd, "Total Available Callno: %d\n"
2687  "Regular Callno Available: %d\n"
2688  "Trunk Callno Available: %d\n",
2689  ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2690  ao2_container_count(callno_pool),
2691  ao2_container_count(callno_pool_trunk));
2692  } else if (a->argc == 5 && !found) {
2693  ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2694  }
2695 
2696 
2697  return CLI_SUCCESS;
2698  default:
2699  return NULL;
2700  }
2701 }
2702 
2703 static struct callno_entry *get_unused_callno(int trunk, int validated)
2704 {
2705  struct callno_entry *callno_entry = NULL;
2706  if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2707  ast_log(LOG_WARNING, "Out of CallNumbers\n");
2708  /* Minor optimization for the extreme case. */
2709  return NULL;
2710  }
2711 
2712  /* the callno_pool container is locked here primarily to ensure thread
2713  * safety of the total_nonval_callno_used check and increment */
2714  ao2_lock(callno_pool);
2715 
2716  /* only a certain number of nonvalidated call numbers should be allocated.
2717  * If there ever is an attack, this separates the calltoken validating
2718  * users from the non calltoken validating users. */
2719  if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2720  ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2721  ao2_unlock(callno_pool);
2722  return NULL;
2723  }
2724 
2725  /* unlink the object from the container, taking over ownership
2726  * of the reference the container had to the object */
2727  callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2728 
2729  if (callno_entry) {
2730  callno_entry->validated = validated;
2731  if (!validated) {
2732  total_nonval_callno_used++;
2733  }
2734  }
2735 
2736  ao2_unlock(callno_pool);
2737  return callno_entry;
2738 }
2739 
2740 static int replace_callno(const void *obj)
2741 {
2742  struct callno_entry *callno_entry = (struct callno_entry *) obj;
2743 
2744  /* the callno_pool container is locked here primarily to ensure thread
2745  * safety of the total_nonval_callno_used check and decrement */
2746  ao2_lock(callno_pool);
2747 
2748  if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2749  total_nonval_callno_used--;
2750  } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2751  ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2752  }
2753 
2754  if (callno_entry->callno < TRUNK_CALL_START) {
2755  ao2_link(callno_pool, callno_entry);
2756  } else {
2757  ao2_link(callno_pool_trunk, callno_entry);
2758  }
2759  ao2_ref(callno_entry, -1); /* only container ref remains */
2760 
2761  ao2_unlock(callno_pool);
2762  return 0;
2763 }
2764 
2765 static int callno_hash(const void *obj, const int flags)
2766 {
2767  return abs(ast_random());
2768 }
2769 
2770 static int create_callno_pools(void)
2771 {
2772  uint16_t i;
2773 
2774  if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2775  return -1;
2776  }
2777 
2778  if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2779  return -1;
2780  }
2781 
2782  /* start at 2, 0 and 1 are reserved */
2783  for (i = 2; i < IAX_MAX_CALLS; i++) {
2784  struct callno_entry *callno_entry;
2785 
2786  if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2787  return -1;
2788  }
2789 
2790  callno_entry->callno = i;
2791 
2792  if (i < TRUNK_CALL_START) {
2793  ao2_link(callno_pool, callno_entry);
2794  } else {
2795  ao2_link(callno_pool_trunk, callno_entry);
2796  }
2797 
2798  ao2_ref(callno_entry, -1);
2799  }
2800 
2801  return 0;
2802 }
2803 
2804 /*!
2805  * \internal
2806  * \brief Schedules delayed removal of iax2_pvt call number data
2807  *
2808  * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2809  * available again, and the address from the previous connection must be decremented
2810  * from the peercnts table. This function schedules these operations to take place.
2811  */
2812 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2813 {
2814  int i;
2815  struct peercnt *peercnt;
2816  struct peercnt tmp = {
2817  .addr = sin->sin_addr.s_addr,
2818  };
2819 
2820  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2821  /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2822  ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2823  i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2824  if (i == -1) {
2825  ao2_ref(peercnt, -1);
2826  }
2827  }
2828 
2829  iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2830 }
2831 
2832 /*!
2833  * \internal
2834  * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2835  *
2836  * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2837  * a new callno.
2838  */
2839 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2840 {
2841  if (frametype != AST_FRAME_IAX) {
2842  return 0;
2843  }
2844  switch (subclass) {
2845  case IAX_COMMAND_NEW:
2846  case IAX_COMMAND_REGREQ:
2847  case IAX_COMMAND_FWDOWNL:
2848  case IAX_COMMAND_REGREL:
2849  return 1;
2850  case IAX_COMMAND_POKE:
2851  if (!inbound) {
2852  return 1;
2853  }
2854  break;
2855  }
2856  return 0;
2857 }
2858 
2859 /*
2860  * \note Calling this function while holding another pvt lock can cause a deadlock.
2861  */
2862 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2863 {
2864  int res = 0;
2865  int x;
2866  /* this call is calltoken validated as long as it is either NEW_FORCE
2867  * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2868  int validated = (new > NEW_ALLOW) ? 1 : 0;
2869  char host[80];
2870 
2871  if (new <= NEW_ALLOW) {
2872  if (callno) {
2873  struct chan_iax2_pvt *pvt;
2874  struct chan_iax2_pvt tmp_pvt = {
2875  .callno = dcallno,
2876  .peercallno = callno,
2877  .transfercallno = callno,
2878  /* hack!! */
2879  .frames_received = check_dcallno,
2880  };
2881 
2882  memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2883  /* this works for finding normal call numbers not involving transfering */
2884  if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2885  if (return_locked) {
2886  ast_mutex_lock(&iaxsl[pvt->callno]);
2887  }
2888  res = pvt->callno;
2889  ao2_ref(pvt, -1);
2890  pvt = NULL;
2891  return res;
2892  }
2893  /* this searches for transfer call numbers that might not get caught otherwise */
2894  memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2895  memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2896  if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2897  if (return_locked) {
2898  ast_mutex_lock(&iaxsl[pvt->callno]);
2899  }
2900  res = pvt->callno;
2901  ao2_ref(pvt, -1);
2902  pvt = NULL;
2903  return res;
2904  }
2905  }
2906  /* This will occur on the first response to a message that we initiated,
2907  * such as a PING. */
2908  if (dcallno) {
2909  ast_mutex_lock(&iaxsl[dcallno]);
2910  }
2911  if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2912  iaxs[dcallno]->peercallno = callno;
2913  res = dcallno;
2914  store_by_peercallno(iaxs[dcallno]);
2915  if (!res || !return_locked) {
2916  ast_mutex_unlock(&iaxsl[dcallno]);
2917  }
2918  return res;
2919  }
2920  if (dcallno) {
2921  ast_mutex_unlock(&iaxsl[dcallno]);
2922  }
2923 #ifdef IAX_OLD_FIND
2924  /* If we get here, we SHOULD NOT find a call structure for this
2925  callno; if we do, it means that there is a call structure that
2926  has a peer callno but did NOT get entered into the hash table,
2927  which is bad.
2928 
2929  If we find a call structure using this old, slow method, output a log
2930  message so we'll know about it. After a few months of leaving this in
2931  place, if we don't hear about people seeing these messages, we can
2932  remove this code for good.
2933  */
2934 
2935  for (x = 1; !res && x < maxnontrunkcall; x++) {
2936  ast_mutex_lock(&iaxsl[x]);
2937  if (iaxs[x]) {
2938  /* Look for an exact match */
2939  if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2940  res = x;
2941  }
2942  }
2943  if (!res || !return_locked)
2944  ast_mutex_unlock(&iaxsl[x]);
2945  }
2946  for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
2947  ast_mutex_lock(&iaxsl[x]);
2948  if (iaxs[x]) {
2949  /* Look for an exact match */
2950  if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2951  res = x;
2952  }
2953  }
2954  if (!res || !return_locked)
2955  ast_mutex_unlock(&iaxsl[x]);
2956  }
2957 #endif
2958  }
2959  if (!res && (new >= NEW_ALLOW)) {
2960  struct callno_entry *callno_entry;
2961  /* It may seem odd that we look through the peer list for a name for
2962  * this *incoming* call. Well, it is weird. However, users don't
2963  * have an IP address/port number that we can match against. So,
2964  * this is just checking for a peer that has that IP/port and
2965  * assuming that we have a user of the same name. This isn't always
2966  * correct, but it will be changed if needed after authentication. */
2967  if (!iax2_getpeername(*sin, host, sizeof(host)))
2968  snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2969 
2970  if (peercnt_add(sin)) {
2971  /* This address has hit its callnumber limit. When the limit
2972  * is reached, the connection is not added to the peercnts table.*/
2973  return 0;
2974  }
2975 
2976  if (!(callno_entry = get_unused_callno(0, validated))) {
2977  /* since we ran out of space, remove the peercnt
2978  * entry we added earlier */
2980  ast_log(LOG_WARNING, "No more space\n");
2981  return 0;
2982  }
2983  x = callno_entry->callno;
2984  ast_mutex_lock(&iaxsl[x]);
2985 
2986  iaxs[x] = new_iax(sin, host);
2988  if (iaxs[x]) {
2989  if (iaxdebug)
2990  ast_debug(1, "Creating new call structure %d\n", x);
2991  iaxs[x]->callno_entry = callno_entry;
2992  iaxs[x]->sockfd = sockfd;
2993  iaxs[x]->addr.sin_port = sin->sin_port;
2994  iaxs[x]->addr.sin_family = sin->sin_family;
2995  iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2996  iaxs[x]->peercallno = callno;
2997  iaxs[x]->callno = x;
2998  iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2999  iaxs[x]->expiry = min_reg_expire;
3000  iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3001  iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3002  iaxs[x]->amaflags = amaflags;
3004  ast_string_field_set(iaxs[x], accountcode, accountcode);
3005  ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3006  ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3007  ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3008 
3009  if (iaxs[x]->peercallno) {
3010  store_by_peercallno(iaxs[x]);
3011  }
3012  } else {
3013  ast_log(LOG_WARNING, "Out of resources\n");
3014  ast_mutex_unlock(&iaxsl[x]);
3015  replace_callno(callno_entry);
3016  return 0;
3017  }
3018  if (!return_locked)
3019  ast_mutex_unlock(&iaxsl[x]);
3020  res = x;
3021  }
3022  return res;
3023 }
3024 
3025 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3026  return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
3027 }
3028 
3029 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3030 
3031  return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
3032 }
3033 
3034 /*!
3035  * \brief Queue a frame to a call's owning asterisk channel
3036  *
3037  * \pre This function assumes that iaxsl[callno] is locked when called.
3038  *
3039  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3040  * was valid before calling it, it may no longer be valid after calling it.
3041  * This function may unlock and lock the mutex associated with this callno,
3042  * meaning that another thread may grab it and destroy the call.
3043  */
3044 static int iax2_queue_frame(int callno, struct ast_frame *f)
3045 {
3046  iax2_lock_owner(callno);
3047  if (iaxs[callno] && iaxs[callno]->owner) {
3048  ast_queue_frame(iaxs[callno]->owner, f);
3049  ast_channel_unlock(iaxs[callno]->owner);
3050  }
3051  return 0;
3052 }
3053 
3054 /*!
3055  * \brief Queue a hangup frame on the ast_channel owner
3056  *
3057  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3058  * is active for the given call number.
3059  *
3060  * \pre Assumes lock for callno is already held.
3061  *
3062  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3063  * was valid before calling it, it may no longer be valid after calling it.
3064  * This function may unlock and lock the mutex associated with this callno,
3065  * meaning that another thread may grab it and destroy the call.
3066  */
3067 static int iax2_queue_hangup(int callno)
3068 {
3069  iax2_lock_owner(callno);
3070  if (iaxs[callno] && iaxs[callno]->owner) {
3071  ast_queue_hangup(iaxs[callno]->owner);
3072  ast_channel_unlock(iaxs[callno]->owner);
3073  }
3074  return 0;
3075 }
3076 
3077 /*!
3078  * \brief Queue a control frame on the ast_channel owner
3079  *
3080  * This function queues a control frame on the owner of the IAX2 pvt struct that
3081  * is active for the given call number.
3082  *
3083  * \pre Assumes lock for callno is already held.
3084  *
3085  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3086  * was valid before calling it, it may no longer be valid after calling it.
3087  * This function may unlock and lock the mutex associated with this callno,
3088  * meaning that another thread may grab it and destroy the call.
3089  */
3091  enum ast_control_frame_type control, const void *data, size_t datalen)
3092 {
3093  iax2_lock_owner(callno);
3094  if (iaxs[callno] && iaxs[callno]->owner) {
3095  ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
3096  ast_channel_unlock(iaxs[callno]->owner);
3097  }
3098  return 0;
3099 }
3100 static void destroy_firmware(struct iax_firmware *cur)
3101 {
3102  /* Close firmware */
3103  if (cur->fwh) {
3104  munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
3105  }
3106  close(cur->fd);
3107  ast_free(cur);
3108 }
3109 
3110 static int try_firmware(char *s)
3111 {
3112  struct stat stbuf;
3113  struct iax_firmware *cur = NULL;
3114  int ifd, fd, res, len, chunk;
3115  struct ast_iax2_firmware_header *fwh, fwh2;
3116  struct MD5Context md5;
3117  unsigned char sum[16], buf[1024];
3118  char *s2, *last;
3119 
3120  s2 = ast_alloca(strlen(s) + 100);
3121 
3122  last = strrchr(s, '/');
3123  if (last)
3124  last++;
3125  else
3126  last = s;
3127 
3128  snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, ast_random());
3129 
3130  if ((res = stat(s, &stbuf) < 0)) {
3131  ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
3132  return -1;
3133  }
3134 
3135  /* Make sure it's not a directory */
3136  if (S_ISDIR(stbuf.st_mode))
3137  return -1;
3138  ifd = open(s, O_RDONLY);
3139  if (ifd < 0) {
3140  ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
3141  return -1;
3142  }
3143  fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
3144  if (fd < 0) {
3145  ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
3146  close(ifd);
3147  return -1;
3148  }
3149  /* Unlink our newly created file */
3150  unlink(s2);
3151 
3152  /* Now copy the firmware into it */
3153  len = stbuf.st_size;
3154  while(len) {
3155  chunk = len;
3156  if (chunk > sizeof(buf))
3157  chunk = sizeof(buf);
3158  res = read(ifd, buf, chunk);
3159  if (res != chunk) {
3160  ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3161  close(ifd);
3162  close(fd);
3163  return -1;
3164  }
3165  res = write(fd, buf, chunk);
3166  if (res != chunk) {
3167  ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3168  close(ifd);
3169  close(fd);
3170  return -1;
3171  }
3172  len -= chunk;
3173  }
3174  close(ifd);
3175  /* Return to the beginning */
3176  lseek(fd, 0, SEEK_SET);
3177  if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
3178  ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
3179  close(fd);
3180  return -1;
3181  }
3182  if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
3183  ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3184  close(fd);
3185  return -1;
3186  }
3187  if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3188  ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3189  close(fd);
3190  return -1;
3191  }
3192  if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3193  ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3194  close(fd);
3195  return -1;
3196  }
3197  fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
3198  if (fwh == MAP_FAILED) {
3199  ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3200  close(fd);
3201  return -1;
3202  }
3203  MD5Init(&md5);
3204  MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3205  MD5Final(sum, &md5);
3206  if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3207  ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3208  munmap((void*)fwh, stbuf.st_size);
3209  close(fd);
3210  return -1;
3211  }
3212 
3213  AST_LIST_TRAVERSE(&firmwares, cur, list) {
3214  if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3215  /* Found a candidate */
3216  if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3217  /* The version we have on loaded is older, load this one instead */
3218  break;
3219  /* This version is no newer than what we have. Don't worry about it.
3220  We'll consider it a proper load anyhow though */
3221  munmap((void*)fwh, stbuf.st_size);
3222  close(fd);
3223  return 0;
3224  }
3225  }
3226 
3227  if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3228  cur->fd = -1;
3229  AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3230  }
3231 
3232  if (cur) {
3233  if (cur->fwh)
3234  munmap((void*)cur->fwh, cur->mmaplen);
3235  if (cur->fd > -1)
3236  close(cur->fd);
3237  cur->fwh = fwh;
3238  cur->fd = fd;
3239  cur->mmaplen = stbuf.st_size;
3240  cur->dead = 0;
3241  }
3242 
3243  return 0;
3244 }
3245 
3246 static int iax_check_version(char *dev)
3247 {
3248  int res = 0;
3249  struct iax_firmware *cur = NULL;
3250 
3251  if (ast_strlen_zero(dev))
3252  return 0;
3253 
3255  AST_LIST_TRAVERSE(&firmwares, cur, list) {
3256  if (!strcmp(dev, (char *)cur->fwh->devname)) {
3257  res = ntohs(cur->fwh->version);
3258  break;
3259  }
3260  }
3262 
3263  return res;
3264 }
3265 
3266 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3267 {
3268  int res = -1;
3269  unsigned int bs = desc & 0xff;
3270  unsigned int start = (desc >> 8) & 0xffffff;
3271  unsigned int bytes;
3272  struct iax_firmware *cur;
3273 
3274  if (ast_strlen_zero((char *)dev) || !bs)
3275  return -1;
3276 
3277  start *= bs;
3278 
3280  AST_LIST_TRAVERSE(&firmwares, cur, list) {
3281  if (strcmp((char *)dev, (char *)cur->fwh->devname))
3282  continue;
3284  if (start < ntohl(cur->fwh->datalen)) {
3285  bytes = ntohl(cur->fwh->datalen) - start;
3286  if (bytes > bs)
3287  bytes = bs;
3288  iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3289  } else {
3290  bytes = 0;
3292  }
3293  if (bytes == bs)
3294  res = 0;
3295  else
3296  res = 1;
3297  break;
3298  }
3300 
3301  return res;
3302 }
3303 
3304 
3305 static void reload_firmware(int unload)
3306 {
3307  struct iax_firmware *cur = NULL;
3308  DIR *fwd;
3309  struct dirent *de;
3310  char dir[256], fn[256];
3311 
3313 
3314  /* Mark all as dead */
3315  AST_LIST_TRAVERSE(&firmwares, cur, list)
3316  cur->dead = 1;
3317 
3318  /* Now that we have marked them dead... load new ones */
3319  if (!unload) {
3320  snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3321  fwd = opendir(dir);
3322  if (fwd) {
3323  while((de = readdir(fwd))) {
3324  if (de->d_name[0] != '.') {
3325  snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3326  if (!try_firmware(fn)) {
3327  ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3328  }
3329  }
3330  }
3331  closedir(fwd);
3332  } else
3333  ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3334  }
3335 
3336  /* Clean up leftovers */
3338  if (!cur->dead)
3339  continue;
3341  destroy_firmware(cur);
3342  }
3344 
3346 }
3347 
3348 /*!
3349  * \note This function assumes that iaxsl[callno] is locked when called.
3350  *
3351  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3352  * was valid before calling it, it may no longer be valid after calling it.
3353  * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3354  * associated with this callno, meaning that another thread may grab it and destroy the call.
3355  */
3356 static int __do_deliver(void *data)
3357 {
3358  /* Just deliver the packet by using queueing. This is called by
3359  the IAX thread with the iaxsl lock held. */
3360  struct iax_frame *fr = data;
3361  fr->retrans = -1;
3363  if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3364  iax2_queue_frame(fr->callno, &fr->af);
3365  /* Free our iax frame */
3366  iax2_frame_free(fr);
3367  /* And don't run again */
3368  return 0;
3369 }
3370 
3371 static int handle_error(void)
3372 {
3373  /* XXX Ideally we should figure out why an error occurred and then abort those
3374  rather than continuing to try. Unfortunately, the published interface does
3375  not seem to work XXX */
3376 #if 0
3377  struct sockaddr_in *sin;
3378  int res;
3379  struct msghdr m;
3380  struct sock_extended_err e;
3381  m.msg_name = NULL;
3382  m.msg_namelen = 0;
3383  m.msg_iov = NULL;
3384  m.msg_control = &e;
3385  m.msg_controllen = sizeof(e);
3386  m.msg_flags = 0;
3387  res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3388  if (res < 0)
3389  ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3390  else {
3391  if (m.msg_controllen) {
3392  sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3393  if (sin)
3394  ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3395  else
3396  ast_log(LOG_WARNING, "No address detected??\n");
3397  } else {
3398  ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3399  }
3400  }
3401 #endif
3402  return 0;
3403 }
3404 
3405 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3406 {
3407  int res;
3408  res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3409  sizeof(*sin));
3410  if (res < 0) {
3411  ast_debug(1, "Received error: %s\n", strerror(errno));
3412  handle_error();
3413  } else
3414  res = 0;
3415  return res;
3416 }
3417 
3418 static int send_packet(struct iax_frame *f)
3419 {
3420  int res;
3421  int callno = f->callno;
3422 
3423  /* Don't send if there was an error, but return error instead */
3424  if (!callno || !iaxs[callno] || iaxs[callno]->error)
3425  return -1;
3426 
3427  /* Called with iaxsl held */
3428  if (iaxdebug)
3429  ast_debug(3, "Sending %u on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
3430 
3431  if (f->transfer) {
3432  iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3433  res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3434  } else {
3435  iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3436  res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3437  }
3438  if (res < 0) {
3439  if (iaxdebug)
3440  ast_debug(1, "Received error: %s\n", strerror(errno));
3441  handle_error();
3442  } else
3443  res = 0;
3444 
3445  return res;
3446 }
3447 
3448 /*!
3449  * \note Since this function calls iax2_queue_hangup(), the pvt struct
3450  * for the given call number may disappear during its execution.
3451  */
3452 static int iax2_predestroy(int callno)
3453 {
3454  struct ast_channel *c = NULL;
3455  struct chan_iax2_pvt *pvt = iaxs[callno];
3456 
3457  if (!pvt)
3458  return -1;
3459 
3460  if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3461  iax2_destroy_helper(pvt);
3463  }
3464 
3465  if ((c = pvt->owner)) {
3466  c->tech_pvt = NULL;
3467  iax2_queue_hangup(callno);
3468  pvt->owner = NULL;
3470  }
3471 
3472  return 0;
3473 }
3474 
3475 static void iax2_destroy(int callno)
3476 {
3477  struct chan_iax2_pvt *pvt = NULL;
3478  struct ast_channel *owner = NULL;
3479 
3480 retry:
3481  if ((pvt = iaxs[callno])) {
3482 #if 0
3483  /* iax2_destroy_helper gets called from this function later on. When
3484  * called twice, we get the (previously) familiar FRACK! errors in
3485  * devmode, from the scheduler. An alternative to this approach is to
3486  * reset the scheduler entries to -1 when they're deleted in
3487  * iax2_destroy_helper(). That approach was previously decided to be
3488  * "wrong" because "the memory is going to be deallocated anyway. Why
3489  * should we be resetting those values?" */
3490  iax2_destroy_helper(pvt);
3491 #endif
3492  }
3493 
3494  owner = pvt ? pvt->owner : NULL;
3495 
3496  if (owner) {
3497  if (ast_channel_trylock(owner)) {
3498  ast_debug(3, "Avoiding IAX destroy deadlock\n");
3499  DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3500  goto retry;
3501  }
3502  }
3503 
3504  if (!owner) {
3505  iaxs[callno] = NULL;
3506  }
3507 
3508  if (pvt) {
3509  if (!owner) {
3510  pvt->owner = NULL;
3511  } else {
3512  /* If there's an owner, prod it to give up */
3513  /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3514  * because we already hold the owner channel lock. */
3515  ast_queue_hangup(owner);
3516  }
3517 
3518  if (pvt->peercallno) {
3519  remove_by_peercallno(pvt);
3520  }
3521 
3522  if (pvt->transfercallno) {
3524  }
3525 
3526  if (!owner) {
3527  ao2_ref(pvt, -1);
3528  pvt = NULL;
3529  }
3530  }
3531 
3532  if (owner) {
3533  ast_channel_unlock(owner);
3534  }
3535 
3536  if (callno & TRUNK_CALL_START) {
3537  update_max_trunk();
3538  }
3539 }
3540 
3541 static int update_packet(struct iax_frame *f)
3542 {
3543  /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3544  struct ast_iax2_full_hdr *fh = f->data;
3545  struct ast_frame af;
3546 
3547  /* if frame is encrypted. decrypt before updating it. */
3548  if (f->encmethods) {
3549  decode_frame(&f->mydcx, fh, &af, &f->datalen);
3550  }
3551  /* Mark this as a retransmission */
3552  fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3553  /* Update iseqno */
3554  f->iseqno = iaxs[f->callno]->iseqno;
3555  fh->iseqno = f->iseqno;
3556 
3557  /* Now re-encrypt the frame */
3558  if (f->encmethods) {
3559  /* since this is a retransmit frame, create a new random padding
3560  * before re-encrypting. */
3561  build_rand_pad(f->semirand, sizeof(f->semirand));
3562  encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3563  }
3564  return 0;
3565 }
3566 
3567 static int attempt_transmit(const void *data);
3568 static void __attempt_transmit(const void *data)
3569 {
3570  /* Attempt to transmit the frame to the remote peer...
3571  Called without iaxsl held. */
3572  struct iax_frame *f = (struct iax_frame *)data;
3573  int freeme = 0;
3574  int callno = f->callno;
3575 
3576  /* Make sure this call is still active */
3577  if (callno)
3578  ast_mutex_lock(&iaxsl[callno]);
3579  if (callno && iaxs[callno]) {
3580  if (f->retries < 0) {
3581  /* Already ACK'd */
3582  freeme = 1;
3583  } else if (f->retries >= max_retries) {
3584  /* Too many attempts. Record an error. */
3585  if (f->transfer) {
3586  /* Transfer timeout */
3587  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3588  } else if (f->final) {
3589  iax2_destroy(callno);
3590  } else {
3591  if (iaxs[callno]->owner) {
3592  ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3593  ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),
3594  iaxs[f->callno]->owner->name,
3595  f->af.frametype,
3596  f->af.subclass.integer,
3597  f->ts,
3598  f->oseqno);
3599  }
3600  iaxs[callno]->error = ETIMEDOUT;
3601  if (iaxs[callno]->owner) {
3603  /* Hangup the fd */
3604  iax2_queue_frame(callno, &fr); /* XXX */
3605  /* Remember, owner could disappear */
3606  if (iaxs[callno] && iaxs[callno]->owner)
3608  } else {
3609  if (iaxs[callno]->reg) {
3610  memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3611  iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3612  iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3613  }
3614  iax2_destroy(callno);
3615  }
3616  }
3617  freeme = 1;
3618  } else {
3619  /* Update it if it needs it */
3620  update_packet(f);
3621  /* Attempt transmission */
3622  send_packet(f);
3623  f->retries++;
3624  /* Try again later after 10 times as long */
3625  f->retrytime *= 10;
3626  if (f->retrytime > MAX_RETRY_TIME)
3628  /* Transfer messages max out at one second */
3629  if (f->transfer && (f->retrytime > 1000))
3630  f->retrytime = 1000;
3631  f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3632  }
3633  } else {
3634  /* Make sure it gets freed */
3635  f->retries = -1;
3636  freeme = 1;
3637  }
3638 
3639  if (freeme) {
3640  /* Don't attempt delivery, just remove it from the queue */
3641  AST_LIST_REMOVE(&frame_queue[callno], f, list);
3642  ast_mutex_unlock(&iaxsl[callno]);
3643  f->retrans = -1; /* this is safe because this is the scheduled function */
3644  /* Free the IAX frame */
3645  iax2_frame_free(f);
3646  } else if (callno) {
3647  ast_mutex_unlock(&iaxsl[callno]);
3648  }
3649 }
3650 
3651 static int attempt_transmit(const void *data)
3652 {
3653 #ifdef SCHED_MULTITHREADED
3655 #endif
3656  __attempt_transmit(data);
3657  return 0;
3658 }
3659 
3660 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3661 {
3662  struct iax2_peer *peer = NULL;
3663  struct iax2_user *user = NULL;
3664  static const char * const choices[] = { "all", NULL };
3665  char *cmplt;
3666 
3667  switch (cmd) {
3668  case CLI_INIT:
3669  e->command = "iax2 prune realtime";
3670  e->usage =
3671  "Usage: iax2 prune realtime [<peername>|all]\n"
3672  " Prunes object(s) from the cache\n";
3673  return NULL;
3674  case CLI_GENERATE:
3675  if (a->pos == 3) {
3676  cmplt = ast_cli_complete(a->word, choices, a->n);
3677  if (!cmplt)
3678  cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3679  return cmplt;
3680  }
3681  return NULL;
3682  }
3683  if (a->argc != 4)
3684  return CLI_SHOWUSAGE;
3685  if (!strcmp(a->argv[3], "all")) {
3686  prune_users();
3687  prune_peers();
3688  ast_cli(a->fd, "Cache flushed successfully.\n");
3689  return CLI_SUCCESS;
3690  }
3691  peer = find_peer(a->argv[3], 0);
3692  user = find_user(a->argv[3]);
3693  if (peer || user) {
3694  if (peer) {
3695  if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3697  expire_registry(peer_ref(peer));
3698  ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3699  } else {
3700  ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3701  }
3702  peer_unref(peer);
3703  }
3704  if (user) {
3705  if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3707  ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3708  } else {
3709  ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3710  }
3711  ao2_unlink(users,user);
3712  user_unref(user);
3713  }
3714  } else {
3715  ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3716  }
3717 
3718  return CLI_SUCCESS;
3719 }
3720 
3721 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3722 {
3723  switch (cmd) {
3724  case CLI_INIT:
3725  e->command = "iax2 test losspct";
3726  e->usage =
3727  "Usage: iax2 test losspct <percentage>\n"
3728  " For testing, throws away <percentage> percent of incoming packets\n";
3729  return NULL;
3730  case CLI_GENERATE:
3731  return NULL;
3732  }
3733  if (a->argc != 4)
3734  return CLI_SHOWUSAGE;
3735 
3736  test_losspct = atoi(a->argv[3]);
3737 
3738  return CLI_SUCCESS;
3739 }
3740 
3741 #ifdef IAXTESTS
3742 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3743 {
3744  switch (cmd) {
3745  case CLI_INIT:
3746  e->command = "iax2 test late";
3747  e->usage =
3748  "Usage: iax2 test late <ms>\n"
3749  " For testing, count the next frame as <ms> ms late\n";
3750  return NULL;
3751  case CLI_GENERATE:
3752  return NULL;
3753  }
3754 
3755  if (a->argc != 4)
3756  return CLI_SHOWUSAGE;
3757 
3758  test_late = atoi(a->argv[3]);
3759 
3760  return CLI_SUCCESS;
3761 }
3762 
3763 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3764 {
3765  switch (cmd) {
3766  case CLI_INIT:
3767  e->command = "iax2 test resync";
3768  e->usage =
3769  "Usage: iax2 test resync <ms>\n"
3770  " For testing, adjust all future frames by <ms> ms\n";
3771  return NULL;
3772  case CLI_GENERATE:
3773  return NULL;
3774  }
3775 
3776  if (a->argc != 4)
3777  return CLI_SHOWUSAGE;
3778 
3779  test_resync = atoi(a->argv[3]);
3780 
3781  return CLI_SUCCESS;
3782 }
3783 
3784 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3785 {
3786  switch (cmd) {
3787  case CLI_INIT:
3788  e->command = "iax2 test jitter";
3789  e->usage =
3790  "Usage: iax2 test jitter <ms> <pct>\n"
3791  " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3792  " percentage of packets. If <pct> is not specified, adds\n"
3793  " jitter to all packets.\n";
3794  return NULL;
3795  case CLI_GENERATE:
3796  return NULL;
3797  }
3798 
3799  if (a->argc < 4 || a->argc > 5)
3800  return CLI_SHOWUSAGE;
3801 
3802  test_jit = atoi(a->argv[3]);
3803  if (a->argc == 5)
3804  test_jitpct = atoi(a->argv[4]);
3805 
3806  return CLI_SUCCESS;
3807 }
3808 #endif /* IAXTESTS */
3809 
3810 /*! \brief peer_status: Report Peer status in character string */
3811 /* returns 1 if peer is online, -1 if unmonitored */
3812 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3813 {
3814  int res = 0;
3815  if (peer->maxms) {
3816  if (peer->lastms < 0) {
3817  ast_copy_string(status, "UNREACHABLE", statuslen);
3818  } else if (peer->lastms > peer->maxms) {
3819  snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3820  res = 1;
3821  } else if (peer->lastms) {
3822  snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3823  res = 1;
3824  } else {
3825  ast_copy_string(status, "UNKNOWN", statuslen);
3826  }
3827  } else {
3828  ast_copy_string(status, "Unmonitored", statuslen);
3829  res = -1;
3830  }
3831  return res;
3832 }
3833 
3834 /*! \brief Show one peer in detail */
3835 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3836 {
3837  char status[30];
3838  char cbuf[256];
3839  struct iax2_peer *peer;
3840  char codec_buf[512];
3841  struct ast_str *encmethods = ast_str_alloca(256);
3842  int x = 0, codec = 0, load_realtime = 0;
3843 
3844  switch (cmd) {
3845  case CLI_INIT:
3846  e->command = "iax2 show peer";
3847  e->usage =
3848  "Usage: iax2 show peer <name>\n"
3849  " Display details on specific IAX peer\n";
3850  return NULL;
3851  case CLI_GENERATE:
3852  if (a->pos == 3)
3853  return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3854  return NULL;
3855  }
3856 
3857  if (a->argc < 4)
3858  return CLI_SHOWUSAGE;
3859 
3860  load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3861 
3862  peer = find_peer(a->argv[3], load_realtime);
3863  if (peer) {
3864  struct sockaddr_in peer_addr;
3865 
3866  ast_sockaddr_to_sin(&peer->addr, &peer_addr);
3867 
3868  encmethods_to_str(peer->encmethods, &encmethods);
3869  ast_cli(a->fd, "\n\n");
3870  ast_cli(a->fd, " * Name : %s\n", peer->name);
3871  ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3872  ast_cli(a->fd, " Context : %s\n", peer->context);
3873  ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3874  ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3875  ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3876  ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3877  ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3878  ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3879  ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3880  ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3881  ast_cli(a->fd, " Expire : %d\n", peer->expire);
3882  ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
3883  ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer_addr.sin_addr.s_addr ? ast_inet_ntoa(peer_addr.sin_addr) : "(Unspecified)", ntohs(peer_addr.sin_port));
3884  ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
3885  ast_cli(a->fd, " Username : %s\n", peer->username);
3886  ast_cli(a->fd, " Codecs : ");
3887  ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
3888  ast_cli(a->fd, "%s\n", codec_buf);
3889 
3890  ast_cli(a->fd, " Codec Order : (");
3891  for(x = 0; x < 32 ; x++) {
3892  codec = ast_codec_pref_index(&peer->prefs,x);
3893  if(!codec)
3894  break;
3895  ast_cli(a->fd, "%s", ast_getformatname(codec));
3896  if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
3897  ast_cli(a->fd, "|");
3898  }
3899 
3900  if (!x)
3901  ast_cli(a->fd, "none");
3902  ast_cli(a->fd, ")\n");
3903 
3904  ast_cli(a->fd, " Status : ");
3905  peer_status(peer, status, sizeof(status));
3906  ast_cli(a->fd, "%s\n",status);
3907  ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
3908  ast_cli(a->fd, "\n");
3909  peer_unref(peer);
3910  } else {
3911  ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3912  ast_cli(a->fd, "\n");
3913  }
3914 
3915  return CLI_SUCCESS;
3916 }
3917 
3918 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3919 {
3920  int which = 0;
3921  struct iax2_peer *peer;
3922  char *res = NULL;
3923  int wordlen = strlen(word);
3924  struct ao2_iterator i;
3925 
3926  i = ao2_iterator_init(peers, 0);
3927  while ((peer = ao2_iterator_next(&i))) {
3928  if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3929  && (!flags || ast_test_flag64(peer, flags))) {
3930  res = ast_strdup(peer->name);
3931  peer_unref(peer);
3932  break;
3933  }
3934  peer_unref(peer);
3935  }
3937 
3938  return res;
3939 }
3940 
3941 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3942 {
3943  struct iax_frame *cur;
3944  int cnt = 0, dead = 0, final = 0, i = 0;
3945 
3946  switch (cmd) {
3947  case CLI_INIT:
3948  e->command = "iax2 show stats";
3949  e->usage =
3950  "Usage: iax2 show stats\n"
3951  " Display statistics on IAX channel driver.\n";
3952  return NULL;
3953  case CLI_GENERATE:
3954  return NULL;
3955  }
3956 
3957  if (a->argc != 3)
3958  return CLI_SHOWUSAGE;
3959 
3960  for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3961  ast_mutex_lock(&iaxsl[i]);
3962  AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
3963  if (cur->retries < 0)
3964  dead++;
3965  if (cur->final)
3966  final++;
3967  cnt++;
3968  }
3969  ast_mutex_unlock(&iaxsl[i]);
3970  }
3971 
3972  ast_cli(a->fd, " IAX Statistics\n");
3973  ast_cli(a->fd, "---------------------\n");
3974  ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3975  ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3976  trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
3977  ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3978 
3979  trunk_timed = trunk_untimed = 0;
3980  if (trunk_maxmtu > trunk_nmaxmtu)
3981  trunk_nmaxmtu = trunk_maxmtu;
3982 
3983  return CLI_SUCCESS;
3984 }
3985 
3986 /*! \brief Set trunk MTU from CLI */
3987 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3988 {
3989  int mtuv;
3990 
3991  switch (cmd) {
3992  case CLI_INIT:
3993  e->command = "iax2 set mtu";
3994  e->usage =
3995  "Usage: iax2 set mtu <value>\n"
3996  " Set the system-wide IAX IP mtu to <value> bytes net or\n"
3997  " zero to disable. Disabling means that the operating system\n"
3998  " must handle fragmentation of UDP packets when the IAX2 trunk\n"
3999  " packet exceeds the UDP payload size. This is substantially\n"
4000  " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
4001  " greater for G.711 samples.\n";
4002  return NULL;
4003  case CLI_GENERATE:
4004  return NULL;
4005  }
4006 
4007  if (a->argc != 4)
4008  return CLI_SHOWUSAGE;
4009  if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
4010  mtuv = MAX_TRUNK_MTU;
4011  else
4012  mtuv = atoi(a->argv[3]);
4013 
4014  if (mtuv == 0) {
4015  ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
4016  global_max_trunk_mtu = 0;
4017  return CLI_SUCCESS;
4018  }
4019  if (mtuv < 172 || mtuv > 4000) {
4020  ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
4021  return CLI_SHOWUSAGE;
4022  }
4023  ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
4024  global_max_trunk_mtu = mtuv;
4025  return CLI_SUCCESS;
4026 }
4027 
4028 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4029 {
4030  struct iax2_dpcache *dp = NULL;
4031  char tmp[1024], *pc = NULL;
4032  int s, x, y;
4033  struct timeval now = ast_tvnow();
4034 
4035  switch (cmd) {
4036  case CLI_INIT:
4037  e->command = "iax2 show cache";
4038  e->usage =
4039  "Usage: iax2 show cache\n"
4040  " Display currently cached IAX Dialplan results.\n";
4041  return NULL;
4042  case CLI_GENERATE:
4043  return NULL;
4044  }
4045 
4047 
4048  ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4049 
4050  AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4051  s = dp->expiry.tv_sec - now.tv_sec;
4052  tmp[0] = '\0';
4053  if (dp->flags & CACHE_FLAG_EXISTS)
4054  strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4055  if (dp->flags & CACHE_FLAG_NONEXISTENT)
4056  strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4057  if (dp->flags & CACHE_FLAG_CANEXIST)
4058  strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4059  if (dp->flags & CACHE_FLAG_PENDING)
4060  strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4061  if (dp->flags & CACHE_FLAG_TIMEOUT)
4062  strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4063  if (dp->flags & CACHE_FLAG_TRANSMITTED)
4064  strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4065  if (dp->flags & CACHE_FLAG_MATCHMORE)
4066  strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4067  if (dp->flags & CACHE_FLAG_UNKNOWN)
4068  strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4069  /* Trim trailing pipe */
4070  if (!ast_strlen_zero(tmp)) {
4071  tmp[strlen(tmp) - 1] = '\0';
4072  } else {
4073  ast_copy_string(tmp, "(none)", sizeof(tmp));
4074  }
4075  y = 0;
4076  pc = strchr(dp->peercontext, '@');
4077  if (!pc) {
4078  pc = dp->peercontext;
4079  } else {
4080  pc++;
4081  }
4082  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4083  if (dp->waiters[x] > -1)
4084  y++;
4085  }
4086  if (s > 0) {
4087  ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4088  } else {
4089  ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4090  }
4091  }
4092 
4094 
4095  return CLI_SUCCESS;
4096 }
4097 
4098 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4099 
4100 static void unwrap_timestamp(struct iax_frame *fr)
4101 {
4102  /* Video mini frames only encode the lower 15 bits of the session
4103  * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4104  const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4105  const int lower_mask = (1 << ts_shift) - 1;
4106  const int upper_mask = ~lower_mask;
4107  const int last_upper = iaxs[fr->callno]->last & upper_mask;
4108 
4109  if ( (fr->ts & upper_mask) == last_upper ) {
4110  const int x = fr->ts - iaxs[fr->callno]->last;
4111  const int threshold = (ts_shift == 15) ? 25000 : 50000;
4112 
4113  if (x < -threshold) {
4114  /* Sudden big jump backwards in timestamp:
4115  What likely happened here is that miniframe timestamp has circled but we haven't
4116  gotten the update from the main packet. We'll just pretend that we did, and
4117  update the timestamp appropriately. */
4118  fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4119  if (iaxdebug)
4120  ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4121  } else if (x > threshold) {
4122  /* Sudden apparent big jump forwards in timestamp:
4123  What's likely happened is this is an old miniframe belonging to the previous
4124  top 15 or 16-bit timestamp that has turned up out of order.
4125  Adjust the timestamp appropriately. */
4126  fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4127  if (iaxdebug)
4128  ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4129  }
4130  }
4131 }
4132 
4133 static int get_from_jb(const void *p);
4134 
4135 static void update_jbsched(struct chan_iax2_pvt *pvt)
4136 {
4137  int when;
4138 
4139  when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4140 
4141  when = jb_next(pvt->jb) - when;
4142 
4143  if (when <= 0) {
4144  /* XXX should really just empty until when > 0.. */
4145  when = 1;
4146  }
4147 
4148  pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4149  CALLNO_TO_PTR(pvt->callno));
4150 }
4151 
4152 static void __get_from_jb(const void *p)
4153 {
4154  int callno = PTR_TO_CALLNO(p);
4155  struct chan_iax2_pvt *pvt = NULL;
4156  struct iax_frame *fr;
4157  jb_frame frame;
4158  int ret;
4159  long ms;
4160  long next;
4161  struct timeval now = ast_tvnow();
4162 
4163  /* Make sure we have a valid private structure before going on */
4164  ast_mutex_lock(&iaxsl[callno]);
4165  pvt = iaxs[callno];
4166  if (!pvt) {
4167  /* No go! */
4168  ast_mutex_unlock(&iaxsl[callno]);
4169  return;
4170  }
4171 
4172  pvt->jbid = -1;
4173 
4174  /* round up a millisecond since ast_sched_runq does; */
4175  /* prevents us from spinning while waiting for our now */
4176  /* to catch up with runq's now */
4177  now.tv_usec += 1000;
4178 
4179  ms = ast_tvdiff_ms(now, pvt->rxcore);
4180 
4181  if(ms >= (next = jb_next(pvt->jb))) {
4182  ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));
4183  switch(ret) {
4184  case JB_OK:
4185  fr = frame.data;
4186  __do_deliver(fr);
4187  /* __do_deliver() can cause the call to disappear */
4188  pvt = iaxs[callno];
4189  break;
4190  case JB_INTERP:
4191  {
4192  struct ast_frame af = { 0, };
4193 
4194  /* create an interpolation frame */
4196  af.subclass.codec = pvt->voiceformat;
4197  af.samples = frame.ms * (ast_format_rate(pvt->voiceformat) / 1000);
4198  af.src = "IAX2 JB interpolation";
4199  af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4201 
4202  /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4203  * which we'd need to malloc, and then it would free it. That seems like a drag */
4204  if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4205  iax2_queue_frame(callno, &af);
4206  /* iax2_queue_frame() could cause the call to disappear */
4207  pvt = iaxs[callno];
4208  }
4209  }
4210  break;
4211  case JB_DROP:
4212  iax2_frame_free(frame.data);
4213  break;
4214  case JB_NOFRAME:
4215  case JB_EMPTY:
4216  /* do nothing */
4217  break;
4218  default:
4219  /* shouldn't happen */
4220  break;
4221  }
4222  }
4223  if (pvt)
4224  update_jbsched(pvt);
4225  ast_mutex_unlock(&iaxsl[callno]);
4226 }
4227 
4228 static int get_from_jb(const void *data)
4229 {
4230 #ifdef SCHED_MULTITHREADED
4231  if (schedule_action(__get_from_jb, data))
4232 #endif
4233  __get_from_jb(data);
4234  return 0;
4235 }
4236 
4237 /*!
4238  * \note This function assumes fr->callno is locked
4239  *
4240  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
4241  * was valid before calling it, it may no longer be valid after calling it.
4242  */
4243 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
4244 {
4245  int type, len;
4246  int ret;
4247  int needfree = 0;
4248  struct ast_channel *owner = NULL;
4249  struct ast_channel *bridge = NULL;
4250 
4251  /*
4252  * Clear fr->af.data if there is no data in the buffer. Things
4253  * like AST_CONTROL_HOLD without a suggested music class must
4254  * have a NULL pointer.
4255  */
4256  if (!fr->af.datalen) {
4257  memset(&fr->af.data, 0, sizeof(fr->af.data));
4258  }
4259 
4260  /* Attempt to recover wrapped timestamps */
4261  unwrap_timestamp(fr);
4262 
4263  /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
4264  if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
4265  fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
4266  else {
4267 #if 0
4268  ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
4269 #endif
4270  fr->af.delivery = ast_tv(0,0);
4271  }
4272 
4273  type = JB_TYPE_CONTROL;
4274  len = 0;
4275 
4276  if(fr->af.frametype == AST_FRAME_VOICE) {
4277  type = JB_TYPE_VOICE;
4278  len = ast_codec_get_samples(&fr->af) / (ast_format_rate(fr->af.subclass.codec) / 1000);
4279  } else if(fr->af.frametype == AST_FRAME_CNG) {
4280  type = JB_TYPE_SILENCE;
4281  }
4282 
4283  if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
4284  if (tsout)
4285  *tsout = fr->ts;
4286  __do_deliver(fr);
4287  return -1;
4288  }
4289 
4290  iax2_lock_owner(fr->callno);
4291  if (!iaxs[fr->callno]) {
4292  /* The call dissappeared so discard this frame that we could not send. */
4293  iax2_frame_free(fr);
4294  return -1;
4295  }
4296  if ((owner = iaxs[fr->callno]->owner))
4297  bridge = ast_bridged_channel(owner);
4298 
4299  /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
4300  * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
4301  if ( (!ast_test_flag64(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
4302  jb_frame frame;
4303 
4304  ast_channel_unlock(owner);
4305 
4306  /* deliver any frames in the jb */
4307  while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
4308  __do_deliver(frame.data);
4309  /* __do_deliver() can make the call disappear */
4310  if (!iaxs[fr->callno])
4311  return -1;
4312  }
4313 
4314  jb_reset(iaxs[fr->callno]->jb);
4315 
4316  ast_sched_thread_del(sched, iaxs[fr->callno]->jbid);
4317 
4318  /* deliver this frame now */
4319  if (tsout)
4320  *tsout = fr->ts;
4321  __do_deliver(fr);
4322  return -1;
4323  }
4324  if (owner) {
4325  ast_channel_unlock(owner);
4326  }
4327 
4328  /* insert into jitterbuffer */
4329  /* TODO: Perhaps we could act immediately if it's not droppable and late */
4330  ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
4331  calc_rxstamp(iaxs[fr->callno],fr->ts));
4332  if (ret == JB_DROP) {
4333  needfree++;
4334  } else if (ret == JB_SCHED) {
4335  update_jbsched(iaxs[fr->callno]);
4336  }
4337  if (tsout)
4338  *tsout = fr->ts;
4339  if (needfree) {
4340  /* Free our iax frame */
4341  iax2_frame_free(fr);
4342  return -1;
4343  }
4344  return 0;
4345 }
4346 
4347 static int transmit_frame(void *data)
4348 {
4349  struct iax_frame *fr = data;
4350 
4351  ast_mutex_lock(&iaxsl[fr->callno]);
4352 
4353  fr->sentyet = 1;
4354 
4355  if (iaxs[fr->callno]) {
4356  send_packet(fr);
4357  }
4358 
4359  if (fr->retries < 0) {
4360  ast_mutex_unlock(&iaxsl[fr->callno]);
4361  /* No retransmit requested */
4362  iax_frame_free(fr);
4363  } else {
4364  /* We need reliable delivery. Schedule a retransmission */
4365  AST_LIST_INSERT_TAIL(&frame_queue[fr->callno], fr, list);
4366  fr->retries++;
4367  fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
4368  ast_mutex_unlock(&iaxsl[fr->callno]);
4369  }
4370 
4371  return 0;
4372 }
4373 
4374 static int iax2_transmit(struct iax_frame *fr)
4375 {
4376  fr->sentyet = 0;
4377 
4378  return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
4379 }
4380 
4381 static int iax2_digit_begin(struct ast_channel *c, char digit)
4382 {
4383  return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
4384 }
4385 
4386 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
4387 {
4388  return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
4389 }
4390 
4391 static int iax2_sendtext(struct ast_channel *c, const char *text)
4392 {
4393 
4395  0, 0, (unsigned char *)text, strlen(text) + 1, -1);
4396 }
4397 
4398 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
4399 {
4401 }
4402 
4403 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
4404 {
4405  return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
4406 }
4407 
4408 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
4409 {
4410  unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
4411  ast_mutex_lock(&iaxsl[callno]);
4412  if (iaxs[callno])
4413  iaxs[callno]->owner = newchan;
4414  else
4415  ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
4416  ast_mutex_unlock(&iaxsl[callno]);
4417  return 0;
4418 }
4419 
4420 /*!
4421  * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
4422  * so do not call this with a pvt lock held.
4423  */
4424 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
4425 {
4426  struct ast_variable *var = NULL;
4427  struct ast_variable *tmp;
4428  struct iax2_peer *peer=NULL;
4429  time_t regseconds = 0, nowtime;
4430  int dynamic=0;
4431 
4432  if (peername) {
4433  var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
4434  if (!var && sin)
4435  var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
4436  } else if (sin) {
4437  char porta[25];
4438  sprintf(porta, "%d", ntohs(sin->sin_port));
4439  var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
4440  if (var) {
4441  /* We'll need the peer name in order to build the structure! */
4442  for (tmp = var; tmp; tmp = tmp->next) {
4443  if (!strcasecmp(tmp->name, "name"))
4444  peername = tmp->value;
4445  }
4446  }
4447  }
4448  if (!var && peername) { /* Last ditch effort */
4449  var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
4450  /*!\note
4451  * If this one loaded something, then we need to ensure that the host
4452  * field matched. The only reason why we can't have this as a criteria
4453  * is because we only have the IP address and the host field might be
4454  * set as a name (and the reverse PTR might not match).
4455  */
4456  if (var && sin) {
4457  for (tmp = var; tmp; tmp = tmp->next) {
4458  if (!strcasecmp(tmp->name, "host")) {
4459  struct ast_hostent ahp;
4460  struct hostent *hp;
4461  if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
4462  /* No match */
4463  ast_variables_destroy(var);
4464  var = NULL;
4465  }
4466  break;
4467  }
4468  }
4469  }
4470  }
4471  if (!var)
4472  return NULL;
4473 
4474  peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
4475 
4476  if (!peer) {
4477  ast_variables_destroy(var);
4478  return NULL;
4479  }
4480 
4481  for (tmp = var; tmp; tmp = tmp->next) {
4482  /* Make sure it's not a user only... */
4483  if (!strcasecmp(tmp->name, "type")) {
4484  if (strcasecmp(tmp->value, "friend") &&
4485  strcasecmp(tmp->value, "peer")) {
4486  /* Whoops, we weren't supposed to exist! */
4487  peer = peer_unref(peer);
4488  break;
4489  }
4490  } else if (!strcasecmp(tmp->name, "regseconds")) {
4491  ast_get_time_t(tmp->value, &regseconds, 0, NULL);
4492  } else if (!strcasecmp(tmp->name, "ipaddr")) {
4493  if (!ast_sockaddr_parse(&peer->addr, tmp->value, PARSE_PORT_IGNORE)) {
4494  ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
4495  }
4496  } else if (!strcasecmp(tmp->name, "port")) {
4497  ast_sockaddr_set_port(&peer->addr, atoi(tmp->value));
4498  } else if (!strcasecmp(tmp->name, "host")) {
4499  if (!strcasecmp(tmp->value, "dynamic"))
4500  dynamic = 1;
4501  }
4502  }
4503 
4504  ast_variables_destroy(var);
4505 
4506  if (!peer)
4507  return NULL;
4508 
4509  if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
4511  if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
4512  if (peer->expire > -1) {
4513  if (!ast_sched_thread_del(sched, peer->expire)) {
4514  peer->expire = -1;
4515  peer_unref(peer);
4516  }
4517  }
4518  peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
4519  if (peer->expire == -1)
4520  peer_unref(peer);
4521  }
4522  ao2_link(peers, peer);
4523  if (ast_test_flag64(peer, IAX_DYNAMIC))
4524  reg_source_db(peer);
4525  } else {
4527  }
4528 
4529  if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
4530  time(&nowtime);
4531  if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
4532  memset(&peer->addr, 0, sizeof(peer->addr));
4533  realtime_update_peer(peer->name, &peer->addr, 0);
4534  ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
4535  peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4536  }
4537  else {
4538  ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
4539  peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4540  }
4541  }
4542 
4543  return peer;
4544 }
4545 
4546 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
4547 {
4548  struct ast_variable *var;
4549  struct ast_variable *tmp;
4550  struct iax2_user *user=NULL;
4551 
4552  var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
4553  if (!var)
4554  var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
4555  if (!var && sin) {
4556  char porta[6];
4557  snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
4558  var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
4559  if (!var)
4560  var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
4561  }
4562  if (!var) { /* Last ditch effort */
4563  var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
4564  /*!\note
4565  * If this one loaded something, then we need to ensure that the host
4566  * field matched. The only reason why we can't have this as a criteria
4567  * is because we only have the IP address and the host field might be
4568  * set as a name (and the reverse PTR might not match).
4569  */
4570  if (var) {
4571  for (tmp = var; tmp; tmp = tmp->next) {
4572  if (!strcasecmp(tmp->name, "host")) {
4573  struct ast_hostent ahp;
4574  struct hostent *hp;
4575  if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
4576  /* No match */
4577  ast_variables_destroy(var);
4578  var = NULL;
4579  }
4580  break;
4581  }
4582  }
4583  }
4584  }
4585  if (!var)
4586  return NULL;
4587 
4588  tmp = var;
4589  while(tmp) {
4590  /* Make sure it's not a peer only... */
4591  if (!strcasecmp(tmp->name, "type")) {
4592  if (strcasecmp(tmp->value, "friend") &&
4593  strcasecmp(tmp->value, "user")) {
4594  return NULL;
4595  }
4596  }
4597  tmp = tmp->next;
4598  }
4599 
4600  user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
4601 
4602  ast_variables_destroy(var);
4603 
4604  if (!user)
4605  return NULL;
4606 
4607  if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
4609  ao2_link(users, user);
4610  } else {
4612  }
4613 
4614  return user;
4615 }
4616 
4617 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
4618 {
4619  char port[10];
4620  char regseconds[20];
4621  const char *sysname = ast_config_AST_SYSTEM_NAME;
4622  char *syslabel = NULL;
4623 
4624  if (ast_strlen_zero(sysname)) /* No system name, disable this */
4625  sysname = NULL;
4626  else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
4627  syslabel = "regserver";
4628 
4629  snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
4630  snprintf(port, sizeof(port), "%d", ast_sockaddr_port(sockaddr));
4631  ast_update_realtime("iaxpeers", "name", peername,
4632  "ipaddr", ast_sockaddr_stringify_addr(sockaddr), "port", port,
4633  "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslable can be NULL */
4634 }
4635 
4638  uint64_t flags;
4639  int maxtime;
4641  int found;
4642  int sockfd;
4643  int adsi;
4644  char username[80];
4645  char secret[80];
4646  char outkey[80];
4647  char timezone[80];
4648  char prefs[32];
4649  char cid_num[80];
4650  char cid_name[80];
4652  char peercontext[AST_MAX_CONTEXT];
4653  char mohinterpret[MAX_MUSICCLASS];
4654  char mohsuggest[MAX_MUSICCLASS];
4655 };
4656 
4657 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
4658 {
4659  struct iax2_peer *peer;
4660  int res = -1;
4661  struct ast_codec_pref ourprefs;
4662  struct sockaddr_in peer_addr;
4663 
4665  cai->sockfd = defaultsockfd;
4666  cai->maxtime = 0;
4667  sin->sin_family = AF_INET;
4668 
4669  if (!(peer = find_peer(peername, 1))) {
4670  struct ast_sockaddr sin_tmp;
4671 
4672  cai->found = 0;
4673  sin_tmp.ss.ss_family = AF_INET;
4674  if (ast_get_ip_or_srv(&sin_tmp, peername, srvlookup ? "_iax._udp" : NULL)) {
4675  ast_log(LOG_WARNING, "No such host: %s\n", peername);
4676  return -1;
4677  }
4678  ast_sockaddr_to_sin(&sin_tmp, sin);
4679  if (sin->sin_port == 0) {
4680  sin->sin_port = htons(IAX_DEFAULT_PORTNO);
4681  }
4682  /* use global iax prefs for unknown peer/user */
4683  /* But move the calling channel's native codec to the top of the preference list */
4684  memcpy(&ourprefs, &prefs, sizeof(ourprefs));
4685  if (c)
4686  ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
4687  ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
4688  return 0;
4689  }
4690 
4691  cai->found = 1;
4692 
4693  ast_sockaddr_to_sin(&peer->addr, &peer_addr);
4694 
4695  /* if the peer has no address (current or default), return failure */
4696  if (!(peer_addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
4697  goto return_unref;
4698  }
4699 
4700  /* if the peer is being monitored and is currently unreachable, return failure */
4701  if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
4702  goto return_unref;
4703 
4705  cai->maxtime = peer->maxms;
4706  cai->capability = peer->capability;
4707  cai->encmethods = peer->encmethods;
4708  cai->sockfd = peer->sockfd;
4709  cai->adsi = peer->adsi;
4710  memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
4711  /* Move the calling channel's native codec to the top of the preference list */
4712  if (c) {
4713  ast_debug(1, "prepending %llx to prefs\n", (unsigned long long) c->nativeformats);
4714  ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
4715  }
4716  ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
4717  ast_copy_string(cai->context, peer->context, sizeof(cai->context));
4718  ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
4719  ast_copy_string(cai->username, peer->username, sizeof(cai->username));
4720  ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
4721  ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
4722  ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
4723  ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
4724  ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
4725  ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
4726  if (ast_strlen_zero(peer->dbsecret)) {
4727  ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
4728  } else {
4729  char *family;
4730  char *key = NULL;
4731 
4732  family = ast_strdupa(peer->dbsecret);
4733  key = strchr(family, '/');
4734  if (key)
4735  *key++ = '\0';
4736  if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
4737  ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
4738  goto return_unref;
4739  }
4740  }
4741 
4742  if (peer_addr.sin_addr.s_addr) {
4743  sin->sin_addr = peer_addr.sin_addr;
4744  sin->sin_port = peer_addr.sin_port;
4745  } else {
4746  sin->sin_addr = peer->defaddr.sin_addr;
4747  sin->sin_port = peer->defaddr.sin_port;
4748  }
4749 
4750  res = 0;
4751 
4752 return_unref:
4753  peer_unref(peer);
4754 
4755  return res;
4756 }
4757 
4758 static void __auto_congest(const void *nothing)
4759 {
4760  int callno = PTR_TO_CALLNO(nothing);
4762  ast_mutex_lock(&iaxsl[callno]);
4763  if (iaxs[callno]) {
4764  iaxs[callno]->initid = -1;
4765  iax2_queue_frame(callno, &f);
4766  ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
4767  }
4768  ast_mutex_unlock(&iaxsl[callno]);
4769 }
4770 
4771 static int auto_congest(const void *data)
4772 {
4773 #ifdef SCHED_MULTITHREADED
4774  if (schedule_action(__auto_congest, data))
4775 #endif
4776  __auto_congest(data);
4777  return 0;
4778 }
4779 
4780 static unsigned int iax2_datetime(const char *tz)
4781 {
4782  struct timeval t = ast_tvnow();
4783  struct ast_tm tm;
4784  unsigned int tmp;
4785  ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
4786  tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
4787  tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
4788  tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
4789  tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
4790  tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
4791  tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
4792  return tmp;
4793 }
4794 
4796  char *username;
4797  char *password;
4798  char *key;
4799  char *peer;
4800  char *port;
4801  char *exten;
4802  char *context;
4803  char *options;
4804 };
4805 
4806 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
4807  struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
4808  int sockfd, struct iax_ie_data *ied)
4809 {
4810  struct {
4811  struct ast_iax2_full_hdr f;
4812  struct iax_ie_data ied;
4813  } data;
4814  size_t size = sizeof(struct ast_iax2_full_hdr);
4815 
4816  if (ied) {
4817  size += ied->pos;
4818  memcpy(&data.ied, ied->buf, ied->pos);
4819  }
4820 
4821  data.f.scallno = htons(0x8000 | callno);
4822  data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
4823  data.f.ts = htonl(ts);
4824  data.f.iseqno = seqno;
4825  data.f.oseqno = 0;
4826  data.f.type = AST_FRAME_IAX;
4827  data.f.csub = compress_subclass(command);
4828 
4829  iax_outputframe(NULL, &data.f, 0, sin, size - sizeof(struct ast_iax2_full_hdr));
4830 
4831  return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
4832 }
4833 
4834 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
4835 {
4836  /* first make sure their are two empty bytes left in ied->buf */
4837  if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
4838  ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
4839  ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
4840  pvt->calltoken_ie_len = 2;
4841  }
4842 }
4843 
4844 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
4845 {
4846  struct chan_iax2_pvt *pvt = iaxs[callno];
4847  int frametype = f->af.frametype;
4848  int subclass = f->af.subclass.integer;
4849  struct {
4850  struct ast_iax2_full_hdr fh;
4851  struct iax_ie_data ied;
4852  } data = {
4853  .ied.buf = { 0 },
4854  .ied.pos = 0,
4855  };
4856  /* total len - header len gives us the frame's IE len */
4857  int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
4858 
4859  if (!pvt) {
4860  return; /* this should not be possible if called from socket_process() */
4861  }
4862 
4863  /*
4864  * Check to make sure last frame sent is valid for call token resend
4865  * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog
4866  * 2. Frame should _NOT_ already have a destination callno
4867  * 3. Frame must be a valid iax_frame subclass capable of starting dialog
4868  * 4. Pvt must have a calltoken_ie_len which represents the number of
4869  * bytes at the end of the frame used for the previous calltoken ie.
4870  * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
4871  * 6. Total length of f->data must be _LESS_ than size of our data struct
4872  * because f->data must be able to fit within data.
4873  */
4874  if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
4875  || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
4876  (f->datalen > sizeof(data))) {
4877 
4878  return; /* ignore resend, token was not valid for the dialog */
4879  }
4880 
4881  /* token is valid
4882  * 1. Copy frame data over
4883  * 2. Redo calltoken IE, it will always be the last ie in the frame.
4884  * NOTE: Having the ie always be last is not protocol specified,
4885  * it is only an implementation choice. Since we only expect the ie to
4886  * be last for frames we have sent, this can no way be affected by
4887  * another end point.
4888  * 3. Remove frame from queue
4889  * 4. Free old frame
4890  * 5. Clear previous seqnos
4891  * 6. Resend with CALLTOKEN ie.
4892  */
4893 
4894  /* ---1.--- */
4895  memcpy(&data, f->data, f->datalen);
4896  data.ied.pos = ie_data_pos;
4897 
4898  /* ---2.--- */
4899  /* move to the beginning of the calltoken ie so we can write over it */
4900  data.ied.pos -= pvt->calltoken_ie_len;
4901  iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
4902 
4903  /* make sure to update token length incase it ever has to be stripped off again */
4904  pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
4905 
4906  /* ---3.--- */
4907  AST_LIST_REMOVE(&frame_queue[callno], f, list);
4908 
4909  /* ---4.--- */
4910  iax2_frame_free(f);
4911 
4912  /* ---5.--- */
4913  pvt->oseqno = 0;
4914  pvt->rseqno = 0;
4915  pvt->iseqno = 0;
4916  pvt->aseqno = 0;
4917  if (pvt->peercallno) {
4918  remove_by_peercallno(pvt);
4919  pvt->peercallno = 0;
4920  }
4921 
4922  /* ---6.--- */
4923  send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
4924 }
4925 
4926 static void requirecalltoken_mark_auto(const char *name, int subclass)
4927 {
4928  struct iax2_user *user = NULL;
4929  struct iax2_peer *peer = NULL;
4930 
4931  if (ast_strlen_zero(name)) {
4932  return; /* no username given */
4933  }
4934 
4935  if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
4937  } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
4939  }
4940 
4941  if (peer) {
4942  peer_unref(peer);
4943  }
4944  if (user) {
4945  user_unref(user);
4946  }
4947 }
4948 
4949 /*!
4950  * \internal
4951  *
4952  * \brief handles calltoken logic for a received iax_frame.
4953  *
4954  * \note frametype must be AST_FRAME_IAX.
4955  *
4956  * \note
4957  * Three different cases are possible here.
4958  * Case 1. An empty calltoken is provided. This means the client supports
4959  * calltokens but has not yet received one from us. In this case
4960  * a full calltoken IE is created and sent in a calltoken fullframe.
4961  * Case 2. A full calltoken is received and must be checked for validity.
4962  * Case 3. No calltoken is received indicating that the client does not
4963  * support calltokens. In this case it is up to the configuration
4964  * to decide how this should be handled (reject or permit without calltoken)
4965  */
4966 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
4967  struct sockaddr_in *sin, int fd)
4968 {
4969 #define CALLTOKEN_HASH_FORMAT "%s%d%u%d" /* address + port + ts + randomcalldata */
4970 #define CALLTOKEN_IE_FORMAT "%u?%s" /* time + ? + (40 char hash) */
4971  struct ast_str *buf = ast_str_alloca(256);
4972  time_t t = time(NULL);
4973  char hash[41]; /* 40 char sha1 hash */
4974  int subclass = uncompress_subclass(fh->csub);
4975 
4976  /* ----- Case 1 ----- */
4977  if (ies->calltoken && !ies->calltokendata) { /* empty calltoken is provided, client supports calltokens */
4978  struct iax_ie_data ied = {
4979  .buf = { 0 },
4980  .pos = 0,
4981  };
4982 
4983  /* create the hash with their address data and our timestamp */
4984  ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
4985  ast_sha1_hash(hash, ast_str_buffer(buf));
4986 
4987  ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
4989  send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
4990 
4991  return 1;
4992 
4993  /* ----- Case 2 ----- */
4994  } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
4995  char *rec_hash = NULL; /* the received hash, make sure it matches with ours. */
4996  char *rec_ts = NULL; /* received timestamp */
4997  unsigned int rec_time; /* received time_t */
4998 
4999  /* split the timestamp from the hash data */
5000  rec_hash = strchr((char *) ies->calltokendata, '?');
5001  if (rec_hash) {
5002  *rec_hash++ = '\0';
5003  rec_ts = (char *) ies->calltokendata;
5004  }
5005 
5006  /* check that we have valid data before we do any comparisons */
5007  if (!rec_hash || !rec_ts) {
5008  goto reject;
5009  } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
5010  goto reject;
5011  }
5012 
5013  /* create a hash with their address and the _TOKEN'S_ timestamp */
5014  ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
5015  ast_sha1_hash(hash, ast_str_buffer(buf));
5016 
5017  /* compare hashes and then check timestamp delay */
5018  if (strcmp(hash, rec_hash)) {
5019  ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
5020  goto reject; /* received hash does not match ours, reject */
5021  } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
5022  ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
5023  goto reject; /* too much delay, reject */
5024  }
5025 
5026  /* at this point the call token is valid, returning 0
5027  * will allow socket_process to continue as usual */
5028  requirecalltoken_mark_auto(ies->username, subclass);
5029  return 0;
5030 
5031  /* ----- Case 3 ----- */
5032  } else { /* calltokens are not supported for this client, how do we respond? */
5033  if (calltoken_required(sin, ies->username, subclass)) {
5034  ast_log(LOG_ERROR, "Call rejected, CallToken Support required. If unexpected, resolve by placing address %s in the calltokenoptional list or setting user %s requirecalltoken=no\n", ast_inet_ntoa(sin->sin_addr), S_OR(ies->username, "guest"));
5035  goto reject;
5036  }
5037  return 0; /* calltoken is not required for this addr, so permit it. */
5038  }
5039 
5040 reject:
5041  /* received frame has failed calltoken inspection, send apathetic reject messages */
5042  if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
5043  send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5044  } else {
5045  send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5046  }
5047 
5048  return 1;
5049 }
5050 
5051 /*!
5052  * \brief Parses an IAX dial string into its component parts.
5053  * \param data the string to be parsed
5054  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
5055  * \return nothing
5056  *
5057  * This function parses the string and fills the structure
5058  * with pointers to its component parts. The input string
5059  * will be modified.
5060  *
5061  * \note This function supports both plaintext passwords and RSA
5062  * key names; if the password string is formatted as '[keyname]',
5063  * then the keyname will be placed into the key field, and the
5064  * password field will be set to NULL.
5065  *
5066  * \note The dial string format is:
5067  * [username[:password]@]peer[:port][/exten[@@context]][/options]
5068  */
5069 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
5070 {
5071  if (ast_strlen_zero(data))
5072  return;
5073 
5074  pds->peer = strsep(&data, "/");
5075  pds->exten = strsep(&data, "/");
5076  pds->options = data;
5077 
5078  if (pds->exten) {
5079  data = pds->exten;
5080  pds->exten = strsep(&data, "@");
5081  pds->context = data;
5082  }
5083 
5084  if (strchr(pds->peer, '@')) {
5085  data = pds->peer;
5086  pds->username = strsep(&data, "@");
5087  pds->peer = data;
5088  }
5089 
5090  if (pds->username) {
5091  data = pds->username;
5092  pds->username = strsep(&data, ":");
5093  pds->password = data;
5094  }
5095 
5096  data = pds->peer;
5097  pds->peer = strsep(&data, ":");
5098  pds->port = data;
5099 
5100  /* check for a key name wrapped in [] in the secret position, if found,
5101  move it to the key field instead
5102  */
5103  if (pds->password && (pds->password[0] == '[')) {
5104  pds->key = ast_strip_quoted(pds->password, "[", "]");
5105  pds->password = NULL;
5106  }
5107 }
5108 
5109 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
5110 {
5111  struct sockaddr_in sin;
5112  char *l=NULL, *n=NULL, *tmpstr;
5113  struct iax_ie_data ied;
5114  char *defaultrdest = "s";
5115  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5116  struct parsed_dial_string pds;
5117  struct create_addr_info cai;
5118  struct ast_var_t *var;
5119  struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
5120  const char* osp_token_ptr;
5121  unsigned int osp_token_length;
5122  unsigned char osp_block_index;
5123  unsigned int osp_block_length;
5124  unsigned char osp_buffer[256];
5125 
5126  if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
5127  ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
5128  return -1;
5129  }
5130 
5131  memset(&cai, 0, sizeof(cai));
5133 
5134  memset(&pds, 0, sizeof(pds));
5135  tmpstr = ast_strdupa(dest);
5136  parse_dial_string(tmpstr, &pds);
5137 
5138  if (ast_strlen_zero(pds.peer)) {
5139  ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
5140  return -1;
5141  }
5142  if (!pds.exten) {
5143  pds.exten = defaultrdest;
5144  }
5145  if (create_addr(pds.peer, c, &sin, &cai)) {
5146  ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
5147  return -1;
5148  }
5149  if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) && !cai.encmethods) {
5150  ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
5152  return -1;
5153  }
5154  if (ast_strlen_zero(cai.secret) && ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
5155  ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
5156  return -1;
5157  }
5158  if (!pds.username && !ast_strlen_zero(cai.username))
5159  pds.username = cai.username;
5160  if (!pds.password && !ast_strlen_zero(cai.secret))
5161  pds.password = cai.secret;
5162  if (!pds.key && !ast_strlen_zero(cai.outkey))
5163  pds.key = cai.outkey;
5164  if (!pds.context && !ast_strlen_zero(cai.peercontext))
5165  pds.context = cai.peercontext;
5166 
5167  /* Keep track of the context for outgoing calls too */
5168  ast_copy_string(c->context, cai.context, sizeof(c->context));
5169 
5170  if (pds.port)
5171  sin.sin_port = htons(atoi(pds.port));
5172 
5173  l = c->connected.id.number.valid ? c->connected.id.number.str : NULL;
5174  n = c->connected.id.name.valid ? c->connected.id.name.str : NULL;
5175 
5176  /* Now build request */
5177  memset(&ied, 0, sizeof(ied));
5178 
5179  /* On new call, first IE MUST be IAX version of caller */
5182  if (pds.options && strchr(pds.options, 'a')) {
5183  /* Request auto answer */
5185  }
5186 
5187  /* WARNING: this breaks down at 190 bits! */
5189 
5190  if (l) {
5194  } else if (n) {
5197  } else {
5199  }
5200 
5203 
5204  if (n)
5206  if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
5207  && c->connected.ani.number.valid
5208  && c->connected.ani.number.str) {
5210  }
5211 
5212  if (!ast_strlen_zero(c->language))
5214  if (!ast_strlen_zero(c->dialed.number.str)) {
5216  }
5217  if (c->redirecting.from.number.valid
5220  }
5221 
5222  if (pds.context)
5224 
5225  if (pds.username)
5227 
5228  if (cai.encmethods)
5230 
5231  ast_mutex_lock(&iaxsl[callno]);
5232 
5233  if (!ast_strlen_zero(c->context))
5234  ast_string_field_set(iaxs[callno], context, c->context);
5235 
5236  if (pds.username)
5237  ast_string_field_set(iaxs[callno], username, pds.username);
5238 
5239  iaxs[callno]->encmethods = cai.encmethods;
5240 
5241  iaxs[callno]->adsi = cai.adsi;
5242 
5243  ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
5244  ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
5245 
5246  if (pds.key)
5247  ast_string_field_set(iaxs[callno], outkey, pds.key);
5248  if (pds.password)
5249  ast_string_field_set(iaxs[callno], secret, pds.password);
5250 
5253  iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
5257 
5258  if (iaxs[callno]->maxtime) {
5259  /* Initialize pingtime and auto-congest time */
5260  iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
5261  iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
5262  } else if (autokill) {
5263  iaxs[callno]->pingtime = autokill / 2;
5264  iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
5265  }
5266 
5267  /* Check if there is an OSP token */
5268  osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
5269  if (!ast_strlen_zero(osp_token_ptr)) {
5270  if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
5271  osp_block_index = 0;
5272  while (osp_token_length > 0) {
5273  osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
5274  osp_buffer[0] = osp_block_index;
5275  memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
5276  iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
5277  osp_block_index++;
5278  osp_token_ptr += osp_block_length;
5279  osp_token_length -= osp_block_length;
5280  }
5281  } else
5282  ast_log(LOG_WARNING, "OSP token is too long\n");
5283  } else if (iaxdebug)
5284  ast_debug(1, "OSP token is undefined\n");
5285 
5286  /* send the command using the appropriate socket for this peer */
5287  iaxs[callno]->sockfd = cai.sockfd;
5288 
5289  /* Add remote vars */
5290  if (variablestore) {
5291  AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
5292  ast_debug(1, "Found an IAX variable store on this channel\n");
5293  AST_LIST_LOCK(variablelist);
5294  AST_LIST_TRAVERSE(variablelist, var, entries) {
5295  char tmp[256];
5296  int i;
5297  ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
5298  /* Automatically divide the value up into sized chunks */
5299  for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
5300  snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
5301  iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
5302  }
5303  }
5304  AST_LIST_UNLOCK(variablelist);
5305  }
5306 
5307  /* Transmit the string in a "NEW" request */
5308  add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
5309  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
5310 
5311  ast_mutex_unlock(&iaxsl[callno]);
5313 
5314  return 0;
5315 }
5316 
5317 static int iax2_hangup(struct ast_channel *c)
5318 {
5319  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5320  struct iax_ie_data ied;
5321  int alreadygone;
5322  memset(&ied, 0, sizeof(ied));
5323  ast_mutex_lock(&iaxsl[callno]);
5324  if (callno && iaxs[callno]) {
5325  ast_debug(1, "We're hanging up %s now...\n", c->name);
5326  alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
5327  /* Send the hangup unless we have had a transmission error or are already gone */
5328  iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
5329  if (!iaxs[callno]->error && !alreadygone) {
5330  if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
5331  ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
5332  }
5333  if (!iaxs[callno]) {
5334  ast_mutex_unlock(&iaxsl[callno]);
5335  return 0;
5336  }
5337  }
5338  /* Explicitly predestroy it */
5339  iax2_predestroy(callno);
5340  /* If we were already gone to begin with, destroy us now */
5341  if (iaxs[callno] && alreadygone) {
5342  ast_debug(1, "Really destroying %s now...\n", c->name);
5343  iax2_destroy(callno);
5344  } else if (iaxs[callno]) {
5345  if (ast_sched_thread_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
5346  ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
5347  iax2_destroy(callno);
5348  }
5349  }
5350  } else if (c->tech_pvt) {
5351  /* If this call no longer exists, but the channel still
5352  * references it we need to set the channel's tech_pvt to null
5353  * to avoid ast_channel_free() trying to free it.
5354  */
5355  c->tech_pvt = NULL;
5356  }
5357  ast_mutex_unlock(&iaxsl[callno]);
5358  ast_verb(3, "Hungup '%s'\n", c->name);
5359  return 0;
5360 }
5361 
5362 /*!
5363  * \note expects the pvt to be locked
5364  */
5365 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
5366 {
5367  unsigned short callno = pvt->callno;
5368 
5369  if (!pvt->peercallno) {
5370  /* We don't know the remote side's call number, yet. :( */
5371  int count = 10;
5372  while (count-- && pvt && !pvt->peercallno) {
5373  DEADLOCK_AVOIDANCE(&iaxsl[callno]);
5374  pvt = iaxs[callno];
5375  }
5376  if (!pvt || !pvt->peercallno) {
5377  return -1;
5378  }
5379  }
5380 
5381  return 0;
5382 }
5383 
5384 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
5385 {
5386  struct ast_option_header *h;
5387  int res;
5388 
5389  switch (option) {
5390  case AST_OPTION_TXGAIN:
5391  case AST_OPTION_RXGAIN:
5392  /* these two cannot be sent, because they require a result */
5393  errno = ENOSYS;
5394  return -1;
5395  case AST_OPTION_OPRMODE:
5396  errno = EINVAL;
5397  return -1;
5400  {
5401  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5402  ast_mutex_lock(&iaxsl[callno]);
5403  if ((*(int *) data)) {
5404  ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
5405  } else {
5406  ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
5407  }
5408  ast_mutex_unlock(&iaxsl[callno]);
5409  return 0;
5410  }
5411  /* These options are sent to the other side across the network where
5412  * they will be passed to whatever channel is bridged there. Don't
5413  * do anything silly like pass an option that transmits pointers to
5414  * memory on this machine to a remote machine to use */
5416  case AST_OPTION_TDD:
5417  case AST_OPTION_RELAXDTMF:
5418  case AST_OPTION_AUDIO_MODE:
5420  case AST_OPTION_FAX_DETECT:
5421  {
5422  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5423  struct chan_iax2_pvt *pvt;
5424 
5425  ast_mutex_lock(&iaxsl[callno]);
5426  pvt = iaxs[callno];
5427 
5428  if (wait_for_peercallno(pvt)) {
5429  ast_mutex_unlock(&iaxsl[callno]);
5430  return -1;
5431  }
5432 
5433  ast_mutex_unlock(&iaxsl[callno]);
5434 
5435  if (!(h = ast_malloc(datalen + sizeof(*h)))) {
5436  return -1;
5437  }
5438 
5439  h->flag = AST_OPTION_FLAG_REQUEST;
5440  h->option = htons(option);
5441  memcpy(h->data, data, datalen);
5443  AST_CONTROL_OPTION, 0, (unsigned char *) h,
5444  datalen + sizeof(*h), -1);
5445  ast_free(h);
5446  return res;
5447  }
5448  default:
5449  return -1;
5450  }
5451 
5452  /* Just in case someone does a break instead of a return */
5453  return -1;
5454 }
5455 
5456 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
5457 {
5458  switch (option) {
5461  {
5462  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5463  ast_mutex_lock(&iaxsl[callno]);
5464  *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
5465  ast_mutex_unlock(&iaxsl[callno]);
5466  return 0;
5467  }
5468  default:
5469  return -1;
5470  }
5471 }
5472 
5473 static struct ast_frame *iax2_read(struct ast_channel *c)
5474 {
5475  ast_debug(1, "I should never be called!\n");
5476  return &ast_null_frame;
5477 }
5478 
5479 static int iax2_key_rotate(const void *vpvt)
5480 {
5481  int res = 0;
5482  struct chan_iax2_pvt *pvt = (void *) vpvt;
5483  struct MD5Context md5;
5484  char key[17] = "";
5485  struct iax_ie_data ied = {
5486  .pos = 0,
5487  };
5488 
5489  ast_mutex_lock(&iaxsl[pvt->callno]);
5490  pvt->keyrotateid =
5491  ast_sched_thread_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
5492 
5493  snprintf(key, sizeof(key), "%lX", (unsigned long)ast_random());
5494 
5495  MD5Init(&md5);
5496  MD5Update(&md5, (unsigned char *) key, strlen(key));
5497  MD5Final((unsigned char *) key, &md5);
5498 
5499  IAX_DEBUGDIGEST("Sending", key);
5500 
5501  iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
5502 
5503  res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
5504 
5505  build_ecx_key((unsigned char *) key, pvt);
5506 
5507  ast_mutex_unlock(&iaxsl[pvt->callno]);
5508 
5509  return res;
5510 }
5511 
5512 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
5513 {
5514  int res;
5515  struct iax_ie_data ied0;
5516  struct iax_ie_data ied1;
5517  unsigned int transferid = (unsigned int)ast_random();
5518 
5519  if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
5520  ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
5521  ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
5522  ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
5523  return 0;
5524  }
5525 
5526  memset(&ied0, 0, sizeof(ied0));
5527  iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
5528  iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
5529  iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
5530 
5531  memset(&ied1, 0, sizeof(ied1));
5532  iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
5533  iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
5534  iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
5535 
5536  res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
5537  if (res)
5538  return -1;
5539  res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
5540  if (res)
5541  return -1;
5542  iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5543  iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5544  return 0;
5545 }
5546 
5547 static void lock_both(unsigned short callno0, unsigned short callno1)
5548 {
5549  ast_mutex_lock(&iaxsl[callno0]);
5550  while (ast_mutex_trylock(&iaxsl[callno1])) {
5551  DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
5552  }
5553 }
5554 
5555 static void unlock_both(unsigned short callno0, unsigned short callno1)
5556 {
5557  ast_mutex_unlock(&iaxsl[callno1]);
5558  ast_mutex_unlock(&iaxsl[callno0]);
5559 }
5560 
5561 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
5562 {
5563  struct ast_channel *cs[3];
5564  struct ast_channel *who, *other;
5565  int to = -1;
5566  int res = -1;
5567  int transferstarted=0;
5568  struct ast_frame *f;
5569  unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
5570  unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
5571  struct timeval waittimer = {0, 0};
5572 
5573  /* We currently do not support native bridging if a timeoutms value has been provided */
5574  if (timeoutms > 0) {
5575  return AST_BRIDGE_FAILED;
5576  }
5577 
5578  timeoutms = -1;
5579 
5580  lock_both(callno0, callno1);
5581  if (!iaxs[callno0] || !iaxs[callno1]) {
5582  unlock_both(callno0, callno1);
5583  return AST_BRIDGE_FAILED;
5584  }
5585  /* Put them in native bridge mode */
5587  iaxs[callno0]->bridgecallno = callno1;
5588  iaxs[callno1]->bridgecallno = callno0;
5589  }
5590  unlock_both(callno0, callno1);
5591 
5592  /* If not, try to bridge until we can execute a transfer, if we can */
5593  cs[0] = c0;
5594  cs[1] = c1;
5595  for (/* ever */;;) {
5596  /* Check in case we got masqueraded into */
5597  if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
5598  ast_verb(3, "Can't masquerade, we're different...\n");
5599  /* Remove from native mode */
5600  if (c0->tech == &iax2_tech) {
5601  ast_mutex_lock(&iaxsl[callno0]);
5602  iaxs[callno0]->bridgecallno = 0;
5603  ast_mutex_unlock(&iaxsl[callno0]);
5604  }
5605  if (c1->tech == &iax2_tech) {
5606  ast_mutex_lock(&iaxsl[callno1]);
5607  iaxs[callno1]->bridgecallno = 0;
5608  ast_mutex_unlock(&iaxsl[callno1]);
5609  }
5610  return AST_BRIDGE_FAILED_NOWARN;
5611  }
5612  if (c0->nativeformats != c1->nativeformats) {
5613  char buf0[256];
5614  char buf1[256];
5615  ast_getformatname_multiple(buf0, sizeof(buf0), c0->nativeformats);
5616  ast_getformatname_multiple(buf1, sizeof(buf1), c1->nativeformats);
5617  ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n", buf0, buf1);
5618  /* Remove from native mode */
5619  lock_both(callno0, callno1);
5620  if (iaxs[callno0])
5621  iaxs[callno0]->bridgecallno = 0;
5622  if (iaxs[callno1])
5623  iaxs[callno1]->bridgecallno = 0;
5624  unlock_both(callno0, callno1);
5625  return AST_BRIDGE_FAILED_NOWARN;
5626  }
5627  /* check if transferred and if we really want native bridging */
5628  if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
5629  /* Try the transfer */
5630  if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
5631  ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
5632  ast_log(LOG_WARNING, "Unable to start the transfer\n");
5633  transferstarted = 1;
5634  }
5635  if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
5636  /* Call has been transferred. We're no longer involved */
5637  struct timeval now = ast_tvnow();
5638  if (ast_tvzero(waittimer)) {
5639  waittimer = now;
5640  } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
5643  *fo = NULL;
5644  *rc = c0;
5645  res = AST_BRIDGE_COMPLETE;
5646  break;
5647  }
5648  }
5649  to = 1000;
5650  who = ast_waitfor_n(cs, 2, &to);
5651  /* XXX This will need to be updated to calculate
5652  * timeout correctly once timeoutms is allowed to be
5653  * > 0. Right now, this can go badly if the waitfor
5654  * times out in less than a millisecond
5655  */
5656  if (timeoutms > -1) {
5657  timeoutms -= (1000 - to);
5658  if (timeoutms < 0)
5659  timeoutms = 0;
5660  }
5661  if (!who) {
5662  if (!timeoutms) {
5663  res = AST_BRIDGE_RETRY;
5664  break;
5665  }
5666  if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
5667  res = AST_BRIDGE_FAILED;
5668  break;
5669  }
5670  continue;
5671  }
5672  f = ast_read(who);
5673  if (!f) {
5674  *fo = NULL;
5675  *rc = who;
5676  res = AST_BRIDGE_COMPLETE;
5677  break;
5678  }
5679  other = (who == c0) ? c1 : c0; /* the 'other' channel */
5680  if (f->frametype == AST_FRAME_CONTROL && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
5681  switch (f->subclass.integer) {
5682  case AST_CONTROL_VIDUPDATE:
5683  case AST_CONTROL_SRCUPDATE:
5684  case AST_CONTROL_SRCCHANGE:
5686  ast_write(other, f);
5687  break;
5688  default:
5689  *fo = f;
5690  *rc = who;
5691  res = AST_BRIDGE_COMPLETE;
5692  break;
5693  }
5694  if (res == AST_BRIDGE_COMPLETE) {
5695  break;
5696  }
5697  } else if (f->frametype == AST_FRAME_VOICE
5698  || f->frametype == AST_FRAME_TEXT
5699  || f->frametype == AST_FRAME_VIDEO
5700  || f->frametype == AST_FRAME_IMAGE) {
5701  ast_write(other, f);
5702  } else if (f->frametype == AST_FRAME_DTMF) {
5703  /* monitored dtmf take out of the bridge.
5704  * check if we monitor the specific source.
5705  */
5706  int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
5707 
5708  if (flags & monitored_source) {
5709  *rc = who;
5710  *fo = f;
5711  res = AST_BRIDGE_COMPLETE;
5712  /* Remove from native mode */
5713  break;
5714  }
5715  ast_write(other, f);
5716  }
5717  ast_frfree(f);
5718  /* Swap who gets priority */
5719  cs[2] = cs[0];
5720  cs[0] = cs[1];
5721  cs[1] = cs[2];
5722  }
5723  lock_both(callno0, callno1);
5724  if(iaxs[callno0])
5725  iaxs[callno0]->bridgecallno = 0;
5726  if(iaxs[callno1])
5727  iaxs[callno1]->bridgecallno = 0;
5728  unlock_both(callno0, callno1);
5729  return res;
5730 }
5731 
5732 static int iax2_answer(struct ast_channel *c)
5733 {
5734  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5735  ast_debug(1, "Answering IAX2 call\n");
5736  ast_mutex_lock(&iaxsl[callno]);
5737  if (iaxs[callno])
5738  iax2_ami_channelupdate(iaxs[callno]);
5739  ast_mutex_unlock(&iaxsl[callno]);
5740  return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
5741 }
5742 
5743 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
5744 {
5745  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5746  struct chan_iax2_pvt *pvt;
5747  int res = 0;
5748 
5749  if (iaxdebug)
5750  ast_debug(1, "Indicating condition %d\n", condition);
5751 
5752  ast_mutex_lock(&iaxsl[callno]);
5753  pvt = iaxs[callno];
5754 
5755  if (wait_for_peercallno(pvt)) {
5756  res = -1;
5757  goto done;
5758  }
5759 
5760  switch (condition) {
5761  case AST_CONTROL_HOLD:
5762  if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5763  ast_moh_start(c, data, pvt->mohinterpret);
5764  goto done;
5765  }
5766  break;
5767  case AST_CONTROL_UNHOLD:
5768  if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5769  ast_moh_stop(c);
5770  goto done;
5771  }
5772  break;
5776  /* We are not configured to allow sending these updates. */
5777  ast_debug(2, "Callno %d: Config blocked sending control frame %d.\n",
5778  callno, condition);
5779  goto done;
5780  }
5781  break;
5782  }
5783 
5784  res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
5785 
5786 done:
5787  ast_mutex_unlock(&iaxsl[callno]);
5788 
5789  return res;
5790 }
5791 
5792 static int iax2_transfer(struct ast_channel *c, const char *dest)
5793 {
5794  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5795  struct iax_ie_data ied = { "", };
5796  char tmp[256], *context;
5798  ast_copy_string(tmp, dest, sizeof(tmp));
5799  context = strchr(tmp, '@');
5800  if (context) {
5801  *context = '\0';
5802  context++;
5803  }
5805  if (context)
5806  iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
5807  ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
5808  ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
5809  return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
5810 }
5811 
5812 static int iax2_getpeertrunk(struct sockaddr_in sin)
5813 {
5814  struct iax2_peer *peer;
5815  int res = 0;
5816  struct ao2_iterator i;
5817 
5818  i = ao2_iterator_init(peers, 0);
5819  while ((peer = ao2_iterator_next(&i))) {
5820  struct sockaddr_in peer_addr;
5821 
5822  ast_sockaddr_to_sin(&peer->addr, &peer_addr);
5823 
5824  if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
5825  (peer_addr.sin_port == sin.sin_port)) {
5826  res = ast_test_flag64(peer, IAX_TRUNK);
5827  peer_unref(peer);
5828  break;
5829  }
5830  peer_unref(peer);
5831  }
5833 
5834  return res;
5835 }
5836 
5837 /*! \brief Create new call, interface with the PBX core */
5838 static struct ast_channel *ast_iax2_new(int callno, int state, format_t capability, const char *linkedid, unsigned int cachable)
5839 {
5840  struct ast_channel *tmp;
5841  struct chan_iax2_pvt *i;
5842  struct ast_variable *v = NULL;
5843 
5844  if (!(i = iaxs[callno])) {
5845  ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
5846  return NULL;
5847  }
5848 
5849  /* Don't hold call lock */
5850  ast_mutex_unlock(&iaxsl[callno]);
5851  tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
5852  ast_mutex_lock(&iaxsl[callno]);
5853  if (i != iaxs[callno]) {
5854  if (tmp) {
5855  /* unlock and relock iaxsl[callno] to preserve locking order */
5856  ast_mutex_unlock(&iaxsl[callno]);
5857  tmp = ast_channel_release(tmp);
5858  ast_mutex_lock(&iaxsl[callno]);
5859  }
5860  return NULL;
5861  }
5863  if (!tmp)
5864  return NULL;
5865  tmp->tech = &iax2_tech;
5866  /* We can support any format by default, until we get restricted */
5867  tmp->nativeformats = capability;
5868  tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
5869  tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
5870  tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
5871 
5872  if (!ast_strlen_zero(i->parkinglot))
5874  /* Don't use ast_set_callerid() here because it will
5875  * generate a NewCallerID event before the NewChannel event */
5876  if (!ast_strlen_zero(i->ani)) {
5877  tmp->caller.ani.number.valid = 1;
5878  tmp->caller.ani.number.str = ast_strdup(i->ani);
5879  } else if (!ast_strlen_zero(i->cid_num)) {
5880  tmp->caller.ani.number.valid = 1;
5881  tmp->caller.ani.number.str = ast_strdup(i->cid_num);
5882  }
5883  tmp->dialed.number.str = ast_strdup(i->dnid);
5884  if (!ast_strlen_zero(i->rdnis)) {
5885  tmp->redirecting.from.number.valid = 1;
5887  }
5890  tmp->caller.id.number.plan = i->calling_ton;
5892  if (!ast_strlen_zero(i->language))
5893  ast_string_field_set(tmp, language, i->language);
5894  if (!ast_strlen_zero(i->accountcode))
5895  ast_string_field_set(tmp, accountcode, i->accountcode);
5896  if (i->amaflags)
5897  tmp->amaflags = i->amaflags;
5898  ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
5899  ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
5900  if (i->adsi)
5901  tmp->adsicpe = i->peeradsicpe;
5902  else
5904  i->owner = tmp;
5905  i->capability = capability;
5906 
5907  if (!cachable) {
5909  }
5910 
5911  /* Set inherited variables */
5912  if (i->vars) {
5913  for (v = i->vars ; v ; v = v->next)
5914  pbx_builtin_setvar_helper(tmp, v->name, v->value);
5915  }
5916  if (i->iaxvars) {
5917  struct ast_datastore *variablestore;
5918  struct ast_variable *var, *prev = NULL;
5919  AST_LIST_HEAD(, ast_var_t) *varlist;
5920  ast_debug(1, "Loading up the channel with IAXVARs\n");
5921  varlist = ast_calloc(1, sizeof(*varlist));
5922  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
5923  if (variablestore && varlist) {
5924  variablestore->data = varlist;
5925  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
5926  AST_LIST_HEAD_INIT(varlist);
5927  for (var = i->iaxvars; var; var = var->next) {
5928  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
5929  if (prev)
5930  ast_free(prev);
5931  prev = var;
5932  if (!newvar) {
5933  /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
5934  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
5935  } else {
5936  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
5937  }
5938  }
5939  if (prev)
5940  ast_free(prev);
5941  i->iaxvars = NULL;
5942  ast_channel_datastore_add(i->owner, variablestore);
5943  } else {
5944  if (variablestore) {
5945  ast_datastore_free(variablestore);
5946  }
5947  if (varlist) {
5948  ast_free(varlist);
5949  }
5950  }
5951  }
5952 
5953  if (state != AST_STATE_DOWN) {
5954  if (ast_pbx_start(tmp)) {
5955  ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
5956  ast_hangup(tmp);
5957  i->owner = NULL;
5958  return NULL;
5959  }
5960  }
5961 
5963  return tmp;
5964 }
5965 
5966 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
5967 {
5968  unsigned long int mssincetx; /* unsigned to handle overflows */
5969  long int ms, pred;
5970 
5971  tpeer->trunkact = *now;
5972  mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
5973  if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
5974  /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
5975  tpeer->txtrunktime = *now;
5976  tpeer->lastsent = 999999;
5977  }
5978  /* Update last transmit time now */
5979  tpeer->lasttxtime = *now;
5980 
5981  /* Calculate ms offset */
5982  ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
5983  /* Predict from last value */
5984  pred = tpeer->lastsent + sampms;
5985  if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
5986  ms = pred;
5987 
5988  /* We never send the same timestamp twice, so fudge a little if we must */
5989  if (ms == tpeer->lastsent)
5990  ms = tpeer->lastsent + 1;
5991  tpeer->lastsent = ms;
5992  return ms;
5993 }
5994 
5995 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
5996 {
5997  long ms; /* NOT unsigned */
5998  if (ast_tvzero(iaxs[callno]->rxcore)) {
5999  /* Initialize rxcore time if appropriate */
6000  iaxs[callno]->rxcore = ast_tvnow();
6001  /* Round to nearest 20ms so traces look pretty */
6002  iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
6003  }
6004  /* Calculate difference between trunk and channel */
6005  ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
6006  /* Return as the sum of trunk time and the difference between trunk and real time */
6007  return ms + ts;
6008 }
6009 
6010 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
6011 {
6012  int ms;
6013  int voice = 0;
6014  int genuine = 0;
6015  int adjust;
6016  int rate = ast_format_rate(f->subclass.codec) / 1000;
6017  struct timeval *delivery = NULL;
6018 
6019 
6020  /* What sort of frame do we have?: voice is self-explanatory
6021  "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
6022  non-genuine frames are CONTROL frames [ringing etc], DTMF
6023  The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
6024  the others need a timestamp slaved to the voice frames so that they go in sequence
6025  */
6026  if (f->frametype == AST_FRAME_VOICE) {
6027  voice = 1;
6028  delivery = &f->delivery;
6029  } else if (f->frametype == AST_FRAME_IAX) {
6030  genuine = 1;
6031  } else if (f->frametype == AST_FRAME_CNG) {
6032  p->notsilenttx = 0;
6033  }
6034 
6035  if (ast_tvzero(p->offset)) {
6036  p->offset = ast_tvnow();
6037  /* Round to nearest 20ms for nice looking traces */
6038  p->offset.tv_usec -= p->offset.tv_usec % 20000;
6039  }
6040  /* If the timestamp is specified, just send it as is */
6041  if (ts)
6042  return ts;
6043  /* If we have a time that the frame arrived, always use it to make our timestamp */
6044  if (delivery && !ast_tvzero(*delivery)) {
6045  ms = ast_tvdiff_ms(*delivery, p->offset);
6046  if (ms < 0) {
6047  ms = 0;
6048  }
6049  if (iaxdebug)
6050  ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
6051  } else {
6052  ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
6053  if (ms < 0)
6054  ms = 0;
6055  if (voice) {
6056  /* On a voice frame, use predicted values if appropriate */
6057  if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
6058  /* Adjust our txcore, keeping voice and non-voice synchronized */
6059  /* AN EXPLANATION:
6060  When we send voice, we usually send "calculated" timestamps worked out
6061  on the basis of the number of samples sent. When we send other frames,
6062  we usually send timestamps worked out from the real clock.
6063  The problem is that they can tend to drift out of step because the
6064  source channel's clock and our clock may not be exactly at the same rate.
6065  We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
6066  for this call. Moving it adjusts timestamps for non-voice frames.
6067  We make the adjustment in the style of a moving average. Each time we
6068  adjust p->offset by 10% of the difference between our clock-derived
6069  timestamp and the predicted timestamp. That's why you see "10000"
6070  below even though IAX2 timestamps are in milliseconds.
6071  The use of a moving average avoids offset moving too radically.
6072  Generally, "adjust" roams back and forth around 0, with offset hardly
6073  changing at all. But if a consistent different starts to develop it
6074  will be eliminated over the course of 10 frames (200-300msecs)
6075  */
6076  adjust = (ms - p->nextpred);
6077  if (adjust < 0)
6078  p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
6079  else if (adjust > 0)
6080  p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
6081 
6082  if (!p->nextpred) {
6083  p->nextpred = ms; /*f->samples / rate;*/
6084  if (p->nextpred <= p->lastsent)
6085  p->nextpred = p->lastsent + 3;
6086  }
6087  ms = p->nextpred;
6088  } else {
6089  /* in this case, just use the actual
6090  * time, since we're either way off
6091  * (shouldn't happen), or we're ending a
6092  * silent period -- and seed the next
6093  * predicted time. Also, round ms to the
6094  * next multiple of frame size (so our
6095  * silent periods are multiples of
6096  * frame size too) */
6097 
6098  if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
6099  ast_debug(1, "predicted timestamp skew (%d) > max (%d), using real ts instead.\n",
6100  abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
6101 
6102  if (f->samples >= rate) /* check to make sure we don't core dump */
6103  {
6104  int diff = ms % (f->samples / rate);
6105  if (diff)
6106  ms += f->samples/rate - diff;
6107  }
6108 
6109  p->nextpred = ms;
6110  p->notsilenttx = 1;
6111  }
6112  } else if ( f->frametype == AST_FRAME_VIDEO ) {
6113  /*
6114  * IAX2 draft 03 says that timestamps MUST be in order.
6115  * It does not say anything about several frames having the same timestamp
6116  * When transporting video, we can have a frame that spans multiple iax packets
6117  * (so called slices), so it would make sense to use the same timestamp for all of
6118  * them
6119  * We do want to make sure that frames don't go backwards though
6120  */
6121  if ( (unsigned int)ms < p->lastsent )
6122  ms = p->lastsent;
6123  } else {
6124  /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
6125  it's a genuine frame */
6126  if (genuine) {
6127  /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
6128  if (ms <= p->lastsent)
6129  ms = p->lastsent + 3;
6130  } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
6131  /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
6132  ms = p->lastsent + 3;
6133  }
6134  }
6135  }
6136  p->lastsent = ms;
6137  if (voice)
6138  p->nextpred = p->nextpred + f->samples / rate;
6139  return ms;
6140 }
6141 
6142 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
6143 {
6144  /* Returns where in "receive time" we are. That is, how many ms
6145  since we received (or would have received) the frame with timestamp 0 */
6146  int ms;
6147 #ifdef IAXTESTS
6148  int jit;
6149 #endif /* IAXTESTS */
6150  /* Setup rxcore if necessary */
6151  if (ast_tvzero(p->rxcore)) {
6152  p->rxcore = ast_tvnow();
6153  if (iaxdebug)
6154  ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %ums\n",
6155  p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
6156  p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
6157 #if 1
6158  if (iaxdebug)
6159  ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
6160  p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
6161 #endif
6162  }
6163 
6164  ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
6165 #ifdef IAXTESTS
6166  if (test_jit) {
6167  if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
6168  jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
6169  if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
6170  jit = -jit;
6171  ms += jit;
6172  }
6173  }
6174  if (test_late) {
6175  ms += test_late;
6176  test_late = 0;
6177  }
6178 #endif /* IAXTESTS */
6179  return ms;
6180 }
6181 
6182 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
6183 {
6184  struct iax2_trunk_peer *tpeer = NULL;
6185 
6186  /* Finds and locks trunk peer */
6187  AST_LIST_LOCK(&tpeers);
6188 
6189  AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
6190  if (!inaddrcmp(&tpeer->addr, sin)) {
6191  ast_mutex_lock(&tpeer->lock);
6192  break;
6193  }
6194  }
6195 
6196  if (!tpeer) {
6197  if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
6198  ast_mutex_init(&tpeer->lock);
6199  tpeer->lastsent = 9999;
6200  memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
6201  tpeer->trunkact = ast_tvnow();
6202  ast_mutex_lock(&tpeer->lock);
6203  tpeer->sockfd = fd;
6204 #ifdef SO_NO_CHECK
6205  setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
6206 #endif
6207  ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
6208  AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
6209  }
6210  }
6211 
6212  AST_LIST_UNLOCK(&tpeers);
6213 
6214  return tpeer;
6215 }
6216 
6217 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
6218 {
6219  struct ast_frame *f;
6220  struct iax2_trunk_peer *tpeer;
6221  void *tmp, *ptr;
6222  struct timeval now;
6223  struct ast_iax2_meta_trunk_entry *met;
6224  struct ast_iax2_meta_trunk_mini *mtm;
6225 
6226  f = &fr->af;
6227  tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
6228  if (tpeer) {
6229  if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
6230  /* Need to reallocate space */
6231  if (tpeer->trunkdataalloc < trunkmaxsize) {
6232  if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
6233  ast_mutex_unlock(&tpeer->lock);
6234  return -1;
6235  }
6236 
6238  tpeer->trunkdata = tmp;
6239  ast_debug(1, "Expanded trunk '%s:%d' to %u bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
6240  } else {
6241  ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
6242  ast_mutex_unlock(&tpeer->lock);
6243  return -1;
6244  }
6245  }
6246 
6247  /* Append to meta frame */
6248  ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
6249  if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
6250  mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
6251  mtm->len = htons(f->datalen);
6252  mtm->mini.callno = htons(pvt->callno);
6253  mtm->mini.ts = htons(0xffff & fr->ts);
6254  ptr += sizeof(struct ast_iax2_meta_trunk_mini);
6255  tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
6256  } else {
6257  met = (struct ast_iax2_meta_trunk_entry *)ptr;
6258  /* Store call number and length in meta header */
6259  met->callno = htons(pvt->callno);
6260  met->len = htons(f->datalen);
6261  /* Advance pointers/decrease length past trunk entry header */
6262  ptr += sizeof(struct ast_iax2_meta_trunk_entry);
6263  tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
6264  }
6265  /* Copy actual trunk data */
6266  memcpy(ptr, f->data.ptr, f->datalen);
6267  tpeer->trunkdatalen += f->datalen;
6268 
6269  tpeer->calls++;
6270 
6271  /* track the largest mtu we actually have sent */
6272  if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
6273  trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
6274 
6275  /* if we have enough for a full MTU, ship it now without waiting */
6276  if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
6277  now = ast_tvnow();
6278  send_trunk(tpeer, &now);
6279  trunk_untimed ++;
6280  }
6281 
6282  ast_mutex_unlock(&tpeer->lock);
6283  }
6284  return 0;
6285 }
6286 
6287 /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
6288  * before the encryption data. This function randomizes that data. */
6289 static void build_rand_pad(unsigned char *buf, ssize_t len)
6290 {
6291  long tmp;
6292  for (tmp = ast_random(); len > 0; tmp = ast_random()) {
6293  memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
6294  buf += sizeof(tmp);
6295  len -= sizeof(tmp);
6296  }
6297 }
6298 
6299 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6300 {
6301  build_ecx_key(digest, pvt);
6302  ast_aes_set_decrypt_key(digest, &pvt->dcx);
6303 }
6304 
6305 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6306 {
6307  /* it is required to hold the corresponding decrypt key to our encrypt key
6308  * in the pvt struct because queued frames occasionally need to be decrypted and
6309  * re-encrypted when updated for a retransmission */
6310  build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
6311  ast_aes_set_encrypt_key(digest, &pvt->ecx);
6312  ast_aes_set_decrypt_key(digest, &pvt->mydcx);
6313 }
6314 
6315 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
6316 {
6317 #if 0
6318  /* Debug with "fake encryption" */
6319  int x;
6320  if (len % 16)
6321  ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6322  for (x=0;x<len;x++)
6323  dst[x] = src[x] ^ 0xff;
6324 #else
6325  unsigned char lastblock[16] = { 0 };
6326  int x;
6327  while(len > 0) {
6328  ast_aes_decrypt(src, dst, dcx);
6329  for (x=0;x<16;x++)
6330  dst[x] ^= lastblock[x];
6331  memcpy(lastblock, src, sizeof(lastblock));
6332  dst += 16;
6333  src += 16;
6334  len -= 16;
6335  }
6336 #endif
6337 }
6338 
6339 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
6340 {
6341 #if 0
6342  /* Debug with "fake encryption" */
6343  int x;
6344  if (len % 16)
6345  ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6346  for (x=0;x<len;x++)
6347  dst[x] = src[x] ^ 0xff;
6348 #else
6349  unsigned char curblock[16] = { 0 };
6350  int x;
6351  while(len > 0) {
6352  for (x=0;x<16;x++)
6353  curblock[x] ^= src[x];
6354  ast_aes_encrypt(curblock, dst, ecx);
6355  memcpy(curblock, dst, sizeof(curblock));
6356  dst += 16;
6357  src += 16;
6358  len -= 16;
6359  }
6360 #endif
6361 }
6362 
6363 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6364 {
6365  int padding;
6366  unsigned char *workspace;
6367 
6368  workspace = ast_alloca(*datalen);
6369  memset(f, 0, sizeof(*f));
6370  if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6371  struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6372  if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
6373  return -1;
6374  /* Decrypt */
6375  memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
6376 
6377  padding = 16 + (workspace[15] & 0x0f);
6378  if (iaxdebug)
6379  ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, (unsigned)workspace[15]);
6380  if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
6381  return -1;
6382 
6383  *datalen -= padding;
6384  memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6385  f->frametype = fh->type;
6386  if (f->frametype == AST_FRAME_VIDEO) {
6387  f->subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
6388  } else if (f->frametype == AST_FRAME_VOICE) {
6390  } else {
6392  }
6393  } else {
6394  struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6395  if (iaxdebug)
6396  ast_debug(1, "Decoding mini with length %d\n", *datalen);
6397  if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
6398  return -1;
6399  /* Decrypt */
6400  memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
6401  padding = 16 + (workspace[15] & 0x0f);
6402  if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
6403  return -1;
6404  *datalen -= padding;
6405  memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6406  }
6407  return 0;
6408 }
6409 
6410 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
6411 {
6412  int padding;
6413  unsigned char *workspace;
6414  workspace = ast_alloca(*datalen + 32);
6415  if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6416  struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6417  if (iaxdebug)
6418  ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
6419  padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
6420  padding = 16 + (padding & 0xf);
6421  memcpy(workspace, poo, padding);
6422  memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6423  workspace[15] &= 0xf0;
6424  workspace[15] |= (padding & 0xf);
6425  if (iaxdebug)
6426  ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, (unsigned)workspace[15]);
6427  *datalen += padding;
6428  memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
6429  if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
6430  memcpy(poo, workspace + *datalen - 32, 32);
6431  } else {
6432  struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6433  if (iaxdebug)
6434  ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
6435  padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
6436  padding = 16 + (padding & 0xf);
6437  memcpy(workspace, poo, padding);
6438  memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6439  workspace[15] &= 0xf0;
6440  workspace[15] |= (padding & 0x0f);
6441  *datalen += padding;
6442  memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
6443  if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
6444  memcpy(poo, workspace + *datalen - 32, 32);
6445  }
6446  return 0;
6447 }
6448 
6449 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6450 {
6451  int res=-1;
6452  if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
6453  /* Search for possible keys, given secrets */
6454  struct MD5Context md5;
6455  unsigned char digest[16];
6456  char *tmppw, *stringp;
6457 
6458  tmppw = ast_strdupa(iaxs[callno]->secret);
6459  stringp = tmppw;
6460  while ((tmppw = strsep(&stringp, ";"))) {
6461  MD5Init(&md5);
6462  MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
6463  MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
6464  MD5Final(digest, &md5);
6465  build_encryption_keys(digest, iaxs[callno]);
6466  res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6467  if (!res) {
6468  ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
6469  break;
6470  }
6471  }
6472  } else
6473  res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6474  return res;
6475 }
6476 
6477 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
6478 {
6479  /* Queue a packet for delivery on a given private structure. Use "ts" for
6480  timestamp, or calculate if ts is 0. Send immediately without retransmission
6481  or delayed, with retransmission */
6482  struct ast_iax2_full_hdr *fh;
6483  struct ast_iax2_mini_hdr *mh;
6484  struct ast_iax2_video_hdr *vh;
6485  struct {
6486  struct iax_frame fr2;
6487  unsigned char buffer[4096];
6488  } frb;
6489  struct iax_frame *fr;
6490  int res;
6491  int sendmini=0;
6492  unsigned int lastsent;
6493  unsigned int fts;
6494 
6495  frb.fr2.afdatalen = sizeof(frb.buffer);
6496 
6497  if (!pvt) {
6498  ast_log(LOG_WARNING, "No private structure for packet?\n");
6499  return -1;
6500  }
6501 
6502  lastsent = pvt->lastsent;
6503 
6504  /* Calculate actual timestamp */
6505  fts = calc_timestamp(pvt, ts, f);
6506 
6507  /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
6508  * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
6509  * increment the "predicted timestamps" for voice, if we're predicting */
6510  if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
6511  return 0;
6512 #if 0
6514  "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
6515  *("=!" + (f->frametype == AST_FRAME_VOICE)),
6516  IAX_CALLENCRYPTED(pvt) ? "" : "not ",
6517  pvt->keyrotateid != -1 ? "" : "no "
6518  );
6519 #endif
6520  if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
6521  iax2_key_rotate(pvt);
6522  }
6523 
6524  if ((ast_test_flag64(pvt, IAX_TRUNK) ||
6525  (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
6526  ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
6527  /* High two bytes are the same on timestamp, or sending on a trunk */ &&
6528  (f->frametype == AST_FRAME_VOICE)
6529  /* is a voice frame */ &&
6530  (f->subclass.codec == pvt->svoiceformat)
6531  /* is the same type */ ) {
6532  /* Force immediate rather than delayed transmission */
6533  now = 1;
6534  /* Mark that mini-style frame is appropriate */
6535  sendmini = 1;
6536  }
6537  if ( f->frametype == AST_FRAME_VIDEO ) {
6538  /*
6539  * If the lower 15 bits of the timestamp roll over, or if
6540  * the video format changed then send a full frame.
6541  * Otherwise send a mini video frame
6542  */
6543  if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
6544  ((f->subclass.codec & ~0x1LL) == pvt->svideoformat)
6545  ) {
6546  now = 1;
6547  sendmini = 1;
6548  } else {
6549  now = 0;
6550  sendmini = 0;
6551  }
6552  pvt->lastvsent = fts;
6553  }
6554  if (f->frametype == AST_FRAME_IAX) {
6555  /* 0x8000 marks this message as TX:, this bit will be stripped later */
6557  if (!pvt->first_iax_message) {
6558  pvt->first_iax_message = pvt->last_iax_message;
6559  }
6560  }
6561  /* Allocate an iax_frame */
6562  if (now) {
6563  fr = &frb.fr2;
6564  } else
6566  if (!fr) {
6567  ast_log(LOG_WARNING, "Out of memory\n");
6568  return -1;
6569  }
6570  /* Copy our prospective frame into our immediate or retransmitted wrapper */
6571  iax_frame_wrap(fr, f);
6572 
6573  fr->ts = fts;
6574  fr->callno = pvt->callno;
6575  fr->transfer = transfer;
6576  fr->final = final;
6577  fr->encmethods = 0;
6578  if (!sendmini) {
6579  /* We need a full frame */
6580  if (seqno > -1)
6581  fr->oseqno = seqno;
6582  else
6583  fr->oseqno = pvt->oseqno++;
6584  fr->iseqno = pvt->iseqno;
6585  fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
6586  fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
6587  fh->ts = htonl(fr->ts);
6588  fh->oseqno = fr->oseqno;
6589  if (transfer) {
6590  fh->iseqno = 0;
6591  } else
6592  fh->iseqno = fr->iseqno;
6593  /* Keep track of the last thing we've acknowledged */
6594  if (!transfer)
6595  pvt->aseqno = fr->iseqno;
6596  fh->type = fr->af.frametype & 0xFF;
6597 
6598  if (fr->af.frametype == AST_FRAME_VIDEO) {
6599  fh->csub = compress_subclass(fr->af.subclass.codec & ~0x1LL) | ((fr->af.subclass.codec & 0x1LL) << 6);
6600  } else if (fr->af.frametype == AST_FRAME_VOICE) {
6601  fh->csub = compress_subclass(fr->af.subclass.codec);
6602  } else {
6604  }
6605 
6606  if (transfer) {
6607  fr->dcallno = pvt->transfercallno;
6608  } else
6609  fr->dcallno = pvt->peercallno;
6610  fh->dcallno = htons(fr->dcallno);
6611  fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
6612  fr->data = fh;
6613  fr->retries = 0;
6614  /* Retry after 2x the ping time has passed */
6615  fr->retrytime = pvt->pingtime * 2;
6616  if (fr->retrytime < MIN_RETRY_TIME)
6617  fr->retrytime = MIN_RETRY_TIME;
6618  if (fr->retrytime > MAX_RETRY_TIME)
6619  fr->retrytime = MAX_RETRY_TIME;
6620  /* Acks' don't get retried */
6621  if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
6622  fr->retries = -1;
6623  else if (f->frametype == AST_FRAME_VOICE)
6624  pvt->svoiceformat = f->subclass.codec;
6625  else if (f->frametype == AST_FRAME_VIDEO)
6626  pvt->svideoformat = f->subclass.codec & ~0x1LL;
6627  if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6628  if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
6629  if (fr->transfer)
6630  iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6631  else
6632  iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6633  encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
6634  fr->encmethods = pvt->encmethods;
6635  fr->ecx = pvt->ecx;
6636  fr->mydcx = pvt->mydcx;
6637  memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
6638  } else
6639  ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6640  }
6641 
6642  if (now) {
6643  res = send_packet(fr);
6644  } else
6645  res = iax2_transmit(fr);
6646  } else {
6647  if (ast_test_flag64(pvt, IAX_TRUNK)) {
6648  iax2_trunk_queue(pvt, fr);
6649  res = 0;
6650  } else if (fr->af.frametype == AST_FRAME_VIDEO) {
6651  /* Video frame have no sequence number */
6652  fr->oseqno = -1;
6653  fr->iseqno = -1;
6654  vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
6655  vh->zeros = 0;
6656  vh->callno = htons(0x8000 | fr->callno);
6657  vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.codec & 0x1LL ? 0x8000 : 0));
6658  fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
6659  fr->data = vh;
6660  fr->retries = -1;
6661  res = send_packet(fr);
6662  } else {
6663  /* Mini-frames have no sequence number */
6664  fr->oseqno = -1;
6665  fr->iseqno = -1;
6666  /* Mini frame will do */
6667  mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
6668  mh->callno = htons(fr->callno);
6669  mh->ts = htons(fr->ts & 0xFFFF);
6670  fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
6671  fr->data = mh;
6672  fr->retries = -1;
6673  if (pvt->transferring == TRANSFER_MEDIAPASS)
6674  fr->transfer = 1;
6675  if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6676  if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
6677  encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
6678  } else
6679  ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6680  }
6681  res = send_packet(fr);
6682  }
6683  }
6684  return res;
6685 }
6686 
6687 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6688 {
6689  regex_t regexbuf;
6690  int havepattern = 0;
6691 
6692 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
6693 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
6694 
6695  struct iax2_user *user = NULL;
6696  char auth[90];
6697  char *pstr = "";
6698  struct ao2_iterator i;
6699 
6700  switch (cmd) {
6701  case CLI_INIT:
6702  e->command = "iax2 show users [like]";
6703  e->usage =
6704  "Usage: iax2 show users [like <pattern>]\n"
6705  " Lists all known IAX2 users.\n"
6706  " Optional regular expression pattern is used to filter the user list.\n";
6707  return NULL;
6708  case CLI_GENERATE:
6709  return NULL;
6710  }
6711 
6712  switch (a->argc) {
6713  case 5:
6714  if (!strcasecmp(a->argv[3], "like")) {
6715  if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
6716  return CLI_SHOWUSAGE;
6717  havepattern = 1;
6718  } else
6719  return CLI_SHOWUSAGE;
6720  case 3:
6721  break;
6722  default:
6723  return CLI_SHOWUSAGE;
6724  }
6725 
6726  ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
6727  i = ao2_iterator_init(users, 0);
6728  for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
6729  if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
6730  continue;
6731 
6732  if (!ast_strlen_zero(user->secret)) {
6733  ast_copy_string(auth,user->secret, sizeof(auth));
6734  } else if (!ast_strlen_zero(user->inkeys)) {
6735  snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
6736  } else
6737  ast_copy_string(auth, "-no secret-", sizeof(auth));
6738 
6739  if(ast_test_flag64(user, IAX_CODEC_NOCAP))
6740  pstr = "REQ Only";
6741  else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
6742  pstr = "Disabled";
6743  else
6744  pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
6745 
6746  ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
6747  user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
6748  user->ha ? "Yes" : "No", pstr);
6749  }
6751 
6752  if (havepattern)
6753  regfree(&regexbuf);
6754 
6755  return CLI_SUCCESS;
6756 #undef FORMAT
6757 #undef FORMAT2
6758 }
6759 
6760 static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
6761 {
6762  regex_t regexbuf;
6763  int havepattern = 0;
6764  int total_peers = 0;
6765  int online_peers = 0;
6766  int offline_peers = 0;
6767  int unmonitored_peers = 0;
6768  struct ao2_iterator i;
6769 
6770 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s\n"
6771 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s\n"
6772 
6773  struct iax2_peer *peer = NULL;
6774  char name[256];
6775  struct ast_str *encmethods = ast_str_alloca(256);
6776  int registeredonly=0;
6777  char idtext[256] = "";
6778  switch (argc) {
6779  case 6:
6780  if (!strcasecmp(argv[3], "registered"))
6781  registeredonly = 1;
6782  else
6783  return RESULT_SHOWUSAGE;
6784  if (!strcasecmp(argv[4], "like")) {
6785  if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
6786  return RESULT_SHOWUSAGE;
6787  havepattern = 1;
6788  } else
6789  return RESULT_SHOWUSAGE;
6790  break;
6791  case 5:
6792  if (!strcasecmp(argv[3], "like")) {
6793  if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
6794  return RESULT_SHOWUSAGE;
6795  havepattern = 1;
6796  } else
6797  return RESULT_SHOWUSAGE;
6798  break;
6799  case 4:
6800  if (!strcasecmp(argv[3], "registered"))
6801  registeredonly = 1;
6802  else
6803  return RESULT_SHOWUSAGE;
6804  break;
6805  case 3:
6806  break;
6807  default:
6808  return RESULT_SHOWUSAGE;
6809  }
6810 
6811 
6812  if (!s)
6813  ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status");
6814 
6815  i = ao2_iterator_init(peers, 0);
6816  for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
6817  char nm[20];
6818  char status[20];
6819  int retstatus;
6820  struct sockaddr_in peer_addr;
6821 
6822  ast_sockaddr_to_sin(&peer->addr, &peer_addr);
6823 
6824  if (registeredonly && !peer_addr.sin_addr.s_addr) {
6825  continue;
6826  }
6827  if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
6828  continue;
6829  }
6830 
6831  if (!ast_strlen_zero(peer->username))
6832  snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
6833  else
6834  ast_copy_string(name, peer->name, sizeof(name));
6835 
6836  encmethods_to_str(peer->encmethods, &encmethods);
6837  retstatus = peer_status(peer, status, sizeof(status));
6838  if (retstatus > 0)
6839  online_peers++;
6840  else if (!retstatus)
6841  offline_peers++;
6842  else
6843  unmonitored_peers++;
6844 
6845  ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
6846 
6847  if (s) {
6848  astman_append(s,
6849  "Event: PeerEntry\r\n%s"
6850  "Channeltype: IAX2\r\n"
6851  "ObjectName: %s\r\n"
6852  "ChanObjectType: peer\r\n"
6853  "IPaddress: %s\r\n"
6854  "IPport: %d\r\n"
6855  "Dynamic: %s\r\n"
6856  "Trunk: %s\r\n"
6857  "Encryption: %s\r\n"
6858  "Status: %s\r\n\r\n",
6859  idtext,
6860  name,
6862  ast_sockaddr_port(&peer->addr),
6863  ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
6864  ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
6865  peer->encmethods ? ast_str_buffer(encmethods) : "no",
6866  status);
6867  } else {
6868  ast_cli(fd, FORMAT, name,
6870  ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
6871  nm,
6872  ast_sockaddr_port(&peer->addr),
6873  ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
6874  peer->encmethods ? "(E)" : " ",
6875  status);
6876  }
6877  total_peers++;
6878  }
6880 
6881  if (!s)
6882  ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
6883  total_peers, online_peers, offline_peers, unmonitored_peers);
6884 
6885  if (havepattern)
6886  regfree(&regexbuf);
6887 
6888  if (total)
6889  *total = total_peers;
6890 
6891  return RESULT_SUCCESS;
6892 #undef FORMAT
6893 #undef FORMAT2
6894 }
6895 
6896 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6897 {
6898  struct iax2_thread *thread = NULL;
6899  time_t t;
6900  int threadcount = 0, dynamiccount = 0;
6901  char type;
6902 
6903  switch (cmd) {
6904  case CLI_INIT:
6905  e->command = "iax2 show threads";
6906  e->usage =
6907  "Usage: iax2 show threads\n"
6908  " Lists status of IAX helper threads\n";
6909  return NULL;
6910  case CLI_GENERATE:
6911  return NULL;
6912  }
6913  if (a->argc != 3)
6914  return CLI_SHOWUSAGE;
6915 
6916  ast_cli(a->fd, "IAX2 Thread Information\n");
6917  time(&t);
6918  ast_cli(a->fd, "Idle Threads:\n");
6920  AST_LIST_TRAVERSE(&idle_list, thread, list) {
6921 #ifdef DEBUG_SCHED_MULTITHREAD
6922  ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
6923  thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
6924 #else
6925  ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
6926  thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
6927 #endif
6928  threadcount++;
6929  }
6931  ast_cli(a->fd, "Active Threads:\n");
6933  AST_LIST_TRAVERSE(&active_list, thread, list) {
6934  if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
6935  type = 'D';
6936  else
6937  type = 'P';
6938 #ifdef DEBUG_SCHED_MULTITHREAD
6939  ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d, func='%s'\n",
6940  type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
6941 #else
6942  ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d\n",
6943  type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
6944 #endif
6945  threadcount++;
6946  }
6948  ast_cli(a->fd, "Dynamic Threads:\n");
6950  AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
6951 #ifdef DEBUG_SCHED_MULTITHREAD
6952  ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
6953  thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
6954 #else
6955  ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
6956  thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
6957 #endif
6958  dynamiccount++;
6959  }
6961  ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
6962  return CLI_SUCCESS;
6963 }
6964 
6965 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6966 {
6967  struct iax2_peer *p;
6968 
6969  switch (cmd) {
6970  case CLI_INIT:
6971  e->command = "iax2 unregister";
6972  e->usage =
6973  "Usage: iax2 unregister <peername>\n"
6974  " Unregister (force expiration) an IAX2 peer from the registry.\n";
6975  return NULL;
6976  case CLI_GENERATE:
6977  return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
6978  }
6979 
6980  if (a->argc != 3)
6981  return CLI_SHOWUSAGE;
6982 
6983  p = find_peer(a->argv[2], 1);
6984  if (p) {
6985  if (p->expire > 0) {
6986  struct iax2_peer tmp_peer = {
6987  .name = a->argv[2],
6988  };
6989  struct iax2_peer *peer;
6990 
6991  peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
6992  if (peer) {
6993  expire_registry(peer_ref(peer)); /* will release its own reference when done */
6994  peer_unref(peer); /* ref from ao2_find() */
6995  ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
6996  } else {
6997  ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
6998  }
6999  } else {
7000  ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
7001  }
7002  peer_unref(p);
7003  } else {
7004  ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
7005  }
7006  return CLI_SUCCESS;
7007 }
7008 
7009 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
7010 {
7011  int which = 0;
7012  struct iax2_peer *p = NULL;
7013  char *res = NULL;
7014  int wordlen = strlen(word);
7015 
7016  /* 0 - iax2; 1 - unregister; 2 - <peername> */
7017  if (pos == 2) {
7018  struct ao2_iterator i = ao2_iterator_init(peers, 0);
7019  while ((p = ao2_iterator_next(&i))) {
7020  if (!strncasecmp(p->name, word, wordlen) &&
7021  ++which > state && p->expire > 0) {
7022  res = ast_strdup(p->name);
7023  peer_unref(p);
7024  break;
7025  }
7026  peer_unref(p);
7027  }
7029  }
7030 
7031  return res;
7032 }
7033 
7034 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7035 {
7036  switch (cmd) {
7037  case CLI_INIT:
7038  e->command = "iax2 show peers";
7039  e->usage =
7040  "Usage: iax2 show peers [registered] [like <pattern>]\n"
7041  " Lists all known IAX2 peers.\n"
7042  " Optional 'registered' argument lists only peers with known addresses.\n"
7043  " Optional regular expression pattern is used to filter the peer list.\n";
7044  return NULL;
7045  case CLI_GENERATE:
7046  return NULL;
7047  }
7048 
7049  switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
7050  case RESULT_SHOWUSAGE:
7051  return CLI_SHOWUSAGE;
7052  case RESULT_FAILURE:
7053  return CLI_FAILURE;
7054  default:
7055  return CLI_SUCCESS;
7056  }
7057 }
7058 
7059 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
7060 {
7061  ast_cli_netstats(s, -1, 0);
7062  astman_append(s, "\r\n");
7063  return RESULT_SUCCESS;
7064 }
7065 
7066 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7067 {
7068  struct iax_firmware *cur = NULL;
7069 
7070  switch (cmd) {
7071  case CLI_INIT:
7072  e->command = "iax2 show firmware";
7073  e->usage =
7074  "Usage: iax2 show firmware\n"
7075  " Lists all known IAX firmware images.\n";
7076  return NULL;
7077  case CLI_GENERATE:
7078  return NULL;
7079  }
7080 
7081  if (a->argc != 3 && a->argc != 4)
7082  return CLI_SHOWUSAGE;
7083 
7084  ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
7086  AST_LIST_TRAVERSE(&firmwares, cur, list) {
7087  if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname))) {
7088  ast_cli(a->fd, "%-15.15s %-15d %-15d\n", cur->fwh->devname,
7089  ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
7090  }
7091  }
7093 
7094  return CLI_SUCCESS;
7095 }
7096 
7097 /*! \brief callback to display iax peers in manager */
7098 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
7099 {
7100  static const char * const a[] = { "iax2", "show", "peers" };
7101  const char *id = astman_get_header(m,"ActionID");
7102  char idtext[256] = "";
7103  int total = 0;
7104 
7105  if (!ast_strlen_zero(id))
7106  snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7107 
7108  astman_send_listack(s, m, "Peer status list will follow", "start");
7109  /* List the peers in separate manager events */
7110  __iax2_show_peers(-1, &total, s, 3, a);
7111  /* Send final confirmation */
7112  astman_append(s,
7113  "Event: PeerlistComplete\r\n"
7114  "EventList: Complete\r\n"
7115  "ListItems: %d\r\n"
7116  "%s"
7117  "\r\n", total, idtext);
7118  return 0;
7119 }
7120 
7121 /*! \brief callback to display iax peers in manager format */
7122 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
7123 {
7124  struct iax2_peer *peer = NULL;
7125  int peer_count = 0;
7126  char nm[20];
7127  char status[20];
7128  const char *id = astman_get_header(m,"ActionID");
7129  char idtext[256] = "";
7130  struct ast_str *encmethods = ast_str_alloca(256);
7131  struct ao2_iterator i;
7132 
7133  if (!ast_strlen_zero(id))
7134  snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7135 
7136  astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
7137 
7138 
7139  i = ao2_iterator_init(peers, 0);
7140  for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7141  encmethods_to_str(peer->encmethods, &encmethods);
7142  astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
7143  if (!ast_strlen_zero(peer->username)) {
7144  astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
7145  } else {
7146  astman_append(s, "ObjectName: %s\r\n", peer->name);
7147  }
7148  astman_append(s, "ChanObjectType: peer\r\n");
7149  astman_append(s, "IPaddress: %s\r\n", ast_sockaddr_stringify_addr(&peer->addr));
7150  ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
7151  astman_append(s, "Mask: %s\r\n", nm);
7152  astman_append(s, "Port: %d\r\n", ast_sockaddr_port(&peer->addr));
7153  astman_append(s, "Dynamic: %s\r\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
7154  astman_append(s, "Trunk: %s\r\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
7155  astman_append(s, "Encryption: %s\r\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
7156  peer_status(peer, status, sizeof(status));
7157  astman_append(s, "Status: %s\r\n\r\n", status);
7158  peer_count++;
7159  }
7161 
7162  astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
7163  return RESULT_SUCCESS;
7164 }
7165 
7166 
7167 static char *regstate2str(int regstate)
7168 {
7169  switch(regstate) {
7171  return "Unregistered";
7172  case REG_STATE_REGSENT:
7173  return "Request Sent";
7174  case REG_STATE_AUTHSENT:
7175  return "Auth. Sent";
7176  case REG_STATE_REGISTERED:
7177  return "Registered";
7178  case REG_STATE_REJECTED:
7179  return "Rejected";
7180  case REG_STATE_TIMEOUT:
7181  return "Timeout";
7182  case REG_STATE_NOAUTH:
7183  return "No Authentication";
7184  default:
7185  return "Unknown";
7186  }
7187 }
7188 
7189 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7190 {
7191 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
7192 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
7193  struct iax2_registry *reg = NULL;
7194  char host[80];
7195  char perceived[80];
7196  int counter = 0;
7197 
7198  switch (cmd) {
7199  case CLI_INIT:
7200  e->command = "iax2 show registry";
7201  e->usage =
7202  "Usage: iax2 show registry\n"
7203  " Lists all registration requests and status.\n";
7204  return NULL;
7205  case CLI_GENERATE:
7206  return NULL;
7207  }
7208  if (a->argc != 3)
7209  return CLI_SHOWUSAGE;
7210  ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
7211  AST_LIST_LOCK(&registrations);
7212  AST_LIST_TRAVERSE(&registrations, reg, entry) {
7213  snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7214  if (reg->us.sin_addr.s_addr)
7215  snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
7216  else
7217  ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
7218  ast_cli(a->fd, FORMAT, host,
7219  (reg->dnsmgr) ? "Y" : "N",
7220  reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
7221  counter++;
7222  }
7223  AST_LIST_UNLOCK(&registrations);
7224  ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
7225  return CLI_SUCCESS;
7226 #undef FORMAT
7227 #undef FORMAT2
7228 }
7229 
7230 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
7231 {
7232  const char *id = astman_get_header(m, "ActionID");
7233  struct iax2_registry *reg = NULL;
7234  char idtext[256] = "";
7235  char host[80] = "";
7236  char perceived[80] = "";
7237  int total = 0;
7238 
7239  if (!ast_strlen_zero(id))
7240  snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7241 
7242  astman_send_listack(s, m, "Registrations will follow", "start");
7243 
7244  AST_LIST_LOCK(&registrations);
7245  AST_LIST_TRAVERSE(&registrations, reg, entry) {
7246  snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7247 
7248  if (reg->us.sin_addr.s_addr) {
7249  snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
7250  } else {
7251  ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
7252  }
7253 
7254  astman_append(s,
7255  "Event: RegistryEntry\r\n"
7256  "%s"
7257  "Host: %s\r\n"
7258  "DNSmanager: %s\r\n"
7259  "Username: %s\r\n"
7260  "Perceived: %s\r\n"
7261  "Refresh: %d\r\n"
7262  "State: %s\r\n"
7263  "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
7264  reg->refresh, regstate2str(reg->regstate));
7265 
7266  total++;
7267  }
7268  AST_LIST_UNLOCK(&registrations);
7269 
7270  astman_append(s,
7271  "Event: RegistrationsComplete\r\n"
7272  "EventList: Complete\r\n"
7273  "ListItems: %d\r\n"
7274  "%s"
7275  "\r\n", total, idtext);
7276 
7277  return 0;
7278 }
7279 
7280 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7281 {
7282 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
7283 #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s %s%s %3s%s\n"
7284 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
7285  int x;
7286  int numchans = 0;
7287  int usedchans = 0;
7288  char first_message[10] = { 0, };
7289  char last_message[10] = { 0, };
7290 
7291  switch (cmd) {
7292  case CLI_INIT:
7293  e->command = "iax2 show channels";
7294  e->usage =
7295  "Usage: iax2 show channels\n"
7296  " Lists all currently active IAX channels.\n";
7297  return NULL;
7298  case CLI_GENERATE:
7299  return NULL;
7300  }
7301 
7302  if (a->argc != 3)
7303  return CLI_SHOWUSAGE;
7304  ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
7305  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7306  ast_mutex_lock(&iaxsl[x]);
7307  if (iaxs[x]) {
7308  int lag, jitter, localdelay;
7309  jb_info jbinfo;
7310  if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
7311  jb_getinfo(iaxs[x]->jb, &jbinfo);
7312  jitter = jbinfo.jitter;
7313  localdelay = jbinfo.current - jbinfo.min;
7314  } else {
7315  jitter = -1;
7316  localdelay = 0;
7317  }
7318 
7319  iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7320  iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7321  lag = iaxs[x]->remote_rr.delay;
7322  ast_cli(a->fd, FORMAT,
7323  iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
7324  ast_inet_ntoa(iaxs[x]->addr.sin_addr),
7325  S_OR(iaxs[x]->username, "(None)"),
7326  iaxs[x]->callno, iaxs[x]->peercallno,
7327  iaxs[x]->oseqno, iaxs[x]->iseqno,
7328  lag,
7329  jitter,
7330  localdelay,
7331  ast_getformatname(iaxs[x]->voiceformat),
7332  (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7333  first_message,
7334  (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7335  last_message);
7336  numchans++;
7337  if (iaxs[x]->owner) { /* Count IAX dialog owned by a real channel */
7338  usedchans++;
7339  }
7340  }
7341  ast_mutex_unlock(&iaxsl[x]);
7342  }
7343  ast_cli(a->fd, "%d active IAX dialog%s\n", numchans, (numchans != 1) ? "s" : "");
7344  ast_cli(a->fd, "%d used IAX channel%s\n", usedchans, (usedchans != 1) ? "s" : "");
7345 
7346  return CLI_SUCCESS;
7347 #undef FORMAT
7348 #undef FORMAT2
7349 #undef FORMATB
7350 }
7351 
7352 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
7353 {
7354  int x;
7355  int numchans = 0;
7356  char first_message[10] = { 0, };
7357  char last_message[10] = { 0, };
7358 #define ACN_FORMAT1 "%-20.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
7359 #define ACN_FORMAT2 "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
7360  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7361  ast_mutex_lock(&iaxsl[x]);
7362  if (iaxs[x]) {
7363  int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
7364  jb_info jbinfo;
7365  iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7366  iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7367 
7368  if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
7369  jb_getinfo(iaxs[x]->jb, &jbinfo);
7370  localjitter = jbinfo.jitter;
7371  localdelay = jbinfo.current - jbinfo.min;
7372  locallost = jbinfo.frames_lost;
7373  locallosspct = jbinfo.losspct/1000;
7374  localdropped = jbinfo.frames_dropped;
7375  localooo = jbinfo.frames_ooo;
7376  } else {
7377  localjitter = -1;
7378  localdelay = 0;
7379  locallost = -1;
7380  locallosspct = -1;
7381  localdropped = 0;
7382  localooo = -1;
7383  }
7384  if (s)
7385  astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7386  iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
7387  iaxs[x]->pingtime,
7388  localjitter,
7389  localdelay,
7390  locallost,
7391  locallosspct,
7392  localdropped,
7393  localooo,
7394  iaxs[x]->frames_received/1000,
7395  iaxs[x]->remote_rr.jitter,
7396  iaxs[x]->remote_rr.delay,
7397  iaxs[x]->remote_rr.losscnt,
7398  iaxs[x]->remote_rr.losspct,
7399  iaxs[x]->remote_rr.dropped,
7400  iaxs[x]->remote_rr.ooo,
7401  iaxs[x]->remote_rr.packets/1000,
7402  (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7403  first_message,
7404  (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7405  last_message);
7406  else
7407  ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7408  iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
7409  iaxs[x]->pingtime,
7410  localjitter,
7411  localdelay,
7412  locallost,
7413  locallosspct,
7414  localdropped,
7415  localooo,
7416  iaxs[x]->frames_received/1000,
7417  iaxs[x]->remote_rr.jitter,
7418  iaxs[x]->remote_rr.delay,
7419  iaxs[x]->remote_rr.losscnt,
7420  iaxs[x]->remote_rr.losspct,
7421  iaxs[x]->remote_rr.dropped,
7422  iaxs[x]->remote_rr.ooo,
7423  iaxs[x]->remote_rr.packets/1000,
7424  (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7425  first_message,
7426  (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7427  last_message);
7428  numchans++;
7429  }
7430  ast_mutex_unlock(&iaxsl[x]);
7431  }
7432 
7433  return numchans;
7434 }
7435 
7436 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7437 {
7438  int numchans = 0;
7439 
7440  switch (cmd) {
7441  case CLI_INIT:
7442  e->command = "iax2 show netstats";
7443  e->usage =
7444  "Usage: iax2 show netstats\n"
7445  " Lists network status for all currently active IAX channels.\n";
7446  return NULL;
7447  case CLI_GENERATE:
7448  return NULL;
7449  }
7450  if (a->argc != 3)
7451  return CLI_SHOWUSAGE;
7452  ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
7453  ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
7454  numchans = ast_cli_netstats(NULL, a->fd, 1);
7455  ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7456  return CLI_SUCCESS;
7457 }
7458 
7459 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7460 {
7461  switch (cmd) {
7462  case CLI_INIT:
7463  e->command = "iax2 set debug {on|off|peer}";
7464  e->usage =
7465  "Usage: iax2 set debug {on|off|peer peername}\n"
7466  " Enables/Disables dumping of IAX packets for debugging purposes.\n";
7467  return NULL;
7468  case CLI_GENERATE:
7469  if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
7470  return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
7471  return NULL;
7472  }
7473 
7474  if (a->argc < e->args || a->argc > e->args + 1)
7475  return CLI_SHOWUSAGE;
7476 
7477  if (!strcasecmp(a->argv[3], "peer")) {
7478  struct iax2_peer *peer;
7479  struct sockaddr_in peer_addr;
7480 
7481 
7482  if (a->argc != e->args + 1)
7483  return CLI_SHOWUSAGE;
7484 
7485  peer = find_peer(a->argv[4], 1);
7486 
7487  if (!peer) {
7488  ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
7489  return CLI_FAILURE;
7490  }
7491 
7492  ast_sockaddr_to_sin(&peer->addr, &peer_addr);
7493 
7494  debugaddr.sin_addr = peer_addr.sin_addr;
7495  debugaddr.sin_port = peer_addr.sin_port;
7496 
7497  ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
7498  ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
7499 
7500  ao2_ref(peer, -1);
7501  } else if (!strncasecmp(a->argv[3], "on", 2)) {
7502  iaxdebug = 1;
7503  ast_cli(a->fd, "IAX2 Debugging Enabled\n");
7504  } else {
7505  iaxdebug = 0;
7506  memset(&debugaddr, 0, sizeof(debugaddr));
7507  ast_cli(a->fd, "IAX2 Debugging Disabled\n");
7508  }
7509  return CLI_SUCCESS;
7510 }
7511 
7512 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7513 {
7514  switch (cmd) {
7515  case CLI_INIT:
7516  e->command = "iax2 set debug trunk {on|off}";
7517  e->usage =
7518  "Usage: iax2 set debug trunk {on|off}\n"
7519  " Enables/Disables debugging of IAX trunking\n";
7520  return NULL;
7521  case CLI_GENERATE:
7522  return NULL;
7523  }
7524 
7525  if (a->argc != e->args)
7526  return CLI_SHOWUSAGE;
7527 
7528  if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
7529  iaxtrunkdebug = 1;
7530  ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
7531  } else {
7532  iaxtrunkdebug = 0;
7533  ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
7534  }
7535  return CLI_SUCCESS;
7536 }
7537 
7538 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7539 {
7540  switch (cmd) {
7541  case CLI_INIT:
7542  e->command = "iax2 set debug jb {on|off}";
7543  e->usage =
7544  "Usage: iax2 set debug jb {on|off}\n"
7545  " Enables/Disables jitterbuffer debugging information\n";
7546  return NULL;
7547  case CLI_GENERATE:
7548  return NULL;
7549  }
7550 
7551  if (a->argc != e->args)
7552  return CLI_SHOWUSAGE;
7553 
7554  if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
7556  ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
7557  } else {
7559  ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
7560  }
7561  return CLI_SUCCESS;
7562 }
7563 
7564 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
7565 {
7566  unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
7567  int res = -1;
7568  ast_mutex_lock(&iaxsl[callno]);
7569  if (iaxs[callno]) {
7570  /* If there's an outstanding error, return failure now */
7571  if (!iaxs[callno]->error) {
7572  if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
7573  res = 0;
7574  /* Don't waste bandwidth sending null frames */
7575  else if (f->frametype == AST_FRAME_NULL)
7576  res = 0;
7577  else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
7578  res = 0;
7579  else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
7580  res = 0;
7581  else
7582  /* Simple, just queue for transmission */
7583  res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
7584  } else {
7585  ast_debug(1, "Write error: %s\n", strerror(errno));
7586  }
7587  }
7588  /* If it's already gone, just return */
7589  ast_mutex_unlock(&iaxsl[callno]);
7590  return res;
7591 }
7592 
7593 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
7594  int now, int transfer, int final)
7595 {
7596  struct ast_frame f = { 0, };
7597  int res = 0;
7598 
7599  f.frametype = type;
7600  f.subclass.integer = command;
7601  f.datalen = datalen;
7602  f.src = __FUNCTION__;
7603  f.data.ptr = (void *) data;
7604 
7605  if ((res = queue_signalling(i, &f)) <= 0) {
7606  return res;
7607  }
7608 
7609  return iax2_send(i, &f, ts, seqno, now, transfer, final);
7610 }
7611 
7612 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7613 {
7614  if (type == AST_FRAME_CONTROL && !iax2_is_control_frame_allowed(command)) {
7615  /* Control frame should not go out on the wire. */
7616  ast_debug(2, "Callno %d: Blocked sending control frame %d.\n",
7617  i->callno, command);
7618  return 0;
7619  }
7620  return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
7621 }
7622 
7623 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7624 {
7625  int res;
7626  ast_mutex_lock(&iaxsl[callno]);
7627  res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
7628  ast_mutex_unlock(&iaxsl[callno]);
7629  return res;
7630 }
7631 
7632 /*!
7633  * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
7634  * the pvt struct for the given call number may disappear during its
7635  * execution.
7636  */
7637 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7638 {
7639  int call_num = i->callno;
7640  /* It is assumed that the callno has already been locked */
7641  iax2_predestroy(i->callno);
7642  if (!iaxs[call_num])
7643  return -1;
7644  return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
7645 }
7646 
7647 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7648 {
7649  return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
7650 }
7651 
7652 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
7653 {
7654  return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
7655 }
7656 
7657 static int apply_context(struct iax2_context *con, const char *context)
7658 {
7659  while(con) {
7660  if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
7661  return -1;
7662  con = con->next;
7663  }
7664  return 0;
7665 }
7666 
7667 
7668 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
7669 {
7670  /* Start pessimistic */
7671  int res = -1;
7672  int version = 2;
7673  struct iax2_user *user = NULL, *best = NULL;
7674  int bestscore = 0;
7675  int gotcapability = 0;
7676  struct ast_variable *v = NULL, *tmpvar = NULL;
7677  struct ao2_iterator i;
7678  struct ast_sockaddr addr;
7679 
7680  if (!iaxs[callno])
7681  return res;
7682  if (ies->called_number)
7683  ast_string_field_set(iaxs[callno], exten, ies->called_number);
7684  if (ies->calling_number) {
7685  if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) {
7687  }
7688  ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
7689  }
7690  if (ies->calling_name)
7691  ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
7692  if (ies->calling_ani)
7693  ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
7694  if (ies->dnid)
7695  ast_string_field_set(iaxs[callno], dnid, ies->dnid);
7696  if (ies->rdnis)
7697  ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
7698  if (ies->called_context)
7699  ast_string_field_set(iaxs[callno], context, ies->called_context);
7700  if (ies->language)
7701  ast_string_field_set(iaxs[callno], language, ies->language);
7702  if (ies->username)
7703  ast_string_field_set(iaxs[callno], username, ies->username);
7704  if (ies->calling_ton > -1)
7705  iaxs[callno]->calling_ton = ies->calling_ton;
7706  if (ies->calling_tns > -1)
7707  iaxs[callno]->calling_tns = ies->calling_tns;
7708  if (ies->calling_pres > -1)
7709  iaxs[callno]->calling_pres = ies->calling_pres;
7710  if (ies->format)
7711  iaxs[callno]->peerformat = ies->format;
7712  if (ies->adsicpe)
7713  iaxs[callno]->peeradsicpe = ies->adsicpe;
7714  if (ies->capability) {
7715  gotcapability = 1;
7716  iaxs[callno]->peercapability = ies->capability;
7717  }
7718  if (ies->version)
7719  version = ies->version;
7720 
7721  /* Use provided preferences until told otherwise for actual preferences */
7722  if (ies->codec_prefs) {
7723  ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
7724  ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
7725  }
7726 
7727  if (!gotcapability)
7728  iaxs[callno]->peercapability = iaxs[callno]->peerformat;
7729  if (version > IAX_PROTO_VERSION) {
7730  ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
7731  ast_inet_ntoa(sin->sin_addr), version);
7732  return res;
7733  }
7734  /* Search the userlist for a compatible entry, and fill in the rest */
7735  ast_sockaddr_from_sin(&addr, sin);
7736  i = ao2_iterator_init(users, 0);
7737  while ((user = ao2_iterator_next(&i))) {
7738  if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
7739  !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
7740  && ast_apply_ha(user->ha, &addr) == AST_SENSE_ALLOW /* Access is permitted from this IP */
7741  && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
7742  apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
7743  if (!ast_strlen_zero(iaxs[callno]->username)) {
7744  /* Exact match, stop right now. */
7745  if (best)
7746  user_unref(best);
7747  best = user;
7748  break;
7749  } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
7750  /* No required authentication */
7751  if (user->ha) {
7752  /* There was host authentication and we passed, bonus! */
7753  if (bestscore < 4) {
7754  bestscore = 4;
7755  if (best)
7756  user_unref(best);
7757  best = user;
7758  continue;
7759  }
7760  } else {
7761  /* No host access, but no secret, either, not bad */
7762  if (bestscore < 3) {
7763  bestscore = 3;
7764  if (best)
7765  user_unref(best);
7766  best = user;
7767  continue;
7768  }
7769  }
7770  } else {
7771  if (user->ha) {
7772  /* Authentication, but host access too, eh, it's something.. */
7773  if (bestscore < 2) {
7774  bestscore = 2;
7775  if (best)
7776  user_unref(best);
7777  best = user;
7778  continue;
7779  }
7780  } else {
7781  /* Authentication and no host access... This is our baseline */
7782  if (bestscore < 1) {
7783  bestscore = 1;
7784  if (best)
7785  user_unref(best);
7786  best = user;
7787  continue;
7788  }
7789  }
7790  }
7791  }
7792  user_unref(user);
7793  }
7795  user = best;
7796  if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
7797  user = realtime_user(iaxs[callno]->username, sin);
7798  if (user && (ast_apply_ha(user->ha, &addr) == AST_SENSE_DENY /* Access is denied from this IP */
7799  || (!ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
7800  !apply_context(user->contexts, iaxs[callno]->context)))) { /* Context is permitted */
7801  user = user_unref(user);
7802  }
7803  }
7804  if (user) {
7805  /* We found our match (use the first) */
7806  /* copy vars */
7807  for (v = user->vars ; v ; v = v->next) {
7808  if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
7809  tmpvar->next = iaxs[callno]->vars;
7810  iaxs[callno]->vars = tmpvar;
7811  }
7812  }
7813  /* If a max AUTHREQ restriction is in place, activate it */
7814  if (user->maxauthreq > 0)
7815  ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
7816  iaxs[callno]->prefs = user->prefs;
7818  iaxs[callno]->encmethods = user->encmethods;
7819  /* Store the requested username if not specified */
7820  if (ast_strlen_zero(iaxs[callno]->username))
7821  ast_string_field_set(iaxs[callno], username, user->name);
7822  /* Store whether this is a trunked call, too, of course, and move if appropriate */
7823  ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
7824  iaxs[callno]->capability = user->capability;
7825  /* And use the default context */
7826  if (ast_strlen_zero(iaxs[callno]->context)) {
7827  if (user->contexts)
7828  ast_string_field_set(iaxs[callno], context, user->contexts->context);
7829  else
7831  }
7832  /* And any input keys */
7833  ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
7834  /* And the permitted authentication methods */
7835  iaxs[callno]->authmethods = user->authmethods;
7836  iaxs[callno]->adsi = user->adsi;
7837  /* If the user has callerid, override the remote caller id. */
7838  if (ast_test_flag64(user, IAX_HASCALLERID)) {
7839  iaxs[callno]->calling_tns = 0;
7840  iaxs[callno]->calling_ton = 0;
7841  ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
7842  ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
7843  ast_string_field_set(iaxs[callno], ani, user->cid_num);
7845  } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
7847  } /* else user is allowed to set their own CID settings */
7848  if (!ast_strlen_zero(user->accountcode))
7849  ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
7850  if (!ast_strlen_zero(user->mohinterpret))
7851  ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
7852  if (!ast_strlen_zero(user->mohsuggest))
7853  ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
7854  if (!ast_strlen_zero(user->parkinglot))
7855  ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
7856  if (user->amaflags)
7857  iaxs[callno]->amaflags = user->amaflags;
7858  if (!ast_strlen_zero(user->language))
7859  ast_string_field_set(iaxs[callno], language, user->language);
7861  /* Keep this check last */
7862  if (!ast_strlen_zero(user->dbsecret)) {
7863  char *family, *key=NULL;
7864  char buf[80];
7865  family = ast_strdupa(user->dbsecret);
7866  key = strchr(family, '/');
7867  if (key) {
7868  *key = '\0';
7869  key++;
7870  }
7871  if (!key || ast_db_get(family, key, buf, sizeof(buf)))
7872  ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
7873  else
7874  ast_string_field_set(iaxs[callno], secret, buf);
7875  } else
7876  ast_string_field_set(iaxs[callno], secret, user->secret);
7877  res = 0;
7878  user = user_unref(user);
7879  } else {
7880  /* user was not found, but we should still fake an AUTHREQ.
7881  * Set authmethods to the last known authmethod used by the system
7882  * Set a fake secret, it's not looked at, just required to attempt authentication.
7883  * Set authrej so the AUTHREP is rejected without even looking at its contents */
7884  iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
7885  ast_string_field_set(iaxs[callno], secret, "badsecret");
7886  iaxs[callno]->authrej = 1;
7887  if (!ast_strlen_zero(iaxs[callno]->username)) {
7888  /* only send the AUTHREQ if a username was specified. */
7889  res = 0;
7890  }
7891  }
7892  ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
7893  return res;
7894 }
7895 
7896 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
7897 {
7898  struct ast_iax2_full_hdr fh;
7899  fh.scallno = htons(src | IAX_FLAG_FULL);
7900  fh.dcallno = htons(dst);
7901  fh.ts = 0;
7902  fh.oseqno = 0;
7903  fh.iseqno = 0;
7904  fh.type = AST_FRAME_IAX;
7906  iax_outputframe(NULL, &fh, 0, sin, 0);
7907 #if 0
7908  if (option_debug)
7909 #endif
7910  ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
7911  ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
7912  return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
7913 }
7914 
7915 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
7916 {
7917  /* Select exactly one common encryption if there are any */
7918  p->encmethods &= enc;
7919  if (p->encmethods) {
7920  if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
7921  p->keyrotateid = -2;
7922  }
7923  if (p->encmethods & IAX_ENCRYPT_AES128)
7925  else
7926  p->encmethods = 0;
7927  }
7928 }
7929 
7930 /*!
7931  * \pre iaxsl[call_num] is locked
7932  *
7933  * \note Since this function calls send_command_final(), the pvt struct for the given
7934  * call number may disappear while executing this function.
7935  */
7936 static int authenticate_request(int call_num)
7937 {
7938  struct iax_ie_data ied;
7939  int res = -1, authreq_restrict = 0;
7940  char challenge[10];
7941  struct chan_iax2_pvt *p = iaxs[call_num];
7942 
7943  memset(&ied, 0, sizeof(ied));
7944 
7945  /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
7946  if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
7947  struct iax2_user *user, tmp_user = {
7948  .name = p->username,
7949  };
7950 
7951  user = ao2_find(users, &tmp_user, OBJ_POINTER);
7952  if (user) {
7953  if (user->curauthreq == user->maxauthreq)
7954  authreq_restrict = 1;
7955  else
7956  user->curauthreq++;
7957  user = user_unref(user);
7958  }
7959  }
7960 
7961  /* If the AUTHREQ limit test failed, send back an error */
7962  if (authreq_restrict) {
7963  iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
7966  return 0;
7967  }
7968 
7970  if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
7971  snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
7972  ast_string_field_set(p, challenge, challenge);
7973  /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
7975  }
7976  if (p->encmethods)
7978 
7980 
7981  res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
7982 
7983  if (p->encmethods)
7985 
7986  return res;
7987 }
7988 
7989 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
7990 {
7991  char requeststr[256];
7992  char md5secret[256] = "";
7993  char secret[256] = "";
7994  char rsasecret[256] = "";
7995  int res = -1;
7996  int x;
7997  struct iax2_user *user, tmp_user = {
7998  .name = p->username,
7999  };
8000 
8001  if (p->authrej) {
8002  return res;
8003  }
8004  user = ao2_find(users, &tmp_user, OBJ_POINTER);
8005  if (user) {
8006  if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
8007  ast_atomic_fetchadd_int(&user->curauthreq, -1);
8009  }
8010  ast_string_field_set(p, host, user->name);
8011  user = user_unref(user);
8012  }
8013  if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) {
8014  ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.\n");
8015  return res;
8016  }
8018  return res;
8019  if (ies->password)
8020  ast_copy_string(secret, ies->password, sizeof(secret));
8021  if (ies->md5_result)
8022  ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8023  if (ies->rsa_result)
8024  ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8025  if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
8026  struct ast_key *key;
8027  char *keyn;
8028  char tmpkey[256];
8029  char *stringp=NULL;
8030  ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
8031  stringp=tmpkey;
8032  keyn = strsep(&stringp, ":");
8033  while(keyn) {
8034  key = ast_key_get(keyn, AST_KEY_PUBLIC);
8035  if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
8036  res = 0;
8037  break;
8038  } else if (!key)
8039  ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
8040  keyn = strsep(&stringp, ":");
8041  }
8042  } else if (p->authmethods & IAX_AUTH_MD5) {
8043  struct MD5Context md5;
8044  unsigned char digest[16];
8045  char *tmppw, *stringp;
8046 
8047  tmppw = ast_strdupa(p->secret);
8048  stringp = tmppw;
8049  while((tmppw = strsep(&stringp, ";"))) {
8050  MD5Init(&md5);
8051  MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
8052  MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8053  MD5Final(digest, &md5);
8054  /* If they support md5, authenticate with it. */
8055  for (x=0;x<16;x++)
8056  sprintf(requeststr + (x << 1), "%2.2x", (unsigned)digest[x]); /* safe */
8057  if (!strcasecmp(requeststr, md5secret)) {
8058  res = 0;
8059  break;
8060  }
8061  }
8062  } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
8063  if (!strcmp(secret, p->secret))
8064  res = 0;
8065  }
8066  return res;
8067 }
8068 
8069 /*! \brief Verify inbound registration */
8070 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
8071 {
8072  char requeststr[256] = "";
8073  char peer[256] = "";
8074  char md5secret[256] = "";
8075  char rsasecret[256] = "";
8076  char secret[256] = "";
8077  struct iax2_peer *p = NULL;
8078  struct ast_key *key;
8079  char *keyn;
8080  int x;
8081  int expire = 0;
8082  int res = -1;
8083  struct ast_sockaddr addr;
8084 
8085  ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8086  /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
8087  if (ies->username)
8088  ast_copy_string(peer, ies->username, sizeof(peer));
8089  if (ies->password)
8090  ast_copy_string(secret, ies->password, sizeof(secret));
8091  if (ies->md5_result)
8092  ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8093  if (ies->rsa_result)
8094  ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8095  if (ies->refresh)
8096  expire = ies->refresh;
8097 
8098  if (ast_strlen_zero(peer)) {
8099  ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
8100  return -1;
8101  }
8102 
8103  /* SLD: first call to lookup peer during registration */
8104  ast_mutex_unlock(&iaxsl[callno]);
8105  p = find_peer(peer, 1);
8106  ast_mutex_lock(&iaxsl[callno]);
8107  if (!p || !iaxs[callno]) {
8108  if (iaxs[callno]) {
8109  int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
8110  /* Anything, as long as it's non-blank */
8111  ast_string_field_set(iaxs[callno], secret, "badsecret");
8112  /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
8113  * 1. A challenge already exists indicating a AUTHREQ was already sent out.
8114  * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
8115  * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
8116  * to be plaintext, indicating it is an authmethod used by other peers on the system.
8117  *
8118  * If none of these cases exist, res will be returned as 0 without authentication indicating
8119  * an AUTHREQ needs to be sent out. */
8120 
8121  if (ast_strlen_zero(iaxs[callno]->challenge) &&
8122  !(!ast_strlen_zero(secret) && plaintext)) {
8123  /* by setting res to 0, an REGAUTH will be sent */
8124  res = 0;
8125  }
8126  }
8127  if (authdebug && !p)
8128  ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
8129  goto return_unref;
8130  }
8131 
8132  if (!ast_test_flag64(p, IAX_DYNAMIC)) {
8133  if (authdebug)
8134  ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
8135  goto return_unref;
8136  }
8137 
8138  ast_sockaddr_from_sin(&addr, sin);
8139  if (!ast_apply_ha(p->ha, &addr)) {
8140  if (authdebug)
8141  ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
8142  goto return_unref;
8143  }
8144  ast_string_field_set(iaxs[callno], secret, p->secret);
8145  ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
8146  /* Check secret against what we have on file */
8147  if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8148  if (!ast_strlen_zero(p->inkeys)) {
8149  char tmpkeys[256];
8150  char *stringp=NULL;
8151  ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
8152  stringp=tmpkeys;
8153  keyn = strsep(&stringp, ":");
8154  while(keyn) {
8155  key = ast_key_get(keyn, AST_KEY_PUBLIC);
8156  if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
8157  ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8158  break;
8159  } else if (!key)
8160  ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
8161  keyn = strsep(&stringp, ":");
8162  }
8163  if (!keyn) {
8164  if (authdebug)
8165  ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
8166  goto return_unref;
8167  }
8168  } else {
8169  if (authdebug)
8170  ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
8171  goto return_unref;
8172  }
8173  } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8174  struct MD5Context md5;
8175  unsigned char digest[16];
8176  char *tmppw, *stringp;
8177 
8178  tmppw = ast_strdupa(p->secret);
8179  stringp = tmppw;
8180  while((tmppw = strsep(&stringp, ";"))) {
8181  MD5Init(&md5);
8182  MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
8183  MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8184  MD5Final(digest, &md5);
8185  for (x=0;x<16;x++)
8186  sprintf(requeststr + (x << 1), "%2.2x", (unsigned)digest[x]); /* safe */
8187  if (!strcasecmp(requeststr, md5secret))
8188  break;
8189  }
8190  if (tmppw) {
8191  ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8192  } else {
8193  if (authdebug)
8194  ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
8195  goto return_unref;
8196  }
8197  } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
8198  /* They've provided a plain text password and we support that */
8199  if (strcmp(secret, p->secret)) {
8200  if (authdebug)
8201  ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
8202  goto return_unref;
8203  } else
8204  ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8205  } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
8206  /* if challenge has been sent, but no challenge response if given, reject. */
8207  goto return_unref;
8208  }
8209  ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8210 
8211  /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
8212  res = 0;
8213 
8214 return_unref:
8215  if (iaxs[callno]) {
8216  ast_string_field_set(iaxs[callno], peer, peer);
8217 
8218  /* Choose lowest expiry number */
8219  if (expire && (expire < iaxs[callno]->expiry)) {
8220  iaxs[callno]->expiry = expire;
8221  }
8222  }
8223 
8224  if (p) {
8225  peer_unref(p);
8226  }
8227  return res;
8228 }
8229 
8230 static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, struct chan_iax2_pvt *pvt)
8231 {
8232  int res = -1;
8233  int x;
8234  if (!ast_strlen_zero(keyn)) {
8235  if (!(authmethods & IAX_AUTH_RSA)) {
8236  if (ast_strlen_zero(secret))
8237  ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_inet_ntoa(sin->sin_addr));
8238  } else if (ast_strlen_zero(challenge)) {
8239  ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
8240  } else {
8241  char sig[256];
8242  struct ast_key *key;
8243  key = ast_key_get(keyn, AST_KEY_PRIVATE);
8244  if (!key) {
8245  ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
8246  } else {
8247  if (ast_sign(key, (char*)challenge, sig)) {
8248  ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
8249  res = -1;
8250  } else {
8252  res = 0;
8253  }
8254  }
8255  }
8256  }
8257  /* Fall back */
8258  if (res && !ast_strlen_zero(secret)) {
8259  if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
8260  struct MD5Context md5;
8261  unsigned char digest[16];
8262  char digres[128];
8263  MD5Init(&md5);
8264  MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
8265  MD5Update(&md5, (unsigned char *)secret, strlen(secret));
8266  MD5Final(digest, &md5);
8267  /* If they support md5, authenticate with it. */
8268  for (x=0;x<16;x++)
8269  sprintf(digres + (x << 1), "%2.2x", (unsigned)digest[x]); /* safe */
8270  if (pvt) {
8271  build_encryption_keys(digest, pvt);
8272  }
8273  iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
8274  res = 0;
8275  } else if (authmethods & IAX_AUTH_PLAINTEXT) {
8276  iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
8277  res = 0;
8278  } else
8279  ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
8280  }
8281  return res;
8282 }
8283 
8284 /*!
8285  * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
8286  * so do not call this function with a pvt lock held.
8287  */
8288 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
8289 {
8290  struct iax2_peer *peer = NULL;
8291  /* Start pessimistic */
8292  int res = -1;
8293  int authmethods = 0;
8294  struct iax_ie_data ied;
8295  uint16_t callno = p->callno;
8296 
8297  memset(&ied, 0, sizeof(ied));
8298 
8299  if (ies->username)
8300  ast_string_field_set(p, username, ies->username);
8301  if (ies->challenge)
8302  ast_string_field_set(p, challenge, ies->challenge);
8303  if (ies->authmethods)
8304  authmethods = ies->authmethods;
8305  if (authmethods & IAX_AUTH_MD5)
8306  merge_encryption(p, ies->encmethods);
8307  else
8308  p->encmethods = 0;
8309 
8310  /* Check for override RSA authentication first */
8311  if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
8312  /* Normal password authentication */
8313  res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
8314  } else {
8315  struct ao2_iterator i = ao2_iterator_init(peers, 0);
8316  while ((peer = ao2_iterator_next(&i))) {
8317  struct sockaddr_in peer_addr;
8318 
8319  ast_sockaddr_to_sin(&peer->addr, &peer_addr);
8320 
8321  if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
8322  /* No peer specified at our end, or this is the peer */
8323  && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
8324  /* No username specified in peer rule, or this is the right username */
8325  && (!peer_addr.sin_addr.s_addr || ((sin->sin_addr.s_addr & peer->mask.s_addr) == (peer_addr.sin_addr.s_addr & peer->mask.s_addr)))
8326  /* No specified host, or this is our host */
8327  ) {
8328  res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
8329  if (!res) {
8330  peer_unref(peer);
8331  break;
8332  }
8333  }
8334  peer_unref(peer);
8335  }
8337  if (!peer) {
8338  /* We checked our list and didn't find one. It's unlikely, but possible,
8339  that we're trying to authenticate *to* a realtime peer */
8340  const char *peer_name = ast_strdupa(p->peer);
8341  ast_mutex_unlock(&iaxsl[callno]);
8342  if ((peer = realtime_peer(peer_name, NULL))) {
8343  ast_mutex_lock(&iaxsl[callno]);
8344  if (!(p = iaxs[callno])) {
8345  peer_unref(peer);
8346  return -1;
8347  }
8348  res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
8349  peer_unref(peer);
8350  }
8351  if (!peer) {
8352  ast_mutex_lock(&iaxsl[callno]);
8353  if (!(p = iaxs[callno]))
8354  return -1;
8355  }
8356  }
8357  }
8358 
8359  if (ies->encmethods) {
8361  } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
8362  ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
8363  return -1; /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
8364  }
8365  if (!res) {
8366  struct ast_datastore *variablestore;
8367  struct ast_variable *var, *prev = NULL;
8368  AST_LIST_HEAD(, ast_var_t) *varlist;
8369  varlist = ast_calloc(1, sizeof(*varlist));
8370  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
8371  if (variablestore && varlist && p->owner) {
8372  variablestore->data = varlist;
8373  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
8374  AST_LIST_HEAD_INIT(varlist);
8375  for (var = ies->vars; var; var = var->next) {
8376  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
8377  if (prev)
8378  ast_free(prev);
8379  prev = var;
8380  if (!newvar) {
8381  /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
8382  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8383  } else {
8384  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
8385  }
8386  }
8387  if (prev)
8388  ast_free(prev);
8389  ies->vars = NULL;
8390  ast_channel_datastore_add(p->owner, variablestore);
8391  } else {
8392  if (p->owner)
8393  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8394  if (variablestore)
8395  ast_datastore_free(variablestore);
8396  if (varlist)
8397  ast_free(varlist);
8398  }
8399  }
8400 
8401  if (!res)
8402  res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
8403  return res;
8404 }
8405 
8406 static int iax2_do_register(struct iax2_registry *reg);
8407 
8408 static void __iax2_do_register_s(const void *data)
8409 {
8410  struct iax2_registry *reg = (struct iax2_registry *)data;
8411  reg->expire = -1;
8412  iax2_do_register(reg);
8413 }
8414 
8415 static int iax2_do_register_s(const void *data)
8416 {
8417 #ifdef SCHED_MULTITHREADED
8419 #endif
8420  __iax2_do_register_s(data);
8421  return 0;
8422 }
8423 
8424 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8425 {
8426  int newcall = 0;
8427  char newip[256];
8428  struct iax_ie_data ied;
8429  struct sockaddr_in new = { 0, };
8430 
8431  memset(&ied, 0, sizeof(ied));
8432  if (ies->apparent_addr)
8433  memmove(&new, ies->apparent_addr, sizeof(new));
8434  if (ies->callno)
8435  newcall = ies->callno;
8436  if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
8437  ast_log(LOG_WARNING, "Invalid transfer request\n");
8438  return -1;
8439  }
8440  pvt->transfercallno = newcall;
8441  memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
8442  inet_aton(newip, &pvt->transfer.sin_addr);
8443  pvt->transfer.sin_family = AF_INET;
8444  pvt->transferid = ies->transferid;
8445  /* only store by transfercallno if this is a new transfer,
8446  * just in case we get a duplicate TXREQ */
8447  if (pvt->transferring == TRANSFER_NONE) {
8449  }
8451 
8452  if (ies->transferid)
8455  return 0;
8456 }
8457 
8458 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8459 {
8460  char exten[256] = "";
8461  int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
8462  struct iax2_dpcache *dp = NULL;
8463 
8464  if (ies->called_number)
8465  ast_copy_string(exten, ies->called_number, sizeof(exten));
8466 
8467  if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
8468  status = CACHE_FLAG_EXISTS;
8469  else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
8470  status = CACHE_FLAG_CANEXIST;
8471  else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
8472  status = CACHE_FLAG_NONEXISTENT;
8473 
8474  if (ies->refresh)
8475  expiry = ies->refresh;
8476  if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
8477  matchmore = CACHE_FLAG_MATCHMORE;
8478 
8481  if (strcmp(dp->exten, exten))
8482  continue;
8484  dp->callno = 0;
8485  dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
8486  if (dp->flags & CACHE_FLAG_PENDING) {
8487  dp->flags &= ~CACHE_FLAG_PENDING;
8488  dp->flags |= status;
8489  dp->flags |= matchmore;
8490  }
8491  /* Wake up waiters */
8492  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
8493  if (dp->waiters[x] > -1) {
8494  if (write(dp->waiters[x], "asdf", 4) < 0) {
8495  }
8496  }
8497  }
8498  }
8501 
8502  return 0;
8503 }
8504 
8505 static int complete_transfer(int callno, struct iax_ies *ies)
8506 {
8507  int peercallno = 0;
8508  struct chan_iax2_pvt *pvt = iaxs[callno];
8509  struct iax_frame *cur;
8510  jb_frame frame;
8511 
8512  if (ies->callno)
8513  peercallno = ies->callno;
8514 
8515  if (peercallno < 1) {
8516  ast_log(LOG_WARNING, "Invalid transfer request\n");
8517  return -1;
8518  }
8520  /* since a transfer has taken place, the address will change.
8521  * This must be accounted for in the peercnts table. Remove
8522  * the old address and add the new one */
8524  peercnt_add(&pvt->transfer);
8525  /* now copy over the new address */
8526  memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
8527  memset(&pvt->transfer, 0, sizeof(pvt->transfer));
8528  /* Reset sequence numbers */
8529  pvt->oseqno = 0;
8530  pvt->rseqno = 0;
8531  pvt->iseqno = 0;
8532  pvt->aseqno = 0;
8533 
8534  if (pvt->peercallno) {
8535  remove_by_peercallno(pvt);
8536  }
8537  pvt->peercallno = peercallno;
8538  /*this is where the transfering call swiches hash tables */
8539  store_by_peercallno(pvt);
8540  pvt->transferring = TRANSFER_NONE;
8541  pvt->svoiceformat = -1;
8542  pvt->voiceformat = 0;
8543  pvt->svideoformat = -1;
8544  pvt->videoformat = 0;
8545  pvt->transfercallno = 0;
8546  memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
8547  memset(&pvt->offset, 0, sizeof(pvt->offset));
8548  /* reset jitterbuffer */
8549  while(jb_getall(pvt->jb,&frame) == JB_OK)
8550  iax2_frame_free(frame.data);
8551  jb_reset(pvt->jb);
8552  pvt->lag = 0;
8553  pvt->last = 0;
8554  pvt->lastsent = 0;
8555  pvt->nextpred = 0;
8557  AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
8558  /* We must cancel any packets that would have been transmitted
8559  because now we're talking to someone new. It's okay, they
8560  were transmitted to someone that didn't care anyway. */
8561  cur->retries = -1;
8562  }
8563  return 0;
8564 }
8565 
8566 /*! \brief Acknowledgment received for OUR registration */
8567 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
8568 {
8569  struct iax2_registry *reg;
8570  /* Start pessimistic */
8571  char peer[256] = "";
8572  char msgstatus[60];
8573  int refresh = 60;
8574  char ourip[256] = "<Unspecified>";
8575  struct sockaddr_in oldus;
8576  struct sockaddr_in us;
8577  int oldmsgs;
8578  struct sockaddr_in reg_addr;
8579 
8580  memset(&us, 0, sizeof(us));
8581  if (ies->apparent_addr) {
8582  memmove(&us, ies->apparent_addr, sizeof(us));
8583  }
8584  if (ies->username) {
8585  ast_copy_string(peer, ies->username, sizeof(peer));
8586  }
8587  if (ies->refresh) {
8588  refresh = ies->refresh;
8589  }
8590  if (ies->calling_number) {
8591  /* We don't do anything with it really, but maybe we should */
8592  }
8593  reg = iaxs[callno]->reg;
8594  if (!reg) {
8595  ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
8596  return -1;
8597  }
8598  memcpy(&oldus, &reg->us, sizeof(oldus));
8599  oldmsgs = reg->messages;
8600  ast_sockaddr_to_sin(&reg->addr, &reg_addr);
8601  if (inaddrcmp(&reg_addr, sin)) {
8602  ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
8603  return -1;
8604  }
8605  memcpy(&reg->us, &us, sizeof(reg->us));
8606  if (ies->msgcount >= 0) {
8607  reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
8608  }
8609  /* always refresh the registration at the interval requested by the server
8610  we are registering to
8611  */
8612  reg->refresh = refresh;
8613  reg->expire = iax2_sched_replace(reg->expire, sched,
8614  (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8615  if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
8616  if (reg->messages > 255) {
8617  snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
8618  } else if (reg->messages > 1) {
8619  snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
8620  } else if (reg->messages > 0) {
8621  ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
8622  } else {
8623  ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
8624  }
8625  snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
8626  ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
8627  manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
8628  }
8630  return 0;
8631 }
8632 
8633 static int iax2_append_register(const char *hostname, const char *username,
8634  const char *secret, const char *porta)
8635 {
8636  struct iax2_registry *reg;
8637 
8638  if (!(reg = ast_calloc(1, sizeof(*reg))))
8639  return -1;
8640 
8641  reg->addr.ss.ss_family = AF_INET;
8642  if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
8643  ast_free(reg);
8644  return -1;
8645  }
8646 
8647  ast_copy_string(reg->username, username, sizeof(reg->username));
8648 
8649  if (secret)
8650  ast_copy_string(reg->secret, secret, sizeof(reg->secret));
8651 
8652  reg->expire = -1;
8654  ast_sockaddr_set_port(&reg->addr, porta ? atoi(porta) : IAX_DEFAULT_PORTNO);
8655 
8656  AST_LIST_LOCK(&registrations);
8657  AST_LIST_INSERT_HEAD(&registrations, reg, entry);
8658  AST_LIST_UNLOCK(&registrations);
8659 
8660  return 0;
8661 }
8662 
8663 static int iax2_register(const char *value, int lineno)
8664 {
8665  char copy[256];
8666  char *username, *hostname, *secret;
8667  char *porta;
8668  char *stringp=NULL;
8669 
8670  if (!value)
8671  return -1;
8672 
8673  ast_copy_string(copy, value, sizeof(copy));
8674  stringp = copy;
8675  username = strsep(&stringp, "@");
8676  hostname = strsep(&stringp, "@");
8677 
8678  if (!hostname) {
8679  ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
8680  return -1;
8681  }
8682 
8683  stringp = username;
8684  username = strsep(&stringp, ":");
8685  secret = strsep(&stringp, ":");
8686  stringp = hostname;
8687  hostname = strsep(&stringp, ":");
8688  porta = strsep(&stringp, ":");
8689 
8690  if (porta && !atoi(porta)) {
8691  ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
8692  return -1;
8693  }
8694 
8695  return iax2_append_register(hostname, username, secret, porta);
8696 }
8697 
8698 
8699 static void register_peer_exten(struct iax2_peer *peer, int onoff)
8700 {
8701  char multi[256];
8702  char *stringp, *ext;
8703  if (!ast_strlen_zero(regcontext)) {
8704  ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
8705  stringp = multi;
8706  while((ext = strsep(&stringp, "&"))) {
8707  if (onoff) {
8708  if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
8709  ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
8710  "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
8711  } else
8712  ast_context_remove_extension(regcontext, ext, 1, NULL);
8713  }
8714  }
8715 }
8716 static void prune_peers(void);
8717 
8718 static void unlink_peer(struct iax2_peer *peer)
8719 {
8720  if (peer->expire > -1) {
8721  if (!ast_sched_thread_del(sched, peer->expire)) {
8722  peer->expire = -1;
8723  peer_unref(peer);
8724  }
8725  }
8726 
8727  if (peer->pokeexpire > -1) {
8728  if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
8729  peer->pokeexpire = -1;
8730  peer_unref(peer);
8731  }
8732  }
8733 
8734  ao2_unlink(peers, peer);
8735 }
8736 
8737 static void __expire_registry(const void *data)
8738 {
8739  struct iax2_peer *peer = (struct iax2_peer *) data;
8740 
8741  if (!peer)
8742  return;
8743  if (peer->expire == -1) {
8744  /* Removed already (possibly through CLI), ignore */
8745  return;
8746  }
8747 
8748  peer->expire = -1;
8749 
8750  ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
8752  realtime_update_peer(peer->name, &peer->addr, 0);
8753  manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
8754  /* modify entry in peercnts table as _not_ registered */
8755  peercnt_modify((unsigned char) 0, 0, &peer->addr);
8756  /* Reset the address */
8757  memset(&peer->addr, 0, sizeof(peer->addr));
8758  /* Reset expiry value */
8759  peer->expiry = min_reg_expire;
8760  if (!ast_test_flag64(peer, IAX_TEMPONLY))
8761  ast_db_del("IAX/Registry", peer->name);
8762  register_peer_exten(peer, 0);
8763  ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
8764  if (iax2_regfunk)
8765  iax2_regfunk(peer->name, 0);
8766 
8767  if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
8768  unlink_peer(peer);
8769 
8770  peer_unref(peer);
8771 }
8772 
8773 static int expire_registry(const void *data)
8774 {
8775 #ifdef SCHED_MULTITHREADED
8777 #endif
8778  __expire_registry(data);
8779  return 0;
8780 }
8781 
8782 static void reg_source_db(struct iax2_peer *p)
8783 {
8784  char data[80];
8785  char *expiry;
8786 
8787  if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
8788  return;
8789  }
8790 
8791  expiry = strrchr(data, ':');
8792  if (!expiry) {
8793  ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
8794  return;
8795  }
8796  *expiry++ = '\0';
8797 
8798  if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
8799  ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
8800  return;
8801  }
8802 
8803  p->expiry = atoi(expiry);
8804 
8805  ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
8807 
8808  iax2_poke_peer(p, 0);
8809  if (p->expire > -1) {
8810  if (!ast_sched_thread_del(sched, p->expire)) {
8811  p->expire = -1;
8812  peer_unref(p);
8813  }
8814  }
8815 
8816  ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8817 
8818  p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
8819  if (p->expire == -1) {
8820  peer_unref(p);
8821  }
8822 
8823  if (iax2_regfunk) {
8824  iax2_regfunk(p->name, 1);
8825  }
8826 
8827  register_peer_exten(p, 1);
8828 }
8829 
8830 /*!
8831  * \pre iaxsl[callno] is locked
8832  *
8833  * \note Since this function calls send_command_final(), the pvt struct for
8834  * the given call number may disappear while executing this function.
8835  */
8836 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
8837 {
8838  /* Called from IAX thread only, with proper iaxsl lock */
8839  struct iax_ie_data ied = {
8840  .pos = 0,
8841  };
8842  struct iax2_peer *p;
8843  int msgcount;
8844  char data[80];
8845  int version;
8846  const char *peer_name;
8847  int res = -1;
8848  struct ast_sockaddr sockaddr;
8849 
8850  ast_sockaddr_from_sin(&sockaddr, sin);
8851 
8852  peer_name = ast_strdupa(iaxs[callno]->peer);
8853 
8854  /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
8855  ast_mutex_unlock(&iaxsl[callno]);
8856  if (!(p = find_peer(peer_name, 1))) {
8857  ast_mutex_lock(&iaxsl[callno]);
8858  ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
8859  return -1;
8860  }
8861  ast_mutex_lock(&iaxsl[callno]);
8862  if (!iaxs[callno])
8863  goto return_unref;
8864 
8866  if (sin->sin_addr.s_addr) {
8867  time_t nowtime;
8868  time(&nowtime);
8869  realtime_update_peer(peer_name, &sockaddr, nowtime);
8870  } else {
8871  realtime_update_peer(peer_name, &sockaddr, 0);
8872  }
8873  }
8874 
8875  /* treat an unspecified refresh interval as the minimum */
8876  if (!refresh) {
8877  refresh = min_reg_expire;
8878  }
8879  if (refresh > max_reg_expire) {
8880  ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
8881  p->name, max_reg_expire, refresh);
8882  p->expiry = max_reg_expire;
8883  } else if (refresh < min_reg_expire) {
8884  ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
8885  p->name, min_reg_expire, refresh);
8886  p->expiry = min_reg_expire;
8887  } else {
8888  p->expiry = refresh;
8889  }
8890 
8891  if (ast_sockaddr_cmp(&p->addr, &sockaddr)) {
8892  if (iax2_regfunk) {
8893  iax2_regfunk(p->name, 1);
8894  }
8895 
8896  /* modify entry in peercnts table as _not_ registered */
8897  peercnt_modify((unsigned char) 0, 0, &p->addr);
8898 
8899  /* Stash the IP address from which they registered */
8900  ast_sockaddr_from_sin(&p->addr, sin);
8901 
8902  snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
8903  if (!ast_test_flag64(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
8904  ast_db_put("IAX/Registry", p->name, data);
8905  ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
8906  ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
8907  manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
8908  register_peer_exten(p, 1);
8909  ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8910  } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
8911  ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
8912  ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
8913  manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
8914  register_peer_exten(p, 0);
8915  ast_db_del("IAX/Registry", p->name);
8916  ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8917  }
8918  /* Update the host */
8919  /* Verify that the host is really there */
8920  iax2_poke_peer(p, callno);
8921  }
8922 
8923  /* modify entry in peercnts table as registered */
8924  if (p->maxcallno) {
8925  peercnt_modify((unsigned char) 1, p->maxcallno, &p->addr);
8926  }
8927 
8928  /* Make sure our call still exists, an INVAL at the right point may make it go away */
8929  if (!iaxs[callno]) {
8930  res = -1;
8931  goto return_unref;
8932  }
8933 
8934  /* Store socket fd */
8935  p->sockfd = fd;
8936  /* Setup the expiry */
8937  if (p->expire > -1) {
8938  if (!ast_sched_thread_del(sched, p->expire)) {
8939  p->expire = -1;
8940  peer_unref(p);
8941  }
8942  }
8943 
8944  if (p->expiry && sin->sin_addr.s_addr) {
8945  p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
8946  if (p->expire == -1)
8947  peer_unref(p);
8948  }
8951  if (sin->sin_addr.s_addr) {
8952  struct sockaddr_in peer_addr;
8953 
8954  ast_sockaddr_to_sin(&p->addr, &peer_addr);
8955 
8957  iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
8958  if (!ast_strlen_zero(p->mailbox)) {
8959  struct ast_event *event;
8960  int new, old;
8961  char *mailbox, *context;
8962 
8963  context = mailbox = ast_strdupa(p->mailbox);
8964  strsep(&context, "@");
8965  if (ast_strlen_zero(context))
8966  context = "default";
8967 
8972  if (event) {
8975  ast_event_destroy(event);
8976  } else { /* Fall back on checking the mailbox directly */
8977  ast_app_inboxcount(p->mailbox, &new, &old);
8978  }
8979 
8980  if (new > 255) {
8981  new = 255;
8982  }
8983  if (old > 255) {
8984  old = 255;
8985  }
8986  msgcount = (old << 8) | new;
8987 
8988  iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
8989  }
8990  if (ast_test_flag64(p, IAX_HASCALLERID)) {
8993  }
8994  }
8995  version = iax_check_version(devtype);
8996  if (version)
8997  iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
8998 
8999  res = 0;
9000 
9001 return_unref:
9002  peer_unref(p);
9003 
9004  return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
9005 }
9006 
9007 static int registry_authrequest(int callno)
9008 {
9009  struct iax_ie_data ied;
9010  struct iax2_peer *p;
9011  char challenge[10];
9012  const char *peer_name;
9013  int sentauthmethod;
9014 
9015  peer_name = ast_strdupa(iaxs[callno]->peer);
9016 
9017  /* SLD: third call to find_peer in registration */
9018  ast_mutex_unlock(&iaxsl[callno]);
9019  if ((p = find_peer(peer_name, 1))) {
9020  last_authmethod = p->authmethods;
9021  }
9022 
9023  ast_mutex_lock(&iaxsl[callno]);
9024  if (!iaxs[callno])
9025  goto return_unref;
9026 
9027  memset(&ied, 0, sizeof(ied));
9028  /* The selection of which delayed reject is sent may leak information,
9029  * if it sets a static response. For example, if a host is known to only
9030  * use MD5 authentication, then an RSA response would indicate that the
9031  * peer does not exist, and vice-versa.
9032  * Therefore, we use whatever the last peer used (which may vary over the
9033  * course of a server, which should leak minimal information). */
9034  sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
9035  if (!p) {
9036  iaxs[callno]->authmethods = sentauthmethod;
9037  }
9038  iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
9039  if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
9040  /* Build the challenge */
9041  snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
9042  ast_string_field_set(iaxs[callno], challenge, challenge);
9043  iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
9044  }
9045  iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
9046 
9047 return_unref:
9048  if (p) {
9049  peer_unref(p);
9050  }
9051 
9052  return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
9053 }
9054 
9055 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
9056 {
9057  struct iax2_registry *reg;
9058  /* Start pessimistic */
9059  struct iax_ie_data ied;
9060  char peer[256] = "";
9061  char challenge[256] = "";
9062  int res;
9063  int authmethods = 0;
9064  if (ies->authmethods)
9065  authmethods = ies->authmethods;
9066  if (ies->username)
9067  ast_copy_string(peer, ies->username, sizeof(peer));
9068  if (ies->challenge)
9069  ast_copy_string(challenge, ies->challenge, sizeof(challenge));
9070  memset(&ied, 0, sizeof(ied));
9071  reg = iaxs[callno]->reg;
9072  if (reg) {
9073  struct sockaddr_in reg_addr;
9074 
9075  ast_sockaddr_to_sin(&reg->addr, &reg_addr);
9076 
9077  if (inaddrcmp(&reg_addr, sin)) {
9078  ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
9079  return -1;
9080  }
9081  if (ast_strlen_zero(reg->secret)) {
9082  ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
9083  reg->regstate = REG_STATE_NOAUTH;
9084  return -1;
9085  }
9088  if (reg->secret[0] == '[') {
9089  char tmpkey[256];
9090  ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
9091  tmpkey[strlen(tmpkey) - 1] = '\0';
9092  res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
9093  } else
9094  res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
9095  if (!res) {
9097  add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
9098  return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
9099  } else
9100  return -1;
9101  ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
9102  } else
9103  ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
9104  return -1;
9105 }
9106 
9107 static void stop_stuff(int callno)
9108 {
9109  iax2_destroy_helper(iaxs[callno]);
9110 }
9111 
9112 static void __auth_reject(const void *nothing)
9113 {
9114  /* Called from IAX thread only, without iaxs lock */
9115  int callno = (int)(long)(nothing);
9116  struct iax_ie_data ied;
9117  ast_mutex_lock(&iaxsl[callno]);
9118  if (iaxs[callno]) {
9119  memset(&ied, 0, sizeof(ied));
9120  if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
9121  iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
9123  } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
9124  iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
9126  }
9127  send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
9128  }
9129  ast_mutex_unlock(&iaxsl[callno]);
9130 }
9131 
9132 static int auth_reject(const void *data)
9133 {
9134  int callno = (int)(long)(data);
9135  ast_mutex_lock(&iaxsl[callno]);
9136  if (iaxs[callno])
9137  iaxs[callno]->authid = -1;
9138  ast_mutex_unlock(&iaxsl[callno]);
9139 #ifdef SCHED_MULTITHREADED
9140  if (schedule_action(__auth_reject, data))
9141 #endif
9142  __auth_reject(data);
9143  return 0;
9144 }
9145 
9146 static int auth_fail(int callno, int failcode)
9147 {
9148  /* Schedule sending the authentication failure in one second, to prevent
9149  guessing */
9150  if (iaxs[callno]) {
9151  iaxs[callno]->authfail = failcode;
9152  if (delayreject) {
9153  iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
9154  sched, 1000, auth_reject, (void *)(long)callno);
9155  } else
9156  auth_reject((void *)(long)callno);
9157  }
9158  return 0;
9159 }
9160 
9161 static void __auto_hangup(const void *nothing)
9162 {
9163  /* Called from IAX thread only, without iaxs lock */
9164  int callno = (int)(long)(nothing);
9165  struct iax_ie_data ied;
9166  ast_mutex_lock(&iaxsl[callno]);
9167  if (iaxs[callno]) {
9168  memset(&ied, 0, sizeof(ied));
9169  iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
9171  send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
9172  }
9173  ast_mutex_unlock(&iaxsl[callno]);
9174 }
9175 
9176 static int auto_hangup(const void *data)
9177 {
9178  int callno = (int)(long)(data);
9179  ast_mutex_lock(&iaxsl[callno]);
9180  if (iaxs[callno]) {
9181  iaxs[callno]->autoid = -1;
9182  }
9183  ast_mutex_unlock(&iaxsl[callno]);
9184 #ifdef SCHED_MULTITHREADED
9185  if (schedule_action(__auto_hangup, data))
9186 #endif
9187  __auto_hangup(data);
9188  return 0;
9189 }
9190 
9191 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
9192 {
9193  struct iax_ie_data ied;
9194  /* Auto-hangup with 30 seconds of inactivity */
9195  iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
9196  sched, 30000, auto_hangup, (void *)(long)callno);
9197  memset(&ied, 0, sizeof(ied));
9199  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
9201 }
9202 
9203 static int iax2_vnak(int callno)
9204 {
9205  return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
9206 }
9207 
9208 static void vnak_retransmit(int callno, int last)
9209 {
9210  struct iax_frame *f;
9211 
9212  AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
9213  /* Send a copy immediately */
9214  if (((unsigned char) (f->oseqno - last) < 128) &&
9215  (f->retries >= 0)) {
9216  send_packet(f);
9217  }
9218  }
9219 }
9220 
9221 static void __iax2_poke_peer_s(const void *data)
9222 {
9223  struct iax2_peer *peer = (struct iax2_peer *)data;
9224  iax2_poke_peer(peer, 0);
9225  peer_unref(peer);
9226 }
9227 
9228 static int iax2_poke_peer_s(const void *data)
9229 {
9230  struct iax2_peer *peer = (struct iax2_peer *)data;
9231  peer->pokeexpire = -1;
9232 #ifdef SCHED_MULTITHREADED
9234 #endif
9235  __iax2_poke_peer_s(data);
9236  return 0;
9237 }
9238 
9239 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
9240 {
9241  int res = 0;
9242  struct iax_frame *fr;
9243  struct ast_iax2_meta_hdr *meta;
9244  struct ast_iax2_meta_trunk_hdr *mth;
9245  int calls = 0;
9246 
9247  /* Point to frame */
9248  fr = (struct iax_frame *)tpeer->trunkdata;
9249  /* Point to meta data */
9250  meta = (struct ast_iax2_meta_hdr *)fr->afdata;
9251  mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
9252  if (tpeer->trunkdatalen) {
9253  /* We're actually sending a frame, so fill the meta trunk header and meta header */
9254  meta->zeros = 0;
9255  meta->metacmd = IAX_META_TRUNK;
9256  if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
9257  meta->cmddata = IAX_META_TRUNK_MINI;
9258  else
9260  mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
9261  /* And the rest of the ast_iax2 header */
9263  fr->retrans = -1;
9264  fr->transfer = 0;
9265  /* Any appropriate call will do */
9266  fr->data = fr->afdata;
9267  fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
9268  res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
9269  calls = tpeer->calls;
9270 #if 0
9271  ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
9272 #endif
9273  /* Reset transmit trunk side data */
9274  tpeer->trunkdatalen = 0;
9275  tpeer->calls = 0;
9276  }
9277  if (res < 0)
9278  return res;
9279  return calls;
9280 }
9281 
9282 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
9283 {
9284  /* Drop when trunk is about 5 seconds idle */
9285  if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
9286  return 1;
9287  return 0;
9288 }
9289 
9290 static int timing_read(int *id, int fd, short events, void *cbdata)
9291 {
9292  int res, processed = 0, totalcalls = 0;
9293  struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
9294  struct timeval now = ast_tvnow();
9295 
9296  if (iaxtrunkdebug)
9297  ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
9298 
9299  if (timer) {
9300  if (ast_timer_ack(timer, 1) < 0) {
9301  ast_log(LOG_ERROR, "Timer failed acknowledge\n");
9302  return 0;
9303  }
9304  }
9305 
9306  /* For each peer that supports trunking... */
9307  AST_LIST_LOCK(&tpeers);
9308  AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
9309  processed++;
9310  res = 0;
9311  ast_mutex_lock(&tpeer->lock);
9312  /* We can drop a single tpeer per pass. That makes all this logic
9313  substantially easier */
9314  if (!drop && iax2_trunk_expired(tpeer, &now)) {
9315  /* Take it out of the list, but don't free it yet, because it
9316  could be in use */
9318  drop = tpeer;
9319  } else {
9320  res = send_trunk(tpeer, &now);
9321  trunk_timed++;
9322  if (iaxtrunkdebug)
9323  ast_verbose(" - Trunk peer (%s:%d) has %d call chunk%s in transit, %u bytes backloged and has hit a high water mark of %u bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), res, (res != 1) ? "s" : "", tpeer->trunkdatalen, tpeer->trunkdataalloc);
9324  }
9325  totalcalls += res;
9326  res = 0;
9327  ast_mutex_unlock(&tpeer->lock);
9328  }
9330  AST_LIST_UNLOCK(&tpeers);
9331 
9332  if (drop) {
9333  ast_mutex_lock(&drop->lock);
9334  /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
9335  because by the time they could get tpeerlock, we've already grabbed it */
9336  ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
9337  if (drop->trunkdata) {
9338  ast_free(drop->trunkdata);
9339  drop->trunkdata = NULL;
9340  }
9341  ast_mutex_unlock(&drop->lock);
9342  ast_mutex_destroy(&drop->lock);
9343  ast_free(drop);
9344 
9345  }
9346 
9347  if (iaxtrunkdebug)
9348  ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
9349  iaxtrunkdebug = 0;
9350 
9351  return 1;
9352 }
9353 
9354 struct dpreq_data {
9355  int callno;
9357  char callednum[AST_MAX_EXTENSION];
9358  char *callerid;
9359 };
9360 
9361 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
9362 {
9363  unsigned short dpstatus = 0;
9364  struct iax_ie_data ied1;
9365  int mm;
9366 
9367  memset(&ied1, 0, sizeof(ied1));
9368  mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
9369  /* Must be started */
9370  if (ast_parking_ext_valid(callednum, NULL, context) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
9371  dpstatus = IAX_DPSTATUS_EXISTS;
9372  } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
9373  dpstatus = IAX_DPSTATUS_CANEXIST;
9374  } else {
9375  dpstatus = IAX_DPSTATUS_NONEXISTENT;
9376  }
9377  if (ast_ignore_pattern(context, callednum))
9378  dpstatus |= IAX_DPSTATUS_IGNOREPAT;
9379  if (mm)
9380  dpstatus |= IAX_DPSTATUS_MATCHMORE;
9381  if (!skiplock)
9382  ast_mutex_lock(&iaxsl[callno]);
9383  if (iaxs[callno]) {
9384  iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
9385  iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
9386  iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
9387  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
9388  }
9389  if (!skiplock)
9390  ast_mutex_unlock(&iaxsl[callno]);
9391 }
9392 
9393 static void *dp_lookup_thread(void *data)
9394 {
9395  /* Look up for dpreq */
9396  struct dpreq_data *dpr = data;
9397  dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
9398  if (dpr->callerid)
9399  ast_free(dpr->callerid);
9400  ast_free(dpr);
9401  return NULL;
9402 }
9403 
9404 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
9405 {
9406  pthread_t newthread;
9407  struct dpreq_data *dpr;
9408 
9409  if (!(dpr = ast_calloc(1, sizeof(*dpr))))
9410  return;
9411 
9412  dpr->callno = callno;
9413  ast_copy_string(dpr->context, context, sizeof(dpr->context));
9414  ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
9415  if (callerid)
9416  dpr->callerid = ast_strdup(callerid);
9417  if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
9418  ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
9419  }
9420 }
9421 
9422 struct iax_dual {
9425  char *park_exten;
9427 };
9428 
9429 static void *iax_park_thread(void *stuff)
9430 {
9431  struct iax_dual *d;
9432  int res;
9433  int ext = 0;
9434 
9435  d = stuff;
9436 
9437  ast_debug(4, "IAX Park: Transferer channel %s, Transferee %s\n",
9438  d->chan2->name, d->chan1->name);
9439 
9440  res = ast_park_call_exten(d->chan1, d->chan2, d->park_exten, d->park_context, 0, &ext);
9441  if (res) {
9442  /* Parking failed. */
9443  ast_hangup(d->chan1);
9444  } else {
9445  ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
9446  }
9447  ast_hangup(d->chan2);
9448 
9449  ast_free(d->park_exten);
9450  ast_free(d->park_context);
9451  ast_free(d);
9452  return NULL;
9453 }
9454 
9455 /*! DO NOT hold any locks while calling iax_park */
9456 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2, const char *park_exten, const char *park_context)
9457 {
9458  struct iax_dual *d;
9459  struct ast_channel *chan1m, *chan2m;/* Chan2m: The transferer, chan1m: The transferee */
9460  pthread_t th;
9461 
9462  chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
9463  chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "IAXPeer/%s", chan2->name);
9464  d = ast_calloc(1, sizeof(*d));
9465  if (!chan1m || !chan2m || !d) {
9466  if (chan1m) {
9467  ast_hangup(chan1m);
9468  }
9469  if (chan2m) {
9470  ast_hangup(chan2m);
9471  }
9472  ast_free(d);
9473  return -1;
9474  }
9475  d->park_exten = ast_strdup(park_exten);
9476  d->park_context = ast_strdup(park_context);
9477  if (!d->park_exten || !d->park_context) {
9478  ast_hangup(chan1m);
9479  ast_hangup(chan2m);
9480  ast_free(d->park_exten);
9481  ast_free(d->park_context);
9482  ast_free(d);
9483  return -1;
9484  }
9485 
9486  /* Make formats okay */
9487  chan1m->readformat = chan1->readformat;
9488  chan1m->writeformat = chan1->writeformat;
9489 
9490  /* Prepare for taking over the channel */
9491  if (ast_channel_masquerade(chan1m, chan1)) {
9492  ast_hangup(chan1m);
9493  ast_hangup(chan2m);
9494  ast_free(d->park_exten);
9495  ast_free(d->park_context);
9496  ast_free(d);
9497  return -1;
9498  }
9499 
9500  /* Setup the extensions and such */
9501  ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
9502  ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
9503  chan1m->priority = chan1->priority;
9504 
9505  ast_do_masquerade(chan1m);
9506 
9507  /* We make a clone of the peer channel too, so we can play
9508  back the announcement */
9509 
9510  /* Make formats okay */
9511  chan2m->readformat = chan2->readformat;
9512  chan2m->writeformat = chan2->writeformat;
9513  ast_string_field_set(chan2m, parkinglot, chan2->parkinglot);
9514 
9515  /* Prepare for taking over the channel */
9516  if (ast_channel_masquerade(chan2m, chan2)) {
9517  ast_hangup(chan1m);
9518  ast_hangup(chan2m);
9519  ast_free(d->park_exten);
9520  ast_free(d->park_context);
9521  ast_free(d);
9522  return -1;
9523  }
9524 
9525  /* Setup the extensions and such */
9526  ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
9527  ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
9528  chan2m->priority = chan2->priority;
9529 
9530  ast_do_masquerade(chan2m);
9531 
9532  d->chan1 = chan1m; /* Transferee */
9533  d->chan2 = chan2m; /* Transferer */
9535  /* Could not start thread */
9536  ast_hangup(chan1m);
9537  ast_hangup(chan2m);
9538  ast_free(d->park_exten);
9539  ast_free(d->park_context);
9540  ast_free(d);
9541  return -1;
9542  }
9543  return 0;
9544 }
9545 
9546 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
9547 {
9548  unsigned int ourver;
9549  char rsi[80];
9550  snprintf(rsi, sizeof(rsi), "si-%s", si);
9551  if (iax_provision_version(&ourver, rsi, 1))
9552  return 0;
9553  ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
9554  if (ourver != ver)
9555  iax2_provision(sin, sockfd, NULL, rsi, 1);
9556  return 0;
9557 }
9558 
9559 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
9560 {
9561  jb_info stats;
9562  jb_getinfo(pvt->jb, &stats);
9563 
9564  memset(iep, 0, sizeof(*iep));
9565 
9567  if(stats.frames_in == 0) stats.frames_in = 1;
9568  iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
9570  iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
9573 }
9574 
9575 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
9576 {
9577  iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
9578  iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
9579  iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
9580  iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
9581  iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
9582  iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
9583  iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
9584 }
9585 
9586 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
9587 {
9588  int i;
9589  unsigned int length, offset = 0;
9590  char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
9591 
9592  for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
9593  length = ies->ospblocklength[i];
9594  if (length != 0) {
9595  if (length > IAX_MAX_OSPBLOCK_SIZE) {
9596  /* OSP token block length wrong, clear buffer */
9597  offset = 0;
9598  break;
9599  } else {
9600  memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
9601  offset += length;
9602  }
9603  } else {
9604  break;
9605  }
9606  }
9607  *(full_osptoken + offset) = '\0';
9608  if (strlen(full_osptoken) != offset) {
9609  /* OSP token length wrong, clear buffer */
9610  *full_osptoken = '\0';
9611  }
9612 
9613  ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
9614 }
9615 
9616 static void log_jitterstats(unsigned short callno)
9617 {
9618  int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
9619  jb_info jbinfo;
9620 
9621  ast_mutex_lock(&iaxsl[callno]);
9622  if (iaxs[callno] && iaxs[callno]->owner && iaxs[callno]->owner->name) {
9623  if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
9624  jb_getinfo(iaxs[callno]->jb, &jbinfo);
9625  localjitter = jbinfo.jitter;
9626  localdelay = jbinfo.current - jbinfo.min;
9627  locallost = jbinfo.frames_lost;
9628  locallosspct = jbinfo.losspct/1000;
9629  localdropped = jbinfo.frames_dropped;
9630  localooo = jbinfo.frames_ooo;
9631  localpackets = jbinfo.frames_in;
9632  }
9633  ast_debug(3, "JB STATS:%s ping=%u ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
9634  iaxs[callno]->owner->name,
9635  iaxs[callno]->pingtime,
9636  localjitter,
9637  localdelay,
9638  locallost,
9639  locallosspct,
9640  localdropped,
9641  localooo,
9642  localpackets,
9643  iaxs[callno]->remote_rr.jitter,
9644  iaxs[callno]->remote_rr.delay,
9645  iaxs[callno]->remote_rr.losscnt,
9646  iaxs[callno]->remote_rr.losspct/1000,
9647  iaxs[callno]->remote_rr.dropped,
9648  iaxs[callno]->remote_rr.ooo,
9649  iaxs[callno]->remote_rr.packets);
9650  manager_event(EVENT_FLAG_REPORTING, "JitterBufStats", "Owner: %s\r\nPing: %u\r\nLocalJitter: %d\r\nLocalJBDelay: %d\r\nLocalTotalLost: %d\r\nLocalLossPercent: %d\r\nLocalDropped: %d\r\nLocalooo: %d\r\nLocalReceived: %d\r\nRemoteJitter: %d\r\nRemoteJBDelay: %d\r\nRemoteTotalLost: %d\r\nRemoteLossPercent: %d\r\nRemoteDropped: %d\r\nRemoteooo: %d\r\nRemoteReceived: %d\r\n",
9651  iaxs[callno]->owner->name,
9652  iaxs[callno]->pingtime,
9653  localjitter,
9654  localdelay,
9655  locallost,
9656  locallosspct,
9657  localdropped,
9658  localooo,
9659  localpackets,
9660  iaxs[callno]->remote_rr.jitter,
9661  iaxs[callno]->remote_rr.delay,
9662  iaxs[callno]->remote_rr.losscnt,
9663  iaxs[callno]->remote_rr.losspct/1000,
9664  iaxs[callno]->remote_rr.dropped,
9665  iaxs[callno]->remote_rr.ooo,
9666  iaxs[callno]->remote_rr.packets);
9667  }
9668  ast_mutex_unlock(&iaxsl[callno]);
9669 }
9670 
9671 static int socket_process(struct iax2_thread *thread);
9672 
9673 /*!
9674  * \brief Handle any deferred full frames for this thread
9675  */
9676 static void handle_deferred_full_frames(struct iax2_thread *thread)
9677 {
9678  struct iax2_pkt_buf *pkt_buf;
9679 
9680  ast_mutex_lock(&thread->lock);
9681 
9682  while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
9683  ast_mutex_unlock(&thread->lock);
9684 
9685  thread->buf = pkt_buf->buf;
9686  thread->buf_len = pkt_buf->len;
9687  thread->buf_size = pkt_buf->len + 1;
9688 
9689  socket_process(thread);
9690 
9691  thread->buf = NULL;
9692  ast_free(pkt_buf);
9693 
9694  ast_mutex_lock(&thread->lock);
9695  }
9696 
9697  ast_mutex_unlock(&thread->lock);
9698 }
9699 
9700 /*!
9701  * \brief Queue the last read full frame for processing by a certain thread
9702  *
9703  * If there are already any full frames queued, they are sorted
9704  * by sequence number.
9705  */
9706 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
9707 {
9708  struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
9709  struct ast_iax2_full_hdr *fh, *cur_fh;
9710 
9711  if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
9712  return;
9713 
9714  pkt_buf->len = from_here->buf_len;
9715  memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
9716 
9717  fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
9718  ast_mutex_lock(&to_here->lock);
9719  AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
9720  cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
9721  if (fh->oseqno < cur_fh->oseqno) {
9722  AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
9723  break;
9724  }
9725  }
9727 
9728  if (!cur_pkt_buf)
9729  AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
9730 
9731  to_here->iostate = IAX_IOSTATE_READY;
9732  ast_cond_signal(&to_here->cond);
9733 
9734  ast_mutex_unlock(&to_here->lock);
9735 }
9736 
9737 static int socket_read(int *id, int fd, short events, void *cbdata)
9738 {
9739  struct iax2_thread *thread;
9740  socklen_t len;
9741  time_t t;
9742  static time_t last_errtime = 0;
9743  struct ast_iax2_full_hdr *fh;
9744 
9745  if (!(thread = find_idle_thread())) {
9746  time(&t);
9747  if (t != last_errtime) {
9748  last_errtime = t;
9749  ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
9750  }
9751  usleep(1);
9752  return 1;
9753  }
9754 
9755  len = sizeof(thread->iosin);
9756  thread->iofd = fd;
9757  thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
9758  thread->buf_size = sizeof(thread->readbuf);
9759  thread->buf = thread->readbuf;
9760  if (thread->buf_len < 0) {
9761  if (errno != ECONNREFUSED && errno != EAGAIN)
9762  ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
9763  handle_error();
9764  thread->iostate = IAX_IOSTATE_IDLE;
9765  signal_condition(&thread->lock, &thread->cond);
9766  return 1;
9767  }
9768  if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
9769  thread->iostate = IAX_IOSTATE_IDLE;
9770  signal_condition(&thread->lock, &thread->cond);
9771  return 1;
9772  }
9773 
9774  /* Determine if this frame is a full frame; if so, and any thread is currently
9775  processing a full frame for the same callno from this peer, then drop this
9776  frame (and the peer will retransmit it) */
9777  fh = (struct ast_iax2_full_hdr *) thread->buf;
9778  if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
9779  struct iax2_thread *cur = NULL;
9780  uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
9781 
9783  AST_LIST_TRAVERSE(&active_list, cur, list) {
9784  if ((cur->ffinfo.callno == callno) &&
9785  !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
9786  break;
9787  }
9788  if (cur) {
9789  /* we found another thread processing a full frame for this call,
9790  so queue it up for processing later. */
9791  defer_full_frame(thread, cur);
9793  thread->iostate = IAX_IOSTATE_IDLE;
9794  signal_condition(&thread->lock, &thread->cond);
9795  return 1;
9796  } else {
9797  /* this thread is going to process this frame, so mark it */
9798  thread->ffinfo.callno = callno;
9799  memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
9800  thread->ffinfo.type = fh->type;
9801  thread->ffinfo.csub = fh->csub;
9802  AST_LIST_INSERT_HEAD(&active_list, thread, list);
9803  }
9805  }
9806 
9807  /* Mark as ready and send on its way */
9808  thread->iostate = IAX_IOSTATE_READY;
9809 #ifdef DEBUG_SCHED_MULTITHREAD
9810  ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
9811 #endif
9812  signal_condition(&thread->lock, &thread->cond);
9813 
9814  return 1;
9815 }
9816 
9817 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
9818  struct iax_frame *fr)
9819 {
9820  unsigned char metatype;
9821  struct ast_iax2_meta_trunk_mini *mtm;
9822  struct ast_iax2_meta_trunk_hdr *mth;
9823  struct ast_iax2_meta_trunk_entry *mte;
9824  struct iax2_trunk_peer *tpeer;
9825  unsigned int ts;
9826  void *ptr;
9827  struct timeval rxtrunktime;
9828  struct ast_frame f = { 0, };
9829 
9830  if (packet_len < sizeof(*meta)) {
9831  ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n",
9832  ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
9833  return 1;
9834  }
9835 
9836  if (meta->metacmd != IAX_META_TRUNK)
9837  return 1;
9838 
9839  if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
9840  ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
9841  (int) (sizeof(*meta) + sizeof(*mth)));
9842  return 1;
9843  }
9844  mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
9845  ts = ntohl(mth->ts);
9846  metatype = meta->cmddata;
9847  packet_len -= (sizeof(*meta) + sizeof(*mth));
9848  ptr = mth->data;
9849  tpeer = find_tpeer(sin, sockfd);
9850  if (!tpeer) {
9851  ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n",
9852  ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
9853  return 1;
9854  }
9855  tpeer->trunkact = ast_tvnow();
9856  if (!ts || ast_tvzero(tpeer->rxtrunktime))
9857  tpeer->rxtrunktime = tpeer->trunkact;
9858  rxtrunktime = tpeer->rxtrunktime;
9859  ast_mutex_unlock(&tpeer->lock);
9860  while (packet_len >= sizeof(*mte)) {
9861  /* Process channels */
9862  unsigned short callno, trunked_ts, len;
9863 
9864  if (metatype == IAX_META_TRUNK_MINI) {
9865  mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
9866  ptr += sizeof(*mtm);
9867  packet_len -= sizeof(*mtm);
9868  len = ntohs(mtm->len);
9869  callno = ntohs(mtm->mini.callno);
9870  trunked_ts = ntohs(mtm->mini.ts);
9871  } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
9872  mte = (struct ast_iax2_meta_trunk_entry *)ptr;
9873  ptr += sizeof(*mte);
9874  packet_len -= sizeof(*mte);
9875  len = ntohs(mte->len);
9876  callno = ntohs(mte->callno);
9877  trunked_ts = 0;
9878  } else {
9879  ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
9880  break;
9881  }
9882  /* Stop if we don't have enough data */
9883  if (len > packet_len)
9884  break;
9885  fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
9886  if (!fr->callno)
9887  continue;
9888 
9889  /* If it's a valid call, deliver the contents. If not, we
9890  drop it, since we don't have a scallno to use for an INVAL */
9891  /* Process as a mini frame */
9892  memset(&f, 0, sizeof(f));
9894  if (!iaxs[fr->callno]) {
9895  /* drop it */
9896  } else if (iaxs[fr->callno]->voiceformat == 0) {
9897  ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
9898  iax2_vnak(fr->callno);
9899  } else {
9900  f.subclass.codec = iaxs[fr->callno]->voiceformat;
9901  f.datalen = len;
9902  if (f.datalen >= 0) {
9903  if (f.datalen)
9904  f.data.ptr = ptr;
9905  else
9906  f.data.ptr = NULL;
9907  if (trunked_ts)
9908  fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
9909  else
9910  fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
9911  /* Don't pass any packets until we're started */
9912  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
9913  struct iax_frame *duped_fr;
9914 
9915  /* Common things */
9916  f.src = "IAX2";
9917  f.mallocd = 0;
9918  f.offset = 0;
9919  if (f.datalen && (f.frametype == AST_FRAME_VOICE))
9921  else
9922  f.samples = 0;
9923  fr->outoforder = 0;
9924  iax_frame_wrap(fr, &f);
9925  duped_fr = iaxfrdup2(fr);
9926  if (duped_fr)
9927  schedule_delivery(duped_fr, 1, 1, &fr->ts);
9928  if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
9929  iaxs[fr->callno]->last = fr->ts;
9930  }
9931  } else {
9932  ast_log(LOG_WARNING, "Datalen < 0?\n");
9933  }
9934  }
9935  ast_mutex_unlock(&iaxsl[fr->callno]);
9936  ptr += len;
9937  packet_len -= len;
9938  }
9939 
9940  return 1;
9941 }
9942 
9943 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9944 {
9945  struct ast_datastore *variablestore;
9946  AST_LIST_HEAD(, ast_var_t) *varlist;
9947  struct ast_var_t *var;
9948 
9949  if (!chan) {
9950  ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
9951  return -1;
9952  }
9953 
9954  variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
9955 
9956  if (!variablestore) {
9957  *buf = '\0';
9958  return 0;
9959  }
9960  varlist = variablestore->data;
9961 
9962  AST_LIST_LOCK(varlist);
9963  AST_LIST_TRAVERSE(varlist, var, entries) {
9964  if (strcmp(var->name, data) == 0) {
9965  ast_copy_string(buf, var->value, len);
9966  break;
9967  }
9968  }
9969  AST_LIST_UNLOCK(varlist);
9970  return 0;
9971 }
9972 
9973 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
9974 {
9975  struct ast_datastore *variablestore;
9976  AST_LIST_HEAD(, ast_var_t) *varlist;
9977  struct ast_var_t *var;
9978 
9979  if (!chan) {
9980  ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
9981  return -1;
9982  }
9983 
9984  variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
9985 
9986  if (!variablestore) {
9987  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
9988  if (!variablestore) {
9989  ast_log(LOG_ERROR, "Memory allocation error\n");
9990  return -1;
9991  }
9992  varlist = ast_calloc(1, sizeof(*varlist));
9993  if (!varlist) {
9994  ast_datastore_free(variablestore);
9995  ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
9996  return -1;
9997  }
9998 
9999  AST_LIST_HEAD_INIT(varlist);
10000  variablestore->data = varlist;
10001  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10002  ast_channel_datastore_add(chan, variablestore);
10003  } else
10004  varlist = variablestore->data;
10005 
10006  AST_LIST_LOCK(varlist);
10007  AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
10008  if (strcmp(var->name, data) == 0) {
10010  ast_var_delete(var);
10011  break;
10012  }
10013  }
10015  var = ast_var_assign(data, value);
10016  if (var)
10017  AST_LIST_INSERT_TAIL(varlist, var, entries);
10018  else
10019  ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10020  AST_LIST_UNLOCK(varlist);
10021  return 0;
10022 }
10023 
10025  .name = "IAXVAR",
10026  .read = acf_iaxvar_read,
10027  .write = acf_iaxvar_write,
10028 };
10029 
10030 static void set_hangup_source_and_cause(int callno, unsigned char causecode)
10031 {
10032  iax2_lock_owner(callno);
10033  if (iaxs[callno] && iaxs[callno]->owner) {
10034  struct ast_channel *owner;
10035  const char *name;
10036 
10037  owner = iaxs[callno]->owner;
10038  if (causecode) {
10039  owner->hangupcause = causecode;
10040  }
10041  name = ast_strdupa(owner->name);
10042  ast_channel_ref(owner);
10043  ast_channel_unlock(owner);
10044  ast_mutex_unlock(&iaxsl[callno]);
10045  ast_set_hangupsource(owner, name, 0);
10046  ast_channel_unref(owner);
10047  ast_mutex_lock(&iaxsl[callno]);
10048  }
10049 }
10050 
10051 static int socket_process(struct iax2_thread *thread)
10052 {
10053  struct sockaddr_in sin;
10054  int res;
10055  int updatehistory=1;
10056  int new = NEW_PREVENT;
10057  int dcallno = 0;
10058  char decrypted = 0;
10059  struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
10060  struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
10061  struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
10062  struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
10063  struct iax_frame *fr;
10064  struct iax_frame *cur;
10065  struct ast_frame f = { 0, };
10066  struct ast_channel *c = NULL;
10067  struct iax2_dpcache *dp;
10068  struct iax2_peer *peer;
10069  struct iax_ies ies;
10070  struct iax_ie_data ied0, ied1;
10071  format_t format;
10072  int fd;
10073  int exists;
10074  int minivid = 0;
10075  char empty[32]=""; /* Safety measure */
10076  struct iax_frame *duped_fr;
10077  char host_pref_buf[128];
10078  char caller_pref_buf[128];
10079  struct ast_codec_pref pref;
10080  char *using_prefs = "mine";
10081 
10082  /* allocate an iax_frame with 4096 bytes of data buffer */
10083  fr = ast_alloca(sizeof(*fr) + 4096);
10084  memset(fr, 0, sizeof(*fr));
10085  fr->afdatalen = 4096; /* From ast_alloca() above */
10086 
10087  /* Copy frequently used parameters to the stack */
10088  res = thread->buf_len;
10089  fd = thread->iofd;
10090  memcpy(&sin, &thread->iosin, sizeof(sin));
10091 
10092  if (res < sizeof(*mh)) {
10093  ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
10094  return 1;
10095  }
10096  if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
10097  if (res < sizeof(*vh)) {
10098  ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a video frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
10099  return 1;
10100  }
10101 
10102  /* This is a video frame, get call number */
10103  fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
10104  minivid = 1;
10105  } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
10106  return socket_process_meta(res, meta, &sin, fd, fr);
10107 
10108 #ifdef DEBUG_SUPPORT
10109  if (res >= sizeof(*fh))
10110  iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
10111 #endif
10112  if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10113  if (res < sizeof(*fh)) {
10114  ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a full frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
10115  return 1;
10116  }
10117 
10118  /* Get the destination call number */
10119  dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
10120 
10121 
10122  /* check to make sure this full frame isn't encrypted before we attempt
10123  * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
10124  * callno is not found here, that just means one hasn't been allocated for
10125  * this connection yet. */
10126  if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
10127  ast_mutex_lock(&iaxsl[fr->callno]);
10128  if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
10129  if (decrypt_frame(fr->callno, fh, &f, &res)) {
10130  ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10131  ast_mutex_unlock(&iaxsl[fr->callno]);
10132  return 1;
10133  }
10134  decrypted = 1;
10135  }
10136  ast_mutex_unlock(&iaxsl[fr->callno]);
10137  }
10138 
10139  /* Retrieve the type and subclass */
10140  f.frametype = fh->type;
10141  if (f.frametype == AST_FRAME_VIDEO) {
10142  f.subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
10143  } else if (f.frametype == AST_FRAME_VOICE) {
10145  } else {
10147  }
10148 
10149  /* Deal with POKE/PONG without allocating a callno */
10151  /* Reply back with a PONG, but don't care about the result. */
10152  send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10153  return 1;
10154  } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10155  /* Ignore */
10156  return 1;
10157  }
10158 
10159  f.datalen = res - sizeof(*fh);
10160  if (f.datalen) {
10161  if (f.frametype == AST_FRAME_IAX) {
10162  if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10163  ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
10165  return 1;
10166  }
10167  f.data.ptr = NULL;
10168  f.datalen = 0;
10169  } else {
10170  f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10171  memset(&ies, 0, sizeof(ies));
10172  }
10173  } else {
10174  if (f.frametype == AST_FRAME_IAX)
10175  f.data.ptr = NULL;
10176  else
10177  f.data.ptr = empty;
10178  memset(&ies, 0, sizeof(ies));
10179  }
10180 
10181  if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10182  /* only set NEW_ALLOW if calltoken checks out */
10183  if (handle_call_token(fh, &ies, &sin, fd)) {
10185  return 1;
10186  }
10187 
10188  if (ies.calltoken && ies.calltokendata) {
10189  /* if we've gotten this far, and the calltoken ie data exists,
10190  * then calltoken validation _MUST_ have taken place. If calltoken
10191  * data is provided, it is always validated reguardless of any
10192  * calltokenoptional or requirecalltoken options */
10194  } else {
10195  new = NEW_ALLOW;
10196  }
10197  }
10198  } else {
10199  /* Don't know anything about it yet */
10201  f.subclass.integer = 0;
10202  memset(&ies, 0, sizeof(ies));
10203  }
10204 
10205  if (!fr->callno) {
10206  int check_dcallno = 0;
10207 
10208  /*
10209  * We enforce accurate destination call numbers for ACKs. This forces the other
10210  * end to know the destination call number before call setup can complete.
10211  *
10212  * Discussed in the following thread:
10213  * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
10214  */
10215 
10216  if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10217  check_dcallno = 1;
10218  }
10219 
10220  if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
10222  send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10224  send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10225  }
10227  return 1;
10228  }
10229  }
10230 
10231  if (fr->callno > 0)
10232  ast_mutex_lock(&iaxsl[fr->callno]);
10233 
10234  if (!fr->callno || !iaxs[fr->callno]) {
10235  /* A call arrived for a nonexistent destination. Unless it's an "inval"
10236  frame, reply with an inval */
10237  if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10238  /* We can only raw hangup control frames */
10239  if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10243  (f.frametype != AST_FRAME_IAX))
10244  raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10245  fd);
10246  }
10247  if (fr->callno > 0)
10248  ast_mutex_unlock(&iaxsl[fr->callno]);
10250  return 1;
10251  }
10252  if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10253  if (decrypt_frame(fr->callno, fh, &f, &res)) {
10254  ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10256  ast_mutex_unlock(&iaxsl[fr->callno]);
10257  return 1;
10258  }
10259  decrypted = 1;
10260  }
10261 
10262 #ifdef DEBUG_SUPPORT
10263  if (decrypted) {
10264  iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
10265  }
10266 #endif
10267 
10268 
10269  /* count this frame */
10270  iaxs[fr->callno]->frames_received++;
10271 
10272  if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
10273  f.subclass.integer != IAX_COMMAND_TXCNT && /* for attended transfer */
10274  f.subclass.integer != IAX_COMMAND_TXACC) { /* for attended transfer */
10275  unsigned short new_peercallno;
10276 
10277  new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10278  if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10279  if (iaxs[fr->callno]->peercallno) {
10280  remove_by_peercallno(iaxs[fr->callno]);
10281  }
10282  iaxs[fr->callno]->peercallno = new_peercallno;
10283  store_by_peercallno(iaxs[fr->callno]);
10284  }
10285  }
10286  if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10287  if (iaxdebug)
10288  ast_debug(1, "Received packet %d, (%u, %d)\n", fh->oseqno, f.frametype, f.subclass.integer);
10289  /* Check if it's out of order (and not an ACK or INVAL) */
10290  fr->oseqno = fh->oseqno;
10291  fr->iseqno = fh->iseqno;
10292  fr->ts = ntohl(fh->ts);
10293 #ifdef IAXTESTS
10294  if (test_resync) {
10295  ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10296  fr->ts += test_resync;
10297  }
10298 #endif /* IAXTESTS */
10299 #if 0
10300  if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10301  ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10302  (f.subclass == IAX_COMMAND_NEW ||
10305  f.subclass == IAX_COMMAND_REJECT)) ) )
10306 #endif
10307  if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10308  updatehistory = 0;
10309  if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10310  (iaxs[fr->callno]->iseqno ||
10312  (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10313  (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10314  (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10316  (f.frametype != AST_FRAME_IAX))) {
10317  if (
10318  ((f.subclass.integer != IAX_COMMAND_ACK) &&
10321  (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10322  (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10323  (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10325  (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10326  (f.frametype != AST_FRAME_IAX)) {
10327  /* If it's not an ACK packet, it's out of order. */
10328  ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %u, subclass = %d)\n",
10329  iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10330  /* Check to see if we need to request retransmission,
10331  * and take sequence number wraparound into account */
10332  if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10333  /* If we've already seen it, ack it XXX There's a border condition here XXX */
10334  if ((f.frametype != AST_FRAME_IAX) ||
10336  ast_debug(1, "Acking anyway\n");
10337  /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10338  we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10339  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10340  }
10341  } else {
10342  /* Send a VNAK requesting retransmission */
10343  iax2_vnak(fr->callno);
10344  }
10346  ast_mutex_unlock(&iaxsl[fr->callno]);
10347  return 1;
10348  }
10349  } else {
10350  /* Increment unless it's an ACK or VNAK */
10351  if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10355  (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10356  (f.frametype != AST_FRAME_IAX))
10357  iaxs[fr->callno]->iseqno++;
10358  }
10359  /* Ensure text frames are NULL-terminated */
10360  if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10361  if (res < thread->buf_size)
10362  thread->buf[res++] = '\0';
10363  else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10364  thread->buf[res - 1] = '\0';
10365  }
10366 
10367  /* Handle implicit ACKing unless this is an INVAL, and only if this is
10368  from the real peer, not the transfer peer */
10369  if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
10371  (f.frametype != AST_FRAME_IAX))) {
10372  unsigned char x;
10373  int call_to_destroy;
10374  /* First we have to qualify that the ACKed value is within our window */
10375  if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10376  x = fr->iseqno;
10377  else
10378  x = iaxs[fr->callno]->oseqno;
10379  if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10380  /* The acknowledgement is within our window. Time to acknowledge everything
10381  that it says to */
10382  for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10383  /* Ack the packet with the given timestamp */
10384  if (iaxdebug)
10385  ast_debug(1, "Cancelling transmission of packet %d\n", x);
10386  call_to_destroy = 0;
10387  AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10388  /* If it's our call, and our timestamp, mark -1 retries */
10389  if (x == cur->oseqno) {
10390  cur->retries = -1;
10391  /* Destroy call if this is the end */
10392  if (cur->final)
10393  call_to_destroy = fr->callno;
10394  }
10395  }
10396  if (call_to_destroy) {
10397  if (iaxdebug)
10398  ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10399  ast_mutex_lock(&iaxsl[call_to_destroy]);
10400  iax2_destroy(call_to_destroy);
10401  ast_mutex_unlock(&iaxsl[call_to_destroy]);
10402  }
10403  }
10404  /* Note how much we've received acknowledgement for */
10405  if (iaxs[fr->callno])
10406  iaxs[fr->callno]->rseqno = fr->iseqno;
10407  else {
10408  /* Stop processing now */
10410  ast_mutex_unlock(&iaxsl[fr->callno]);
10411  return 1;
10412  }
10413  } else {
10414  ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10415  }
10416  }
10417  if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
10418  ((f.frametype != AST_FRAME_IAX) ||
10420  (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
10421  /* Only messages we accept from a transfer host are TXACC and TXCNT */
10423  ast_mutex_unlock(&iaxsl[fr->callno]);
10424  return 1;
10425  }
10426 
10427  /* when we receive the first full frame for a new incoming channel,
10428  it is safe to start the PBX on the channel because we have now
10429  completed a 3-way handshake with the peer */
10430  if ((f.frametype == AST_FRAME_VOICE) ||
10431  (f.frametype == AST_FRAME_VIDEO) ||
10432  (f.frametype == AST_FRAME_IAX)) {
10433  if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
10435  if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat, NULL,
10438  ast_mutex_unlock(&iaxsl[fr->callno]);
10439  return 1;
10440  }
10441  }
10442 
10443  if (ies.vars) {
10444  struct ast_datastore *variablestore = NULL;
10445  struct ast_variable *var, *prev = NULL;
10446  AST_LIST_HEAD(, ast_var_t) *varlist;
10447 
10448  iax2_lock_owner(fr->callno);
10449  if (!iaxs[fr->callno]) {
10451  ast_mutex_unlock(&iaxsl[fr->callno]);
10452  return 1;
10453  }
10454  if ((c = iaxs[fr->callno]->owner)) {
10455  varlist = ast_calloc(1, sizeof(*varlist));
10456  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10457 
10458  if (variablestore && varlist) {
10459  variablestore->data = varlist;
10460  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10461  AST_LIST_HEAD_INIT(varlist);
10462  ast_debug(1, "I can haz IAX vars?\n");
10463  for (var = ies.vars; var; var = var->next) {
10464  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10465  if (prev) {
10466  ast_free(prev);
10467  }
10468  prev = var;
10469  if (!newvar) {
10470  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10471  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10472  } else {
10473  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10474  }
10475  }
10476  if (prev) {
10477  ast_free(prev);
10478  }
10479  ies.vars = NULL;
10480  ast_channel_datastore_add(c, variablestore);
10481  } else {
10482  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10483  if (variablestore) {
10484  ast_datastore_free(variablestore);
10485  }
10486  if (varlist) {
10487  ast_free(varlist);
10488  }
10489  }
10490  ast_channel_unlock(c);
10491  } else {
10492  /* No channel yet, so transfer the variables directly over to the pvt,
10493  * for later inheritance. */
10494  ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10495  for (var = ies.vars; var && var->next; var = var->next);
10496  if (var) {
10497  var->next = iaxs[fr->callno]->iaxvars;
10498  iaxs[fr->callno]->iaxvars = ies.vars;
10499  ies.vars = NULL;
10500  }
10501  }
10502  }
10503 
10504  if (ies.vars) {
10505  ast_debug(1, "I have IAX variables, but they were not processed\n");
10506  }
10507  }
10508 
10509  /* once we receive our first IAX Full Frame that is not CallToken related, send all
10510  * queued signaling frames that were being held. */
10511  if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
10512  send_signaling(iaxs[fr->callno]);
10513  }
10514 
10515  if (f.frametype == AST_FRAME_VOICE) {
10516  if (f.subclass.codec != iaxs[fr->callno]->voiceformat) {
10517  iaxs[fr->callno]->voiceformat = f.subclass.codec;
10518  ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_getformatname(f.subclass.codec));
10519  if (iaxs[fr->callno]->owner) {
10520  iax2_lock_owner(fr->callno);
10521  if (iaxs[fr->callno]) {
10522  if (iaxs[fr->callno]->owner) {
10523  format_t orignative;
10524 
10525  orignative = iaxs[fr->callno]->owner->nativeformats;
10526  iaxs[fr->callno]->owner->nativeformats = f.subclass.codec;
10527  if (iaxs[fr->callno]->owner->readformat)
10528  ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
10529  iaxs[fr->callno]->owner->nativeformats = orignative;
10530  ast_channel_unlock(iaxs[fr->callno]->owner);
10531  }
10532  } else {
10533  ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10534  /* Free remote variables (if any) */
10535  if (ies.vars) {
10537  ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
10538  ies.vars = NULL;
10539  }
10540  ast_mutex_unlock(&iaxsl[fr->callno]);
10541  return 1;
10542  }
10543  }
10544  }
10545  }
10546  if (f.frametype == AST_FRAME_VIDEO) {
10547  if (f.subclass.codec != iaxs[fr->callno]->videoformat) {
10548  ast_debug(1, "Ooh, video format changed to %s\n", ast_getformatname(f.subclass.codec & ~0x1LL));
10549  iaxs[fr->callno]->videoformat = f.subclass.codec & ~0x1LL;
10550  }
10551  }
10552  if (f.frametype == AST_FRAME_IAX) {
10553  ast_sched_thread_del(sched, iaxs[fr->callno]->initid);
10554  /* Handle the IAX pseudo frame itself */
10555  if (iaxdebug)
10556  ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10557 
10558  /* Update last ts unless the frame's timestamp originated with us. */
10559  if (iaxs[fr->callno]->last < fr->ts &&
10563  iaxs[fr->callno]->last = fr->ts;
10564  if (iaxdebug)
10565  ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
10566  }
10567  iaxs[fr->callno]->last_iax_message = f.subclass.integer;
10568  if (!iaxs[fr->callno]->first_iax_message) {
10569  iaxs[fr->callno]->first_iax_message = f.subclass.integer;
10570  }
10571  switch(f.subclass.integer) {
10572  case IAX_COMMAND_ACK:
10573  /* Do nothing */
10574  break;
10575  case IAX_COMMAND_QUELCH:
10576  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10577  /* Generate Manager Hold event, if necessary*/
10578  if (iaxs[fr->callno]->owner) {
10579  ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10580  "Status: On\r\n"
10581  "Channel: %s\r\n"
10582  "Uniqueid: %s\r\n",
10583  iaxs[fr->callno]->owner->name,
10584  iaxs[fr->callno]->owner->uniqueid);
10585  }
10586 
10587  ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
10588  if (ies.musiconhold) {
10589  iax2_lock_owner(fr->callno);
10590  if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10591  break;
10592  }
10593  if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10594  const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
10595 
10596  /*
10597  * We already hold the owner lock so we do not
10598  * need to check iaxs[fr->callno] after it returns.
10599  */
10601  S_OR(moh_suggest, NULL),
10602  !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
10603  }
10604  ast_channel_unlock(iaxs[fr->callno]->owner);
10605  }
10606  }
10607  break;
10608  case IAX_COMMAND_UNQUELCH:
10609  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10610  iax2_lock_owner(fr->callno);
10611  if (!iaxs[fr->callno]) {
10612  break;
10613  }
10614  /* Generate Manager Unhold event, if necessary */
10615  if (iaxs[fr->callno]->owner && ast_test_flag64(iaxs[fr->callno], IAX_QUELCH)) {
10616  ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10617  "Status: Off\r\n"
10618  "Channel: %s\r\n"
10619  "Uniqueid: %s\r\n",
10620  iaxs[fr->callno]->owner->name,
10621  iaxs[fr->callno]->owner->uniqueid);
10622  }
10623 
10624  ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
10625  if (!iaxs[fr->callno]->owner) {
10626  break;
10627  }
10628  if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10629  /*
10630  * We already hold the owner lock so we do not
10631  * need to check iaxs[fr->callno] after it returns.
10632  */
10634  }
10635  ast_channel_unlock(iaxs[fr->callno]->owner);
10636  }
10637  break;
10638  case IAX_COMMAND_TXACC:
10639  if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10640  /* Ack the packet with the given timestamp */
10641  AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10642  /* Cancel any outstanding txcnt's */
10643  if (cur->transfer) {
10644  cur->retries = -1;
10645  }
10646  }
10647  memset(&ied1, 0, sizeof(ied1));
10648  iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10649  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10650  iaxs[fr->callno]->transferring = TRANSFER_READY;
10651  }
10652  break;
10653  case IAX_COMMAND_NEW:
10654  /* Ignore if it's already up */
10656  break;
10657  if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
10658  ast_mutex_unlock(&iaxsl[fr->callno]);
10659  check_provisioning(&sin, fd, ies.serviceident, ies.provver);
10660  ast_mutex_lock(&iaxsl[fr->callno]);
10661  if (!iaxs[fr->callno]) {
10662  break;
10663  }
10664  }
10665  /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10666  if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10667  int new_callno;
10668  if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10669  fr->callno = new_callno;
10670  }
10671  /* For security, always ack immediately */
10672  if (delayreject)
10673  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10674  if (check_access(fr->callno, &sin, &ies)) {
10675  /* They're not allowed on */
10677  if (authdebug)
10678  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
10679  break;
10680  }
10681  if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10683  ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10684  break;
10685  }
10686  if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10687  const char *context, *exten, *cid_num;
10688 
10689  context = ast_strdupa(iaxs[fr->callno]->context);
10690  exten = ast_strdupa(iaxs[fr->callno]->exten);
10691  cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10692 
10693  /* This might re-enter the IAX code and need the lock */
10694  ast_mutex_unlock(&iaxsl[fr->callno]);
10695  exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10696  ast_mutex_lock(&iaxsl[fr->callno]);
10697 
10698  if (!iaxs[fr->callno]) {
10699  break;
10700  }
10701  } else
10702  exists = 0;
10703  /* Get OSP token if it does exist */
10704  save_osptoken(fr, &ies);
10705  if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10706  if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10707  memset(&ied0, 0, sizeof(ied0));
10708  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10710  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10711  if (!iaxs[fr->callno]) {
10712  break;
10713  }
10714  if (authdebug)
10715  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
10716  } else {
10717  /* Select an appropriate format */
10718 
10719  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10720  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10721  using_prefs = "reqonly";
10722  } else {
10723  using_prefs = "disabled";
10724  }
10725  format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10726  memset(&pref, 0, sizeof(pref));
10727  strcpy(caller_pref_buf, "disabled");
10728  strcpy(host_pref_buf, "disabled");
10729  } else {
10730  using_prefs = "mine";
10731  /* If the information elements are in here... use them */
10732  if (ies.codec_prefs)
10733  ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10734  if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10735  /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
10736  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10737  pref = iaxs[fr->callno]->rprefs;
10738  using_prefs = "caller";
10739  } else {
10740  pref = iaxs[fr->callno]->prefs;
10741  }
10742  } else
10743  pref = iaxs[fr->callno]->prefs;
10744 
10745  format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10746  ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10747  ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10748  }
10749  if (!format) {
10750  if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
10751  format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10752  if (!format) {
10753  memset(&ied0, 0, sizeof(ied0));
10754  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10756  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10757  if (!iaxs[fr->callno]) {
10758  break;
10759  }
10760  if (authdebug) {
10761  char tmp[256], tmp2[256], tmp3[256];
10762  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10763  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
10764  ast_inet_ntoa(sin.sin_addr),
10765  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10766  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10767  } else {
10768  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10769  ast_inet_ntoa(sin.sin_addr),
10770  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10771  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10772  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10773  }
10774  }
10775  } else {
10776  /* Pick one... */
10777  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10778  if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10779  format = 0;
10780  } else {
10781  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10782  using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10783  memset(&pref, 0, sizeof(pref));
10784  format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10785  strcpy(caller_pref_buf,"disabled");
10786  strcpy(host_pref_buf,"disabled");
10787  } else {
10788  using_prefs = "mine";
10789  if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10790  /* Do the opposite of what we tried above. */
10791  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10792  pref = iaxs[fr->callno]->prefs;
10793  } else {
10794  pref = iaxs[fr->callno]->rprefs;
10795  using_prefs = "caller";
10796  }
10797  format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
10798  } else /* if no codec_prefs IE do it the old way */
10799  format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10800  }
10801  }
10802 
10803  if (!format) {
10804  char tmp[256], tmp2[256], tmp3[256];
10805  memset(&ied0, 0, sizeof(ied0));
10806  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10808  ast_log(LOG_ERROR, "No best format in '%s'???\n", ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
10809  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10810  if (!iaxs[fr->callno]) {
10811  break;
10812  }
10813  if (authdebug) {
10814  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10815  ast_inet_ntoa(sin.sin_addr),
10816  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10817  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10818  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10819  }
10821  break;
10822  }
10823  }
10824  }
10825  if (format) {
10826  /* No authentication required, let them in */
10827  memset(&ied1, 0, sizeof(ied1));
10828  iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10830  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10831  if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10833  ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
10834  "%srequested format = %s,\n"
10835  "%srequested prefs = %s,\n"
10836  "%sactual format = %s,\n"
10837  "%shost prefs = %s,\n"
10838  "%spriority = %s\n",
10839  ast_inet_ntoa(sin.sin_addr),
10841  ast_getformatname(iaxs[fr->callno]->peerformat),
10843  caller_pref_buf,
10845  ast_getformatname(format),
10847  host_pref_buf,
10849  using_prefs);
10850 
10851  iaxs[fr->callno]->chosenformat = format;
10853  } else {
10854  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10855  /* If this is a TBD call, we're ready but now what... */
10856  ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
10857  }
10858  }
10859  }
10860  break;
10861  }
10862  if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
10863  merge_encryption(iaxs[fr->callno],ies.encmethods);
10864  else
10865  iaxs[fr->callno]->encmethods = 0;
10866  if (!authenticate_request(fr->callno) && iaxs[fr->callno])
10868  break;
10869  case IAX_COMMAND_DPREQ:
10870  /* Request status in the dialplan */
10871  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
10872  !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
10873  if (iaxcompat) {
10874  /* Spawn a thread for the lookup */
10875  spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
10876  } else {
10877  /* Just look it up */
10878  dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
10879  }
10880  }
10881  break;
10882  case IAX_COMMAND_HANGUP:
10884  ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
10885  /* Set hangup cause according to remote and hangupsource */
10886  if (iaxs[fr->callno]->owner) {
10888  if (!iaxs[fr->callno]) {
10889  break;
10890  }
10891  }
10892 
10893  /* Send ack immediately, before we destroy */
10894  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10895  iax2_destroy(fr->callno);
10896  break;
10897  case IAX_COMMAND_REJECT:
10898  /* Set hangup cause according to remote and hangup source */
10899  if (iaxs[fr->callno]->owner) {
10901  if (!iaxs[fr->callno]) {
10902  break;
10903  }
10904  }
10905 
10906  if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10907  if (iaxs[fr->callno]->owner && authdebug)
10908  ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
10909  ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
10910  ies.cause ? ies.cause : "<Unknown>");
10911  ast_debug(1, "Immediately destroying %d, having received reject\n",
10912  fr->callno);
10913  }
10914  /* Send ack immediately, before we destroy */
10916  fr->ts, NULL, 0, fr->iseqno);
10917  if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
10918  iaxs[fr->callno]->error = EPERM;
10919  iax2_destroy(fr->callno);
10920  break;
10921  case IAX_COMMAND_TRANSFER:
10922  {
10923  struct ast_channel *bridged_chan;
10924  struct ast_channel *owner;
10925 
10926  iax2_lock_owner(fr->callno);
10927  if (!iaxs[fr->callno]) {
10928  /* Initiating call went away before we could transfer. */
10929  break;
10930  }
10931  owner = iaxs[fr->callno]->owner;
10932  bridged_chan = owner ? ast_bridged_channel(owner) : NULL;
10933  if (bridged_chan && ies.called_number) {
10934  const char *context;
10935 
10936  context = ast_strdupa(iaxs[fr->callno]->context);
10937 
10938  ast_channel_ref(owner);
10939  ast_channel_ref(bridged_chan);
10940  ast_channel_unlock(owner);
10941  ast_mutex_unlock(&iaxsl[fr->callno]);
10942 
10943  /* Set BLINDTRANSFER channel variables */
10944  pbx_builtin_setvar_helper(owner, "BLINDTRANSFER", bridged_chan->name);
10945  pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", owner->name);
10946 
10947  /* DO NOT hold any locks while calling ast_parking_ext_valid() */
10948  if (ast_parking_ext_valid(ies.called_number, owner, context)) {
10949  ast_debug(1, "Parking call '%s'\n", bridged_chan->name);
10950  if (iax_park(bridged_chan, owner, ies.called_number, context)) {
10951  ast_log(LOG_WARNING, "Failed to park call '%s'\n",
10952  bridged_chan->name);
10953  }
10954  } else {
10955  if (ast_async_goto(bridged_chan, context, ies.called_number, 1)) {
10957  "Async goto of '%s' to '%s@%s' failed\n",
10958  bridged_chan->name, ies.called_number, context);
10959  } else {
10960  ast_debug(1, "Async goto of '%s' to '%s@%s' started\n",
10961  bridged_chan->name, ies.called_number, context);
10962  }
10963  }
10964  ast_channel_unref(owner);
10965  ast_channel_unref(bridged_chan);
10966 
10967  ast_mutex_lock(&iaxsl[fr->callno]);
10968  } else {
10969  ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
10970  if (owner) {
10971  ast_channel_unlock(owner);
10972  }
10973  }
10974 
10975  break;
10976  }
10977  case IAX_COMMAND_ACCEPT:
10978  /* Ignore if call is already up or needs authentication or is a TBD */
10980  break;
10981  if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10982  /* Send ack immediately, before we destroy */
10983  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10984  iax2_destroy(fr->callno);
10985  break;
10986  }
10987  if (ies.format) {
10988  iaxs[fr->callno]->peerformat = ies.format;
10989  } else {
10990  if (iaxs[fr->callno]->owner)
10991  iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
10992  else
10993  iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
10994  }
10995  ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
10996  if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
10997  memset(&ied0, 0, sizeof(ied0));
10998  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11000  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11001  if (!iaxs[fr->callno]) {
11002  break;
11003  }
11004  if (authdebug) {
11005  char tmp1[256], tmp2[256];
11006  ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
11007  ast_inet_ntoa(sin.sin_addr),
11008  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11009  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11010  }
11011  } else {
11012  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11013  iax2_lock_owner(fr->callno);
11014  if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
11015  /* Switch us to use a compatible format */
11016  iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
11017  ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
11018 
11019  /* Setup read/write formats properly. */
11020  if (iaxs[fr->callno]->owner->writeformat)
11021  ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
11022  if (iaxs[fr->callno]->owner->readformat)
11023  ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
11024  ast_channel_unlock(iaxs[fr->callno]->owner);
11025  }
11026  }
11027  if (iaxs[fr->callno]) {
11029  AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
11030  if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
11031  iax2_dprequest(dp, fr->callno);
11033  }
11034  break;
11035  case IAX_COMMAND_POKE:
11036  /* Send back a pong packet with the original timestamp */
11037  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
11038  break;
11039  case IAX_COMMAND_PING:
11040  {
11041  struct iax_ie_data pingied;
11042  construct_rr(iaxs[fr->callno], &pingied);
11043  /* Send back a pong packet with the original timestamp */
11044  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
11045  }
11046  break;
11047  case IAX_COMMAND_PONG:
11048  /* Calculate ping time */
11049  iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
11050  /* save RR info */
11051  save_rr(fr, &ies);
11052 
11053  /* Good time to write jb stats for this call */
11054  log_jitterstats(fr->callno);
11055 
11056  if (iaxs[fr->callno]->peerpoke) {
11057  peer = iaxs[fr->callno]->peerpoke;
11058  if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
11059  if (iaxs[fr->callno]->pingtime <= peer->maxms) {
11060  ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %u\n", peer->name, iaxs[fr->callno]->pingtime);
11061  manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %u\r\n", peer->name, iaxs[fr->callno]->pingtime);
11062  ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11063  }
11064  } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
11065  if (iaxs[fr->callno]->pingtime > peer->maxms) {
11066  ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%u ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
11067  manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %u\r\n", peer->name, iaxs[fr->callno]->pingtime);
11068  ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11069  }
11070  }
11071  peer->lastms = iaxs[fr->callno]->pingtime;
11072  if (peer->smoothing && (peer->lastms > -1))
11073  peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
11074  else if (peer->smoothing && peer->lastms < 0)
11075  peer->historicms = (0 + peer->historicms) / 2;
11076  else
11077  peer->historicms = iaxs[fr->callno]->pingtime;
11078 
11079  /* Remove scheduled iax2_poke_noanswer */
11080  if (peer->pokeexpire > -1) {
11081  if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
11082  peer_unref(peer);
11083  peer->pokeexpire = -1;
11084  }
11085  }
11086  /* Schedule the next cycle */
11087  if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
11088  peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
11089  else
11090  peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
11091  if (peer->pokeexpire == -1)
11092  peer_unref(peer);
11093  /* and finally send the ack */
11094  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11095  /* And wrap up the qualify call */
11096  iax2_destroy(fr->callno);
11097  peer->callno = 0;
11098  ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
11099  }
11100  break;
11101  case IAX_COMMAND_LAGRQ:
11102  case IAX_COMMAND_LAGRP:
11103  f.src = "LAGRQ";
11104  f.mallocd = 0;
11105  f.offset = 0;
11106  f.samples = 0;
11107  iax_frame_wrap(fr, &f);
11108  if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
11109  /* Received a LAGRQ - echo back a LAGRP */
11111  iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
11112  } else {
11113  /* Received LAGRP in response to our LAGRQ */
11114  unsigned int ts;
11115  /* This is a reply we've been given, actually measure the difference */
11116  ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
11117  iaxs[fr->callno]->lag = ts - fr->ts;
11118  if (iaxdebug)
11119  ast_debug(1, "Peer %s lag measured as %dms\n",
11120  ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
11121  }
11122  break;
11123  case IAX_COMMAND_AUTHREQ:
11124  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11125  ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11126  break;
11127  }
11128  if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
11129  struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
11130  .subclass.integer = AST_CONTROL_HANGUP,
11131  };
11133  "I don't know how to authenticate %s to %s\n",
11134  ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
11135  iax2_queue_frame(fr->callno, &hangup_fr);
11136  }
11137  break;
11138  case IAX_COMMAND_AUTHREP:
11139  /* For security, always ack immediately */
11140  if (delayreject)
11141  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11142  /* Ignore once we've started */
11143  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11144  ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11145  break;
11146  }
11147  if (authenticate_verify(iaxs[fr->callno], &ies)) {
11148  if (authdebug)
11149  ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->username);
11150  memset(&ied0, 0, sizeof(ied0));
11152  break;
11153  }
11154  if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11155  /* This might re-enter the IAX code and need the lock */
11156  exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
11157  } else
11158  exists = 0;
11159  if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11160  if (authdebug)
11161  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
11162  memset(&ied0, 0, sizeof(ied0));
11163  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11165  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11166  if (!iaxs[fr->callno]) {
11167  break;
11168  }
11169  } else {
11170  /* Select an appropriate format */
11171  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11172  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11173  using_prefs = "reqonly";
11174  } else {
11175  using_prefs = "disabled";
11176  }
11177  format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11178  memset(&pref, 0, sizeof(pref));
11179  strcpy(caller_pref_buf, "disabled");
11180  strcpy(host_pref_buf, "disabled");
11181  } else {
11182  using_prefs = "mine";
11183  if (ies.codec_prefs)
11184  ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
11185  if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
11186  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11187  pref = iaxs[fr->callno]->rprefs;
11188  using_prefs = "caller";
11189  } else {
11190  pref = iaxs[fr->callno]->prefs;
11191  }
11192  } else /* if no codec_prefs IE do it the old way */
11193  pref = iaxs[fr->callno]->prefs;
11194  format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
11195  ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11196  ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11197  }
11198  if (!format) {
11199  char tmp1[256], tmp2[256], tmp3[256];
11200  if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11201  ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11202  ast_getformatname(iaxs[fr->callno]->peerformat),
11203  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability));
11204  format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11205  }
11206  if (!format) {
11207  if (authdebug) {
11208  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11209  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n", ast_inet_ntoa(sin.sin_addr),
11210  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11211  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11212  } else {
11213  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11214  ast_inet_ntoa(sin.sin_addr),
11215  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11216  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11217  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11218  }
11219  }
11220  memset(&ied0, 0, sizeof(ied0));
11221  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11223  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11224  if (!iaxs[fr->callno]) {
11225  break;
11226  }
11227  } else {
11228  /* Pick one... */
11229  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11230  if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11231  format = 0;
11232  } else {
11233  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11234  using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11235  memset(&pref, 0, sizeof(pref));
11236  format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
11237  iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11238  strcpy(caller_pref_buf,"disabled");
11239  strcpy(host_pref_buf,"disabled");
11240  } else {
11241  using_prefs = "mine";
11242  if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
11243  /* Do the opposite of what we tried above. */
11244  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11245  pref = iaxs[fr->callno]->prefs;
11246  } else {
11247  pref = iaxs[fr->callno]->rprefs;
11248  using_prefs = "caller";
11249  }
11250  format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
11251  } else /* if no codec_prefs IE do it the old way */
11252  format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11253  }
11254  }
11255  if (!format) {
11256  char tmp1[256], tmp2[256], tmp3[256];
11257  ast_log(LOG_ERROR, "No best format in %s???\n",
11258  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
11259  if (authdebug) {
11260  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11261  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11262  ast_inet_ntoa(sin.sin_addr),
11263  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11264  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11265  } else {
11266  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11267  ast_inet_ntoa(sin.sin_addr),
11268  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11269  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11270  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11271  }
11272  }
11273  memset(&ied0, 0, sizeof(ied0));
11274  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11276  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11277  if (!iaxs[fr->callno]) {
11278  break;
11279  }
11280  }
11281  }
11282  }
11283  if (format) {
11284  /* Authentication received */
11285  memset(&ied1, 0, sizeof(ied1));
11286  iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11288  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11289  if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11290  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11291  ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11292  "%srequested format = %s,\n"
11293  "%srequested prefs = %s,\n"
11294  "%sactual format = %s,\n"
11295  "%shost prefs = %s,\n"
11296  "%spriority = %s\n",
11297  ast_inet_ntoa(sin.sin_addr),
11299  ast_getformatname(iaxs[fr->callno]->peerformat),
11301  caller_pref_buf,
11303  ast_getformatname(format),
11305  host_pref_buf,
11307  using_prefs);
11308 
11309  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11310  if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format, NULL, 1)))
11311  iax2_destroy(fr->callno);
11312  else if (ies.vars) {
11313  struct ast_datastore *variablestore;
11314  struct ast_variable *var, *prev = NULL;
11315  AST_LIST_HEAD(, ast_var_t) *varlist;
11316  varlist = ast_calloc(1, sizeof(*varlist));
11317  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11318  if (variablestore && varlist) {
11319  variablestore->data = varlist;
11320  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11321  AST_LIST_HEAD_INIT(varlist);
11322  ast_debug(1, "I can haz IAX vars? w00t\n");
11323  for (var = ies.vars; var; var = var->next) {
11324  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11325  if (prev)
11326  ast_free(prev);
11327  prev = var;
11328  if (!newvar) {
11329  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11330  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11331  } else {
11332  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11333  }
11334  }
11335  if (prev)
11336  ast_free(prev);
11337  ies.vars = NULL;
11338  ast_channel_datastore_add(c, variablestore);
11339  } else {
11340  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11341  if (variablestore)
11342  ast_datastore_free(variablestore);
11343  if (varlist)
11344  ast_free(varlist);
11345  }
11346  }
11347  } else {
11348  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11349  /* If this is a TBD call, we're ready but now what... */
11350  ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
11351  if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
11352  goto immediatedial;
11353  }
11354  }
11355  }
11356  }
11357  break;
11358  case IAX_COMMAND_DIAL:
11359 immediatedial:
11360  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
11361  ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11362  ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11363  if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11364  if (authdebug)
11365  ast_log(LOG_NOTICE, "Rejected dial attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
11366  memset(&ied0, 0, sizeof(ied0));
11367  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11369  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11370  if (!iaxs[fr->callno]) {
11371  break;
11372  }
11373  } else {
11374  char tmp[256];
11375  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11376  ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11377  ast_inet_ntoa(sin.sin_addr),
11378  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat));
11379  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11380  send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
11381  if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat, NULL, 1)))
11382  iax2_destroy(fr->callno);
11383  else if (ies.vars) {
11384  struct ast_datastore *variablestore;
11385  struct ast_variable *var, *prev = NULL;
11386  AST_LIST_HEAD(, ast_var_t) *varlist;
11387  varlist = ast_calloc(1, sizeof(*varlist));
11388  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11389  ast_debug(1, "I can haz IAX vars? w00t\n");
11390  if (variablestore && varlist) {
11391  variablestore->data = varlist;
11392  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11393  AST_LIST_HEAD_INIT(varlist);
11394  for (var = ies.vars; var; var = var->next) {
11395  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11396  if (prev)
11397  ast_free(prev);
11398  prev = var;
11399  if (!newvar) {
11400  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11401  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11402  } else {
11403  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11404  }
11405  }
11406  if (prev)
11407  ast_free(prev);
11408  ies.vars = NULL;
11409  ast_channel_datastore_add(c, variablestore);
11410  } else {
11411  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11412  if (variablestore)
11413  ast_datastore_free(variablestore);
11414  if (varlist)
11415  ast_free(varlist);
11416  }
11417  }
11418  }
11419  }
11420  break;
11421  case IAX_COMMAND_INVAL:
11422  iaxs[fr->callno]->error = ENOTCONN;
11423  ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11424  iax2_destroy(fr->callno);
11425  ast_debug(1, "Destroying call %d\n", fr->callno);
11426  break;
11427  case IAX_COMMAND_VNAK:
11428  ast_debug(1, "Received VNAK: resending outstanding frames\n");
11429  /* Force retransmission */
11430  vnak_retransmit(fr->callno, fr->iseqno);
11431  break;
11432  case IAX_COMMAND_REGREQ:
11433  case IAX_COMMAND_REGREL:
11434  /* For security, always ack immediately */
11435  if (delayreject)
11436  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11437  if (register_verify(fr->callno, &sin, &ies)) {
11438  if (!iaxs[fr->callno]) {
11439  break;
11440  }
11441  /* Send delayed failure */
11443  break;
11444  }
11445  if (!iaxs[fr->callno]) {
11446  break;
11447  }
11448  if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
11449  ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
11450 
11451  if (f.subclass.integer == IAX_COMMAND_REGREL) {
11452  memset(&sin, 0, sizeof(sin));
11453  sin.sin_family = AF_INET;
11454  }
11455  if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh)) {
11456  ast_log(LOG_WARNING, "Registry error\n");
11457  }
11458  if (!iaxs[fr->callno]) {
11459  break;
11460  }
11461  if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
11462  ast_mutex_unlock(&iaxsl[fr->callno]);
11463  check_provisioning(&sin, fd, ies.serviceident, ies.provver);
11464  ast_mutex_lock(&iaxsl[fr->callno]);
11465  }
11466  break;
11467  }
11469  break;
11470  case IAX_COMMAND_REGACK:
11471  if (iax2_ack_registry(&ies, &sin, fr->callno))
11472  ast_log(LOG_WARNING, "Registration failure\n");
11473  /* Send ack immediately, before we destroy */
11474  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11475  iax2_destroy(fr->callno);
11476  break;
11477  case IAX_COMMAND_REGREJ:
11478  if (iaxs[fr->callno]->reg) {
11479  if (authdebug) {
11480  ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>", ast_inet_ntoa(sin.sin_addr));
11481  manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
11482  }
11483  iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
11484  }
11485  /* Send ack immediately, before we destroy */
11486  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11487  iax2_destroy(fr->callno);
11488  break;
11489  case IAX_COMMAND_REGAUTH:
11490  /* Authentication request */
11491  if (registry_rerequest(&ies, fr->callno, &sin)) {
11492  memset(&ied0, 0, sizeof(ied0));
11493  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11495  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11496  }
11497  break;
11498  case IAX_COMMAND_TXREJ:
11499  while (iaxs[fr->callno]
11500  && iaxs[fr->callno]->bridgecallno
11501  && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
11502  DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
11503  }
11504  if (!iaxs[fr->callno]) {
11505  break;
11506  }
11507 
11508  iaxs[fr->callno]->transferring = TRANSFER_NONE;
11509  ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11510  memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11511 
11512  if (!iaxs[fr->callno]->bridgecallno) {
11513  break;
11514  }
11515 
11516  if (iaxs[iaxs[fr->callno]->bridgecallno]
11517  && iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
11518  iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_NONE;
11519  send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
11520  }
11521  ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11522  break;
11523  case IAX_COMMAND_TXREADY:
11524  while (iaxs[fr->callno]
11525  && iaxs[fr->callno]->bridgecallno
11526  && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
11527  DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
11528  }
11529  if (!iaxs[fr->callno]) {
11530  break;
11531  }
11532 
11533  if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
11534  iaxs[fr->callno]->transferring = TRANSFER_READY;
11535  } else if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN) {
11536  iaxs[fr->callno]->transferring = TRANSFER_MREADY;
11537  } else {
11538  if (iaxs[fr->callno]->bridgecallno) {
11539  ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11540  }
11541  break;
11542  }
11543  ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11544 
11545  if (!iaxs[fr->callno]->bridgecallno) {
11546  break;
11547  }
11548 
11549  if (!iaxs[iaxs[fr->callno]->bridgecallno]
11550  || (iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_READY
11551  && iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_MREADY)) {
11552  ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11553  break;
11554  }
11555 
11556  /* Both sides are ready */
11557 
11558  /* XXX what isn't checked here is that both sides match transfer types. */
11559 
11560  if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11561  ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11562  iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11563 
11564  iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
11565  iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
11566 
11567  memset(&ied0, 0, sizeof(ied0));
11568  memset(&ied1, 0, sizeof(ied1));
11569  iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11570  iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11571  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11572  send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11573  } else {
11574  ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11575  iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11576 
11577  iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
11578  iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
11579  ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
11581 
11582  /* Stop doing lag & ping requests */
11583  stop_stuff(fr->callno);
11584  stop_stuff(iaxs[fr->callno]->bridgecallno);
11585 
11586  memset(&ied0, 0, sizeof(ied0));
11587  memset(&ied1, 0, sizeof(ied1));
11588  iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11589  iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11590  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11591  send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11592  }
11593  ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11594  break;
11595  case IAX_COMMAND_TXREQ:
11596  try_transfer(iaxs[fr->callno], &ies);
11597  break;
11598  case IAX_COMMAND_TXCNT:
11599  if (iaxs[fr->callno]->transferring)
11601  break;
11602  case IAX_COMMAND_TXREL:
11603  /* Send ack immediately, rather than waiting until we've changed addresses */
11604  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11605  complete_transfer(fr->callno, &ies);
11606  stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11607  break;
11608  case IAX_COMMAND_TXMEDIA:
11609  if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11610  AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11611  /* Cancel any outstanding frames and start anew */
11612  if (cur->transfer) {
11613  cur->retries = -1;
11614  }
11615  }
11616  /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11617  iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
11618  }
11619  break;
11620  case IAX_COMMAND_RTKEY:
11621  if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11623  "we've been told to rotate our encryption key, "
11624  "but this isn't an encrypted call. bad things will happen.\n"
11625  );
11626  break;
11627  }
11628 
11629  IAX_DEBUGDIGEST("Receiving", ies.challenge);
11630 
11631  ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11632  break;
11633  case IAX_COMMAND_DPREP:
11634  complete_dpreply(iaxs[fr->callno], &ies);
11635  break;
11636  case IAX_COMMAND_UNSUPPORT:
11637  ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11638  break;
11639  case IAX_COMMAND_FWDOWNL:
11640  /* Firmware download */
11641  if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
11642  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
11643  break;
11644  }
11645  memset(&ied0, 0, sizeof(ied0));
11646  res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
11647  if (res < 0)
11648  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11649  else if (res > 0)
11650  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11651  else
11652  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11653  break;
11654  case IAX_COMMAND_CALLTOKEN:
11655  {
11656  struct iax_frame *cur;
11657  /* find last sent frame */
11658  if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11659  resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11660  }
11661  break;
11662  }
11663  default:
11664  ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11665  memset(&ied0, 0, sizeof(ied0));
11667  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11668  }
11669  /* Free remote variables (if any) */
11670  if (ies.vars) {
11672  ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11673  ies.vars = NULL;
11674  }
11675 
11676  /* Don't actually pass these frames along */
11677  if ((f.subclass.integer != IAX_COMMAND_ACK) &&
11682  if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno) {
11683  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11684  }
11685  }
11686  ast_mutex_unlock(&iaxsl[fr->callno]);
11687  return 1;
11688  }
11689  /* Unless this is an ACK or INVAL frame, ack it */
11690  if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11691  send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11692  } else if (minivid) {
11694  if (iaxs[fr->callno]->videoformat > 0)
11695  f.subclass.codec = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000LL ? 1 : 0);
11696  else {
11697  ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
11698  iax2_vnak(fr->callno);
11700  ast_mutex_unlock(&iaxsl[fr->callno]);
11701  return 1;
11702  }
11703  f.datalen = res - sizeof(*vh);
11704  if (f.datalen)
11705  f.data.ptr = thread->buf + sizeof(*vh);
11706  else
11707  f.data.ptr = NULL;
11708 #ifdef IAXTESTS
11709  if (test_resync) {
11710  fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
11711  } else
11712 #endif /* IAXTESTS */
11713  fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
11714  } else {
11715  /* A mini frame */
11717  if (iaxs[fr->callno]->voiceformat > 0)
11718  f.subclass.codec = iaxs[fr->callno]->voiceformat;
11719  else {
11720  ast_debug(1, "Received mini frame before first full voice frame\n");
11721  iax2_vnak(fr->callno);
11723  ast_mutex_unlock(&iaxsl[fr->callno]);
11724  return 1;
11725  }
11726  f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
11727  if (f.datalen < 0) {
11728  ast_log(LOG_WARNING, "Datalen < 0?\n");
11730  ast_mutex_unlock(&iaxsl[fr->callno]);
11731  return 1;
11732  }
11733  if (f.datalen)
11734  f.data.ptr = thread->buf + sizeof(*mh);
11735  else
11736  f.data.ptr = NULL;
11737 #ifdef IAXTESTS
11738  if (test_resync) {
11739  fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
11740  } else
11741 #endif /* IAXTESTS */
11742  fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
11743  /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
11744  }
11745 
11746  /* Don't pass any packets until we're started */
11747  if (!iaxs[fr->callno]
11748  || !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
11750  ast_mutex_unlock(&iaxsl[fr->callno]);
11751  return 1;
11752  }
11753 
11754  if (f.frametype == AST_FRAME_CONTROL) {
11756  /* Control frame not allowed to come from the wire. */
11757  ast_debug(2, "Callno %d: Blocked receiving control frame %d.\n",
11758  fr->callno, f.subclass.integer);
11760  ast_mutex_unlock(&iaxsl[fr->callno]);
11761  return 1;
11762  }
11765  if (iaxs[fr->callno]
11766  && !ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
11767  /* We are not configured to allow receiving these updates. */
11768  ast_debug(2, "Callno %d: Config blocked receiving control frame %d.\n",
11769  fr->callno, f.subclass.integer);
11771  ast_mutex_unlock(&iaxsl[fr->callno]);
11772  return 1;
11773  }
11774  }
11775 
11776  iax2_lock_owner(fr->callno);
11777  if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
11778  if (f.subclass.integer == AST_CONTROL_BUSY) {
11779  iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_BUSY;
11780  } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
11782  }
11783  ast_channel_unlock(iaxs[fr->callno]->owner);
11784  }
11785  }
11786 
11787  if (f.frametype == AST_FRAME_CONTROL
11789  && iaxs[fr->callno]) {
11790  struct ast_party_connected_line connected;
11791 
11792  /*
11793  * Process a received connected line update.
11794  *
11795  * Initialize defaults.
11796  */
11797  ast_party_connected_line_init(&connected);
11798  connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
11799  connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
11800 
11801  if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
11802  ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
11803  ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
11804  iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
11805 
11806  iax2_lock_owner(fr->callno);
11807  if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
11808  ast_set_callerid(iaxs[fr->callno]->owner,
11809  S_COR(connected.id.number.valid, connected.id.number.str, ""),
11810  S_COR(connected.id.name.valid, connected.id.name.str, ""),
11811  NULL);
11812  iaxs[fr->callno]->owner->caller.id.number.presentation = connected.id.number.presentation;
11813  iaxs[fr->callno]->owner->caller.id.name.presentation = connected.id.name.presentation;
11814  ast_channel_unlock(iaxs[fr->callno]->owner);
11815  }
11816  }
11817  ast_party_connected_line_free(&connected);
11818  }
11819 
11820  /* Common things */
11821  f.src = "IAX2";
11822  f.mallocd = 0;
11823  f.offset = 0;
11824  f.len = 0;
11825  if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
11827  /* We need to byteswap incoming slinear samples from network byte order */
11830  } else
11831  f.samples = 0;
11832  iax_frame_wrap(fr, &f);
11833 
11834  /* If this is our most recent packet, use it as our basis for timestamping */
11835  if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11836  /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
11837  fr->outoforder = 0;
11838  } else {
11839  if (iaxdebug && iaxs[fr->callno]) {
11840  ast_debug(1, "Received out of order packet... (type=%u, subclass %d, ts = %u, last = %u)\n", f.frametype, f.subclass.integer, fr->ts, iaxs[fr->callno]->last);
11841  }
11842  fr->outoforder = -1;
11843  }
11844  fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
11845  if (iaxs[fr->callno]) {
11846  duped_fr = iaxfrdup2(fr);
11847  if (duped_fr) {
11848  schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
11849  }
11850  }
11851  if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11852  iaxs[fr->callno]->last = fr->ts;
11853 #if 1
11854  if (iaxdebug)
11855  ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
11856 #endif
11857  }
11858 
11859  /* Always run again */
11861  ast_mutex_unlock(&iaxsl[fr->callno]);
11862  return 1;
11863 }
11864 
11865 /* Function to clean up process thread if it is cancelled */
11866 static void iax2_process_thread_cleanup(void *data)
11867 {
11868  struct iax2_thread *thread = data;
11869  ast_mutex_destroy(&thread->lock);
11870  ast_cond_destroy(&thread->cond);
11871  ast_mutex_destroy(&thread->init_lock);
11872  ast_cond_destroy(&thread->init_cond);
11873  ast_free(thread);
11874  /* Ignore check_return warning from Coverity for ast_atomic_dec_and_test below */
11876 }
11877 
11878 static void *iax2_process_thread(void *data)
11879 {
11880  struct iax2_thread *thread = data;
11881  struct timeval wait;
11882  struct timespec ts;
11883  int put_into_idle = 0;
11884  int first_time = 1;
11885  int old_state;
11886 
11888 
11889  pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
11890  pthread_cleanup_push(iax2_process_thread_cleanup, data);
11891 
11892  for (;;) {
11893  /* Wait for something to signal us to be awake */
11894  ast_mutex_lock(&thread->lock);
11895 
11896  if (thread->stop) {
11897  ast_mutex_unlock(&thread->lock);
11898  break;
11899  }
11900 
11901  /* Flag that we're ready to accept signals */
11902  if (first_time) {
11903  signal_condition(&thread->init_lock, &thread->init_cond);
11904  first_time = 0;
11905  }
11906 
11907  /* Put into idle list if applicable */
11908  if (put_into_idle) {
11909  insert_idle_thread(thread);
11910  }
11911 
11912  if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
11913  struct iax2_thread *t = NULL;
11914  /* Wait to be signalled or time out */
11915  wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11916  ts.tv_sec = wait.tv_sec;
11917  ts.tv_nsec = wait.tv_usec * 1000;
11918  if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11919  /* This thread was never put back into the available dynamic
11920  * thread list, so just go away. */
11921  if (!put_into_idle || thread->stop) {
11922  ast_mutex_unlock(&thread->lock);
11923  break;
11924  }
11926  /* Account for the case where this thread is acquired *right* after a timeout */
11927  if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
11930  if (t) {
11931  /* This dynamic thread timed out waiting for a task and was
11932  * not acquired immediately after the timeout,
11933  * so it's time to go away. */
11934  ast_mutex_unlock(&thread->lock);
11935  break;
11936  }
11937  /* Someone grabbed our thread *right* after we timed out.
11938  * Wait for them to set us up with something to do and signal
11939  * us to continue. */
11940  wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11941  ts.tv_sec = wait.tv_sec;
11942  ts.tv_nsec = wait.tv_usec * 1000;
11943  if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11944  ast_mutex_unlock(&thread->lock);
11945  break;
11946  }
11947  }
11948  } else {
11949  ast_cond_wait(&thread->cond, &thread->lock);
11950  }
11951 
11952  /* Go back into our respective list */
11953  put_into_idle = 1;
11954 
11955  ast_mutex_unlock(&thread->lock);
11956 
11957  if (thread->stop) {
11958  break;
11959  }
11960 
11961  /* See what we need to do */
11962  switch (thread->iostate) {
11963  case IAX_IOSTATE_IDLE:
11964  continue;
11965  case IAX_IOSTATE_READY:
11966  thread->actions++;
11967  thread->iostate = IAX_IOSTATE_PROCESSING;
11968  socket_process(thread);
11970  break;
11972  thread->actions++;
11973  thread->iostate = IAX_IOSTATE_PROCESSING;
11974 #ifdef SCHED_MULTITHREADED
11975  thread->schedfunc(thread->scheddata);
11976 #endif
11977  break;
11978  default:
11979  break;
11980  }
11981 
11982  /* The network thread added us to the active_thread list when we were given
11983  * frames to process, Now that we are done, we must remove ourselves from
11984  * the active list, and return to the idle list */
11986  AST_LIST_REMOVE(&active_list, thread, list);
11988 
11989  /* Make sure another frame didn't sneak in there after we thought we were done. */
11991 
11992  time(&thread->checktime);
11993  thread->iostate = IAX_IOSTATE_IDLE;
11994 #ifdef DEBUG_SCHED_MULTITHREAD
11995  thread->curfunc[0]='\0';
11996 #endif
11997  }
11998 
11999  /*!
12000  * \note For some reason, idle threads are exiting without being
12001  * removed from an idle list, which is causing memory
12002  * corruption. Forcibly remove it from the list, if it's there.
12003  */
12005  AST_LIST_REMOVE(&idle_list, thread, list);
12007 
12009  AST_LIST_REMOVE(&dynamic_list, thread, list);
12011 
12012  if (!thread->stop) {
12013  /* Nobody asked me to stop so nobody is waiting to join me. */
12014  pthread_detach(pthread_self());
12015  }
12016 
12017  /* I am exiting here on my own volition, I need to clean up my own data structures
12018  * Assume that I am no longer in any of the lists (idle, active, or dynamic)
12019  */
12020  pthread_cleanup_pop(1);
12021  return NULL;
12022 }
12023 
12024 static int iax2_do_register(struct iax2_registry *reg)
12025 {
12026  struct iax_ie_data ied;
12027  if (iaxdebug)
12028  ast_debug(1, "Sending registration request for '%s'\n", reg->username);
12029 
12030  if (reg->dnsmgr &&
12031  ((reg->regstate == REG_STATE_TIMEOUT) || !ast_sockaddr_ipv4(&reg->addr))) {
12032  /* Maybe the IP has changed, force DNS refresh */
12033  ast_dnsmgr_refresh(reg->dnsmgr);
12034  }
12035 
12036  /*
12037  * if IP has Changed, free allocated call to create a new one with new IP
12038  * call has the pointer to IP and must be updated to the new one
12039  */
12040  if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
12041  int callno = reg->callno;
12042  ast_mutex_lock(&iaxsl[callno]);
12043  iax2_destroy(callno);
12044  ast_mutex_unlock(&iaxsl[callno]);
12045  reg->callno = 0;
12046  }
12047  if (!ast_sockaddr_ipv4(&reg->addr)) {
12048  if (iaxdebug)
12049  ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
12050  /* Setup the next registration attempt */
12051  reg->expire = iax2_sched_replace(reg->expire, sched,
12052  (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12053  return -1;
12054  }
12055 
12056  if (!reg->callno) {
12057  struct sockaddr_in reg_addr;
12058 
12059  ast_debug(3, "Allocate call number\n");
12060 
12061  ast_sockaddr_to_sin(&reg->addr, &reg_addr);
12062 
12063  reg->callno = find_callno_locked(0, 0, &reg_addr, NEW_FORCE, defaultsockfd, 0);
12064  if (reg->callno < 1) {
12065  ast_log(LOG_WARNING, "Unable to create call for registration\n");
12066  return -1;
12067  } else
12068  ast_debug(3, "Registration created on call %d\n", reg->callno);
12069  iaxs[reg->callno]->reg = reg;
12070  ast_mutex_unlock(&iaxsl[reg->callno]);
12071  }
12072  /* Setup the next registration a little early */
12073  reg->expire = iax2_sched_replace(reg->expire, sched,
12074  (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12075  /* Send the request */
12076  memset(&ied, 0, sizeof(ied));
12079  add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
12080  send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
12081  reg->regstate = REG_STATE_REGSENT;
12082  return 0;
12083 }
12084 
12085 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force)
12086 {
12087  /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
12088  is found for template */
12089  struct iax_ie_data provdata;
12090  struct iax_ie_data ied;
12091  unsigned int sig;
12092  struct sockaddr_in sin;
12093  int callno;
12094  struct create_addr_info cai;
12095 
12096  memset(&cai, 0, sizeof(cai));
12097 
12098  ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
12099 
12100  if (iax_provision_build(&provdata, &sig, template, force)) {
12101  ast_debug(1, "No provisioning found for template '%s'\n", template);
12102  return 0;
12103  }
12104 
12105  if (end) {
12106  memcpy(&sin, end, sizeof(sin));
12107  cai.sockfd = sockfd;
12108  } else if (create_addr(dest, NULL, &sin, &cai))
12109  return -1;
12110 
12111  /* Build the rest of the message */
12112  memset(&ied, 0, sizeof(ied));
12113  iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
12114 
12115  callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
12116  if (!callno)
12117  return -1;
12118 
12119  if (iaxs[callno]) {
12120  /* Schedule autodestruct in case they don't ever give us anything back */
12121  iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
12122  sched, 15000, auto_hangup, (void *)(long)callno);
12123  ast_set_flag64(iaxs[callno], IAX_PROVISION);
12124  /* Got a call number now, so go ahead and send the provisioning information */
12125  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
12126  }
12127  ast_mutex_unlock(&iaxsl[callno]);
12128 
12129  return 1;
12130 }
12131 
12132 static char *papp = "IAX2Provision";
12133 
12134 /*! iax2provision
12135 \ingroup applications
12136 */
12137 static int iax2_prov_app(struct ast_channel *chan, const char *data)
12138 {
12139  int res;
12140  char *sdata;
12141  char *opts;
12142  int force =0;
12143  unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
12144  if (ast_strlen_zero(data))
12145  data = "default";
12146  sdata = ast_strdupa(data);
12147  opts = strchr(sdata, '|');
12148  if (opts)
12149  *opts='\0';
12150 
12151  if (chan->tech != &iax2_tech) {
12152  ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
12153  return -1;
12154  }
12155  if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
12156  ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
12157  return -1;
12158  }
12159  res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
12160  ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
12161  ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
12162  sdata, res);
12163  return res;
12164 }
12165 
12166 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12167 {
12168  int force = 0;
12169  int res;
12170 
12171  switch (cmd) {
12172  case CLI_INIT:
12173  e->command = "iax2 provision";
12174  e->usage =
12175  "Usage: iax2 provision <host> <template> [forced]\n"
12176  " Provisions the given peer or IP address using a template\n"
12177  " matching either 'template' or '*' if the template is not\n"
12178  " found. If 'forced' is specified, even empty provisioning\n"
12179  " fields will be provisioned as empty fields.\n";
12180  return NULL;
12181  case CLI_GENERATE:
12182  if (a->pos == 3)
12183  return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
12184  return NULL;
12185  }
12186 
12187  if (a->argc < 4)
12188  return CLI_SHOWUSAGE;
12189  if (a->argc > 4) {
12190  if (!strcasecmp(a->argv[4], "forced"))
12191  force = 1;
12192  else
12193  return CLI_SHOWUSAGE;
12194  }
12195  res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
12196  if (res < 0)
12197  ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
12198  else if (res < 1)
12199  ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
12200  else
12201  ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
12202  return CLI_SUCCESS;
12203 }
12204 
12205 static void __iax2_poke_noanswer(const void *data)
12206 {
12207  struct iax2_peer *peer = (struct iax2_peer *)data;
12208  int callno;
12209 
12210  if (peer->lastms > -1) {
12211  ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
12212  manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
12213  ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
12214  }
12215  if ((callno = peer->callno) > 0) {
12216  ast_mutex_lock(&iaxsl[callno]);
12217  iax2_destroy(callno);
12218  ast_mutex_unlock(&iaxsl[callno]);
12219  }
12220  peer->callno = 0;
12221  peer->lastms = -1;
12222  /* Try again quickly */
12223  peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
12224  if (peer->pokeexpire == -1)
12225  peer_unref(peer);
12226 }
12227 
12228 static int iax2_poke_noanswer(const void *data)
12229 {
12230  struct iax2_peer *peer = (struct iax2_peer *)data;
12231  peer->pokeexpire = -1;
12232 #ifdef SCHED_MULTITHREADED
12234 #endif
12235  __iax2_poke_noanswer(data);
12236  peer_unref(peer);
12237  return 0;
12238 }
12239 
12240 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12241 {
12242  struct iax2_peer *peer = obj;
12243 
12244  iax2_poke_peer(peer, 0);
12245 
12246  return 0;
12247 }
12248 
12249 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12250 {
12251  int callno;
12252  struct sockaddr_in peer_addr;
12253 
12254  if (!peer->maxms || (!ast_sockaddr_ipv4(&peer->addr) && !peer->dnsmgr)) {
12255  /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
12256  immediately after clearing things out */
12257  peer->lastms = 0;
12258  peer->historicms = 0;
12259  peer->pokeexpire = -1;
12260  peer->callno = 0;
12261  return 0;
12262  }
12263 
12264  ast_sockaddr_to_sin(&peer->addr, &peer_addr);
12265 
12266  /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
12267  if ((callno = peer->callno) > 0) {
12268  ast_log(LOG_NOTICE, "Still have a callno...\n");
12269  ast_mutex_lock(&iaxsl[callno]);
12270  iax2_destroy(callno);
12271  ast_mutex_unlock(&iaxsl[callno]);
12272  }
12273  if (heldcall)
12274  ast_mutex_unlock(&iaxsl[heldcall]);
12275  callno = peer->callno = find_callno(0, 0, &peer_addr, NEW_FORCE, peer->sockfd, 0);
12276  if (heldcall)
12277  ast_mutex_lock(&iaxsl[heldcall]);
12278  if (peer->callno < 1) {
12279  ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12280  return -1;
12281  }
12282 
12283  /* Speed up retransmission times for this qualify call */
12284  iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
12285  iaxs[peer->callno]->peerpoke = peer;
12286 
12287  if (peer->pokeexpire > -1) {
12288  if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
12289  peer->pokeexpire = -1;
12290  peer_unref(peer);
12291  }
12292  }
12293 
12294  /* Queue up a new task to handle no reply */
12295  /* If the host is already unreachable then use the unreachable interval instead */
12296  if (peer->lastms < 0)
12297  peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
12298  else
12300 
12301  if (peer->pokeexpire == -1)
12302  peer_unref(peer);
12303 
12304  /* And send the poke */
12305  ast_mutex_lock(&iaxsl[callno]);
12306  if (iaxs[callno]) {
12307  struct iax_ie_data ied = {
12308  .buf = { 0 },
12309  .pos = 0,
12310  };
12311  add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
12312  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12313  }
12314  ast_mutex_unlock(&iaxsl[callno]);
12315 
12316  return 0;
12317 }
12318 
12319 static void free_context(struct iax2_context *con)
12320 {
12321  struct iax2_context *conl;
12322  while(con) {
12323  conl = con;
12324  con = con->next;
12325  ast_free(conl);
12326  }
12327 }
12328 
12329 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
12330 {
12331  int callno;
12332  int res;
12333  format_t fmt, native;
12334  struct sockaddr_in sin;
12335  struct ast_channel *c;
12336  struct parsed_dial_string pds;
12337  struct create_addr_info cai;
12338  char *tmpstr;
12339 
12340  memset(&pds, 0, sizeof(pds));
12341  tmpstr = ast_strdupa(data);
12342  parse_dial_string(tmpstr, &pds);
12343 
12344  if (ast_strlen_zero(pds.peer)) {
12345  ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
12346  return NULL;
12347  }
12348 
12349  memset(&cai, 0, sizeof(cai));
12351 
12353 
12354  /* Populate our address from the given */
12355  if (create_addr(pds.peer, NULL, &sin, &cai)) {
12356  *cause = AST_CAUSE_UNREGISTERED;
12357  return NULL;
12358  }
12359 
12360  if (pds.port)
12361  sin.sin_port = htons(atoi(pds.port));
12362 
12363  callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
12364  if (callno < 1) {
12365  ast_log(LOG_WARNING, "Unable to create call\n");
12366  *cause = AST_CAUSE_CONGESTION;
12367  return NULL;
12368  }
12369 
12370  /* If this is a trunk, update it now */
12372  if (ast_test_flag64(&cai, IAX_TRUNK)) {
12373  int new_callno;
12374  if ((new_callno = make_trunk(callno, 1)) != -1)
12375  callno = new_callno;
12376  }
12377  iaxs[callno]->maxtime = cai.maxtime;
12378  if (cai.found)
12379  ast_string_field_set(iaxs[callno], host, pds.peer);
12380 
12381  c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, requestor ? requestor->linkedid : NULL, cai.found);
12382 
12383  ast_mutex_unlock(&iaxsl[callno]);
12384 
12385  if (c) {
12386  /* Choose a format we can live with */
12387  if (c->nativeformats & format)
12388  c->nativeformats &= format;
12389  else {
12390  native = c->nativeformats;
12391  fmt = format;
12392  res = ast_translator_best_choice(&fmt, &native);
12393  if (res < 0) {
12394  ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12396  ast_hangup(c);
12397  return NULL;
12398  }
12399  c->nativeformats = native;
12400  }
12402  c->writeformat = c->readformat;
12403  }
12404 
12405  return c;
12406 }
12407 
12408 static void *network_thread(void *ignore)
12409 {
12410  if (timer) {
12411  ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
12412  }
12413 
12414  for (;;) {
12415  pthread_testcancel();
12416  /* Wake up once a second just in case SIGURG was sent while
12417  * we weren't in poll(), to make sure we don't hang when trying
12418  * to unload. */
12419  if (ast_io_wait(io, 1000) <= 0) {
12420  break;
12421  }
12422  }
12423 
12424  return NULL;
12425 }
12426 
12427 static int start_network_thread(void)
12428 {
12429  struct iax2_thread *thread;
12430  int threadcount = 0;
12431  int x;
12432  for (x = 0; x < iaxthreadcount; x++) {
12433  thread = ast_calloc(1, sizeof(*thread));
12434  if (thread) {
12435  thread->type = IAX_THREAD_TYPE_POOL;
12436  thread->threadnum = ++threadcount;
12437  ast_mutex_init(&thread->lock);
12438  ast_cond_init(&thread->cond, NULL);
12439  ast_mutex_init(&thread->init_lock);
12440  ast_cond_init(&thread->init_cond, NULL);
12441 
12442  ast_mutex_lock(&thread->init_lock);
12443 
12444  if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
12445  ast_log(LOG_WARNING, "Failed to create new thread!\n");
12446  ast_mutex_destroy(&thread->lock);
12447  ast_cond_destroy(&thread->cond);
12448  ast_mutex_unlock(&thread->init_lock);
12449  ast_mutex_destroy(&thread->init_lock);
12450  ast_cond_destroy(&thread->init_cond);
12451  ast_free(thread);
12452  thread = NULL;
12453  continue;
12454  }
12455  /* Wait for the thread to be ready */
12456  ast_cond_wait(&thread->init_cond, &thread->init_lock);
12457 
12458  /* Done with init_lock */
12459  ast_mutex_unlock(&thread->init_lock);
12460 
12462  AST_LIST_INSERT_TAIL(&idle_list, thread, list);
12464  }
12465  }
12466  if (ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL)) {
12467  ast_log(LOG_ERROR, "Failed to create new thread!\n");
12468  return -1;
12469  }
12470  ast_verb(2, "%d helper threads started\n", threadcount);
12471  return 0;
12472 }
12473 
12474 static struct iax2_context *build_context(const char *context)
12475 {
12476  struct iax2_context *con;
12477 
12478  if ((con = ast_calloc(1, sizeof(*con))))
12479  ast_copy_string(con->context, context, sizeof(con->context));
12480 
12481  return con;
12482 }
12483 
12484 static int get_auth_methods(const char *value)
12485 {
12486  int methods = 0;
12487  if (strstr(value, "rsa"))
12488  methods |= IAX_AUTH_RSA;
12489  if (strstr(value, "md5"))
12490  methods |= IAX_AUTH_MD5;
12491  if (strstr(value, "plaintext"))
12492  methods |= IAX_AUTH_PLAINTEXT;
12493  return methods;
12494 }
12495 
12496 
12497 /*! \brief Check if address can be used as packet source.
12498  \return 0 address available, 1 address unavailable, -1 error
12499 */
12500 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
12501 {
12502  int sd;
12503  int res;
12504 
12505  sd = socket(AF_INET, SOCK_DGRAM, 0);
12506  if (sd < 0) {
12507  ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12508  return -1;
12509  }
12510 
12511  res = bind(sd, sa, salen);
12512  if (res < 0) {
12513  ast_debug(1, "Can't bind: %s\n", strerror(errno));
12514  close(sd);
12515  return 1;
12516  }
12517 
12518  close(sd);
12519  return 0;
12520 }
12521 
12522 /*! \brief Parse the "sourceaddress" value,
12523  lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12524  not found. */
12525 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12526 {
12527  struct sockaddr_in sin;
12528  struct ast_sockaddr sin_tmp;
12529  int nonlocal = 1;
12530  int port = IAX_DEFAULT_PORTNO;
12531  int sockfd = defaultsockfd;
12532  char *tmp;
12533  char *addr;
12534  char *portstr;
12535 
12536  tmp = ast_strdupa(srcaddr);
12537  addr = strsep(&tmp, ":");
12538  portstr = tmp;
12539 
12540  if (portstr) {
12541  port = atoi(portstr);
12542  if (port < 1)
12543  port = IAX_DEFAULT_PORTNO;
12544  }
12545 
12546  sin_tmp.ss.ss_family = AF_INET;
12547  if (!ast_get_ip(&sin_tmp, addr)) {
12548  struct ast_netsock *sock;
12549  int res;
12550 
12551  ast_sockaddr_to_sin(&sin_tmp, &sin);
12552  sin.sin_port = 0;
12553  sin.sin_family = AF_INET;
12554  res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
12555  if (res == 0) {
12556  /* ip address valid. */
12557  sin.sin_port = htons(port);
12558  if (!(sock = ast_netsock_find(netsock, &sin)))
12559  sock = ast_netsock_find(outsock, &sin);
12560  if (sock) {
12561  sockfd = ast_netsock_sockfd(sock);
12562  nonlocal = 0;
12563  } else {
12564  unsigned int orig_saddr = sin.sin_addr.s_addr;
12565  /* INADDR_ANY matches anyway! */
12566  sin.sin_addr.s_addr = INADDR_ANY;
12567  if (ast_netsock_find(netsock, &sin)) {
12568  sin.sin_addr.s_addr = orig_saddr;
12569  sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12570  if (sock) {
12571  sockfd = ast_netsock_sockfd(sock);
12572  ast_netsock_unref(sock);
12573  nonlocal = 0;
12574  } else {
12575  nonlocal = 2;
12576  }
12577  }
12578  }
12579  }
12580  }
12581 
12582  peer->sockfd = sockfd;
12583 
12584  if (nonlocal == 1) {
12585  ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12586  srcaddr, peer->name);
12587  return -1;
12588  } else if (nonlocal == 2) {
12589  ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
12590  srcaddr, peer->name);
12591  return -1;
12592  } else {
12593  ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
12594  return 0;
12595  }
12596 }
12597 
12598 static void peer_destructor(void *obj)
12599 {
12600  struct iax2_peer *peer = obj;
12601  int callno = peer->callno;
12602 
12603  ast_free_ha(peer->ha);
12604 
12605  if (callno > 0) {
12606  ast_mutex_lock(&iaxsl[callno]);
12607  iax2_destroy(callno);
12608  ast_mutex_unlock(&iaxsl[callno]);
12609  }
12610 
12611  register_peer_exten(peer, 0);
12612 
12613  if (peer->dnsmgr)
12614  ast_dnsmgr_release(peer->dnsmgr);
12615 
12616  if (peer->mwi_event_sub)
12618 
12620 }
12621 
12622 /*! \brief Create peer structure based on configuration */
12623 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12624 {
12625  struct iax2_peer *peer = NULL;
12626  struct ast_ha *oldha = NULL;
12627  int maskfound = 0;
12628  int found = 0;
12629  int firstpass = 1;
12630  struct iax2_peer tmp_peer = {
12631  .name = name,
12632  };
12633 
12634  if (!temponly) {
12635  peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
12636  if (peer && !ast_test_flag64(peer, IAX_DELME))
12637  firstpass = 0;
12638  }
12639 
12640  if (peer) {
12641  found++;
12642  if (firstpass) {
12643  oldha = peer->ha;
12644  peer->ha = NULL;
12645  }
12646  unlink_peer(peer);
12647  } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
12648  peer->expire = -1;
12649  peer->pokeexpire = -1;
12650  peer->sockfd = defaultsockfd;
12651  peer->addr.ss.ss_family = AF_INET;
12652  peer->addr.len = sizeof(struct sockaddr_in);
12653  if (ast_string_field_init(peer, 32))
12654  peer = peer_unref(peer);
12655  }
12656 
12657  if (peer) {
12658  if (firstpass) {
12660  peer->encmethods = iax2_encryption;
12661  peer->adsi = adsi;
12662  ast_string_field_set(peer,secret,"");
12663  if (!found) {
12664  ast_string_field_set(peer, name, name);
12666  peer->expiry = min_reg_expire;
12667  }
12668  peer->prefs = prefs;
12669  peer->capability = iax2_capability;
12670  peer->smoothing = 0;
12671  peer->pokefreqok = DEFAULT_FREQ_OK;
12673  peer->maxcallno = 0;
12674  peercnt_modify((unsigned char) 0, 0, &peer->addr);
12676  ast_string_field_set(peer,context,"");
12677  ast_string_field_set(peer,peercontext,"");
12679  ast_string_field_set(peer, cid_name, "");
12680  ast_string_field_set(peer, cid_num, "");
12681  ast_string_field_set(peer, mohinterpret, mohinterpret);
12682  ast_string_field_set(peer, mohsuggest, mohsuggest);
12683  }
12684 
12685  if (!v) {
12686  v = alt;
12687  alt = NULL;
12688  }
12689  while(v) {
12690  if (!strcasecmp(v->name, "secret")) {
12691  ast_string_field_set(peer, secret, v->value);
12692  } else if (!strcasecmp(v->name, "mailbox")) {
12693  ast_string_field_set(peer, mailbox, v->value);
12694  } else if (!strcasecmp(v->name, "hasvoicemail")) {
12695  if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
12696  ast_string_field_set(peer, mailbox, name);
12697  }
12698  } else if (!strcasecmp(v->name, "mohinterpret")) {
12699  ast_string_field_set(peer, mohinterpret, v->value);
12700  } else if (!strcasecmp(v->name, "mohsuggest")) {
12701  ast_string_field_set(peer, mohsuggest, v->value);
12702  } else if (!strcasecmp(v->name, "dbsecret")) {
12703  ast_string_field_set(peer, dbsecret, v->value);
12704  } else if (!strcasecmp(v->name, "trunk")) {
12705  ast_set2_flag64(peer, ast_true(v->value), IAX_TRUNK);
12706  if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
12707  ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
12708  ast_clear_flag64(peer, IAX_TRUNK);
12709  }
12710  } else if (!strcasecmp(v->name, "auth")) {
12711  peer->authmethods = get_auth_methods(v->value);
12712  } else if (!strcasecmp(v->name, "encryption")) {
12713  peer->encmethods |= get_encrypt_methods(v->value);
12714  if (!peer->encmethods) {
12716  }
12717  } else if (!strcasecmp(v->name, "forceencryption")) {
12718  if (ast_false(v->value)) {
12720  } else {
12721  peer->encmethods |= get_encrypt_methods(v->value);
12722  if (peer->encmethods) {
12724  }
12725  }
12726  } else if (!strcasecmp(v->name, "transfer")) {
12727  if (!strcasecmp(v->value, "mediaonly")) {
12729  } else if (ast_true(v->value)) {
12731  } else
12733  } else if (!strcasecmp(v->name, "jitterbuffer")) {
12735  } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12737  } else if (!strcasecmp(v->name, "host")) {
12738  if (!strcasecmp(v->value, "dynamic")) {
12739  /* They'll register with us */
12740  ast_set_flag64(peer, IAX_DYNAMIC);
12741  if (!found) {
12742  /* Initialize stuff iff we're not found, otherwise
12743  we keep going with what we had */
12744  if (ast_sockaddr_port(&peer->addr)) {
12745  peer->defaddr.sin_port = htons(ast_sockaddr_port(&peer->addr));
12746  }
12747  ast_sockaddr_setnull(&peer->addr);
12748  }
12749  } else {
12750  /* Non-dynamic. Make sure we become that way if we're not */
12751  ast_sched_thread_del(sched, peer->expire);
12753  if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
12754  return peer_unref(peer);
12755  if (!ast_sockaddr_port(&peer->addr)) {
12757  }
12758  }
12759  if (!maskfound)
12760  inet_aton("255.255.255.255", &peer->mask);
12761  } else if (!strcasecmp(v->name, "defaultip")) {
12762  struct ast_sockaddr peer_defaddr_tmp;
12763 
12764  peer_defaddr_tmp.ss.ss_family = AF_INET;
12765  if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
12766  return peer_unref(peer);
12767  }
12768  ast_sockaddr_to_sin(&peer_defaddr_tmp,
12769  &peer->defaddr);
12770  } else if (!strcasecmp(v->name, "sourceaddress")) {
12771  peer_set_srcaddr(peer, v->value);
12772  } else if (!strcasecmp(v->name, "permit") ||
12773  !strcasecmp(v->name, "deny")) {
12774  peer->ha = ast_append_ha(v->name, v->value, peer->ha, NULL);
12775  } else if (!strcasecmp(v->name, "mask")) {
12776  maskfound++;
12777  inet_aton(v->value, &peer->mask);
12778  } else if (!strcasecmp(v->name, "context")) {
12779  ast_string_field_set(peer, context, v->value);
12780  } else if (!strcasecmp(v->name, "regexten")) {
12781  ast_string_field_set(peer, regexten, v->value);
12782  } else if (!strcasecmp(v->name, "peercontext")) {
12783  ast_string_field_set(peer, peercontext, v->value);
12784  } else if (!strcasecmp(v->name, "port")) {
12785  if (ast_test_flag64(peer, IAX_DYNAMIC)) {
12786  peer->defaddr.sin_port = htons(atoi(v->value));
12787  } else {
12788  ast_sockaddr_set_port(&peer->addr, atoi(v->value));
12789  }
12790  } else if (!strcasecmp(v->name, "username")) {
12791  ast_string_field_set(peer, username, v->value);
12792  } else if (!strcasecmp(v->name, "allow")) {
12793  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
12794  } else if (!strcasecmp(v->name, "disallow")) {
12795  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
12796  } else if (!strcasecmp(v->name, "callerid")) {
12797  if (!ast_strlen_zero(v->value)) {
12798  char name2[80];
12799  char num2[80];
12800  ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12801  ast_string_field_set(peer, cid_name, name2);
12802  ast_string_field_set(peer, cid_num, num2);
12803  } else {
12804  ast_string_field_set(peer, cid_name, "");
12805  ast_string_field_set(peer, cid_num, "");
12806  }
12808  } else if (!strcasecmp(v->name, "fullname")) {
12809  ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
12811  } else if (!strcasecmp(v->name, "cid_number")) {
12812  ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
12814  } else if (!strcasecmp(v->name, "sendani")) {
12816  } else if (!strcasecmp(v->name, "inkeys")) {
12817  ast_string_field_set(peer, inkeys, v->value);
12818  } else if (!strcasecmp(v->name, "outkey")) {
12819  ast_string_field_set(peer, outkey, v->value);
12820  } else if (!strcasecmp(v->name, "qualify")) {
12821  if (!strcasecmp(v->value, "no")) {
12822  peer->maxms = 0;
12823  } else if (!strcasecmp(v->value, "yes")) {
12824  peer->maxms = DEFAULT_MAXMS;
12825  } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
12826  ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
12827  peer->maxms = 0;
12828  }
12829  } else if (!strcasecmp(v->name, "qualifysmoothing")) {
12830  peer->smoothing = ast_true(v->value);
12831  } else if (!strcasecmp(v->name, "qualifyfreqok")) {
12832  if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
12833  ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
12834  }
12835  } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
12836  if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
12837  ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
12838  }
12839  } else if (!strcasecmp(v->name, "timezone")) {
12840  ast_string_field_set(peer, zonetag, v->value);
12841  } else if (!strcasecmp(v->name, "adsi")) {
12842  peer->adsi = ast_true(v->value);
12843  } else if (!strcasecmp(v->name, "connectedline")) {
12844  if (ast_true(v->value)) {
12846  } else if (!strcasecmp(v->value, "send")) {
12849  } else if (!strcasecmp(v->value, "receive")) {
12852  } else {
12854  }
12855  } else if (!strcasecmp(v->name, "maxcallnumbers")) {
12856  if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
12857  ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
12858  } else {
12859  peercnt_modify((unsigned char) 1, peer->maxcallno, &peer->addr);
12860  }
12861  } else if (!strcasecmp(v->name, "requirecalltoken")) {
12862  /* default is required unless in optional ip list */
12863  if (ast_false(v->value)) {
12865  } else if (!strcasecmp(v->value, "auto")) {
12867  } else if (ast_true(v->value)) {
12869  } else {
12870  ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12871  }
12872  } /* else if (strcasecmp(v->name,"type")) */
12873  /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
12874  v = v->next;
12875  if (!v) {
12876  v = alt;
12877  alt = NULL;
12878  }
12879  }
12880  if (!peer->authmethods)
12882  ast_clear_flag64(peer, IAX_DELME);
12883  }
12884 
12885  if (oldha)
12886  ast_free_ha(oldha);
12887 
12888  if (!ast_strlen_zero(peer->mailbox)) {
12889  char *mailbox, *context;
12890  context = mailbox = ast_strdupa(peer->mailbox);
12891  strsep(&context, "@");
12892  if (ast_strlen_zero(context))
12893  context = "default";
12894  peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "IAX MWI subscription", NULL,
12898  }
12899 
12900  return peer;
12901 }
12902 
12903 static void user_destructor(void *obj)
12904 {
12905  struct iax2_user *user = obj;
12906 
12907  ast_free_ha(user->ha);
12908  free_context(user->contexts);
12909  if(user->vars) {
12910  ast_variables_destroy(user->vars);
12911  user->vars = NULL;
12912  }
12914 }
12915 
12916 /*! \brief Create in-memory user structure from configuration */
12917 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12918 {
12919  struct iax2_user *user = NULL;
12920  struct iax2_context *con, *conl = NULL;
12921  struct ast_ha *oldha = NULL;
12922  struct iax2_context *oldcon = NULL;
12923  int format;
12924  int firstpass=1;
12925  int oldcurauthreq = 0;
12926  char *varname = NULL, *varval = NULL;
12927  struct ast_variable *tmpvar = NULL;
12928  struct iax2_user tmp_user = {
12929  .name = name,
12930  };
12931 
12932  if (!temponly) {
12933  user = ao2_find(users, &tmp_user, OBJ_POINTER);
12934  if (user && !ast_test_flag64(user, IAX_DELME))
12935  firstpass = 0;
12936  }
12937 
12938  if (user) {
12939  if (firstpass) {
12940  oldcurauthreq = user->curauthreq;
12941  oldha = user->ha;
12942  oldcon = user->contexts;
12943  user->ha = NULL;
12944  user->contexts = NULL;
12945  }
12946  /* Already in the list, remove it and it will be added back (or FREE'd) */
12947  ao2_unlink(users, user);
12948  } else {
12949  user = ao2_alloc(sizeof(*user), user_destructor);
12950  }
12951 
12952  if (user) {
12953  if (firstpass) {
12955  memset(user, 0, sizeof(struct iax2_user));
12956  if (ast_string_field_init(user, 32)) {
12957  user = user_unref(user);
12958  goto cleanup;
12959  }
12960  user->maxauthreq = maxauthreq;
12961  user->curauthreq = oldcurauthreq;
12962  user->prefs = prefs;
12963  user->capability = iax2_capability;
12964  user->encmethods = iax2_encryption;
12965  user->adsi = adsi;
12967  ast_string_field_set(user, name, name);
12968  ast_string_field_set(user, language, language);
12971  ast_string_field_set(user, cid_name, "");
12972  ast_string_field_set(user, cid_num, "");
12973  ast_string_field_set(user, accountcode, accountcode);
12974  ast_string_field_set(user, mohinterpret, mohinterpret);
12975  ast_string_field_set(user, mohsuggest, mohsuggest);
12976  }
12977  if (!v) {
12978  v = alt;
12979  alt = NULL;
12980  }
12981  while(v) {
12982  if (!strcasecmp(v->name, "context")) {
12983  con = build_context(v->value);
12984  if (con) {
12985  if (conl)
12986  conl->next = con;
12987  else
12988  user->contexts = con;
12989  conl = con;
12990  }
12991  } else if (!strcasecmp(v->name, "permit") ||
12992  !strcasecmp(v->name, "deny")) {
12993  user->ha = ast_append_ha(v->name, v->value, user->ha, NULL);
12994  } else if (!strcasecmp(v->name, "setvar")) {
12995  varname = ast_strdupa(v->value);
12996  if ((varval = strchr(varname, '='))) {
12997  *varval = '\0';
12998  varval++;
12999  if((tmpvar = ast_variable_new(varname, varval, ""))) {
13000  tmpvar->next = user->vars;
13001  user->vars = tmpvar;
13002  }
13003  }
13004  } else if (!strcasecmp(v->name, "allow")) {
13005  ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
13006  } else if (!strcasecmp(v->name, "disallow")) {
13007  ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
13008  } else if (!strcasecmp(v->name, "trunk")) {
13009  ast_set2_flag64(user, ast_true(v->value), IAX_TRUNK);
13010  if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
13011  ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
13012  ast_clear_flag64(user, IAX_TRUNK);
13013  }
13014  } else if (!strcasecmp(v->name, "auth")) {
13015  user->authmethods = get_auth_methods(v->value);
13016  } else if (!strcasecmp(v->name, "encryption")) {
13017  user->encmethods |= get_encrypt_methods(v->value);
13018  if (!user->encmethods) {
13020  }
13021  } else if (!strcasecmp(v->name, "forceencryption")) {
13022  if (ast_false(v->value)) {
13024  } else {
13025  user->encmethods |= get_encrypt_methods(v->value);
13026  if (user->encmethods) {
13028  }
13029  }
13030  } else if (!strcasecmp(v->name, "transfer")) {
13031  if (!strcasecmp(v->value, "mediaonly")) {
13033  } else if (ast_true(v->value)) {
13035  } else
13037  } else if (!strcasecmp(v->name, "codecpriority")) {
13038  if(!strcasecmp(v->value, "caller"))
13040  else if(!strcasecmp(v->value, "disabled"))
13042  else if(!strcasecmp(v->value, "reqonly")) {
13045  }
13046  } else if (!strcasecmp(v->name, "immediate")) {
13048  } else if (!strcasecmp(v->name, "jitterbuffer")) {
13050  } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
13052  } else if (!strcasecmp(v->name, "dbsecret")) {
13053  ast_string_field_set(user, dbsecret, v->value);
13054  } else if (!strcasecmp(v->name, "secret")) {
13055  if (!ast_strlen_zero(user->secret)) {
13056  char *old = ast_strdupa(user->secret);
13057 
13058  ast_string_field_build(user, secret, "%s;%s", old, v->value);
13059  } else
13060  ast_string_field_set(user, secret, v->value);
13061  } else if (!strcasecmp(v->name, "callerid")) {
13062  if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
13063  char name2[80];
13064  char num2[80];
13065  ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13066  ast_string_field_set(user, cid_name, name2);
13067  ast_string_field_set(user, cid_num, num2);
13069  } else {
13071  ast_string_field_set(user, cid_name, "");
13072  ast_string_field_set(user, cid_num, "");
13073  }
13074  } else if (!strcasecmp(v->name, "fullname")) {
13075  if (!ast_strlen_zero(v->value)) {
13076  ast_string_field_set(user, cid_name, v->value);
13078  } else {
13079  ast_string_field_set(user, cid_name, "");
13080  if (ast_strlen_zero(user->cid_num))
13082  }
13083  } else if (!strcasecmp(v->name, "cid_number")) {
13084  if (!ast_strlen_zero(v->value)) {
13085  ast_string_field_set(user, cid_num, v->value);
13087  } else {
13088  ast_string_field_set(user, cid_num, "");
13089  if (ast_strlen_zero(user->cid_name))
13091  }
13092  } else if (!strcasecmp(v->name, "accountcode")) {
13093  ast_string_field_set(user, accountcode, v->value);
13094  } else if (!strcasecmp(v->name, "mohinterpret")) {
13095  ast_string_field_set(user, mohinterpret, v->value);
13096  } else if (!strcasecmp(v->name, "mohsuggest")) {
13097  ast_string_field_set(user, mohsuggest, v->value);
13098  } else if (!strcasecmp(v->name, "parkinglot")) {
13100  } else if (!strcasecmp(v->name, "language")) {
13101  ast_string_field_set(user, language, v->value);
13102  } else if (!strcasecmp(v->name, "amaflags")) {
13103  format = ast_cdr_amaflags2int(v->value);
13104  if (format < 0) {
13105  ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13106  } else {
13107  user->amaflags = format;
13108  }
13109  } else if (!strcasecmp(v->name, "inkeys")) {
13110  ast_string_field_set(user, inkeys, v->value);
13111  } else if (!strcasecmp(v->name, "maxauthreq")) {
13112  user->maxauthreq = atoi(v->value);
13113  if (user->maxauthreq < 0)
13114  user->maxauthreq = 0;
13115  } else if (!strcasecmp(v->name, "adsi")) {
13116  user->adsi = ast_true(v->value);
13117  } else if (!strcasecmp(v->name, "connectedline")) {
13118  if (ast_true(v->value)) {
13120  } else if (!strcasecmp(v->value, "send")) {
13123  } else if (!strcasecmp(v->value, "receive")) {
13126  } else {
13128  }
13129  } else if (!strcasecmp(v->name, "requirecalltoken")) {
13130  /* default is required unless in optional ip list */
13131  if (ast_false(v->value)) {
13133  } else if (!strcasecmp(v->value, "auto")) {
13135  } else if (ast_true(v->value)) {
13137  } else {
13138  ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13139  }
13140  } /* else if (strcasecmp(v->name,"type")) */
13141  /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13142  v = v->next;
13143  if (!v) {
13144  v = alt;
13145  alt = NULL;
13146  }
13147  }
13148  if (!user->authmethods) {
13149  if (!ast_strlen_zero(user->secret)) {
13151  if (!ast_strlen_zero(user->inkeys))
13152  user->authmethods |= IAX_AUTH_RSA;
13153  } else if (!ast_strlen_zero(user->inkeys)) {
13154  user->authmethods = IAX_AUTH_RSA;
13155  } else {
13157  }
13158  }
13159  ast_clear_flag64(user, IAX_DELME);
13160  }
13161 cleanup:
13162  if (oldha)
13163  ast_free_ha(oldha);
13164  if (oldcon)
13165  free_context(oldcon);
13166  return user;
13167 }
13168 
13169 static int peer_delme_cb(void *obj, void *arg, int flags)
13170 {
13171  struct iax2_peer *peer = obj;
13172 
13173  ast_set_flag64(peer, IAX_DELME);
13174 
13175  return 0;
13176 }
13177 
13178 static int user_delme_cb(void *obj, void *arg, int flags)
13179 {
13180  struct iax2_user *user = obj;
13181 
13182  ast_set_flag64(user, IAX_DELME);
13183 
13184  return 0;
13185 }
13186 
13187 static void delete_users(void)
13188 {
13189  struct iax2_registry *reg;
13190 
13191  ao2_callback(users, 0, user_delme_cb, NULL);
13192 
13193  AST_LIST_LOCK(&registrations);
13194  while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
13195  if (sched) {
13196  ast_sched_thread_del(sched, reg->expire);
13197  }
13198  if (reg->callno) {
13199  int callno = reg->callno;
13200  ast_mutex_lock(&iaxsl[callno]);
13201  if (iaxs[callno]) {
13202  iaxs[callno]->reg = NULL;
13203  iax2_destroy(callno);
13204  }
13205  ast_mutex_unlock(&iaxsl[callno]);
13206  }
13207  if (reg->dnsmgr)
13208  ast_dnsmgr_release(reg->dnsmgr);
13209  ast_free(reg);
13210  }
13211  AST_LIST_UNLOCK(&registrations);
13212 
13213  ao2_callback(peers, 0, peer_delme_cb, NULL);
13214 }
13215 
13216 static void prune_users(void)
13217 {
13218  struct iax2_user *user;
13219  struct ao2_iterator i;
13220 
13221  i = ao2_iterator_init(users, 0);
13222  while ((user = ao2_iterator_next(&i))) {
13224  ao2_unlink(users, user);
13225  }
13226  user_unref(user);
13227  }
13229 }
13230 
13231 /* Prune peers who still are supposed to be deleted */
13232 static void prune_peers(void)
13233 {
13234  struct iax2_peer *peer;
13235  struct ao2_iterator i;
13236 
13237  i = ao2_iterator_init(peers, 0);
13238  while ((peer = ao2_iterator_next(&i))) {
13240  unlink_peer(peer);
13241  }
13242  peer_unref(peer);
13243  }
13245 }
13246 
13247 static void set_config_destroy(void)
13248 {
13249  strcpy(accountcode, "");
13250  strcpy(language, "");
13251  strcpy(mohinterpret, "");
13252  strcpy(mohsuggest, "");
13253  trunkmaxsize = MAX_TRUNKDATA;
13254  amaflags = 0;
13255  delayreject = 0;
13258  delete_users();
13259  ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
13260  ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
13261 }
13262 
13263 /*! \brief Load configuration */
13264 static int set_config(const char *config_file, int reload)
13265 {
13266  struct ast_config *cfg, *ucfg;
13268  struct ast_variable *v;
13269  char *cat;
13270  const char *utype;
13271  const char *tosval;
13272  int format;
13273  int portno = IAX_DEFAULT_PORTNO;
13274  int x;
13275  int mtuv;
13276  int subscribe_network_change = 1;
13277  struct iax2_user *user;
13278  struct iax2_peer *peer;
13279  struct ast_netsock *ns;
13280  struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13281 #if 0
13282  static unsigned short int last_port=0;
13283 #endif
13284 
13285  cfg = ast_config_load(config_file, config_flags);
13286 
13287  if (!cfg) {
13288  ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13289  return -1;
13290  } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13291  ucfg = ast_config_load("users.conf", config_flags);
13292  if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
13293  return 0;
13294  /* Otherwise we need to reread both files */
13295  ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13296  if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13297  ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13298  ast_config_destroy(ucfg);
13299  return 0;
13300  }
13301  if (!cfg) {
13302  /* should have been able to load the config here */
13303  ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13304  return -1;
13305  }
13306  } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13307  ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13308  return 0;
13309  } else { /* iax.conf changed, gotta reread users.conf, too */
13310  ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13311  if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
13312  ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Aborting.\n");
13313  ast_config_destroy(cfg);
13314  return 0;
13315  }
13316  }
13317 
13318  if (reload) {
13320  }
13321 
13322  /* Reset global codec prefs */
13323  memset(&prefs, 0 , sizeof(struct ast_codec_pref));
13324 
13325  /* Reset Global Flags */
13326  memset(&globalflags, 0, sizeof(globalflags));
13327  ast_set_flag64(&globalflags, IAX_RTUPDATE);
13328  ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13329 
13330 #ifdef SO_NO_CHECK
13331  nochecksums = 0;
13332 #endif
13333  /* Reset default parking lot */
13334  default_parkinglot[0] = '\0';
13335 
13336  min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13337  max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13338  global_max_trunk_mtu = MAX_TRUNK_MTU;
13339  global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
13340  global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
13341 
13342  maxauthreq = 3;
13343 
13344  srvlookup = 0;
13345 
13346  v = ast_variable_browse(cfg, "general");
13347 
13348  /* Seed initial tos value */
13349  tosval = ast_variable_retrieve(cfg, "general", "tos");
13350  if (tosval) {
13351  if (ast_str2tos(tosval, &qos.tos))
13352  ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13353  }
13354  /* Seed initial cos value */
13355  tosval = ast_variable_retrieve(cfg, "general", "cos");
13356  if (tosval) {
13357  if (ast_str2cos(tosval, &qos.cos))
13358  ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13359  }
13360  while(v) {
13361  if (!strcasecmp(v->name, "bindport")){
13362  if (reload)
13363  ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13364  else
13365  portno = atoi(v->value);
13366  } else if (!strcasecmp(v->name, "pingtime"))
13367  ping_time = atoi(v->value);
13368  else if (!strcasecmp(v->name, "iaxthreadcount")) {
13369  if (reload) {
13370  if (atoi(v->value) != iaxthreadcount)
13371  ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13372  } else {
13373  iaxthreadcount = atoi(v->value);
13374  if (iaxthreadcount < 1) {
13375  ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13376  iaxthreadcount = 1;
13377  } else if (iaxthreadcount > 256) {
13378  ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13379  iaxthreadcount = 256;
13380  }
13381  }
13382  } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13383  if (reload) {
13385  iaxmaxthreadcount = atoi(v->value);
13387  } else {
13388  iaxmaxthreadcount = atoi(v->value);
13389  if (iaxmaxthreadcount < 0) {
13390  ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13391  iaxmaxthreadcount = 0;
13392  } else if (iaxmaxthreadcount > 256) {
13393  ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13394  iaxmaxthreadcount = 256;
13395  }
13396  }
13397  } else if (!strcasecmp(v->name, "nochecksums")) {
13398 #ifdef SO_NO_CHECK
13399  if (ast_true(v->value))
13400  nochecksums = 1;
13401  else
13402  nochecksums = 0;
13403 #else
13404  if (ast_true(v->value))
13405  ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13406 #endif
13407  }
13408  else if (!strcasecmp(v->name, "maxjitterbuffer"))
13409  maxjitterbuffer = atoi(v->value);
13410  else if (!strcasecmp(v->name, "resyncthreshold"))
13411  resyncthreshold = atoi(v->value);
13412  else if (!strcasecmp(v->name, "maxjitterinterps"))
13413  maxjitterinterps = atoi(v->value);
13414  else if (!strcasecmp(v->name, "jittertargetextra"))
13415  jittertargetextra = atoi(v->value);
13416  else if (!strcasecmp(v->name, "lagrqtime"))
13417  lagrq_time = atoi(v->value);
13418  else if (!strcasecmp(v->name, "maxregexpire"))
13419  max_reg_expire = atoi(v->value);
13420  else if (!strcasecmp(v->name, "minregexpire"))
13421  min_reg_expire = atoi(v->value);
13422  else if (!strcasecmp(v->name, "bindaddr")) {
13423  if (reload) {
13424  ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13425  } else {
13426  if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
13427  ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
13428  } else {
13429  if (strchr(v->value, ':'))
13430  ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
13431  else
13432  ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
13433  if (defaultsockfd < 0)
13434  defaultsockfd = ast_netsock_sockfd(ns);
13435  ast_netsock_unref(ns);
13436  }
13437  }
13438  } else if (!strcasecmp(v->name, "authdebug")) {
13439  authdebug = ast_true(v->value);
13440  } else if (!strcasecmp(v->name, "encryption")) {
13441  iax2_encryption |= get_encrypt_methods(v->value);
13442  if (!iax2_encryption) {
13443  ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13444  }
13445  } else if (!strcasecmp(v->name, "forceencryption")) {
13446  if (ast_false(v->value)) {
13447  ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13448  } else {
13449  iax2_encryption |= get_encrypt_methods(v->value);
13450  if (iax2_encryption) {
13451  ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13452  }
13453  }
13454  } else if (!strcasecmp(v->name, "transfer")) {
13455  if (!strcasecmp(v->value, "mediaonly")) {
13457  } else if (ast_true(v->value)) {
13459  } else
13461  } else if (!strcasecmp(v->name, "codecpriority")) {
13462  if(!strcasecmp(v->value, "caller"))
13463  ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
13464  else if(!strcasecmp(v->value, "disabled"))
13465  ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13466  else if(!strcasecmp(v->value, "reqonly")) {
13467  ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
13468  ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13469  }
13470  } else if (!strcasecmp(v->name, "jitterbuffer"))
13471  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
13472  else if (!strcasecmp(v->name, "forcejitterbuffer"))
13473  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
13474  else if (!strcasecmp(v->name, "delayreject"))
13475  delayreject = ast_true(v->value);
13476  else if (!strcasecmp(v->name, "allowfwdownload"))
13477  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
13478  else if (!strcasecmp(v->name, "rtcachefriends"))
13479  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
13480  else if (!strcasecmp(v->name, "rtignoreregexpire"))
13481  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
13482  else if (!strcasecmp(v->name, "rtupdate"))
13483  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
13484  else if (!strcasecmp(v->name, "rtsavesysname"))
13485  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
13486  else if (!strcasecmp(v->name, "trunktimestamps"))
13487  ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
13488  else if (!strcasecmp(v->name, "rtautoclear")) {
13489  int i = atoi(v->value);
13490  if(i > 0)
13491  global_rtautoclear = i;
13492  else
13493  i = 0;
13494  ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
13495  } else if (!strcasecmp(v->name, "trunkfreq")) {
13496  trunkfreq = atoi(v->value);
13497  if (trunkfreq < 10) {
13498  ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13499  trunkfreq = 10;
13500  } else if (trunkfreq > 1000) {
13501  ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13502  trunkfreq = 1000;
13503  }
13504  if (timer) {
13505  ast_timer_set_rate(timer, 1000 / trunkfreq);
13506  }
13507  } else if (!strcasecmp(v->name, "trunkmtu")) {
13508  mtuv = atoi(v->value);
13509  if (mtuv == 0 )
13510  global_max_trunk_mtu = 0;
13511  else if (mtuv >= 172 && mtuv < 4000)
13512  global_max_trunk_mtu = mtuv;
13513  else
13514  ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13515  mtuv, v->lineno);
13516  } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13517  trunkmaxsize = atoi(v->value);
13518  if (trunkmaxsize == 0)
13519  trunkmaxsize = MAX_TRUNKDATA;
13520  } else if (!strcasecmp(v->name, "autokill")) {
13521  if (sscanf(v->value, "%30d", &x) == 1) {
13522  if (x >= 0)
13523  autokill = x;
13524  else
13525  ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13526  } else if (ast_true(v->value)) {
13527  autokill = DEFAULT_MAXMS;
13528  } else {
13529  autokill = 0;
13530  }
13531  } else if (!strcasecmp(v->name, "bandwidth")) {
13532  if (!strcasecmp(v->value, "low")) {
13533  capability = IAX_CAPABILITY_LOWBANDWIDTH;
13534  } else if (!strcasecmp(v->value, "medium")) {
13535  capability = IAX_CAPABILITY_MEDBANDWIDTH;
13536  } else if (!strcasecmp(v->value, "high")) {
13537  capability = IAX_CAPABILITY_FULLBANDWIDTH;
13538  } else
13539  ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13540  } else if (!strcasecmp(v->name, "allow")) {
13541  ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
13542  } else if (!strcasecmp(v->name, "disallow")) {
13543  ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
13544  } else if (!strcasecmp(v->name, "register")) {
13545  iax2_register(v->value, v->lineno);
13546  } else if (!strcasecmp(v->name, "iaxcompat")) {
13547  iaxcompat = ast_true(v->value);
13548  } else if (!strcasecmp(v->name, "regcontext")) {
13549  ast_copy_string(regcontext, v->value, sizeof(regcontext));
13550  /* Create context if it doesn't exist already */
13551  ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
13552  } else if (!strcasecmp(v->name, "tos")) {
13553  if (ast_str2tos(v->value, &qos.tos))
13554  ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
13555  } else if (!strcasecmp(v->name, "cos")) {
13556  if (ast_str2cos(v->value, &qos.cos))
13557  ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
13558  } else if (!strcasecmp(v->name, "parkinglot")) {
13559  ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
13560  } else if (!strcasecmp(v->name, "accountcode")) {
13561  ast_copy_string(accountcode, v->value, sizeof(accountcode));
13562  } else if (!strcasecmp(v->name, "mohinterpret")) {
13563  ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
13564  } else if (!strcasecmp(v->name, "mohsuggest")) {
13565  ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
13566  } else if (!strcasecmp(v->name, "amaflags")) {
13567  format = ast_cdr_amaflags2int(v->value);
13568  if (format < 0) {
13569  ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13570  } else {
13571  amaflags = format;
13572  }
13573  } else if (!strcasecmp(v->name, "language")) {
13574  ast_copy_string(language, v->value, sizeof(language));
13575  } else if (!strcasecmp(v->name, "maxauthreq")) {
13576  maxauthreq = atoi(v->value);
13577  if (maxauthreq < 0)
13578  maxauthreq = 0;
13579  } else if (!strcasecmp(v->name, "adsi")) {
13580  adsi = ast_true(v->value);
13581  } else if (!strcasecmp(v->name, "srvlookup")) {
13582  srvlookup = ast_true(v->value);
13583  } else if (!strcasecmp(v->name, "connectedline")) {
13584  if (ast_true(v->value)) {
13586  } else if (!strcasecmp(v->value, "send")) {
13587  ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13588  ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13589  } else if (!strcasecmp(v->value, "receive")) {
13590  ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13591  ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13592  } else {
13594  }
13595  } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13596  if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
13597  ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
13598  }
13599  } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
13600  if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
13601  ast_log(LOG_WARNING, "maxcallnumbers_nonvalidated must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
13602  }
13603  } else if (!strcasecmp(v->name, "calltokenoptional")) {
13604  if (add_calltoken_ignore(v->value)) {
13605  ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
13606  }
13607  } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
13608  if (ast_true(v->value)) {
13609  subscribe_network_change = 1;
13610  } else if (ast_false(v->value)) {
13611  subscribe_network_change = 0;
13612  } else {
13613  ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
13614  }
13615  } else if (!strcasecmp(v->name, "shrinkcallerid")) {
13616  if (ast_true(v->value)) {
13617  ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13618  } else if (ast_false(v->value)) {
13619  ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
13620  } else {
13621  ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
13622  }
13623  }/*else if (strcasecmp(v->name,"type")) */
13624  /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13625  v = v->next;
13626  }
13627 
13628  if (subscribe_network_change) {
13630  } else {
13632  }
13633 
13634  if (defaultsockfd < 0) {
13635  if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
13636  ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
13637  } else {
13638  ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
13639  defaultsockfd = ast_netsock_sockfd(ns);
13640  ast_netsock_unref(ns);
13641  }
13642  }
13643  if (reload) {
13644  ast_netsock_release(outsock);
13645  outsock = ast_netsock_list_alloc();
13646  if (!outsock) {
13647  ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
13648  return -1;
13649  }
13650  ast_netsock_init(outsock);
13651  }
13652 
13653  if (min_reg_expire > max_reg_expire) {
13654  ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
13655  min_reg_expire, max_reg_expire, max_reg_expire);
13656  min_reg_expire = max_reg_expire;
13657  }
13658  iax2_capability = capability;
13659 
13660  if (ucfg) {
13661  struct ast_variable *gen;
13662  int genhasiax;
13663  int genregisteriax;
13664  const char *hasiax, *registeriax;
13665 
13666  genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
13667  genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
13668  gen = ast_variable_browse(ucfg, "general");
13669  cat = ast_category_browse(ucfg, NULL);
13670  while (cat) {
13671  if (strcasecmp(cat, "general")) {
13672  hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
13673  registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
13674  if (ast_true(hasiax) || (!hasiax && genhasiax)) {
13675  /* Start with general parameters, then specific parameters, user and peer */
13676  user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
13677  if (user) {
13678  ao2_link(users, user);
13679  user = user_unref(user);
13680  }
13681  peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
13682  if (peer) {
13683  if (ast_test_flag64(peer, IAX_DYNAMIC))
13684  reg_source_db(peer);
13685  ao2_link(peers, peer);
13686  peer = peer_unref(peer);
13687  }
13688  }
13689  if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
13690  char tmp[256];
13691  const char *host = ast_variable_retrieve(ucfg, cat, "host");
13692  const char *username = ast_variable_retrieve(ucfg, cat, "username");
13693  const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
13694  if (!host)
13695  host = ast_variable_retrieve(ucfg, "general", "host");
13696  if (!username)
13697  username = ast_variable_retrieve(ucfg, "general", "username");
13698  if (!secret)
13699  secret = ast_variable_retrieve(ucfg, "general", "secret");
13700  if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
13701  if (!ast_strlen_zero(secret))
13702  snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
13703  else
13704  snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
13705  iax2_register(tmp, 0);
13706  }
13707  }
13708  }
13709  cat = ast_category_browse(ucfg, cat);
13710  }
13711  ast_config_destroy(ucfg);
13712  }
13713 
13714  cat = ast_category_browse(cfg, NULL);
13715  while(cat) {
13716  if (strcasecmp(cat, "general")) {
13717  utype = ast_variable_retrieve(cfg, cat, "type");
13718  if (!strcasecmp(cat, "callnumberlimits")) {
13720  } else if (utype) {
13721  if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
13722  user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
13723  if (user) {
13724  ao2_link(users, user);
13725  user = user_unref(user);
13726  }
13727  }
13728  if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
13729  peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
13730  if (peer) {
13731  if (ast_test_flag64(peer, IAX_DYNAMIC))
13732  reg_source_db(peer);
13733  ao2_link(peers, peer);
13734  peer = peer_unref(peer);
13735  }
13736  } else if (strcasecmp(utype, "user")) {
13737  ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
13738  }
13739  } else
13740  ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
13741  }
13742  cat = ast_category_browse(cfg, cat);
13743  }
13744  ast_config_destroy(cfg);
13745  return 1;
13746 }
13747 
13748 static void poke_all_peers(void)
13749 {
13750  struct ao2_iterator i;
13751  struct iax2_peer *peer;
13752 
13753  i = ao2_iterator_init(peers, 0);
13754  while ((peer = ao2_iterator_next(&i))) {
13755  iax2_poke_peer(peer, 0);
13756  peer_unref(peer);
13757  }
13759 }
13760 static int reload_config(void)
13761 {
13762  static const char config[] = "iax.conf";
13763  struct iax2_registry *reg;
13764 
13765  if (set_config(config, 1) > 0) {
13766  prune_peers();
13767  prune_users();
13769  ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13771  trunk_timed = trunk_untimed = 0;
13772  trunk_nmaxmtu = trunk_maxmtu = 0;
13773  memset(&debugaddr, '\0', sizeof(debugaddr));
13774 
13775  AST_LIST_LOCK(&registrations);
13776  AST_LIST_TRAVERSE(&registrations, reg, entry)
13777  iax2_do_register(reg);
13778  AST_LIST_UNLOCK(&registrations);
13779 
13780  /* Qualify hosts, too */
13781  poke_all_peers();
13782  }
13783 
13784  reload_firmware(0);
13786  ast_unload_realtime("iaxpeers");
13787 
13788  return 0;
13789 }
13790 
13791 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13792 {
13793  switch (cmd) {
13794  case CLI_INIT:
13795  e->command = "iax2 reload";
13796  e->usage =
13797  "Usage: iax2 reload\n"
13798  " Reloads IAX configuration from iax.conf\n";
13799  return NULL;
13800  case CLI_GENERATE:
13801  return NULL;
13802  }
13803 
13804  reload_config();
13805 
13806  return CLI_SUCCESS;
13807 }
13808 
13809 static int reload(void)
13810 {
13811  return reload_config();
13812 }
13813 
13814 static int cache_get_callno_locked(const char *data)
13815 {
13816  struct sockaddr_in sin;
13817  int x;
13818  int callno;
13819  struct iax_ie_data ied;
13820  struct create_addr_info cai;
13821  struct parsed_dial_string pds;
13822  char *tmpstr;
13823 
13824  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
13825  /* Look for an *exact match* call. Once a call is negotiated, it can only
13826  look up entries for a single context */
13827  if (!ast_mutex_trylock(&iaxsl[x])) {
13828  if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
13829  return x;
13830  ast_mutex_unlock(&iaxsl[x]);
13831  }
13832  }
13833 
13834  /* No match found, we need to create a new one */
13835 
13836  memset(&cai, 0, sizeof(cai));
13837  memset(&ied, 0, sizeof(ied));
13838  memset(&pds, 0, sizeof(pds));
13839 
13840  tmpstr = ast_strdupa(data);
13841  parse_dial_string(tmpstr, &pds);
13842 
13843  if (ast_strlen_zero(pds.peer)) {
13844  ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
13845  return -1;
13846  }
13847 
13848  /* Populate our address from the given */
13849  if (create_addr(pds.peer, NULL, &sin, &cai))
13850  return -1;
13851 
13852  ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
13853  pds.peer, pds.username, pds.password, pds.context);
13854 
13855  callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
13856  if (callno < 1) {
13857  ast_log(LOG_WARNING, "Unable to create call\n");
13858  return -1;
13859  }
13860 
13861  ast_string_field_set(iaxs[callno], dproot, data);
13862  iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
13863 
13866  /* the string format is slightly different from a standard dial string,
13867  because the context appears in the 'exten' position
13868  */
13869  if (pds.exten)
13871  if (pds.username)
13875  /* Keep password handy */
13876  if (pds.password)
13877  ast_string_field_set(iaxs[callno], secret, pds.password);
13878  if (pds.key)
13879  ast_string_field_set(iaxs[callno], outkey, pds.key);
13880  /* Start the call going */
13881  add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
13882  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
13883 
13884  return callno;
13885 }
13886 
13887 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
13888 {
13889  struct iax2_dpcache *dp = NULL;
13890  struct timeval now = ast_tvnow();
13891  int x, com[2], timeout, old = 0, outfd, doabort, callno;
13892  struct ast_channel *c = NULL;
13893  struct ast_frame *f = NULL;
13894 
13895  AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
13896  if (ast_tvcmp(now, dp->expiry) > 0) {
13897  AST_LIST_REMOVE_CURRENT(cache_list);
13898  if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
13899  ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
13900  else
13901  ast_free(dp);
13902  continue;
13903  }
13904  if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
13905  break;
13906  }
13908 
13909  if (!dp) {
13910  /* No matching entry. Create a new one. */
13911  /* First, can we make a callno? */
13912  if ((callno = cache_get_callno_locked(data)) < 0) {
13913  ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
13914  return NULL;
13915  }
13916  if (!(dp = ast_calloc(1, sizeof(*dp)))) {
13917  ast_mutex_unlock(&iaxsl[callno]);
13918  return NULL;
13919  }
13920  ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
13921  ast_copy_string(dp->exten, exten, sizeof(dp->exten));
13922  dp->expiry = ast_tvnow();
13923  dp->orig = dp->expiry;
13924  /* Expires in 30 mins by default */
13925  dp->expiry.tv_sec += iaxdefaultdpcache;
13926  dp->flags = CACHE_FLAG_PENDING;
13927  for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
13928  dp->waiters[x] = -1;
13929  /* Insert into the lists */
13930  AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
13931  AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
13932  /* Send the request if we're already up */
13933  if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
13934  iax2_dprequest(dp, callno);
13935  ast_mutex_unlock(&iaxsl[callno]);
13936  }
13937 
13938  /* By here we must have a dp */
13939  if (dp->flags & CACHE_FLAG_PENDING) {
13940  struct timeval start;
13941  int ms;
13942  /* Okay, here it starts to get nasty. We need a pipe now to wait
13943  for a reply to come back so long as it's pending */
13944  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13945  /* Find an empty slot */
13946  if (dp->waiters[x] < 0)
13947  break;
13948  }
13949  if (x >= ARRAY_LEN(dp->waiters)) {
13950  ast_log(LOG_WARNING, "No more waiter positions available\n");
13951  return NULL;
13952  }
13953  if (pipe(com)) {
13954  ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
13955  return NULL;
13956  }
13957  dp->waiters[x] = com[1];
13958  /* Okay, now we wait */
13959  timeout = iaxdefaulttimeout * 1000;
13960  /* Temporarily unlock */
13962  /* Defer any dtmf */
13963  if (chan)
13964  old = ast_channel_defer_dtmf(chan);
13965  doabort = 0;
13966  start = ast_tvnow();
13967  while ((ms = ast_remaining_ms(start, timeout))) {
13968  c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &ms);
13969  if (outfd > -1)
13970  break;
13971  if (!c)
13972  continue;
13973  if (!(f = ast_read(c))) {
13974  doabort = 1;
13975  break;
13976  }
13977  ast_frfree(f);
13978  }
13979  if (!ms) {
13980  ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
13981  }
13983  dp->waiters[x] = -1;
13984  close(com[1]);
13985  close(com[0]);
13986  if (doabort) {
13987  /* Don't interpret anything, just abort. Not sure what th epoint
13988  of undeferring dtmf on a hung up channel is but hey whatever */
13989  if (!old && chan)
13991  return NULL;
13992  }
13993  if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
13994  /* Now to do non-independent analysis the results of our wait */
13995  if (dp->flags & CACHE_FLAG_PENDING) {
13996  /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
13997  pending. Don't let it take as long to timeout. */
13998  dp->flags &= ~CACHE_FLAG_PENDING;
13999  dp->flags |= CACHE_FLAG_TIMEOUT;
14000  /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
14001  systems without leaving it unavailable once the server comes back online */
14002  dp->expiry.tv_sec = dp->orig.tv_sec + 60;
14003  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14004  if (dp->waiters[x] > -1) {
14005  if (write(dp->waiters[x], "asdf", 4) < 0) {
14006  ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14007  }
14008  }
14009  }
14010  }
14011  }
14012  /* Our caller will obtain the rest */
14013  if (!old && chan)
14015  }
14016  return dp;
14017 }
14018 
14019 /*! \brief Part of the IAX2 switch interface */
14020 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14021 {
14022  int res = 0;
14023  struct iax2_dpcache *dp = NULL;
14024 #if 0
14025  ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14026 #endif
14027  if ((priority != 1) && (priority != 2))
14028  return 0;
14029 
14031  if ((dp = find_cache(chan, data, context, exten, priority))) {
14032  if (dp->flags & CACHE_FLAG_EXISTS)
14033  res = 1;
14034  } else {
14035  ast_log(LOG_WARNING, "Unable to make DP cache\n");
14036  }
14038 
14039  return res;
14040 }
14041 
14042 /*! \brief part of the IAX2 dial plan switch interface */
14043 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14044 {
14045  int res = 0;
14046  struct iax2_dpcache *dp = NULL;
14047 #if 0
14048  ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14049 #endif
14050  if ((priority != 1) && (priority != 2))
14051  return 0;
14052 
14054  if ((dp = find_cache(chan, data, context, exten, priority))) {
14055  if (dp->flags & CACHE_FLAG_CANEXIST)
14056  res = 1;
14057  } else {
14058  ast_log(LOG_WARNING, "Unable to make DP cache\n");
14059  }
14061 
14062  return res;
14063 }
14064 
14065 /*! \brief Part of the IAX2 Switch interface */
14066 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14067 {
14068  int res = 0;
14069  struct iax2_dpcache *dp = NULL;
14070 #if 0
14071  ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14072 #endif
14073  if ((priority != 1) && (priority != 2))
14074  return 0;
14075 
14077  if ((dp = find_cache(chan, data, context, exten, priority))) {
14078  if (dp->flags & CACHE_FLAG_MATCHMORE)
14079  res = 1;
14080  } else {
14081  ast_log(LOG_WARNING, "Unable to make DP cache\n");
14082  }
14084 
14085  return res;
14086 }
14087 
14088 /*! \brief Execute IAX2 dialplan switch */
14089 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14090 {
14091  char odata[256];
14092  char req[256];
14093  char *ncontext;
14094  struct iax2_dpcache *dp = NULL;
14095  struct ast_app *dial = NULL;
14096 #if 0
14097  ast_log(LOG_NOTICE, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context, exten, priority, callerid ? callerid : "<unknown>", data, newstack);
14098 #endif
14099  if (priority == 2) {
14100  /* Indicate status, can be overridden in dialplan */
14101  const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
14102  if (dialstatus) {
14103  dial = pbx_findapp(dialstatus);
14104  if (dial)
14105  pbx_exec(chan, dial, "");
14106  }
14107  return -1;
14108  } else if (priority != 1)
14109  return -1;
14110 
14112  if ((dp = find_cache(chan, data, context, exten, priority))) {
14113  if (dp->flags & CACHE_FLAG_EXISTS) {
14114  ast_copy_string(odata, data, sizeof(odata));
14115  ncontext = strchr(odata, '/');
14116  if (ncontext) {
14117  *ncontext = '\0';
14118  ncontext++;
14119  snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
14120  } else {
14121  snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
14122  }
14123  ast_verb(3, "Executing Dial('%s')\n", req);
14124  } else {
14126  ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
14127  return -1;
14128  }
14129  }
14131 
14132  if ((dial = pbx_findapp("Dial")))
14133  return pbx_exec(chan, dial, req);
14134  else
14135  ast_log(LOG_WARNING, "No dial application registered\n");
14136 
14137  return -1;
14138 }
14139 
14140 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14141 {
14142  struct iax2_peer *peer;
14143  char *peername, *colname;
14144 
14145  peername = ast_strdupa(data);
14146 
14147  /* if our channel, return the IP address of the endpoint of current channel */
14148  if (!strcmp(peername,"CURRENTCHANNEL")) {
14149  unsigned short callno;
14150  if (!chan || chan->tech != &iax2_tech) {
14151  return -1;
14152  }
14153  callno = PTR_TO_CALLNO(chan->tech_pvt);
14154  ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
14155  return 0;
14156  }
14157 
14158  if ((colname = strchr(peername, ',')))
14159  *colname++ = '\0';
14160  else
14161  colname = "ip";
14162 
14163  if (!(peer = find_peer(peername, 1)))
14164  return -1;
14165 
14166  if (!strcasecmp(colname, "ip")) {
14168  } else if (!strcasecmp(colname, "status")) {
14169  peer_status(peer, buf, len);
14170  } else if (!strcasecmp(colname, "mailbox")) {
14171  ast_copy_string(buf, peer->mailbox, len);
14172  } else if (!strcasecmp(colname, "context")) {
14173  ast_copy_string(buf, peer->context, len);
14174  } else if (!strcasecmp(colname, "expire")) {
14175  snprintf(buf, len, "%d", peer->expire);
14176  } else if (!strcasecmp(colname, "dynamic")) {
14177  ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
14178  } else if (!strcasecmp(colname, "callerid_name")) {
14179  ast_copy_string(buf, peer->cid_name, len);
14180  } else if (!strcasecmp(colname, "callerid_num")) {
14181  ast_copy_string(buf, peer->cid_num, len);
14182  } else if (!strcasecmp(colname, "codecs")) {
14183  ast_getformatname_multiple(buf, len -1, peer->capability);
14184  } else if (!strncasecmp(colname, "codec[", 6)) {
14185  char *codecnum, *ptr;
14186  int codec = 0;
14187 
14188  /* skip over "codec" to the '[' */
14189  codecnum = colname + 5;
14190  *codecnum = '\0';
14191  codecnum++;
14192  if ((ptr = strchr(codecnum, ']'))) {
14193  *ptr = '\0';
14194  }
14195  if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
14196  ast_copy_string(buf, ast_getformatname(codec), len);
14197  } else {
14198  buf[0] = '\0';
14199  }
14200  } else {
14201  buf[0] = '\0';
14202  }
14203 
14204  peer_unref(peer);
14205 
14206  return 0;
14207 }
14208 
14210  .name = "IAXPEER",
14211  .read = function_iaxpeer,
14212 };
14213 
14214 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
14215 {
14216  struct chan_iax2_pvt *pvt;
14217  unsigned int callno;
14218  int res = 0;
14219 
14220  if (!chan || chan->tech != &iax2_tech) {
14221  ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
14222  return -1;
14223  }
14224 
14225  callno = PTR_TO_CALLNO(chan->tech_pvt);
14226  ast_mutex_lock(&iaxsl[callno]);
14227  if (!(pvt = iaxs[callno])) {
14228  ast_mutex_unlock(&iaxsl[callno]);
14229  return -1;
14230  }
14231 
14232  if (!strcasecmp(args, "osptoken")) {
14233  ast_copy_string(buf, pvt->osptoken, buflen);
14234  } else if (!strcasecmp(args, "peerip")) {
14235  ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
14236  } else if (!strcasecmp(args, "peername")) {
14237  ast_copy_string(buf, pvt->username, buflen);
14238  } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14239  snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14240  } else {
14241  res = -1;
14242  }
14243 
14244  ast_mutex_unlock(&iaxsl[callno]);
14245 
14246  return res;
14247 }
14248 
14249 /*! \brief Part of the device state notification system ---*/
14250 static int iax2_devicestate(void *data)
14251 {
14252  struct parsed_dial_string pds;
14253  char *tmp = ast_strdupa(data);
14254  struct iax2_peer *p;
14255  int res = AST_DEVICE_INVALID;
14256 
14257  memset(&pds, 0, sizeof(pds));
14258  parse_dial_string(tmp, &pds);
14259 
14260  if (ast_strlen_zero(pds.peer)) {
14261  ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
14262  return res;
14263  }
14264 
14265  ast_debug(3, "Checking device state for device %s\n", pds.peer);
14266 
14267  /* SLD: FIXME: second call to find_peer during registration */
14268  if (!(p = find_peer(pds.peer, 1)))
14269  return res;
14270 
14271  res = AST_DEVICE_UNAVAILABLE;
14272  ast_debug(3, "Found peer. What's device state of %s? addr=%u, defaddr=%u maxms=%d, lastms=%d\n",
14273  pds.peer, ast_sockaddr_ipv4(&p->addr), p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
14274 
14275  if ((ast_sockaddr_ipv4(&p->addr) || p->defaddr.sin_addr.s_addr) &&
14276  (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14277  /* Peer is registered, or have default IP address
14278  and a valid registration */
14279  if (p->historicms == 0 || p->historicms <= p->maxms)
14280  /* let the core figure out whether it is in use or not */
14281  res = AST_DEVICE_UNKNOWN;
14282  }
14283 
14284  peer_unref(p);
14285 
14286  return res;
14287 }
14288 
14289 static struct ast_switch iax2_switch =
14290 {
14291  .name = "IAX2",
14292  .description = "IAX Remote Dialplan Switch",
14293  .exists = iax2_exists,
14294  .canmatch = iax2_canmatch,
14295  .exec = iax2_exec,
14296  .matchmore = iax2_matchmore,
14297 };
14298 
14299 /*
14300  { { "iax2", "show", "cache", NULL },
14301  iax2_show_cache, "Display IAX cached dialplan",
14302  show_cache_usage },
14303 
14304  { { "iax2", "show", "channels", NULL },
14305  iax2_show_channels, "List active IAX channels",
14306  show_channels_usage },
14307 
14308  { { "iax2", "show", "firmware", NULL },
14309  iax2_show_firmware, "List available IAX firmwares",
14310  show_firmware_usage },
14311 
14312  { { "iax2", "show", "netstats", NULL },
14313  iax2_show_netstats, "List active IAX channel netstats",
14314  show_netstats_usage },
14315 
14316  { { "iax2", "show", "peers", NULL },
14317  iax2_show_peers, "List defined IAX peers",
14318  show_peers_usage },
14319 
14320  { { "iax2", "show", "registry", NULL },
14321  iax2_show_registry, "Display IAX registration status",
14322  show_reg_usage },
14323 
14324  { { "iax2", "show", "stats", NULL },
14325  iax2_show_stats, "Display IAX statistics",
14326  show_stats_usage },
14327 
14328  { { "iax2", "show", "threads", NULL },
14329  iax2_show_threads, "Display IAX helper thread info",
14330  show_threads_usage },
14331 
14332  { { "iax2", "unregister", NULL },
14333  iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry",
14334  unregister_usage, complete_iax2_unregister },
14335 
14336  { { "iax2", "set", "mtu", NULL },
14337  iax2_set_mtu, "Set the IAX systemwide trunking MTU",
14338  set_mtu_usage, NULL, NULL },
14339 
14340  { { "iax2", "show", "users", NULL },
14341  iax2_show_users, "List defined IAX users",
14342  show_users_usage },
14343 
14344  { { "iax2", "prune", "realtime", NULL },
14345  iax2_prune_realtime, "Prune a cached realtime lookup",
14346  prune_realtime_usage, complete_iax2_show_peer },
14347 
14348  { { "iax2", "reload", NULL },
14349  iax2_reload, "Reload IAX configuration",
14350  iax2_reload_usage },
14351 
14352  { { "iax2", "show", "peer", NULL },
14353  iax2_show_peer, "Show details on specific IAX peer",
14354  show_peer_usage, complete_iax2_show_peer },
14355 
14356  { { "iax2", "set", "debug", NULL },
14357  iax2_do_debug, "Enable IAX debugging",
14358  debug_usage },
14359 
14360  { { "iax2", "set", "debug", "trunk", NULL },
14361  iax2_do_trunk_debug, "Enable IAX trunk debugging",
14362  debug_trunk_usage },
14363 
14364  { { "iax2", "set", "debug", "jb", NULL },
14365  iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
14366  debug_jb_usage },
14367 
14368  { { "iax2", "set", "debug", "off", NULL },
14369  iax2_no_debug, "Disable IAX debugging",
14370  no_debug_usage },
14371 
14372  { { "iax2", "set", "debug", "trunk", "off", NULL },
14373  iax2_no_trunk_debug, "Disable IAX trunk debugging",
14374  no_debug_trunk_usage },
14375 
14376  { { "iax2", "set", "debug", "jb", "off", NULL },
14377  iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
14378  no_debug_jb_usage },
14379 
14380  { { "iax2", "test", "losspct", NULL },
14381  iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
14382  iax2_test_losspct_usage },
14383 
14384  { { "iax2", "provision", NULL },
14385  iax2_prov_cmd, "Provision an IAX device",
14386  show_prov_usage, iax2_prov_complete_template_3rd },
14387 
14388 #ifdef IAXTESTS
14389  { { "iax2", "test", "late", NULL },
14390  iax2_test_late, "Test the receipt of a late frame",
14391  iax2_test_late_usage },
14392 
14393  { { "iax2", "test", "resync", NULL },
14394  iax2_test_resync, "Test a resync in received timestamps",
14395  iax2_test_resync_usage },
14396 
14397  { { "iax2", "test", "jitter", NULL },
14398  iax2_test_jitter, "Simulates jitter for testing",
14399  iax2_test_jitter_usage },
14400 #endif
14401 */
14402 
14403 static struct ast_cli_entry cli_iax2[] = {
14404  AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
14405  AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
14406  AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
14407  AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
14408  AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
14409  AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
14410  AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
14411  AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
14412  AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
14413  AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
14414  AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
14415  AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
14416  AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
14417  AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
14418  AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
14419  AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
14420  AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
14421  AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
14422  AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
14423  AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
14424 #ifdef IAXTESTS
14425  AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
14426  AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
14427  AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
14428 #endif /* IAXTESTS */
14429 };
14430 
14431 #ifdef TEST_FRAMEWORK
14432 AST_TEST_DEFINE(test_iax2_peers_get)
14433 {
14434  struct ast_data_query query = {
14435  .path = "/asterisk/channel/iax2/peers",
14436  .search = "peers/peer/name=test_peer_data_provider"
14437  };
14438  struct ast_data *node;
14439  struct iax2_peer *peer;
14440 
14441  switch (cmd) {
14442  case TEST_INIT:
14443  info->name = "iax2_peers_get_data_test";
14444  info->category = "/main/data/iax2/peers/";
14445  info->summary = "IAX2 peers data providers unit test";
14446  info->description =
14447  "Tests whether the IAX2 peers data provider implementation works as expected.";
14448  return AST_TEST_NOT_RUN;
14449  case TEST_EXECUTE:
14450  break;
14451  }
14452 
14453  /* build a test peer */
14454  peer = build_peer("test_peer_data_provider", NULL, NULL, 0);
14455  if (!peer) {
14456  return AST_TEST_FAIL;
14457  }
14458  peer->expiry= 1010;
14459  ao2_link(peers, peer);
14460 
14461  node = ast_data_get(&query);
14462  if (!node) {
14463  ao2_unlink(peers, peer);
14464  peer_unref(peer);
14465  return AST_TEST_FAIL;
14466  }
14467 
14468  /* check returned data node. */
14469  if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
14470  ao2_unlink(peers, peer);
14471  peer_unref(peer);
14472  ast_data_free(node);
14473  return AST_TEST_FAIL;
14474  }
14475 
14476  if (ast_data_retrieve_int(node, "peer/expiry") != 1010) {
14477  ao2_unlink(peers, peer);
14478  peer_unref(peer);
14479  ast_data_free(node);
14480  return AST_TEST_FAIL;
14481  }
14482 
14483  /* release resources */
14484  ast_data_free(node);
14485 
14486  ao2_unlink(peers, peer);
14487  peer_unref(peer);
14488 
14489  return AST_TEST_PASS;
14490 }
14491 
14492 AST_TEST_DEFINE(test_iax2_users_get)
14493 {
14494  struct ast_data_query query = {
14495  .path = "/asterisk/channel/iax2/users",
14496  .search = "users/user/name=test_user_data_provider"
14497  };
14498  struct ast_data *node;
14499  struct iax2_user *user;
14500 
14501  switch (cmd) {
14502  case TEST_INIT:
14503  info->name = "iax2_users_get_data_test";
14504  info->category = "/main/data/iax2/users/";
14505  info->summary = "IAX2 users data providers unit test";
14506  info->description =
14507  "Tests whether the IAX2 users data provider implementation works as expected.";
14508  return AST_TEST_NOT_RUN;
14509  case TEST_EXECUTE:
14510  break;
14511  }
14512 
14513  user = build_user("test_user_data_provider", NULL, NULL, 0);
14514  if (!user) {
14515  ast_test_status_update(test, "Failed to build a test user\n");
14516  return AST_TEST_FAIL;
14517  }
14518  user->amaflags = 1010;
14519  ao2_link(users, user);
14520 
14521  node = ast_data_get(&query);
14522  if (!node) {
14523  ast_test_status_update(test, "The data query to find our test user failed\n");
14524  ao2_unlink(users, user);
14525  user_unref(user);
14526  return AST_TEST_FAIL;
14527  }
14528 
14529  if (strcmp(ast_data_retrieve_string(node, "user/name"), "test_user_data_provider")) {
14530  ast_test_status_update(test, "Our data results did not return the test user created in the previous step.\n");
14531  ao2_unlink(users, user);
14532  user_unref(user);
14533  ast_data_free(node);
14534  return AST_TEST_FAIL;
14535  }
14536 
14537  if (ast_data_retrieve_int(node, "user/amaflags/value") != 1010) {
14538  ast_test_status_update(test, "The amaflags field in our test user was '%d' not the expected value '1010'\n", ast_data_retrieve_int(node, "user/amaflags/value"));
14539  ao2_unlink(users, user);
14540  user_unref(user);
14541  ast_data_free(node);
14542  return AST_TEST_FAIL;
14543  }
14544 
14545  ast_data_free(node);
14546 
14547  ao2_unlink(users, user);
14548  user_unref(user);
14549 
14550  return AST_TEST_PASS;
14551 }
14552 #endif
14553 
14554 static void cleanup_thread_list(void *head)
14555 {
14556  AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14557  struct iax2_thread_list *list_head = head;
14558  struct iax2_thread *thread;
14559 
14560  AST_LIST_LOCK(list_head);
14561  while ((thread = AST_LIST_REMOVE_HEAD(list_head, list))) {
14562  pthread_t thread_id = thread->threadid;
14563 
14564  thread->stop = 1;
14565  signal_condition(&thread->lock, &thread->cond);
14566 
14567  AST_LIST_UNLOCK(list_head);
14568  pthread_join(thread_id, NULL);
14569  AST_LIST_LOCK(list_head);
14570  }
14571  AST_LIST_UNLOCK(list_head);
14572 }
14573 
14574 static int __unload_module(void)
14575 {
14576  struct ast_context *con;
14577  int x;
14578 
14580 
14581  ast_manager_unregister("IAXpeers");
14582  ast_manager_unregister("IAXpeerlist");
14583  ast_manager_unregister("IAXnetstats");
14584  ast_manager_unregister("IAXregistry");
14586  ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14587  ast_unregister_switch(&iax2_switch);
14588  ast_channel_unregister(&iax2_tech);
14589 
14590  if (netthreadid != AST_PTHREADT_NULL) {
14591  pthread_cancel(netthreadid);
14592  pthread_kill(netthreadid, SIGURG);
14593  pthread_join(netthreadid, NULL);
14594  }
14595 
14596  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14597  if (iaxs[x]) {
14598  iax2_destroy(x);
14599  }
14600  }
14601 
14602  /* Call for all threads to halt */
14606 
14607  ast_netsock_release(netsock);
14608  ast_netsock_release(outsock);
14609  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14610  if (iaxs[x]) {
14611  iax2_destroy(x);
14612  }
14613  }
14614  ast_manager_unregister( "IAXpeers" );
14615  ast_manager_unregister( "IAXpeerlist" );
14616  ast_manager_unregister( "IAXnetstats" );
14617  ast_manager_unregister( "IAXregistry" );
14619 #ifdef TEST_FRAMEWORK
14620  AST_TEST_UNREGISTER(test_iax2_peers_get);
14621  AST_TEST_UNREGISTER(test_iax2_users_get);
14622 #endif
14623  ast_data_unregister(NULL);
14624  ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14625  ast_unregister_switch(&iax2_switch);
14626  ast_channel_unregister(&iax2_tech);
14627  delete_users();
14629  reload_firmware(1);
14630 
14631  for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14632  ast_mutex_destroy(&iaxsl[x]);
14633  }
14634 
14635  ao2_ref(peers, -1);
14636  ao2_ref(users, -1);
14637  ao2_ref(iax_peercallno_pvts, -1);
14638  ao2_ref(iax_transfercallno_pvts, -1);
14639  ao2_ref(peercnts, -1);
14640  ao2_ref(callno_limits, -1);
14641  ao2_ref(calltoken_ignores, -1);
14642  ao2_ref(callno_pool, -1);
14643  ao2_ref(callno_pool_trunk, -1);
14644  if (timer) {
14645  ast_timer_close(timer);
14646  timer = NULL;
14647  }
14648  transmit_processor = ast_taskprocessor_unreference(transmit_processor);
14649  sched = ast_sched_thread_destroy(sched);
14650 
14651  con = ast_context_find(regcontext);
14652  if (con)
14653  ast_context_destroy(con, "IAX2");
14654  ast_unload_realtime("iaxpeers");
14655  return 0;
14656 }
14657 
14658 static int unload_module(void)
14659 {
14660  ast_custom_function_unregister(&iaxpeer_function);
14661  ast_custom_function_unregister(&iaxvar_function);
14662  return __unload_module();
14663 }
14664 
14665 static int peer_set_sock_cb(void *obj, void *arg, int flags)
14666 {
14667  struct iax2_peer *peer = obj;
14668 
14669  if (peer->sockfd < 0)
14670  peer->sockfd = defaultsockfd;
14671 
14672  return 0;
14673 }
14674 
14675 static int pvt_hash_cb(const void *obj, const int flags)
14676 {
14677  const struct chan_iax2_pvt *pvt = obj;
14678 
14679  return pvt->peercallno;
14680 }
14681 
14682 static int pvt_cmp_cb(void *obj, void *arg, int flags)
14683 {
14684  struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14685 
14686  /* The frames_received field is used to hold whether we're matching
14687  * against a full frame or not ... */
14688 
14689  return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
14690  pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14691 }
14692 
14693 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14694 {
14695  const struct chan_iax2_pvt *pvt = obj;
14696 
14697  return pvt->transfercallno;
14698 }
14699 
14700 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14701 {
14702  struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14703 
14704  /* The frames_received field is used to hold whether we're matching
14705  * against a full frame or not ... */
14706 
14707  return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14708  pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14709 }
14710 
14711 static int load_objects(void)
14712 {
14713  peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
14714  peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
14715 
14717  goto container_fail;
14718  } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
14719  goto container_fail;
14720  } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
14721  goto container_fail;
14722  } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
14723  goto container_fail;
14725  goto container_fail;
14726  } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14727  goto container_fail;
14728  } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14729  goto container_fail;
14730  } else if (create_callno_pools()) {
14731  goto container_fail;
14732  } else if (!(transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT))) {
14733  goto container_fail;
14734  }
14735 
14736  return 0;
14737 
14738 container_fail:
14739  if (peers) {
14740  ao2_ref(peers, -1);
14741  }
14742  if (users) {
14743  ao2_ref(users, -1);
14744  }
14745  if (iax_peercallno_pvts) {
14746  ao2_ref(iax_peercallno_pvts, -1);
14747  }
14748  if (iax_transfercallno_pvts) {
14749  ao2_ref(iax_transfercallno_pvts, -1);
14750  }
14751  if (peercnts) {
14752  ao2_ref(peercnts, -1);
14753  }
14754  if (callno_limits) {
14755  ao2_ref(callno_limits, -1);
14756  }
14757  if (calltoken_ignores) {
14758  ao2_ref(calltoken_ignores, -1);
14759  }
14760  if (callno_pool) {
14761  ao2_ref(callno_pool, -1);
14762  }
14763  if (callno_pool_trunk) {
14764  ao2_ref(callno_pool_trunk, -1);
14765  }
14766  return AST_MODULE_LOAD_FAILURE;
14767 }
14768 
14769 
14770 #define DATA_EXPORT_IAX2_PEER(MEMBER) \
14771  MEMBER(iax2_peer, name, AST_DATA_STRING) \
14772  MEMBER(iax2_peer, username, AST_DATA_STRING) \
14773  MEMBER(iax2_peer, secret, AST_DATA_PASSWORD) \
14774  MEMBER(iax2_peer, dbsecret, AST_DATA_PASSWORD) \
14775  MEMBER(iax2_peer, outkey, AST_DATA_STRING) \
14776  MEMBER(iax2_peer, regexten, AST_DATA_STRING) \
14777  MEMBER(iax2_peer, context, AST_DATA_STRING) \
14778  MEMBER(iax2_peer, peercontext, AST_DATA_STRING) \
14779  MEMBER(iax2_peer, mailbox, AST_DATA_STRING) \
14780  MEMBER(iax2_peer, mohinterpret, AST_DATA_STRING) \
14781  MEMBER(iax2_peer, mohsuggest, AST_DATA_STRING) \
14782  MEMBER(iax2_peer, inkeys, AST_DATA_STRING) \
14783  MEMBER(iax2_peer, cid_num, AST_DATA_STRING) \
14784  MEMBER(iax2_peer, cid_name, AST_DATA_STRING) \
14785  MEMBER(iax2_peer, zonetag, AST_DATA_STRING) \
14786  MEMBER(iax2_peer, parkinglot, AST_DATA_STRING) \
14787  MEMBER(iax2_peer, expiry, AST_DATA_SECONDS) \
14788  MEMBER(iax2_peer, callno, AST_DATA_INTEGER) \
14789  MEMBER(iax2_peer, lastms, AST_DATA_MILLISECONDS) \
14790  MEMBER(iax2_peer, maxms, AST_DATA_MILLISECONDS) \
14791  MEMBER(iax2_peer, pokefreqok, AST_DATA_MILLISECONDS) \
14792  MEMBER(iax2_peer, pokefreqnotok, AST_DATA_MILLISECONDS) \
14793  MEMBER(iax2_peer, historicms, AST_DATA_INTEGER) \
14794  MEMBER(iax2_peer, smoothing, AST_DATA_BOOLEAN) \
14795  MEMBER(iax2_peer, maxcallno, AST_DATA_INTEGER)
14796 
14798 
14799 static int peers_data_provider_get(const struct ast_data_search *search,
14800  struct ast_data *data_root)
14801 {
14802  struct ast_data *data_peer;
14803  struct iax2_peer *peer;
14804  struct ao2_iterator i;
14805  char status[20];
14806  struct ast_str *encmethods = ast_str_alloca(256);
14807 
14808  i = ao2_iterator_init(peers, 0);
14809  while ((peer = ao2_iterator_next(&i))) {
14810  data_peer = ast_data_add_node(data_root, "peer");
14811  if (!data_peer) {
14812  peer_unref(peer);
14813  continue;
14814  }
14815 
14816  ast_data_add_structure(iax2_peer, data_peer, peer);
14817 
14818  ast_data_add_codecs(data_peer, "codecs", peer->capability);
14819 
14820  peer_status(peer, status, sizeof(status));
14821  ast_data_add_str(data_peer, "status", status);
14822 
14823  ast_data_add_str(data_peer, "host", ast_sockaddr_stringify_host(&peer->addr));
14824 
14825  ast_data_add_str(data_peer, "mask", ast_inet_ntoa(peer->mask));
14826 
14827  ast_data_add_int(data_peer, "port", ast_sockaddr_port(&peer->addr));
14828 
14829  ast_data_add_bool(data_peer, "trunk", ast_test_flag64(peer, IAX_TRUNK));
14830 
14831  ast_data_add_bool(data_peer, "dynamic", ast_test_flag64(peer, IAX_DYNAMIC));
14832 
14833  encmethods_to_str(peer->encmethods, &encmethods);
14834  ast_data_add_str(data_peer, "encryption", peer->encmethods ? ast_str_buffer(encmethods) : "no");
14835 
14836  peer_unref(peer);
14837 
14838  if (!ast_data_search_match(search, data_peer)) {
14839  ast_data_remove_node(data_root, data_peer);
14840  }
14841  }
14843 
14844  return 0;
14845 }
14846 
14847 #define DATA_EXPORT_IAX2_USER(MEMBER) \
14848  MEMBER(iax2_user, name, AST_DATA_STRING) \
14849  MEMBER(iax2_user, dbsecret, AST_DATA_PASSWORD) \
14850  MEMBER(iax2_user, accountcode, AST_DATA_STRING) \
14851  MEMBER(iax2_user, mohinterpret, AST_DATA_STRING) \
14852  MEMBER(iax2_user, mohsuggest, AST_DATA_STRING) \
14853  MEMBER(iax2_user, inkeys, AST_DATA_STRING) \
14854  MEMBER(iax2_user, language, AST_DATA_STRING) \
14855  MEMBER(iax2_user, cid_num, AST_DATA_STRING) \
14856  MEMBER(iax2_user, cid_name, AST_DATA_STRING) \
14857  MEMBER(iax2_user, parkinglot, AST_DATA_STRING) \
14858  MEMBER(iax2_user, maxauthreq, AST_DATA_INTEGER) \
14859  MEMBER(iax2_user, curauthreq, AST_DATA_INTEGER)
14860 
14862 
14863 static int users_data_provider_get(const struct ast_data_search *search,
14864  struct ast_data *data_root)
14865 {
14866  struct ast_data *data_user, *data_authmethods, *data_enum_node;
14867  struct iax2_user *user;
14868  struct ao2_iterator i;
14869  char auth[90];
14870  char *pstr = "";
14871 
14872  i = ao2_iterator_init(users, 0);
14873  for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
14874  data_user = ast_data_add_node(data_root, "user");
14875  if (!data_user) {
14876  continue;
14877  }
14878 
14879  ast_data_add_structure(iax2_user, data_user, user);
14880 
14881  ast_data_add_codecs(data_user, "codecs", user->capability);
14882 
14883  if (!ast_strlen_zero(user->secret)) {
14884  ast_copy_string(auth, user->secret, sizeof(auth));
14885  } else if (!ast_strlen_zero(user->inkeys)) {
14886  snprintf(auth, sizeof(auth), "Key: %s", user->inkeys);
14887  } else {
14888  ast_copy_string(auth, "no secret", sizeof(auth));
14889  }
14890  ast_data_add_password(data_user, "secret", auth);
14891 
14892  ast_data_add_str(data_user, "context", user->contexts ? user->contexts->context : DEFAULT_CONTEXT);
14893 
14894  /* authmethods */
14895  data_authmethods = ast_data_add_node(data_user, "authmethods");
14896  if (!data_authmethods) {
14897  ast_data_remove_node(data_root, data_user);
14898  continue;
14899  }
14900  ast_data_add_bool(data_authmethods, "rsa", user->authmethods & IAX_AUTH_RSA);
14901  ast_data_add_bool(data_authmethods, "md5", user->authmethods & IAX_AUTH_MD5);
14902  ast_data_add_bool(data_authmethods, "plaintext", user->authmethods & IAX_AUTH_PLAINTEXT);
14903 
14904  /* amaflags */
14905  data_enum_node = ast_data_add_node(data_user, "amaflags");
14906  if (!data_enum_node) {
14907  ast_data_remove_node(data_root, data_user);
14908  continue;
14909  }
14910  ast_data_add_int(data_enum_node, "value", user->amaflags);
14911  ast_data_add_str(data_enum_node, "text", ast_cdr_flags2str(user->amaflags));
14912 
14913  ast_data_add_bool(data_user, "access-control", user->ha ? 1 : 0);
14914 
14915  if (ast_test_flag64(user, IAX_CODEC_NOCAP)) {
14916  pstr = "REQ only";
14917  } else if (ast_test_flag64(user, IAX_CODEC_NOPREFS)) {
14918  pstr = "disabled";
14919  } else {
14920  pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "caller" : "host";
14921  }
14922  ast_data_add_str(data_user, "codec-preferences", pstr);
14923 
14924  if (!ast_data_search_match(search, data_user)) {
14925  ast_data_remove_node(data_root, data_user);
14926  }
14927  }
14929 
14930  return 0;
14931 }
14932 
14933 static const struct ast_data_handler peers_data_provider = {
14936 };
14937 
14938 static const struct ast_data_handler users_data_provider = {
14941 };
14942 
14943 static const struct ast_data_entry iax2_data_providers[] = {
14944  AST_DATA_ENTRY("asterisk/channel/iax2/peers", &peers_data_provider),
14945  AST_DATA_ENTRY("asterisk/channel/iax2/users", &users_data_provider),
14946 };
14947 
14948 /*! \brief Load IAX2 module, load configuraiton ---*/
14949 static int load_module(void)
14950 {
14951  static const char config[] = "iax.conf";
14952  int x = 0;
14953  struct iax2_registry *reg = NULL;
14954 
14955  if (load_objects()) {
14956  return AST_MODULE_LOAD_FAILURE;
14957  }
14958 
14959  memset(iaxs, 0, sizeof(iaxs));
14960 
14961  for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14962  ast_mutex_init(&iaxsl[x]);
14963  }
14964 
14965  if (!(sched = ast_sched_thread_create())) {
14966  ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
14967  return AST_MODULE_LOAD_FAILURE;
14968  }
14969 
14970  if (!(io = io_context_create())) {
14971  ast_log(LOG_ERROR, "Failed to create I/O context\n");
14972  sched = ast_sched_thread_destroy(sched);
14973  return AST_MODULE_LOAD_FAILURE;
14974  }
14975 
14976  if (!(netsock = ast_netsock_list_alloc())) {
14977  ast_log(LOG_ERROR, "Failed to create netsock list\n");
14978  io_context_destroy(io);
14979  sched = ast_sched_thread_destroy(sched);
14980  return AST_MODULE_LOAD_FAILURE;
14981  }
14982  ast_netsock_init(netsock);
14983 
14984  outsock = ast_netsock_list_alloc();
14985  if (!outsock) {
14986  ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14987  io_context_destroy(io);
14988  sched = ast_sched_thread_destroy(sched);
14989  return AST_MODULE_LOAD_FAILURE;
14990  }
14991  ast_netsock_init(outsock);
14992 
14993  randomcalltokendata = ast_random();
14994 
14998 
14999  if ((timer = ast_timer_open())) {
15000  ast_timer_set_rate(timer, 1000 / trunkfreq);
15001  }
15002 
15003  if (set_config(config, 0) == -1) {
15004  if (timer) {
15005  ast_timer_close(timer);
15006  timer = NULL;
15007  }
15008  return AST_MODULE_LOAD_DECLINE;
15009  }
15010 
15011 #ifdef TEST_FRAMEWORK
15012  AST_TEST_REGISTER(test_iax2_peers_get);
15013  AST_TEST_REGISTER(test_iax2_users_get);
15014 #endif
15015 
15016  /* Register AstData providers */
15017  ast_data_register_multiple(iax2_data_providers, ARRAY_LEN(iax2_data_providers));
15018  ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
15019 
15021 
15022  ast_custom_function_register(&iaxpeer_function);
15023  ast_custom_function_register(&iaxvar_function);
15024 
15029 
15030  if (ast_channel_register(&iax2_tech)) {
15031  ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
15032  __unload_module();
15033  return AST_MODULE_LOAD_FAILURE;
15034  }
15035 
15036  if (ast_register_switch(&iax2_switch)) {
15037  ast_log(LOG_ERROR, "Unable to register IAX switch\n");
15038  }
15039 
15040  if (start_network_thread()) {
15041  ast_log(LOG_ERROR, "Unable to start network thread\n");
15042  __unload_module();
15043  return AST_MODULE_LOAD_FAILURE;
15044  } else {
15045  ast_verb(2, "IAX Ready and Listening\n");
15046  }
15047 
15048  AST_LIST_LOCK(&registrations);
15049  AST_LIST_TRAVERSE(&registrations, reg, entry)
15050  iax2_do_register(reg);
15051  AST_LIST_UNLOCK(&registrations);
15052 
15053  ao2_callback(peers, 0, peer_set_sock_cb, NULL);
15054  ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
15055 
15056 
15057  reload_firmware(0);
15059 
15060  ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
15061 
15063 
15064  return AST_MODULE_LOAD_SUCCESS;
15065 }
15066 
15067 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
15068  .load = load_module,
15069  .unload = unload_module,
15070  .reload = reload,
15071  .load_pri = AST_MODPRI_CHANNEL_DRIVER,
15072  .nonoptreq = "res_crypto",
15073  );
static char * ast_sockaddr_stringify_addr(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return an address only.
Definition: netsock2.h:240
static char user[512]
int ast_io_wait(struct io_context *ioc, int howlong)
Waits for IO.
Definition: io.c:273
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)]
chan_iax2_pvt structure locks
Definition: chan_iax2.c:1087
static int iaxdefaultdpcache
Definition: chan_iax2.c:299
static int peercnt_add(struct sockaddr_in *sin)
Definition: chan_iax2.c:2432
static void requirecalltoken_mark_auto(const char *name, int subclass)
Definition: chan_iax2.c:4926
static struct iax_frame * iaxfrdup2(struct iax_frame *fr)
Definition: chan_iax2.c:2040
static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: chan_iax2.c:9943
char mohsuggest[MAX_MUSICCLASS]
Definition: chan_iax2.c:4654
unsigned char data[0]
Definition: iax2.h:293
const char * type
Definition: datastore.h:32
unsigned int notsilenttx
Definition: chan_iax2.c:678
int calling_pres
Definition: chan_iax2.c:820
unsigned char buf[1]
Definition: chan_iax2.c:999
long max_jitterbuf
Definition: jitterbuf.h:67
struct ast_channel * ast_waitfor_n(struct ast_channel **chan, int n, int *ms)
Waits for input on a group of channels Wait for input on an array of channels for a given # of millis...
Definition: channel.c:3534
Require call token validation after a successful registration using call token validation occurs...
Definition: chan_iax2.c:453
int ast_queue_hangup(struct ast_channel *chan)
Queue a hangup frame.
Definition: channel.c:1569
union ast_frame_subclass subclass
Definition: frame.h:146
struct ast_frame af
Definition: iax2-parser.h:139
int ast_hangup(struct ast_channel *chan)
Hang up a channel.
Definition: channel.c:2804
static char * handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7459
struct sockaddr_storage ss
Definition: netsock2.h:64
static int load_module(void)
Load IAX2 module, load configuraiton —.
Definition: chan_iax2.c:14949
static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
Definition: chan_iax2.c:7230
static uint16_t global_maxcallno_nonval
Definition: chan_iax2.c:906
static void jb_error_output(const char *fmt,...)
Definition: chan_iax2.c:1131
void ast_party_connected_line_init(struct ast_party_connected_line *init)
Initialize the given connected line structure.
Definition: channel.c:2308
unsigned int datalen
Definition: iax2.h:291
static char accountcode[AST_MAX_ACCOUNT_CODE]
Definition: chan_iax2.c:383
int presentation
Q.931 encoded presentation-indicator encoded field.
Definition: channel.h:227
unsigned int fwdesc
Definition: iax2-parser.h:64
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
Definition: chan_iax2.c:4403
unsigned int trunkdatalen
Definition: chan_iax2.c:558
static int socket_process(struct iax2_thread *thread)
Definition: chan_iax2.c:10051
pthread_t thread
Definition: app_meetme.c:962
static char * complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
Definition: chan_iax2.c:3918
unsigned short callno
Definition: iax2.h:251
void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
Set caller ID number, name and ANI and generate AMI event.
Definition: channel.c:7051
static int handle_error(void)
Definition: chan_iax2.c:3371
#define IAX_IE_IAX_UNKNOWN
Definition: iax2.h:153
static int test_losspct
Definition: chan_iax2.c:375
int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Looks to see if adding anything to this extension might match something. (exists ^ canmatch) ...
Definition: pbx.c:5420
static char * handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:6896
#define attribute_pure
Definition: compiler.h:35
const ast_string_field secret
Definition: chan_iax2.c:769
void iax_frame_subclass2str(enum iax_frame_subclass subclass, char *str, size_t len)
Definition: iax2-parser.c:435
const ast_string_field rdnis
Definition: chan_iax2.c:769
static char exten[AST_MAX_EXTENSION]
Definition: chan_alsa.c:109
Main Channel structure associated with a channel.
Definition: channel.h:742
struct timeval lasttxtime
Definition: chan_iax2.c:553
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL
Definition: chan_iax2.c:901
static void build_rand_pad(unsigned char *buf, ssize_t len)
Definition: chan_iax2.c:6289
Music on hold handling.
#define DIRECTION_INGRESS
Definition: iax2-parser.h:85
#define FORMAT
#define AST_CLI_DEFINE(fn, txt,...)
Definition: cli.h:191
#define IAX_RTSAVE_SYSNAME
Definition: chan_iax2.c:415
An event.
Definition: event.c:85
char * str
Subscriber phone number (Malloced)
Definition: channel.h:241
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
Definition: chan_iax2.c:4408
#define MAX_PEER_BUCKETS
Definition: chan_iax2.c:883
#define IAX_TRUNKTIMESTAMPS
Definition: chan_iax2.c:429
uint16_t limit
Definition: chan_iax2.c:918
static int srvlookup
Definition: chan_iax2.c:311
struct ast_party_connected_line connected
Channel Connected Line ID information.
Definition: channel.h:811
#define IAX_IE_CAPABILITY2
Definition: iax2.h:187
#define IAX_CALLENCRYPTED(pvt)
Definition: chan_iax2.c:348
#define AST_LIST_LOCK(head)
Locks a list.
Definition: linkedlists.h:39
unsigned char csub
Definition: iax2.h:229
unsigned char data[0]
Definition: iax2.h:259
struct timeval rxcore
Definition: chan_iax2.c:706
uint32_t version
const char *const type
Definition: channel.h:508
static void free_context(struct iax2_context *con)
Definition: chan_iax2.c:12319
unsigned short callno
Definition: chan_iax2.c:1032
int encmethods
Definition: chan_iax2.c:474
int calling_tns
Definition: iax2-parser.h:31
Asterisk locking-related definitions:
int iax_parse_ies(struct iax_ies *ies, unsigned char *data, int datalen)
Definition: iax2-parser.c:762
void astman_append(struct mansession *s, const char *fmt,...)
Definition: manager.c:2068
static int make_trunk(unsigned short callno, int locked)
Definition: chan_iax2.c:2135
#define IAX_IE_CALLINGTNS
Definition: iax2.h:170
const ast_string_field osptoken
Definition: chan_iax2.c:769
Asterisk main include file. File version handling, generic pbx functions.
#define AST_BRIDGE_IGNORE_SIGS
Ignore all signal frames except NULL.
Definition: channel.h:1940
#define ao2_link(arg1, arg2)
Definition: astobj2.h:785
static const char config_file[]
Definition: cdr_odbc.c:49
int encmethods
Definition: chan_iax2.c:521
#define AST_OPTION_AUDIO_MODE
Definition: frame.h:453
unsigned char iseqno
Definition: chan_iax2.c:726
static char language[MAX_LANGUAGE]
Definition: chan_iax2.c:274
struct iax2_thread::@95 full_frames
struct ast_sched_thread * ast_sched_thread_destroy(struct ast_sched_thread *st)
Destroy a scheduler and its thread.
Definition: sched.c:143
int ao2_container_count(struct ao2_container *c)
Returns the number of elements in a container.
Definition: astobj2.c:470
const char * ast_variable_retrieve(const struct ast_config *config, const char *category, const char *variable)
Gets a variable.
Definition: config.c:625
void iax_showframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
Definition: iax2-parser.c:567
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
Definition: chan_iax2.c:1903
static struct iax2_peer * realtime_peer(const char *peername, struct sockaddr_in *sin)
Definition: chan_iax2.c:4424
#define AST_LIST_HEAD(name, type)
Defines a structure to be used to hold a list of specified type.
Definition: linkedlists.h:172
static const char config[]
Definition: cdr_csv.c:57
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
const ast_string_field cid_num
Definition: chan_iax2.c:769
int offset
Definition: frame.h:156
The data tree to be returned by the callbacks and managed by functions local to this file...
Definition: data.c:85
char * str
Subscriber phone number (Malloced)
Definition: channel.h:336
void ast_module_unref(struct ast_module *)
Definition: loader.c:1312
char * serviceident
Definition: iax2-parser.h:62
static int jittertargetextra
Definition: chan_iax2.c:287
#define ast_copy_flags64(dest, src, flagz)
Definition: utils.h:141
static struct iax2_peer * find_peer(const char *name, int realtime)
Definition: chan_iax2.c:1769
void ast_data_free(struct ast_data *root)
Release the allocated memory of a tree.
Definition: data.c:2491
static char parkinglot[AST_MAX_CONTEXT]
Definition: chan_mgcp.c:156
void iax_set_output(void(*func)(const char *))
Definition: iax2-parser.c:752
struct ast_frame ast_null_frame
Definition: frame.c:131
struct ast_party_caller caller
Channel Caller ID information.
Definition: channel.h:804
static int prune_addr_range_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2388
int iax_provision_build(struct iax_ie_data *provdata, unsigned int *signature, const char *template, int force)
static char * handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7538
const ast_string_field exten
Definition: chan_iax2.c:769
char * strsep(char **str, const char *delims)
int expire
Definition: chan_iax2.c:523
char * rsa_result
Definition: iax2-parser.h:48
static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
Definition: chan_iax2.c:4657
static int amaflags
Definition: chan_iax2.c:386
struct ast_app * pbx_findapp(const char *app)
Look up an application.
Definition: pbx.c:1537
static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
Definition: chan_iax2.c:6217
static int iax2_predestroy(int callno)
Definition: chan_iax2.c:3452
unsigned char calltoken_ie_len
Definition: chan_iax2.c:836
static char * complete_iax2_unregister(const char *line, const char *word, int pos, int state)
Definition: chan_iax2.c:7009
static uint16_t DEFAULT_MAXCALLNO_LIMIT
Definition: chan_iax2.c:899
int ast_callerid_split(const char *src, char *name, int namelen, char *num, int numlen)
Definition: callerid.c:1093
static void __auth_reject(const void *nothing)
Definition: chan_iax2.c:9112
static pthread_t netthreadid
Definition: chan_iax2.c:393
int priority
Definition: channel.h:841
struct ast_sched_thread * ast_sched_thread_create(void)
Create a scheduler with a dedicated thread.
Definition: sched.c:167
ast_aes_decrypt_key dcx
Definition: chan_iax2.c:781
int pbx_exec(struct ast_channel *c, struct ast_app *app, const char *data)
Execute an application.
Definition: pbx.c:1497
#define IAX_FLAG_SC_LOG
Definition: iax2.h:44
char * md5_result
Definition: iax2-parser.h:47
const ast_string_field uniqueid
Definition: channel.h:787
static int send_apathetic_reply(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int command, int ts, unsigned char seqno, int sockfd, struct iax_ie_data *ied)
Definition: chan_iax2.c:4806
#define DIRECTION_OUTGRESS
Definition: iax2-parser.h:86
int ast_codec_pref_string(struct ast_codec_pref *pref, char *buf, size_t size)
Dump audio codec preference list into a string.
Definition: frame.c:1025
unsigned char aseqno
Definition: chan_iax2.c:728
#define DATA_EXPORT_IAX2_PEER(MEMBER)
Definition: chan_iax2.c:14770
String manipulation functions.
const ast_string_field dnid
Definition: chan_iax2.c:769
int presentation
Q.931 presentation-indicator and screening-indicator encoded fields.
Definition: channel.h:245
int seqno
Definition: frame.h:172
static void handle_deferred_full_frames(struct iax2_thread *thread)
Handle any deferred full frames for this thread.
Definition: chan_iax2.c:9676
format_t videoformat
Definition: chan_iax2.c:658
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
Definition: chan_iax2.c:4617
#define ast_strdup(a)
Definition: astmm.h:109
int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
Weird function made for call transfers.
Definition: channel.c:6110
CallerID (and other GR30) management and generation Includes code and algorithms from the Zapata libr...
format_t writeformat
Definition: channel.h:854
unsigned char encdata[0]
Definition: iax2.h:237
unsigned int magic
Definition: iax2.h:288
static struct iax2_peer * peer_unref(struct iax2_peer *peer)
Definition: chan_iax2.c:1791
#define CALLTOKEN_HASH_FORMAT
static unsigned int tos
Definition: chan_h323.c:146
#define ast_pthread_create_detached(a, b, c, d)
Definition: utils.h:422
int ast_sockaddr_parse(struct ast_sockaddr *addr, const char *str, int flags)
Parse an IPv4 or IPv6 address string.
Definition: netsock2.c:198
Definition: iax2.h:274
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: utils.h:653
struct ast_party_id id
Connected party ID.
Definition: channel.h:403
static struct ao2_container * iax_peercallno_pvts
Another container of iax2_pvt structures.
Definition: chan_iax2.c:1078
static int iax2_write(struct ast_channel *c, struct ast_frame *f)
Definition: chan_iax2.c:7564
int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
Unregister multiple commands.
Definition: cli.c:2177
void iax_frame_wrap(struct iax_frame *fr, struct ast_frame *f)
Definition: iax2-parser.c:1152
static void __attempt_transmit(const void *data)
Definition: chan_iax2.c:3568
#define ast_channel_unref(c)
Decrease channel reference count.
Definition: channel.h:2502
unsigned short scallno
Definition: iax2.h:223
static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:14693
struct iax2_registry * reg
Definition: chan_iax2.c:788
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7623
static const unsigned int CALLNO_POOL_BUCKETS
Definition: chan_iax2.c:854
size_t afdatalen
Definition: iax2-parser.h:141
static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
part of the IAX2 dial plan switch interface
Definition: chan_iax2.c:14043
struct ast_codec_pref prefs
Definition: chan_iax2.c:686
int ast_db_get(const char *family, const char *key, char *out, int outlen)
Get key value specified by family/key.
Definition: db.c:348
static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
Definition: chan_iax2.c:9546
int ast_aes_set_encrypt_key(const unsigned char *key, ast_aes_encrypt_key *ctx)
Set an encryption key.
Definition: res_crypto.c:461
static int send_lagrq(const void *data)
Definition: chan_iax2.c:1675
#define ast_test_flag(p, flag)
Definition: utils.h:63
static void mwi_event_cb(const struct ast_event *event, void *userdata)
Definition: chan_iax2.c:1359
int option_debug
Definition: asterisk.c:182
#define IAX_USEJITTERBUF
Definition: chan_iax2.c:412
static int addr_range_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2233
static int exists(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_logic.c:126
int ast_netsock_sockfd(const struct ast_netsock *ns)
Definition: netsock.c:202
struct ast_sockaddr addr
Definition: acl.h:50
Device state management.
static int ast_codec_interp_len(format_t format)
Gets duration in ms of interpolation frame for a format.
Definition: frame.h:782
Support for translation of data formats. translate.c.
int ast_unload_realtime(const char *family)
Release any resources cached for a realtime family.
Definition: config.c:2630
#define IAX_SHRINKCALLERID
Definition: chan_iax2.c:438
#define MAX_MUSICCLASS
Definition: channel.h:139
const char * ast_var_value(const struct ast_var_t *var)
Definition: chanvars.c:89
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:6305
struct ast_party_name name
Subscriber name.
Definition: channel.h:290
#define RESULT_SHOWUSAGE
Definition: cli.h:40
void ast_channel_unregister(const struct ast_channel_tech *tech)
Unregister a channel technology.
Definition: channel.c:938
struct ast_party_id from
Who is redirecting the call (Sent to the party the call is redirected toward)
Definition: channel.h:449
const ast_string_field name
Definition: chan_iax2.c:471
void * ptr
Definition: frame.h:160
ast_aes_encrypt_key ecx
Definition: chan_iax2.c:777
unsigned int transferid
Definition: iax2-parser.h:59
void * tech_pvt
Definition: channel.h:744
static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
Verify inbound registration.
Definition: chan_iax2.c:8070
static void __iax2_do_register_s(const void *data)
Definition: chan_iax2.c:8408
struct ast_var_t * ast_var_assign(const char *name, const char *value)
Definition: chanvars.c:41
struct ast_ha ha
Definition: chan_iax2.c:927
#define IAX_META_TRUNK_MINI
Definition: iax2.h:206
static struct sockaddr_in debugaddr
Definition: chan_iax2.c:1101
#define schedule_action(func, data)
Definition: chan_iax2.c:1569
static char * handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:13791
unsigned short version
Definition: iax2.h:289
format_t svideoformat
Definition: chan_iax2.c:662
struct ast_variable * vars
Definition: chan_iax2.c:824
static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Part of the IAX2 Switch interface.
Definition: chan_iax2.c:14066
static void unlink_peer(struct iax2_peer *peer)
Definition: chan_iax2.c:8718
static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies, struct sockaddr_in *sin, int fd)
Definition: chan_iax2.c:4966
int ast_taskprocessor_push(struct ast_taskprocessor *tps, int(*task_exe)(void *datap), void *datap)
Push a task into the specified taskprocessor queue and signal the taskprocessor thread.
unsigned char oseqno
Definition: chan_iax2.c:722
static struct ast_data_handler peers_data_provider
Definition: chan_iax2.c:14933
#define IAX_IE_VARIABLE
Definition: iax2.h:183
#define IAX_IE_RR_LOSS
Definition: iax2.h:178
char context[AST_MAX_CONTEXT]
Definition: channel.h:868
struct iax_frame * iax_frame_new(int direction, int datalen, unsigned int cacheable)
Definition: iax2-parser.c:1183
iax2_thread_iostate
Definition: chan_iax2.c:984
int iax_provision_reload(int reload)
int ast_apply_ha(const struct ast_ha *ha, const struct ast_sockaddr *addr)
Apply a set of rules to a given IP address.
Definition: acl.c:518
struct ast_channel * ast_channel_release(struct ast_channel *chan)
Unlink and release reference to a channel.
Definition: channel.c:1921
const char * ast_var_name(const struct ast_var_t *var)
Definition: chanvars.c:69
static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2, const char *park_exten, const char *park_context)
Definition: chan_iax2.c:9456
static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
Definition: chan_iax2.c:3266
struct sockaddr_in * apparent_addr
Definition: iax2-parser.h:49
int sockfd
Definition: chan_iax2.c:513
#define ao2_iterator_next(arg1)
Definition: astobj2.h:1126
int ast_netsock_release(struct ast_netsock_list *list)
Definition: netsock.c:84
#define ast_set_flag(p, flag)
Definition: utils.h:70
static int send_ping(const void *data)
Definition: chan_iax2.c:1608
void jb_setoutput(jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg)
Definition: jitterbuf.c:57
struct iax2_context * next
Definition: chan_iax2.c:403
static int peercnt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:2256
struct sockaddr_in defaddr
Definition: chan_iax2.c:519
static int max_reg_expire
Definition: chan_iax2.c:309
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
Definition: chan_iax2.c:12249
#define update_max_trunk()
Definition: chan_iax2.c:2130
#define DEADLOCK_AVOIDANCE(lock)
Definition: lock.h:485
static struct ast_netsock_list * netsock
Definition: chan_iax2.c:315
descriptor for a cli entry.
Definition: cli.h:165
const int argc
Definition: cli.h:154
static int update_packet(struct iax_frame *f)
Definition: chan_iax2.c:3541
#define LOG_WARNING
Definition: logger.h:144
#define IAX_IE_DATETIME
Definition: iax2.h:161
enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
Create a new thread and start the PBX.
Definition: pbx.c:5879
static int iax2_queue_frame(int callno, struct ast_frame *f)
Queue a frame to a call&#39;s owning asterisk channel.
Definition: chan_iax2.c:3044
const ast_string_field dbsecret
Definition: chan_iax2.c:471
static int iax2_devicestate(void *data)
Part of the device state notification system —.
Definition: chan_iax2.c:14250
long losspct
Definition: jitterbuf.h:88
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
Definition: linkedlists.h:139
static const time_t MAX_CALLTOKEN_DELAY
Definition: chan_iax2.c:871
struct sockaddr_in iosin
Definition: chan_iax2.c:1016
static char * handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:6687
struct ast_variable * ast_variable_browse(const struct ast_config *config, const char *category)
Goes through variables.
Definition: config.c:597
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:497
char * username
Definition: iax2-parser.h:34
unsigned char oseqno
Definition: iax2.h:226
static void lock_both(unsigned short callno0, unsigned short callno1)
Definition: chan_iax2.c:5547
#define MARK_IAX_SUBCLASS_TX
Definition: chan_iax2.c:632
enum iax_transfer_state transferring
Definition: chan_iax2.c:796
static struct ast_datastore_info iax2_variable_datastore_info
Definition: chan_iax2.c:1414
int historicms
Definition: chan_iax2.c:535
int ast_party_id_presentation(const struct ast_party_id *id)
Determine the overall presentation value for the given party.
Definition: channel.c:2151
#define ao2_callback(c, flags, cb_fn, arg)
Definition: astobj2.h:910
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
Definition: chan_iax2.c:5456
unsigned int rr_dropped
Definition: iax2-parser.h:76
struct ast_taskprocessor * ast_taskprocessor_get(const char *name, enum ast_tps_options create)
Get a reference to a taskprocessor with the specified name and create the taskprocessor if necessary...
Provide cryptographic signature routines.
static void __get_from_jb(const void *p)
Definition: chan_iax2.c:4152
unsigned char semirand[32]
Definition: chan_iax2.c:786
int ooo
Definition: chan_iax2.c:647
int lineno
Definition: config.h:87
#define IAX_ENCRYPT_KEYROTATE
Definition: iax2.h:200
void ast_verbose(const char *fmt,...)
Definition: logger.c:1568
#define IAX_META_TRUNK
Definition: iax2.h:202
int calling_ton
Definition: iax2-parser.h:30
enum iax_reg_state regstate
Definition: chan_iax2.c:607
static int iax2_transmit(struct iax_frame *fr)
Definition: chan_iax2.c:4374
static int iaxmaxthreadcount
Definition: chan_iax2.c:635
const ast_string_field language
Definition: chan_iax2.c:471
#define AST_FRAME_DTMF
Definition: frame.h:128
static int auto_congest(const void *data)
Definition: chan_iax2.c:4771
#define IAX_FORCE_ENCRYPT
Definition: chan_iax2.c:437
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
Definition: chan_iax2.c:14214
format_t capability
Definition: chan_iax2.c:664
static unsigned int iax2_datetime(const char *tz)
Definition: chan_iax2.c:4780
const ast_string_field inkeys
Definition: chan_iax2.c:471
static void register_peer_exten(struct iax2_peer *peer, int onoff)
Definition: chan_iax2.c:8699
unsigned char type
Definition: chan_iax2.c:1034
struct ast_tm * ast_localtime(const struct timeval *timep, struct ast_tm *p_tm, const char *zone)
Timezone-independent version of localtime_r(3).
Definition: localtime.c:1570
#define IAX_DEFAULT_REG_EXPIRE
Definition: iax2.h:123
#define IAX_QUELCH
Definition: chan_iax2.c:418
#define IAX_DELAYPBXSTART
Definition: chan_iax2.c:432
#define IAX_LINGER_TIMEOUT
Definition: iax2.h:126
socklen_t len
Definition: netsock2.h:65
#define IAX_IE_CALLNO
Definition: iax2.h:151
This entries are for multiple registers.
Definition: data.h:253
#define AST_CAUSE_FACILITY_REJECTED
Definition: causes.h:116
static int delayreject
Definition: chan_iax2.c:388
#define IAX_DELME
Definition: chan_iax2.c:408
#define AST_OPTION_DIGIT_DETECT
Definition: frame.h:508
#define DEFAULT_MAX_THREAD_COUNT
Definition: chan_iax2.c:246
static int load_objects(void)
Definition: chan_iax2.c:14711
Data retrieval API.
static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Execute IAX2 dialplan switch.
Definition: chan_iax2.c:14089
struct sockaddr_in transfer
Definition: chan_iax2.c:800
static int trunk_untimed
Definition: chan_iax2.c:268
static int ping_time
Definition: chan_iax2.c:282
Structure for variables, used for configurations and for channel variables.
Definition: config.h:75
static void unwrap_timestamp(struct iax_frame *fr)
Definition: chan_iax2.c:4100
static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
Definition: chan_iax2.c:6010
#define IAX_IE_MD5_RESULT
Definition: iax2.h:146
const ast_string_field challenge
Definition: chan_iax2.c:769
static void iax_debug_output(const char *data)
Definition: chan_iax2.c:1120
#define var
Definition: ast_expr2f.c:606
void MD5Final(unsigned char digest[16], struct MD5Context *context)
Definition: md5.c:122
#define MAX_TIMESTAMP_SKEW
Definition: chan_iax2.c:626
unsigned short bridgecallno
Definition: chan_iax2.c:810
struct ast_variable * iaxvars
Definition: chan_iax2.c:826
#define ast_sched_thread_del(st, id)
Delete a scheduler entry.
Definition: sched.h:403
#define IAX_DPSTATUS_MATCHMORE
Definition: iax2.h:219
#define IAX_DEFAULT_PORTNO
Definition: iax2.h:128
#define AST_MAX_ACCOUNT_CODE
Definition: cdr.h:73
#define IAX_IE_FIRMWAREVER
Definition: iax2.h:164
static force_inline int inaddrcmp(const struct sockaddr_in *sin1, const struct sockaddr_in *sin2)
Compares the source address and port of two sockaddr_in.
Definition: network.h:90
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition: chan_iax2.c:9239
#define MIN_RETRY_TIME
Definition: chan_iax2.c:618
enum jb_return_code jb_put(jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts, long now)
queue a frame
Definition: jitterbuf.c:527
struct iax2_trunk_peer::@85 list
long frames_lost
Definition: jitterbuf.h:80
format_t rawwriteformat
Definition: channel.h:856
format_t capability
Definition: iax2-parser.h:36
int ast_tvzero(const struct timeval t)
Returns true if the argument is 0,0.
Definition: time.h:100
format_t ast_codec_pref_index(struct ast_codec_pref *pref, int index)
Codec located at a particular place in the preference index.
Definition: frame.c:1061
time_t checktime
Definition: chan_iax2.c:1022
return a reference to a taskprocessor, create one if it does not exist
Definition: taskprocessor.h:58
#define AST_OPTION_TDD
Definition: frame.h:445
#define IAX_ENCRYPTED
Definition: chan_iax2.c:419
Test Framework API.
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition: channel.c:4383
static int peercnt_remove_by_addr(struct sockaddr_in *sin)
Definition: chan_iax2.c:2524
#define AST_IO_IN
Definition: io.h:33
unsigned char delme
Definition: chan_iax2.c:931
struct ast_party_redirecting redirecting
Redirecting/Diversion information.
Definition: channel.h:814
static struct iax2_user * user_ref(struct iax2_user *user)
Definition: chan_iax2.c:1805
const ast_string_field name
Definition: chan_iax2.c:508
const ast_string_field language
Definition: chan_iax2.c:769
#define AST_OPTION_OPRMODE
Definition: frame.h:469
#define EVENT_FLAG_CALL
Definition: manager.h:72
#define AST_TEST_REGISTER(cb)
Definition: test.h:127
Definition: cli.h:146
static struct iax2_thread * find_idle_thread(void)
Definition: chan_iax2.c:1477
struct ast_event * ast_event_get_cached(enum ast_event_type,...)
Retrieve an event from the cache.
Definition: event.c:1342
void ast_timer_close(struct ast_timer *handle)
Close an opened timing handle.
Definition: timing.c:150
static void unlock_both(unsigned short callno0, unsigned short callno1)
Definition: chan_iax2.c:5555
static char * handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:12166
static struct ast_channel * iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
Definition: chan_iax2.c:12329
static void jb_debug_output(const char *fmt,...)
Definition: chan_iax2.c:1155
unsigned char afdata[0]
Definition: iax2-parser.h:143
int ast_ignore_pattern(const char *context, const char *pattern)
Checks to see if a number should be ignored.
Definition: pbx.c:8650
#define IAX_IE_RR_DELAY
Definition: iax2.h:180
long ts
Definition: frame.h:168
Structure for a data store type.
Definition: datastore.h:31
Continue if a match is not found in the hashed out bucket.
Definition: astobj2.h:687
Configuration File Parser.
#define DEFAULT_FREQ_OK
Definition: chan_iax2.c:344
unsigned int lastvsent
Definition: chan_iax2.c:670
static char * handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7436
struct ast_timer * ast_timer_open(void)
Open a timer.
Definition: timing.c:123
static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:5365
unsigned char semirand[32]
Definition: iax2-parser.h:135
char * str
Subscriber name (Malloced)
Definition: channel.h:214
unsigned int stop
Definition: app_meetme.c:969
int * ast_io_add(struct io_context *ioc, int fd, ast_io_cb callback, short events, void *data)
Adds an IO context.
Definition: io.c:157
static int registry_authrequest(int callno)
Definition: chan_iax2.c:9007
void ast_unregister_switch(struct ast_switch *sw)
Unregister an alternative switch.
Definition: pbx.c:6457
struct ast_variable * ast_load_realtime(const char *family,...) attribute_sentinel
Retrieve realtime configuration.
Definition: config.c:2548
static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:6299
int packets
Definition: chan_iax2.c:644
uint32_t ast_sockaddr_ipv4(const struct ast_sockaddr *addr)
Get an IPv4 address of an ast_sockaddr.
Definition: netsock2.c:394
#define ast_cond_wait(cond, mutex)
Definition: lock.h:171
#define IAX_CODEC_NOPREFS
Definition: chan_iax2.c:422
static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
Acknowledgment received for OUR registration.
Definition: chan_iax2.c:8567
Background DNS update manager.
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition: strings.h:900
#define ast_cond_init(cond, attr)
Definition: lock.h:167
static char * handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3721
struct ast_netsock_list * ast_netsock_list_alloc(void)
Definition: netsock.c:71
#define IAX_CAPABILITY_FULLBANDWIDTH
Definition: chan_iax2.c:322
struct ast_data * ast_data_get(const struct ast_data_query *query)
Retrieve a subtree from the asterisk data API.
Definition: data.c:2065
static int matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Definition: pbx_lua.c:1258
unsigned short transfercallno
Definition: chan_iax2.c:802
int callno
Definition: chan_iax2.c:528
static int auto_hangup(const void *data)
Definition: chan_iax2.c:9176
format_t ast_best_codec(format_t fmts)
Pick the best audio codec.
Definition: channel.c:1062
static int copy(char *infile, char *outfile)
Utility function to copy a file.
int dropped
Definition: chan_iax2.c:646
#define IAX_IE_AUTOANSWER
Definition: iax2.h:155
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:142
#define AST_DECLARE_STRING_FIELDS(field_list)
Declare the fields needed in a structure.
Definition: stringfields.h:235
struct ast_dnsmgr_entry * dnsmgr
Definition: chan_iax2.c:611
#define IAX_SENDANI
Definition: chan_iax2.c:414
Number of new messages Used by: AST_EVENT_MWI Payload type: UINT.
Definition: event_defs.h:71
static force_inline int ast_format_rate(format_t format)
Get the sample rate for a given format.
Definition: frame.h:809
struct ast_flags state
Definition: chan_iax2.c:718
struct ast_data * ast_data_add_bool(struct ast_data *root, const char *childname, unsigned int boolean)
Add a boolean node type.
Definition: data.c:2344
#define ast_set_flag64(p, flag)
Definition: utils.h:127
Number of Used by: AST_EVENT_MWI Payload type: UINT.
Definition: event_defs.h:77
#define AST_OPTION_TONE_VERIFY
Definition: frame.h:441
#define ast_frame_byteswap_be(fr)
Definition: frame.h:616
#define IAX_CODEC_USER_FIRST
Definition: chan_iax2.c:421
#define ast_mutex_lock(a)
Definition: lock.h:155
struct ast_codec_pref prefs
Definition: chan_iax2.c:481
static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
Definition: chan_iax2.c:4834
unsigned char stop
Definition: chan_iax2.c:1041
#define IAX_MAX_OSPTOKEN_SIZE
Definition: iax2.h:192
#define IAX_DPSTATUS_IGNOREPAT
Definition: iax2.h:218
#define ao2_unlock(a)
Definition: astobj2.h:497
static int iax2_sched_add(struct ast_sched_thread *st, int when, ast_sched_cb callback, const void *data)
Definition: chan_iax2.c:1580
static void user_destructor(void *obj)
Definition: chan_iax2.c:12903
static void set_hangup_source_and_cause(int callno, unsigned char causecode)
Definition: chan_iax2.c:10030
int ast_channel_register(const struct ast_channel_tech *tech)
Register a channel technology (a new channel driver) Called by a channel module to register the kind ...
Definition: channel.c:907
static char * tz
Definition: cdr_pgsql.c:56
struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags)
Create an iterator for a container.
Definition: astobj2.c:818
#define AST_MODULE_INFO(keystr, flags_to_set, desc, fields...)
Definition: module.h:374
char * text
Definition: app_queue.c:1091
unsigned int last
Definition: chan_iax2.c:666
format_t nativeformats
Definition: channel.h:852
#define ast_str_alloca(init_len)
Definition: strings.h:608
char * park_context
Definition: chan_iax2.c:9426
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:90
static struct @81 qos
Structure for a data store object.
Definition: datastore.h:54
static char * handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7189
static int socket_read(int *id, int fd, short events, void *cbdata)
Definition: chan_iax2.c:9737
void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
Destroy the connected line information contents.
Definition: channel.c:2353
static int peers_data_provider_get(const struct ast_data_search *search, struct ast_data *data_root)
Definition: chan_iax2.c:14799
unsigned int rr_loss
Definition: iax2-parser.h:73
struct ast_datastore * ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
Find a datastore on a channel.
Definition: channel.c:2604
Definition: dnsmgr.c:56
int smoothing
Definition: chan_iax2.c:536
void ast_variables_destroy(struct ast_variable *var)
Free variable list.
Definition: config.c:586
static void * iax_park_thread(void *stuff)
Definition: chan_iax2.c:9429
#define IAX_DEBUGDIGEST(msg, key)
Definition: chan_iax2.c:351
int ast_str2tos(const char *value, unsigned int *tos)
Convert a string to the appropriate TOS value.
Definition: acl.c:667
jitterbuf * jb
Definition: chan_iax2.c:708
format_t codec
Definition: frame.h:137
static void log_jitterstats(unsigned short callno)
Definition: chan_iax2.c:9616
int iax_get_iframes(void)
Definition: iax2-parser.c:1294
static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when, ast_sched_cb callback, const void *data)
Definition: chan_iax2.c:1572
static void network_change_event_subscribe(void)
Definition: chan_iax2.c:1366
#define MAX_TRUNKDATA
Definition: chan_iax2.c:289
int ast_sockaddr_cmp(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares two ast_sockaddr structures.
Definition: netsock2.c:300
calltoken_peer_enum
Call token validation settings.
Definition: chan_iax2.c:446
const char * data
Definition: channel.h:755
#define IAX_IE_CHALLENGE
Definition: iax2.h:145
unsigned int provver
Definition: iax2-parser.h:69
static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
Definition: chan_iax2.c:7896
#define AST_CAUSE_NO_USER_RESPONSE
Definition: causes.h:107
enum jb_return_code jb_get(jitterbuf *jb, jb_frame *frame, long now, long interpl)
get a frame for time now (receiver&#39;s time) return value is one of JB_OK: You&#39;ve got frame! JB_DROP: H...
Definition: jitterbuf.c:787
char prefs[32]
Definition: chan_iax2.c:4648
I/O Management (derived from Cheops-NG)
char * ast_cdr_flags2str(int flags)
Definition: cdr.c:977
Definition: chan_iax2.c:934
unsigned short dpstatus
Definition: iax2-parser.h:51
static void send_signaling(struct chan_iax2_pvt *pvt)
This function must be called once we are sure the other side has given us a call number. All signaling is held here until that point.
Definition: chan_iax2.c:1913
static int iax2_getpeertrunk(struct sockaddr_in sin)
Definition: chan_iax2.c:5812
static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
Definition: chan_iax2.c:9973
static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
Definition: chan_iax2.c:4243
char username[80]
Definition: chan_iax2.c:4644
ast_mutex_t lock
Definition: chan_iax2.c:548
char * iax_prov_complete_template(const char *line, const char *word, int pos, int state)
int value
Definition: syslog.c:39
int ast_dnsmgr_refresh(struct ast_dnsmgr_entry *entry)
Force a refresh of a dnsmgr entry.
Definition: dnsmgr.c:230
static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
Definition: chan_iax2.c:7059
void ast_cli(int fd, const char *fmt,...)
Definition: cli.c:105
struct ast_netsock * ast_netsock_find(struct ast_netsock_list *list, struct sockaddr_in *sa)
Definition: netsock.c:93
#define AST_LIST_REMOVE(head, elm, field)
Removes a specific entry from a list.
Definition: linkedlists.h:841
static char mohinterpret[MAX_MUSICCLASS]
Definition: chan_iax2.c:384
static char * handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7512
static struct iax2_user * build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
Create in-memory user structure from configuration.
Definition: chan_iax2.c:12917
#define IAX_IE_DPSTATUS
Definition: iax2.h:150
const ast_string_field linkedid
Definition: channel.h:787
char * devicetype
Definition: iax2-parser.h:61
#define LOG_DEBUG
Definition: logger.h:122
#define AST_DATA_ENTRY(__path, __handler)
Definition: data.h:260
#define update_max_nontrunk()
Definition: chan_iax2.c:2131
#define IAX_IE_LANGUAGE
Definition: iax2.h:140
Structure used to handle a large number of boolean flags == used only in app_dial?
Definition: utils.h:206
char * calling_number
Definition: iax2-parser.h:27
int iax_ie_append_versioned_uint64(struct iax_ie_data *ied, unsigned char ie, unsigned char version, uint64_t value)
Definition: iax2-parser.c:713
const char * ext
Definition: http.c:112
struct sockaddr_in us
Definition: chan_iax2.c:610
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
Definition: chan_iax2.c:4386
enum ast_channel_adsicpe adsicpe
Definition: channel.h:844
format_t format
Definition: iax2-parser.h:37
int ast_unregister_application(const char *app)
Unregister an application.
Definition: pbx.c:7705
static char default_parkinglot[AST_MAX_CONTEXT]
Definition: chan_iax2.c:272
#define AST_FILE_MODE
Definition: asterisk.h:36
format_t rawreadformat
Definition: channel.h:855
static void network_change_event_cb(const struct ast_event *, void *)
Definition: chan_iax2.c:1394
static void set_config_destroy(void)
Definition: chan_iax2.c:13247
void ast_moh_stop(struct ast_channel *chan)
Turn off music on hold on a given channel.
Definition: channel.c:8051
#define AST_LIST_TRAVERSE_SAFE_END
Closes a safe loop traversal block.
Definition: linkedlists.h:600
void ast_free_ptr(void *ptr)
Socket address structure.
Definition: netsock2.h:63
static char cid_num[AST_MAX_EXTENSION]
Definition: chan_mgcp.c:157
#define ast_cond_signal(cond)
Definition: lock.h:169
#define IAX_PROVISION
Definition: chan_iax2.c:417
struct ast_channel * ast_waitfor_nandfds(struct ast_channel **chan, int n, int *fds, int nfds, int *exception, int *outfd, int *ms)
Waits for activity on a group of channels.
Definition: channel.c:3188
struct ast_codec_pref prefs
Definition: chan_iax2.c:509
int tm_year
Definition: localtime.h:41
static int iaxactivethreadcount
Definition: chan_iax2.c:638
void ast_var_delete(struct ast_var_t *var)
Definition: chanvars.c:63
#define ast_pthread_create_detached_background(a, b, c, d)
Definition: utils.h:431
#define ast_verb(level,...)
Definition: logger.h:243
static int transfer
Definition: chan_mgcp.c:187
int ast_sockaddr_cmp_addr(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares the addresses of two ast_sockaddr structures.
Definition: netsock2.c:325
static int lagrq_time
Definition: chan_iax2.c:283
static struct callno_entry * get_unused_callno(int trunk, int validated)
Definition: chan_iax2.c:2703
Definition: ael.tab.c:203
struct ast_netsock * ast_netsock_bind(struct ast_netsock_list *list, struct io_context *ioc, const char *bindinfo, int defaultport, int tos, int cos, ast_io_cb callback, void *data)
Definition: netsock.c:178
static void pvt_destructor(void *obj)
Definition: chan_iax2.c:1951
void ast_config_destroy(struct ast_config *config)
Destroys a config.
Definition: config.c:1037
static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
callback to display iax peers in manager format
Definition: chan_iax2.c:7122
#define IAX_IE_RR_JITTER
Definition: iax2.h:177
void MD5Init(struct MD5Context *context)
Definition: md5.c:59
#define MAX_RETRY_TIME
Definition: chan_iax2.c:619
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return * the previous value of *p. This can be used to handle reference co...
Definition: lock.h:603
const ast_string_field inkeys
Definition: chan_iax2.c:508
const char * line
Definition: cli.h:156
int ast_custom_function_unregister(struct ast_custom_function *acf)
Unregister a custom function.
Definition: pbx.c:3814
int ast_datastore_free(struct ast_datastore *datastore)
Free a data store object.
Definition: datastore.c:65
#define IAX_IE_CALLING_NUMBER
Definition: iax2.h:132
struct ast_channel * ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *acctcode, const char *exten, const char *context, const char *linkedid, const int amaflag, const char *name_fmt,...)
Definition: channel.c:9825
int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Looks for a valid matching extension.
Definition: pbx.c:5415
ast_aes_decrypt_key mydcx
Definition: iax2-parser.h:133
unsigned int nextpred
Definition: chan_iax2.c:672
void ast_aes_decrypt(const unsigned char *in, unsigned char *out, const ast_aes_decrypt_key *ctx)
AES decrypt data.
Definition: res_crypto.c:476
unsigned short callno
Definition: iax2.h:264
static char * handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:6965
const char * pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name)
Return a pointer to the value of the corresponding channel variable.
Definition: pbx.c:10475
static struct ast_custom_function iaxpeer_function
Definition: chan_iax2.c:14209
struct sockaddr_in addr
Definition: chan_iax2.c:684
const ast_string_field parkinglot
Definition: chan_iax2.c:769
static struct iax2_context * build_context(const char *context)
Definition: chan_iax2.c:12474
static struct ao2_container * iax_transfercallno_pvts
Another container of iax2_pvt structures.
Definition: chan_iax2.c:1094
#define IAX_IE_CALLING_ANI
Definition: iax2.h:133
static struct ast_event_sub * network_change_event_subscription
Definition: chan_iax2.c:277
#define MAX_LANGUAGE
Definition: channel.h:138
int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
Simply remove extension from context.
Definition: pbx.c:6114
uint16_t maxcallno
Definition: chan_iax2.c:537
String fields in structures.
Utility functions.
static void ast_sockaddr_setnull(struct ast_sockaddr *addr)
Sets address addr to null.
Definition: netsock2.h:106
#define IAX_META_TRUNK_SUPERMINI
Definition: iax2.h:205
int authmethods
Definition: chan_iax2.c:520
int args
This gets set in ast_cli_register()
Definition: cli.h:179
threshold
Definition: dsp.h:62
const char * astman_get_header(const struct message *m, char *var)
Get header from mananger transaction.
Definition: manager.c:1860
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int)
Definition: chan_iax2.c:7652
unsigned short callno
Definition: iax2.h:242
#define IAX_CAPABILITY_LOWBANDWIDTH
Definition: chan_iax2.c:334
static char * handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:4028
unsigned int pingtime
Definition: chan_iax2.c:680
pthread_cond_t ast_cond_t
Definition: lock.h:144
struct chan_iax2_pvt::signaling_queue signaling_queue
static int resyncthreshold
Definition: chan_iax2.c:285
format_t voiceformat
Definition: chan_iax2.c:656
static int iax2_queue_control_data(int callno, enum ast_control_frame_type control, const void *data, size_t datalen)
Queue a control frame on the ast_channel owner.
Definition: chan_iax2.c:3090
#define AST_LIST_HEAD_DESTROY(head)
Destroys a list head structure.
Definition: linkedlists.h:638
int expiry
Definition: chan_iax2.c:524
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:1854
#define ast_manager_event(chan, category, event, contents,...)
Definition: manager.h:221
char * ast_cli_complete(const char *word, const char *const choices[], int pos)
Definition: cli.c:1535
int ast_channel_defer_dtmf(struct ast_channel *chan)
Defers DTMF so that you only read things like hangups and audio.
Definition: channel.c:1616
unsigned char type
Definition: iax2.h:228
#define ast_pthread_create_background(a, b, c, d)
Definition: utils.h:426
const char * ast_config_AST_SYSTEM_NAME
Definition: asterisk.c:273
static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
Queue the last read full frame for processing by a certain thread.
Definition: chan_iax2.c:9706
#define IAX_IE_ENCRYPTION
Definition: iax2.h:173
int iax_get_oframes(void)
Definition: iax2-parser.c:1295
ast_control_transfer
Definition: frame.h:422
jitterbuf * jb_new(void)
new jitterbuf
Definition: jitterbuf.c:88
unsigned int flags
Definition: channel.h:850
#define ast_sockaddr_port(addr)
Get the port number of a socket address.
Definition: netsock2.h:406
int msgcount
Definition: iax2-parser.h:56
Custom localtime functions for multiple timezones.
internal representation of acl entries In principle user applications would have no need for this...
Definition: acl.h:48
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
Definition: chan_iax2.c:6477
Call Detail Record API.
int ast_str_set(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Set a dynamic string using variable arguments.
Definition: strings.h:874
unsigned short dcallno
Definition: iax2.h:224
struct ast_party_id id
Caller party ID.
Definition: channel.h:370
static int __unload_module(void)
Definition: chan_iax2.c:14574
#define AST_OPTION_SECURE_MEDIA
Definition: frame.h:525
int ast_set_write_format(struct ast_channel *chan, format_t format)
Sets write format on channel chan Set write format for channel to whichever component of &quot;format&quot; is ...
Definition: channel.c:5307
static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
Definition: chan_iax2.c:9191
int ast_update_realtime(const char *family, const char *keyfield, const char *lookup,...) attribute_sentinel
Update realtime configuration.
Definition: config.c:2679
static int netsocket
Definition: pbx_dundi.c:178
static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
Definition: chan_iax2.c:2812
static int autokill
Definition: chan_iax2.c:295
#define IAX_DYNAMIC
Definition: chan_iax2.c:413
char * called_context
Definition: iax2-parser.h:33
static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
Definition: chan_iax2.c:1817
AES_KEY ast_aes_encrypt_key
Definition: crypto.h:35
iax2_state
Definition: chan_iax2.c:395
static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
Definition: chan_iax2.c:3405
void ast_aes_encrypt(const unsigned char *in, unsigned char *out, const ast_aes_encrypt_key *ctx)
AES encrypt data.
Definition: res_crypto.c:471
unsigned int ts
Definition: iax2.h:270
struct iax2_context * contexts
Definition: chan_iax2.c:483
char * codec_prefs
Definition: iax2-parser.h:38
int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
get values from config variables.
Definition: utils.c:2118
char * ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
Strip leading/trailing whitespace and quotes from a string.
Definition: utils.c:1431
static int global_max_trunk_mtu
Definition: chan_iax2.c:267
char * challenge
Definition: iax2-parser.h:46
struct ast_iax2_mini_hdr mini
Definition: iax2.h:282
#define EVENT_FLAG_SYSTEM
Definition: manager.h:71
static struct iax2_peer * build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
Create peer structure based on configuration.
Definition: chan_iax2.c:12623
static struct ast_data_handler users_data_provider
Definition: chan_iax2.c:14938
unsigned int sentyet
Definition: iax2-parser.h:113
int ast_set_read_format(struct ast_channel *chan, format_t format)
Sets read format on channel chan Set read format for channel to whichever component of &quot;format&quot; is be...
Definition: channel.c:5301
Definition: config.h:68
long frames_in
Definition: jitterbuf.h:77
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:236
iax2_thread_type
Definition: chan_iax2.c:991
static unsigned char compress_subclass(format_t subclass)
Definition: chan_iax2.c:1691
long jb_next(jitterbuf *jb)
when is the next frame due out, in receiver&#39;s time (0=EMPTY) This value may change as frames are adde...
Definition: jitterbuf.c:769
#define MAX_TRUNK_MTU
Maximum transmission unit for the UDP packet in the trunk not to be fragmented. This is based on 1516...
Definition: chan_iax2.c:265
long resync_threshold
Definition: jitterbuf.h:68
static int defaultsockfd
Definition: chan_iax2.c:317
static void * iax2_process_thread(void *data)
Definition: chan_iax2.c:11878
#define SENTINEL
Definition: compiler.h:75
const char * name
Definition: pbx.h:130
Context IE Used by AST_EVENT_MWI Payload type: str.
Definition: event_defs.h:121
static struct iax2_user * realtime_user(const char *username, struct sockaddr_in *sin)
Definition: chan_iax2.c:4546
#define AST_DATA_HANDLER_VERSION
The Data API structures version.
Definition: data.h:204
#define IAX_MAX_OSPBLOCK_NUM
Definition: iax2.h:191
static struct ao2_container * callno_pool_trunk
Definition: chan_iax2.c:852
unsigned int encmethods
Definition: iax2-parser.h:45
const char * value
Definition: config.h:79
void ast_netsock_unref(struct ast_netsock *ns)
Definition: netsock.c:217
#define MAX_USER_BUCKETS
Definition: chan_iax2.c:887
unsigned short callno
Definition: iax2-parser.h:52
int provverpres
Definition: iax2-parser.h:71
int iax_ie_append_addr(struct iax_ie_data *ied, unsigned char ie, const struct sockaddr_in *sin)
Definition: iax2-parser.c:708
int ast_devstate_changed(enum ast_device_state state, enum ast_devstate_cache cachable, const char *fmt,...)
Tells Asterisk the State for Device is changed.
Definition: devicestate.c:516
struct ast_module * self
Definition: module.h:227
char * ast_callerid_merge(char *buf, int bufsiz, const char *name, const char *num, const char *unknown)
Definition: callerid.c:1074
static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
Definition: chan_iax2.c:7989
unsigned short len
Definition: iax2.h:281
static int scheduled_destroy(const void *vid)
Definition: chan_iax2.c:1889
struct ast_party_id ani
Automatic Number Identification (ANI)
Definition: channel.h:377
static void __send_lagrq(const void *data)
Definition: chan_iax2.c:1655
unsigned char * calltokendata
Definition: iax2-parser.h:82
#define VERBOSE_PREFIX_4
Definition: logger.h:44
#define IAX_IE_FORMAT2
Definition: iax2.h:188
General Asterisk PBX channel definitions.
static void * iax2_dup_variable_datastore(void *)
Definition: chan_iax2.c:1420
static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
Definition: chan_iax2.c:1103
static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
Definition: chan_iax2.c:6315
static int iax2_transfer(struct ast_channel *c, const char *dest)
Definition: chan_iax2.c:5792
static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
Definition: chan_iax2.c:4844
static void iax2_destroy(int callno)
Definition: chan_iax2.c:3475
struct ast_codec_pref rprefs
Definition: chan_iax2.c:688
struct timeval txtrunktime
Definition: chan_iax2.c:551
struct ast_party_dialed::@155 number
Dialed/Called number.
static struct ao2_container * users
Definition: chan_iax2.c:888
static void * dp_lookup_thread(void *data)
Definition: chan_iax2.c:9393
struct iax2_thread::@94 ffinfo
#define DEFAULT_RETRY_TIME
Definition: chan_iax2.c:247
#define DEFAULT_THREAD_COUNT
Definition: chan_iax2.c:245
unsigned char causecode
Definition: iax2-parser.h:54
#define AST_FRIENDLY_OFFSET
Offset into a frame&#39;s data buffer.
Definition: frame.h:204
void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
Set the source of the hangup in this channel and it&#39;s bridge.
Definition: channel.c:2769
Asterisk file paths, configured in asterisk.conf.
struct ast_channel * chan2
Definition: chan_iax2.c:9424
void io_context_destroy(struct io_context *ioc)
Destroys a context.
Definition: io.c:102
static struct ao2_container * peers
Definition: chan_iax2.c:885
const char * src
Definition: frame.h:158
#define ast_sockaddr_from_sin(addr, sin)
Converts a struct sockaddr_in to a struct ast_sockaddr.
Definition: netsock2.h:642
void ast_channel_undefer_dtmf(struct ast_channel *chan)
Unset defer DTMF flag on channel.
Definition: channel.c:1628
#define ast_mutex_trylock(a)
Definition: lock.h:157
unsigned int cacheable
Definition: iax2-parser.h:121
struct ast_sockaddr netmask
Definition: acl.h:51
#define AST_IO_PRI
Definition: io.h:37
long frames_ooo
Definition: jitterbuf.h:82
char exten[AST_MAX_EXTENSION]
Definition: chan_iax2.c:964
#define IAX_IE_CAUSECODE
Definition: iax2.h:172
static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
Definition: chan_iax2.c:8288
Network socket handling.
#define ast_test_status_update(a, b, c...)
Definition: test.h:129
unsigned int rr_jitter
Definition: iax2-parser.h:72
struct timeval offset
Definition: chan_iax2.c:704
static struct ast_generator gen
const int fd
Definition: cli.h:153
void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry)
Free a DNS manager entry.
Definition: dnsmgr.c:126
#define IAX_IE_VERSION
Definition: iax2.h:141
static int peer_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:1728
#define ast_string_field_init(x, size)
Initialize a field pool and fields.
Definition: stringfields.h:249
void(* schedfunc)(const void *)
Definition: chan_iax2.c:1007
#define ast_config_load(filename, flags)
Load a config file.
Definition: config.h:170
#define PTR_TO_CALLNO(a)
Definition: chan_iax2.c:242
int losspct
Definition: chan_iax2.c:642
#define ast_manager_register_xml(a, b, c)
Register a manager callback using XML documentation to describe the manager.
Definition: manager.h:172
#define AST_PTHREADT_NULL
Definition: lock.h:65
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:63
#define IAX_HASCALLERID
Definition: chan_iax2.c:407
char username[80]
Definition: chan_iax2.c:603
const int n
Definition: cli.h:159
enum iax2_thread_type type
Definition: chan_iax2.c:1004
unsigned char iax_unknown
Definition: iax2-parser.h:55
size_t buf_size
Definition: chan_iax2.c:1020
format_t peerformat
Definition: chan_iax2.c:700
struct sla_ringing_trunk * last
Definition: app_meetme.c:965
Data structure associated with a custom dialplan function.
Definition: pbx.h:95
Access Control of various sorts.
Asterisk internal frame definitions.
unsigned char validated
Definition: chan_iax2.c:938
struct ast_data * ast_data_add_node(struct ast_data *root, const char *childname)
Add a container child.
Definition: data.c:2317
Global IO variables are now in a struct in order to be made threadsafe.
Definition: io.c:66
static int callno_hash(const void *obj, const int flags)
Definition: chan_iax2.c:2765
#define IAX_RTCACHEFRIENDS
Definition: chan_iax2.c:424
static char mohsuggest[MAX_MUSICCLASS]
Definition: chan_iax2.c:385
#define AST_MAX_EXTENSION
Definition: channel.h:135
static int iaxtrunkdebug
Definition: chan_iax2.c:373
unsigned short peercallno
Definition: chan_iax2.c:694
int datalen
Definition: frame.h:148
Scheduler Routines (derived from cheops)
enum iax2_thread_iostate iostate
Definition: chan_iax2.c:1005
const ast_string_field zonetag
Definition: chan_iax2.c:508
const ast_string_field mohinterpret
Definition: chan_iax2.c:769
#define AST_STRING_FIELD(name)
Declare a string field.
Definition: stringfields.h:220
#define ast_data_unregister(path)
Definition: data.h:394
char * osptokenblock[IAX_MAX_OSPBLOCK_NUM]
Definition: iax2-parser.h:79
#define IAX_FIRMWARE_MAGIC
Definition: iax2.h:285
static char * handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7034
unsigned short len
Definition: iax2.h:276
int tm_mon
Definition: localtime.h:40
#define IAX_DPSTATUS_NONEXISTENT
Definition: iax2.h:217
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
Definition: linkedlists.h:554
struct ast_ha * ha
Definition: chan_iax2.c:541
int iax_ie_append_short(struct iax_ie_data *ied, unsigned char ie, unsigned short value)
Definition: iax2-parser.c:730
unsigned short zeros
Definition: iax2.h:256
static int complete_transfer(int callno, struct iax_ies *ies)
Definition: chan_iax2.c:8505
char * ast_category_browse(struct ast_config *config, const char *prev)
Goes through categories.
Definition: config.c:810
#define ao2_ref(o, delta)
Definition: astobj2.h:472
#define S_COR(a, b, c)
returns the equivalent of logic or for strings, with an additional boolean check: second one if not e...
Definition: strings.h:83
static char * papp
Definition: chan_iax2.c:12132
#define IAX_IE_CALLING_NAME
Definition: iax2.h:134
static struct @82 frame_queue[IAX_MAX_CALLS]
a list of frames that may need to be retransmitted
unsigned char data[0]
Definition: iax2.h:271
const ast_string_field regexten
Definition: chan_iax2.c:508
static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd, struct iax_frame *fr)
Definition: chan_iax2.c:9817
static int iax2_call(struct ast_channel *c, char *dest, int timeout)
Definition: chan_iax2.c:5109
long int ast_random(void)
Definition: utils.c:1640
const ast_string_field username
Definition: chan_iax2.c:769
unsigned int lastsent
Definition: chan_iax2.c:555
#define ao2_lock(a)
Definition: astobj2.h:488
struct timeval ast_samp2tv(unsigned int _nsamp, unsigned int _rate)
Returns a timeval corresponding to the duration of n samples at rate r. Useful to convert samples to ...
Definition: time.h:191
static uint16_t total_nonval_callno_used
Definition: chan_iax2.c:908
const ast_string_field parkinglot
Definition: channel.h:787
#define IAX_IE_PROVISIONING
Definition: iax2.h:159
static void __auto_hangup(const void *nothing)
Definition: chan_iax2.c:9161
Require call token validation.
Definition: chan_iax2.c:450
static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno, int now, int transfer, int final)
Definition: chan_iax2.c:7593
static int try_firmware(char *s)
Definition: chan_iax2.c:3110
#define AST_BRIDGE_DTMF_CHANNEL_1
Report DTMF on channel 1.
Definition: channel.h:1934
static struct ao2_container * calltoken_ignores
Definition: chan_iax2.c:897
static struct chan_iax2_pvt * new_iax(struct sockaddr_in *sin, const char *host)
Definition: chan_iax2.c:1998
static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: chan_iax2.c:14140
int ast_atomic_dec_and_test(volatile int *p)
decrement *p by 1 and return true if the variable has reached 0. Useful e.g. to check if a refcount h...
Definition: lock.h:649
static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
Definition: chan_iax2.c:5561
char * value
Definition: chanvars.h:30
Default calltoken required unless the ip is in the ignorelist.
Definition: chan_iax2.c:448
int last_iax_message
Definition: chan_iax2.c:676
A set of macros to manage forward-linked lists.
const char * name
Definition: config.h:77
unsigned char * buf
Definition: chan_iax2.c:1018
long frames_dropped
Definition: jitterbuf.h:81
#define AST_KEY_PRIVATE
Definition: crypto.h:43
static char zonetag[80]
int ast_data_add_codecs(struct ast_data *root, const char *node_name, format_t capability)
Add the list of codecs in the root node based on the capability parameter.
Definition: data.c:3112
unsigned short adsicpe
Definition: iax2-parser.h:41
#define IAX_AUTH_RSA
Definition: iax2.h:197
static void __send_ping(const void *data)
Definition: chan_iax2.c:1588
char name[0]
Definition: chanvars.h:31
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
Definition: linkedlists.h:818
static void delete_users(void)
Definition: chan_iax2.c:13187
int tm_mday
Definition: localtime.h:39
static int trunkfreq
Definition: chan_iax2.c:291
int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
Determine number of new/old messages in a mailbox.
Definition: app.c:435
static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
Definition: chan_iax2.c:9361
int iax_get_frames(void)
Definition: iax2-parser.c:1293
static int iaxdebug
Definition: chan_iax2.c:371
int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Determine whether an extension exists.
Definition: pbx.c:5400
struct ast_party_id ani
Automatic Number Identification (ANI)
Definition: channel.h:410
#define AST_SENSE_DENY
Definition: acl.h:35
#define ast_data_register_multiple(data_entries, entries)
Definition: data.h:377
struct ast_frame f
Definition: chan_iax2.c:844
static int unload_module(void)
Definition: chan_iax2.c:14658
int iax_provision_version(unsigned int *version, const char *template, int force)
iax_reg_state
Definition: chan_iax2.c:577
#define IAX2_TRUNK_PREFACE
Definition: chan_iax2.c:545
#define IAX_IE_DNID
Definition: iax2.h:143
static void iax2_free_variable_datastore(void *)
Definition: chan_iax2.c:1444
static int timing_read(int *id, int fd, short events, void *cbdata)
Definition: chan_iax2.c:9290
const ast_string_field accountcode
Definition: chan_iax2.c:471
unsigned short callno
Definition: iax2.h:275
ast_cond_t cond
Definition: chan_iax2.c:1024
static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
Definition: chan_iax2.c:2289
Structure to describe a channel &quot;technology&quot;, ie a channel driver See for examples: ...
Definition: channel.h:507
char * park_exten
Definition: chan_iax2.c:9425
static int peercnt_remove_cb(const void *obj)
Definition: chan_iax2.c:2510
Network socket handling.
Core PBX routines and definitions.
static int trunk_timed
Definition: chan_iax2.c:268
static int user_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:13178
uint16_t limit
Definition: chan_iax2.c:929
int ast_queue_frame(struct ast_channel *chan, struct ast_frame *f)
Queue one or more frames to a channel&#39;s frame queue.
Definition: channel.c:1558
int lastms
Definition: chan_iax2.c:530
int ast_check_hangup(struct ast_channel *chan)
Check to see if a channel is needing hang up.
Definition: channel.c:806
static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition: chan_iax2.c:8458
static int __do_deliver(void *data)
Definition: chan_iax2.c:3356
static void poke_all_peers(void)
Definition: chan_iax2.c:13748
#define AST_OPTION_FAX_DETECT
Definition: frame.h:512
#define IAX_RECVCONNECTEDLINE
Definition: chan_iax2.c:436
enum calltoken_peer_enum calltoken_required
Definition: chan_iax2.c:485
int version
Definition: iax2-parser.h:40
#define AST_CAUSE_DESTINATION_OUT_OF_ORDER
Definition: causes.h:114
#define ast_data_add_structure(structure_name, root, structure)
Definition: data.h:620
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2213
unsigned int direction
Definition: iax2-parser.h:119
struct iax2_trunk_peer * next
Definition: chan_iax2.c:563
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
peer_status: Report Peer status in character string
Definition: chan_iax2.c:3812
int formats
Definition: chan_iax2.c:512
int pokefreqok
Definition: chan_iax2.c:533
static struct sched_context * sched
Definition: chan_gtalk.c:227
The list of nodes with their search requirement.
Definition: data.c:122
long target_extra
Definition: jitterbuf.h:70
char peercontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:4652
int first_iax_message
Definition: chan_iax2.c:674
static struct ao2_container * callno_pool
Definition: chan_iax2.c:849
uint64_t flags
Definition: chan_iax2.c:516
void ast_sha1_hash(char *output, const char *input)
Produces SHA1 hash based on input string.
Definition: utils.c:261
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
Definition: linkedlists.h:290
struct timeval expiry
Definition: chan_iax2.c:966
static int maxjitterbuffer
Definition: chan_iax2.c:284
jitterbuf: an application-independent jitterbuffer jitterbuf.c
static int iax2_answer(struct ast_channel *c)
Definition: chan_iax2.c:5732
int delay
Definition: chan_iax2.c:645
#define IAX_IE_CALLTOKEN
Definition: iax2.h:185
static int set_config(const char *config_file, int reload)
Load configuration.
Definition: chan_iax2.c:13264
const char *const * argv
Definition: cli.h:155
unsigned int rr_ooo
Definition: iax2-parser.h:77
unsigned char reg
Definition: chan_iax2.c:921
struct ast_party_dialed dialed
Dialed/Called information.
Definition: channel.h:797
static int iax2_queue_hangup(int callno)
Queue a hangup frame on the ast_channel owner.
Definition: chan_iax2.c:3067
static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force)
Definition: chan_iax2.c:12085
static int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
Definition: chan_iax2.c:2839
static int iax2_register(const char *value, int lineno)
Definition: chan_iax2.c:8663
const char * ast_config_AST_DATA_DIR
Definition: asterisk.c:262
static int replace_callno(const void *obj)
Definition: chan_iax2.c:2740
static void reload_firmware(int unload)
Definition: chan_iax2.c:3305
static struct ast_taskprocessor * transmit_processor
Definition: chan_iax2.c:867
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len)
Definition: md5.c:74
The AMI - Asterisk Manager Interface - is a TCP protocol created to manage Asterisk with third-party ...
#define AST_LIST_HEAD_NOLOCK(name, type)
Defines a structure to be used to hold a list of specified type (with no lock).
Definition: linkedlists.h:224
uint16_t callno
Definition: chan_iax2.c:936
static const char desc[]
Definition: cdr_radius.c:85
char secret[80]
Definition: chan_iax2.c:4645
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: utils.h:663
ast_aes_decrypt_key mydcx
Definition: chan_iax2.c:779
#define IAX_IE_CALLED_NUMBER
Definition: iax2.h:131
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
Definition: chan_iax2.c:5384
int ast_connected_line_parse_data(const unsigned char *data, size_t datalen, struct ast_party_connected_line *connected)
Parse connected line indication frame data.
Definition: channel.c:8886
const ast_string_field outkey
Definition: chan_iax2.c:508
static int iaxdynamicthreadcount
Definition: chan_iax2.c:636
int curauthreq
Definition: chan_iax2.c:480
static int iax2_poke_peer_s(const void *data)
Definition: chan_iax2.c:9228
#define AST_CAUSE_FACILITY_NOT_SUBSCRIBED
Definition: causes.h:125
static void iax2_frame_free(struct iax_frame *fr)
Definition: chan_iax2.c:1883
unsigned short ts
Definition: iax2.h:265
int ast_timer_ack(const struct ast_timer *handle, unsigned int quantity)
Acknowledge a timer event.
Definition: timing.c:172
char * path
Path to the node to retrieve.
Definition: data.h:267
#define IAX_IE_ADSICPE
Definition: iax2.h:142
static void set_peercnt_limit(struct peercnt *peercnt)
Definition: chan_iax2.c:2348
ast_control_frame_type
Internal control frame subtype field values.
Definition: frame.h:319
char * ast_getformatname(format_t format)
Get the name of a format.
Definition: frame.c:578
#define IAX_MAX_OSPBLOCK_SIZE
Definition: iax2.h:190
#define AST_OPTION_FLAG_REQUEST
Definition: frame.h:431
#define LOG_ERROR
Definition: logger.h:155
int ast_tvcmp(struct timeval _a, struct timeval _b)
Compres two struct timeval instances returning -1, 0, 1 if the first arg is smaller, equal or greater to the second.
Definition: time.h:120
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
Definition: chan_iax2.c:5743
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:716
static struct ast_data_entry iax2_data_providers[]
Definition: chan_iax2.c:14943
unsigned int final
Definition: iax2-parser.h:117
const void * scheddata
Definition: chan_iax2.c:1008
uint16_t cur
Definition: chan_iax2.c:916
#define IAX_CODEC_NOCAP
Definition: chan_iax2.c:423
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is &quot;true&quot;. This function checks to see whether a string passed to it is an indication of an &quot;true&quot; value. It checks to see if the string is &quot;yes&quot;, &quot;true&quot;, &quot;y&quot;, &quot;t&quot;, &quot;on&quot; or &quot;1&quot;.
Definition: utils.c:1533
const ast_string_field accountcode
Definition: chan_iax2.c:769
static int iaxcompat
Definition: chan_iax2.c:296
#define IAX_TRUNK
Definition: chan_iax2.c:410
int pokeexpire
Definition: chan_iax2.c:529
Implementation of Inter-Asterisk eXchange, version 2 iax2-parser.c iax2-parser.h chan_iax2.c.
The descriptor of a dynamic string XXX storage will be optimized later if needed We use the ts field ...
Definition: strings.h:364
static int iax2_vnak(int callno)
Definition: chan_iax2.c:9203
int64_t format_t
Definition: frame_defs.h:32
const char * file
Definition: config.h:85
unsigned int transfer
Definition: iax2-parser.h:115
static int maxauthreq
Definition: chan_iax2.c:280
const ast_string_field mohinterpret
Definition: chan_iax2.c:508
uint64_t flags
Definition: chan_iax2.c:477
static void destroy_firmware(struct iax_firmware *cur)
Definition: chan_iax2.c:3100
void * data
Definition: jitterbuf.h:100
static struct @350 args
const ast_string_field parkinglot
Definition: chan_iax2.c:471
void * data
Definition: iax2-parser.h:101
const ast_string_field peer
Definition: chan_iax2.c:769
#define CLI_SHOWUSAGE
Definition: cli.h:44
unsigned char csub
Definition: chan_iax2.c:1035
static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
Definition: chan_iax2.c:5995
static int peer_set_sock_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14665
#define ast_sockaddr_set_port(addr, port)
Sets the port number of a socket address.
Definition: netsock2.h:422
void ast_data_remove_node(struct ast_data *root, struct ast_data *child)
Remove a node that was added using ast_data_add_.
Definition: data.c:2486
#define AST_OPTION_RELAXDTMF
Definition: frame.h:449
static struct chan_iax2_pvt * iaxs[IAX_MAX_CALLS]
an array of iax2 pvt structures
Definition: chan_iax2.c:1067
unsigned short ts
Definition: iax2.h:243
int plan
Q.931 Type-Of-Number and Numbering-Plan encoded fields.
Definition: channel.h:243
int calling_pres
Definition: iax2-parser.h:32
#define AST_TEST_UNREGISTER(cb)
Definition: test.h:128
static void iax2_process_thread_cleanup(void *data)
Definition: chan_iax2.c:11866
static struct ast_codec_pref prefs
Definition: chan_iax2.c:258
int ast_remaining_ms(struct timeval start, int max_ms)
Calculate remaining milliseconds given a starting timestamp and upper bound.
Definition: utils.c:1615
static void iax_error_output(const char *data)
Definition: chan_iax2.c:1126
static char * handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Show one peer in detail.
Definition: chan_iax2.c:3835
unsigned short callno
Definition: iax2-parser.h:97
enum jb_return_code jb_setconf(jitterbuf *jb, jb_conf *conf)
set jitterbuf conf
Definition: jitterbuf.c:827
static struct ast_frame * iax2_read(struct ast_channel *c)
Definition: chan_iax2.c:5473
const ast_string_field mohsuggest
Definition: chan_iax2.c:769
static struct ast_netsock_list * outsock
Definition: chan_iax2.c:316
#define IAX_FORCEJITTERBUF
Definition: chan_iax2.c:427
#define IAX_IE_AUTHMETHODS
Definition: iax2.h:144
int ast_aes_set_decrypt_key(const unsigned char *key, ast_aes_decrypt_key *ctx)
Set a decryption key.
Definition: res_crypto.c:466
unsigned char cmddata
Definition: iax2.h:258
Event subscription.
Definition: event.c:124
static void __iax2_poke_peer_s(const void *data)
Definition: chan_iax2.c:9221
struct iax2_peer * peerpoke
Definition: chan_iax2.c:790
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
static struct iax2_user * user_unref(struct iax2_user *user)
Definition: chan_iax2.c:1811
int ast_cdr_amaflags2int(const char *flag)
Convert a string to a detail record AMA flag.
Definition: cdr.c:1105
char cid_name[80]
Definition: chan_iax2.c:4650
enum ast_channel_state _state
Definition: channel.h:839
char * language
Definition: iax2-parser.h:39
struct ast_channel * ast_bridged_channel(struct ast_channel *chan)
Find bridged channel.
Definition: channel.c:7160
char mohinterpret[MAX_MUSICCLASS]
Definition: chan_iax2.c:4653
const ast_string_field inkeys
Definition: chan_iax2.c:769
static int network_change_event_sched_cb(const void *data)
Definition: chan_iax2.c:1381
static int max_retries
Definition: chan_iax2.c:281
const ast_string_field mohinterpret
Definition: chan_iax2.c:471
#define AST_SENSE_ALLOW
Definition: acl.h:36
static int iax2_sendtext(struct ast_channel *c, const char *text)
Definition: chan_iax2.c:4391
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
Definition: utils.c:1587
Definition: chan_iax2.c:843
Connected Line/Party information.
Definition: channel.h:401
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
Definition: chan_iax2.c:2399
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2374
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
Definition: netsock2.h:210
ast_aes_encrypt_key ecx
Definition: iax2-parser.h:131
const ast_string_field name
Definition: channel.h:787
pthread_t threadid
Definition: chan_iax2.c:1014
static int min_reg_expire
Definition: chan_iax2.c:308
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
Definition: chan_iax2.c:4398
static struct ast_channel_tech iax2_tech
Definition: chan_iax2.c:1216
int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
Turn on music on hold on a given channel.
Definition: channel.c:8040
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7647
static int transmit_frame(void *data)
Definition: chan_iax2.c:4347
const ast_string_field mohsuggest
Definition: chan_iax2.c:508
static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
Definition: chan_iax2.c:9586
void ast_log(int level, const char *file, int line, const char *function, const char *fmt,...)
Used for sending a log message This is the standard logger function. Probably the only way you will i...
Definition: logger.c:1207
long ms
Definition: jitterbuf.h:102
struct in_addr mask
Definition: chan_iax2.c:514
#define AST_OPTION_SECURE_SIGNALING
Definition: frame.h:524
int _softhangup
Definition: channel.h:832
Do not require call token validation.
Definition: chan_iax2.c:455
static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:12240
unsigned int ts
Definition: iax2-parser.h:107
#define ast_cond_destroy(cond)
Definition: lock.h:168
unsigned short callno
Definition: chan_iax2.c:968
format_t ast_codec_choose(struct ast_codec_pref *pref, format_t formats, int find_best)
Select the best audio format according to preference list from supplied options. If &quot;find_best&quot; is no...
Definition: frame.c:1249
static int iaxdynamicthreadnum
Definition: chan_iax2.c:637
#define ao2_alloc(data_size, destructor_fn)
Definition: astobj2.h:430
struct ast_datastore * ast_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
Definition: datastore.c:98
#define AST_PRES_NUMBER_NOT_AVAILABLE
Definition: callerid.h:353
int ast_get_ip(struct ast_sockaddr *addr, const char *hostname)
Get the IP address given a hostname.
Definition: acl.c:700
#define DEFAULT_CONTEXT
Definition: chan_iax2.c:270
#define AST_LIST_LAST(head)
Returns the last entry contained in a list.
Definition: linkedlists.h:428
#define IAX_IE_PASSWORD
Definition: iax2.h:137
#define LOG_NOTICE
Definition: logger.h:133
const ast_string_field username
Definition: chan_iax2.c:508
char * rdnis
Definition: iax2-parser.h:43
static int trunk_maxmtu
Definition: chan_iax2.c:268
#define IAX_ALLOWFWDOWNLOAD
Definition: chan_iax2.c:433
static int pvt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14682
#define IAX_IE_MSGCOUNT
Definition: iax2.h:154
const ast_string_field ani
Definition: chan_iax2.c:769
unsigned char devname[16]
Definition: iax2.h:290
static int maxjitterinterps
Definition: chan_iax2.c:286
static int ast_data_retrieve_int(struct ast_data *tree, const char *path)
Retrieve the integer value of a node.
Definition: data.h:673
static int totalcalls
Definition: pbx.c:1229
static int trunkmaxsize
Definition: chan_iax2.c:292
struct ast_bridge * bridge
Definition: channel.h:865
struct timeval orig
Definition: chan_iax2.c:965
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
Definition: linkedlists.h:490
static struct ast_flags64 globalflags
Definition: chan_iax2.c:391
void iax_set_error(void(*func)(const char *))
Definition: iax2-parser.c:757
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
Definition: linkedlists.h:409
static struct ast_threadstorage buf1
#define AST_LIST_INSERT_HEAD(head, elm, field)
Inserts a list entry at the head of a list.
Definition: linkedlists.h:696
unsigned long addr
Definition: chan_iax2.c:914
static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
Parse the &quot;sourceaddress&quot; value, lookup in netsock list and set peer&#39;s sockfd. Defaults to defaults...
Definition: chan_iax2.c:12525
static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition: chan_iax2.c:6449
int ast_sign(struct ast_key *key, char *msg, char *sig)
Sign a message signature using a given private key.
Definition: res_crypto.c:394
const ast_string_field host
Definition: chan_iax2.c:769
static int iax2_encryption
Definition: chan_iax2.c:389
char outkey[80]
Definition: chan_iax2.c:4646
static const char tdesc[]
Definition: chan_iax2.c:260
uint64_t flags
Definition: chan_iax2.c:792
struct sched_context * ast_sched_thread_get_context(struct ast_sched_thread *st)
Get the scheduler context for a given ast_sched_thread.
Definition: sched.c:138
static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
callback to display iax peers in manager
Definition: chan_iax2.c:7098
static void vnak_retransmit(int callno, int last)
Definition: chan_iax2.c:9208
#define ao2_find(arg1, arg2, arg3)
Definition: astobj2.h:964
#define ast_channel_unlock(chan)
Definition: channel.h:2467
#define IAX_TRANSFERMEDIA
Definition: chan_iax2.c:430
#define IAX_IE_FWBLOCKDESC
Definition: iax2.h:165
char context[AST_MAX_CONTEXT]
Definition: chan_iax2.c:402
#define CLI_FAILURE
Definition: cli.h:45
static int addr_range_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:2240
int errno
char * calling_name
Definition: iax2-parser.h:29
struct chan_iax2_pvt::@88 dpentries
static void parse_dial_string(char *data, struct parsed_dial_string *pds)
Parses an IAX dial string into its component parts.
Definition: chan_iax2.c:5069
#define DEFAULT_MAXMS
Definition: chan_iax2.c:343
static void __iax2_poke_noanswer(const void *data)
Definition: chan_iax2.c:12205
static const char name[]
#define AST_MAX_CONTEXT
Definition: channel.h:136
struct ast_var_t::@158 entries
const char * ast_inet_ntoa(struct in_addr ia)
thread-safe replacement for inet_ntoa().
Definition: utils.c:564
#define AST_CAUSE_UNREGISTERED
Definition: causes.h:153
#define IAX_IE_RR_OOO
Definition: iax2.h:182
unsigned int authmethods
Definition: iax2-parser.h:44
format_t capability
Definition: chan_iax2.c:4637
#define AST_LIST_HEAD_INIT(head)
Initializes a list head structure.
Definition: linkedlists.h:611
format_t chosenformat
Definition: chan_iax2.c:698
#define ast_free(a)
Definition: astmm.h:97
char * command
Definition: cli.h:180
unsigned char calltoken
Definition: iax2-parser.h:81
AES_KEY ast_aes_decrypt_key
Definition: crypto.h:36
static int user_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:1748
static void cleanup_thread_list(void *head)
Definition: chan_iax2.c:14554
struct ast_jb jb
Definition: channel.h:821
unsigned char iseqno
Definition: iax2.h:227
int ast_str2cos(const char *value, unsigned int *cos)
Convert a string to the appropriate COS value.
Definition: acl.c:653
#define IAX_IE_CODEC_PREFS
Definition: iax2.h:175
int ast_register_switch(struct ast_switch *sw)
Register an alternative dialplan switch.
Definition: pbx.c:6439
int retrytime
Definition: iax2-parser.h:109
static int randomcalltokendata
Definition: chan_iax2.c:869
unsigned char * trunkdata
Definition: chan_iax2.c:557
#define CALLNO_TO_PTR(a)
Definition: chan_iax2.c:243
static int iax_check_version(char *dev)
Definition: chan_iax2.c:3246
static struct ast_format f[]
Definition: format_g726.c:181
static void insert_idle_thread(struct iax2_thread *thread)
Definition: chan_iax2.c:1462
#define IAX_RTIGNOREREGEXPIRE
Definition: chan_iax2.c:428
int ast_write(struct ast_channel *chan, struct ast_frame *frame)
Write a frame to a channel This function writes the given frame to the indicated channel.
Definition: channel.c:4916
static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition: chan_iax2.c:6363
int maxms
Definition: chan_iax2.c:531
const char * word
Definition: cli.h:157
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7637
static format_t capability
Definition: chan_mgcp.c:228
char * called_number
Definition: iax2-parser.h:26
char callednum[AST_MAX_EXTENSION]
Definition: chan_iax2.c:9357
static int cache_get_callno_locked(const char *data)
Definition: chan_iax2.c:13814
static int get_auth_methods(const char *value)
Definition: chan_iax2.c:12484
struct ast_variable * vars
Definition: chan_iax2.c:484
#define DATASTORE_INHERIT_FOREVER
Definition: channel.h:156
#define IAX_IMMEDIATE
Definition: chan_iax2.c:434
#define IAX_NOTRANSFER
Definition: chan_iax2.c:411
char context[AST_MAX_EXTENSION]
Definition: chan_iax2.c:9356
struct timeval trunkact
Definition: chan_iax2.c:554
ssize_t buf_len
Definition: chan_iax2.c:1019
const ast_string_field cid_num
Definition: chan_iax2.c:508
An API for managing task processing threads that can be shared across modules.
unsigned int inheritance
Definition: datastore.h:58
static int iaxthreadcount
Definition: chan_iax2.c:634
int tm_hour
Definition: localtime.h:38
static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
Send manager event at call setup to link between Asterisk channel name and IAX2 call identifiers...
Definition: chan_iax2.c:1406
int ast_timer_fd(const struct ast_timer *handle)
Get a poll()-able file descriptor for a timer.
Definition: timing.c:158
int ast_timer_set_rate(const struct ast_timer *handle, unsigned int rate)
Set the timing tick rate.
Definition: timing.c:163
int iax_ie_append_raw(struct iax_ie_data *ied, unsigned char ie, const void *data, int datalen)
Definition: iax2-parser.c:693
int losscnt
Definition: chan_iax2.c:643
static int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition: chan_iax2.c:9282
struct sockaddr_in addr
Definition: chan_iax2.c:550
if(yyss+yystacksize-1<=yyssp)
Definition: ast_expr2.c:1874
static struct iax2_dpcache * find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
Definition: chan_iax2.c:13887
static const char type[]
Definition: chan_nbs.c:57
#define IAX_MAX_CALLS
Definition: iax2.h:37
static void __auto_congest(const void *nothing)
Definition: chan_iax2.c:4758
unsigned char buf[1024]
Definition: iax2-parser.h:147
#define IAX_IE_OSPTOKEN
Definition: iax2.h:184
struct iax2_dpcache::@91 peer_list
#define ast_set2_flag64(p, value, flag)
Definition: utils.h:151
int encmethods
Definition: iax2-parser.h:129
structure to hold users read from users.conf
void ao2_iterator_destroy(struct ao2_iterator *i)
Destroy a container iterator.
Definition: astobj2.c:833
#define ast_string_field_build(x, field, fmt, args...)
Set a field to a complex (built) value.
Definition: stringfields.h:367
static void * cleanup(void *unused)
Definition: pbx_realtime.c:125
static void reg_source_db(struct iax2_peer *p)
Definition: chan_iax2.c:8782
Structure used to handle boolean flags.
Definition: utils.h:200
static void * network_thread(void *ignore)
Definition: chan_iax2.c:12408
static int iax2_poke_noanswer(const void *data)
Definition: chan_iax2.c:12228
static int create_callno_pools(void)
Definition: chan_iax2.c:2770
static char * handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3941
struct iax_rr remote_rr
Definition: chan_iax2.c:828
ast_mutex_t init_lock
Definition: chan_iax2.c:1025
#define ast_clear_flag64(p, flag)
Definition: utils.h:134
int ast_realtime_require_field(const char *family,...) attribute_sentinel
Inform realtime what fields that may be stored.
Definition: config.c:2606
#define IAX_DPSTATUS_CANEXIST
Definition: iax2.h:216
#define FORMAT2
#define ast_clear_flag(p, flag)
Definition: utils.h:77
#define IAX_CAPABILITY_MEDBANDWIDTH
Definition: chan_iax2.c:324
uint8_t data[0]
Definition: frame.h:545
Definition: md5.h:26
static char cid_name[AST_MAX_EXTENSION]
Definition: chan_mgcp.c:158
struct timeval delivery
Definition: frame.h:162
static char * regstate2str(int regstate)
Definition: chan_iax2.c:7167
static struct ast_cli_entry cli_iax2[]
Definition: chan_iax2.c:14403
char peercontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:963
format_t capability
Definition: chan_iax2.c:478
static void iax2_lock_owner(int callno)
Definition: chan_iax2.c:1260
int mallocd
Definition: frame.h:152
unsigned short rr_delay
Definition: iax2-parser.h:75
static int user_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:1758
static int expire_registry(const void *data)
Definition: chan_iax2.c:8773
const ast_string_field context
Definition: chan_iax2.c:508
int pokefreqnotok
Definition: chan_iax2.c:534
const char * usage
Definition: cli.h:171
static int send_packet(struct iax_frame *f)
Definition: chan_iax2.c:3418
static struct iax2_user * find_user(const char *name)
Definition: chan_iax2.c:1797
int ast_get_ip_or_srv(struct ast_sockaddr *addr, const char *hostname, const char *service)
Get the IP address given a hostname and optional service.
Definition: acl.c:597
static int start_network_thread(void)
Definition: chan_iax2.c:12427
int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
Add a variable to the channel variable stack, removing the most recently set value for the same name...
Definition: pbx.c:10546
uint32_t ast_event_get_ie_uint(const struct ast_event *event, enum ast_event_ie_type ie_type)
Get the value of an information element that has an integer payload.
Definition: event.c:1075
ast_cond_t init_cond
Definition: chan_iax2.c:1026
static int reload_config(void)
Definition: chan_iax2.c:13760
unsigned char encdata[0]
Definition: iax2.h:252
struct ast_sockaddr addr
Definition: chan_iax2.c:511
static char * handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Set trunk MTU from CLI.
Definition: chan_iax2.c:3987
int iax_ie_append(struct iax_ie_data *ied, unsigned char ie)
Definition: iax2-parser.c:747
ast_mutex_t lock
Definition: chan_iax2.c:1023
#define IAX_IE_CALLINGTON
Definition: iax2.h:169
int tm_sec
Definition: localtime.h:36
int amaflags
Definition: chan_iax2.c:475
void ast_free_ha(struct ast_ha *ha)
Free a list of HAs.
Definition: acl.c:223
#define IAX_IE_REFRESH
Definition: iax2.h:149
#define AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
Definition: callerid.h:332
unsigned char readbuf[4096]
Definition: chan_iax2.c:1017
#define EVENT_FLAG_REPORTING
Definition: manager.h:80
#define CLI_SUCCESS
Definition: cli.h:43
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2204
static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
Check if address can be used as packet source.
Definition: chan_iax2.c:12500
struct ast_event_sub * mwi_event_sub
Definition: chan_iax2.c:539
const ast_string_field secret
Definition: chan_iax2.c:508
char curfunc[80]
Definition: chan_iax2.c:1011
size_t ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition: strings.h:471
static int get_from_jb(const void *p)
Definition: chan_iax2.c:4228
#define IAX_RTAUTOCLEAR
Definition: chan_iax2.c:426
void * data
Definition: datastore.h:56
static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
Definition: chan_iax2.c:9575
int transit_network_select
Transit Network Select.
Definition: channel.h:347
struct hostent * ast_gethostbyname(const char *host, struct ast_hostent *hp)
Thread-safe gethostbyname function to use in Asterisk.
Definition: utils.c:195
#define AST_LIST_HEAD_INIT_NOLOCK(head)
Initializes a list head structure.
Definition: linkedlists.h:666
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
Definition: chan_iax2.c:6410
static char secret[50]
Definition: chan_h323.c:148
const ast_string_field mohsuggest
Definition: chan_iax2.c:471
char hold_signaling
Definition: chan_iax2.c:838
int maxauthreq
Definition: chan_iax2.c:479
static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition: chan_iax2.c:8424
struct ast_variable * vars
Definition: iax2-parser.h:78
A ast_taskprocessor structure is a singleton by name.
Definition: taskprocessor.c:67
#define AST_CAUSE_NO_ROUTE_DESTINATION
Definition: causes.h:99
#define IAX_IE_CALLINGPRES
Definition: iax2.h:168
static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
Definition: chan_iax2.c:8836
void ast_event_destroy(struct ast_event *event)
Destroy an event.
Definition: event.c:1314
#define IAX_ALREADYGONE
Definition: chan_iax2.c:416
#define AST_FORMAT_SLINEAR
Definition: frame.h:254
#define ast_channel_ref(c)
Increase channel reference count.
Definition: channel.h:2491
int ast_add_extension(const char *context, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void(*datad)(void *), const char *registrar)
Add and extension to an extension context.
Definition: pbx.c:8691
static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
Definition: chan_iax2.c:2862
#define IAX_PROTO_VERSION
Definition: iax2.h:27
When we need to walk through a container, we use an ao2_iterator to keep track of the current positio...
Definition: astobj2.h:1053
static struct io_context * io
Definition: chan_iax2.c:364
static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
Definition: chan_iax2.c:7915
#define IAX_IE_RDNIS
Definition: iax2.h:158
int ast_netsock_init(struct ast_netsock_list *list)
Definition: netsock.c:76
static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
Definition: chan_iax2.c:7668
static int adsi
Definition: chan_iax2.c:387
Standard Command Line Interface.
static void update_jbsched(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:4135
format_t readformat
Definition: channel.h:853
int musiconhold
Definition: iax2-parser.h:58
int ast_db_del(const char *family, const char *key)
Delete entry in astdb.
Definition: db.c:365
#define ast_calloc(a, b)
Definition: astmm.h:82
struct ast_event_sub * ast_event_subscribe(enum ast_event_type event_type, ast_event_cb_t cb, const char *description, void *userdata,...)
Subscribe to events.
Definition: event.c:909
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:223
static int iaxdefaulttimeout
Definition: chan_iax2.c:301
#define ao2_container_alloc(arg1, arg2, arg3)
Definition: astobj2.h:734
static int authdebug
Definition: chan_iax2.c:294
int ast_dnsmgr_lookup(const char *name, struct ast_sockaddr *result, struct ast_dnsmgr_entry **dnsmgr, const char *service)
Allocate and initialize a DNS manager entry.
Definition: dnsmgr.c:180
#define IAX_IE_USERNAME
Definition: iax2.h:136
int adsi
Definition: chan_iax2.c:515
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one...
Definition: strings.h:77
void * ast_taskprocessor_unreference(struct ast_taskprocessor *tps)
Unreference the specified taskprocessor and its reference count will decrement.
struct timeval ast_tv(ast_time_t sec, ast_suseconds_t usec)
Returns a timeval from sec, usec.
Definition: time.h:179
ast_app: A registered application
Definition: pbx.c:971
static void prune_peers(void)
Definition: chan_iax2.c:13232
#define DATA_EXPORT_IAX2_USER(MEMBER)
Definition: chan_iax2.c:14847
unsigned char rseqno
Definition: chan_iax2.c:724
int ast_codec_get_samples(struct ast_frame *f)
Returns the number of samples contained in the frame.
Definition: frame.c:1470
unsigned char chksum[16]
Definition: iax2.h:292
int attribute_pure ast_false(const char *val)
Make sure something is false. Determine if a string containing a boolean value is &quot;false&quot;...
Definition: utils.c:1550
Implementation of the IAX2 protocol.
#define IAX_IE_RR_DROPPED
Definition: iax2.h:181
int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
Register multiple commands.
Definition: cli.c:2167
const int pos
Definition: cli.h:158
#define AST_OPTION_RXGAIN
Definition: frame.h:463
static char * handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3660
#define ast_realloc(a, b)
Definition: astmm.h:103
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2194
char secret[80]
Definition: chan_iax2.c:604
char timezone[80]
Definition: chan_iax2.c:4647
int iax_ie_append_int(struct iax_ie_data *ied, unsigned char ie, unsigned int value)
Definition: iax2-parser.c:723
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2223
#define IAX_KEYPOPULATED
Definition: chan_iax2.c:420
enum jb_return_code jb_getinfo(jitterbuf *jb, jb_info *stats)
get jitterbuf info: only &quot;statistics&quot; may be valid
Definition: jitterbuf.c:817
int ast_setstate(struct ast_channel *chan, enum ast_channel_state)
Change the state of a channel.
Definition: channel.c:7119
static struct iax2_trunk_peer * find_tpeer(struct sockaddr_in *sin, int fd)
Definition: chan_iax2.c:6182
struct ast_channel * owner
Definition: chan_iax2.c:716
int ast_async_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
Set the channel to next execute the specified dialplan location.
Definition: pbx.c:8731
static struct iax2_peer * peer_ref(struct iax2_peer *peer)
Definition: chan_iax2.c:1785
const ast_string_field mailbox
Definition: chan_iax2.c:508
unsigned int rr_pkts
Definition: iax2-parser.h:74
struct ast_sockaddr addr
Definition: chan_iax2.c:602
static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char *const argv[])
Definition: chan_iax2.c:6760
char cid_num[80]
Definition: chan_iax2.c:4649
const ast_string_field cid_name
Definition: chan_iax2.c:769
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7612
int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control, const void *data, size_t datalen)
Queue a control frame with payload.
Definition: channel.c:1608
static int users_data_provider_get(const struct ast_data_search *search, struct ast_data *data_root)
Definition: chan_iax2.c:14863
static int apply_context(struct iax2_context *con, const char *context)
Definition: chan_iax2.c:7657
Application convenience functions, designed to give consistent look and feel to Asterisk apps...
static void prune_users(void)
Definition: chan_iax2.c:13216
#define AST_CAUSE_BUSY
Definition: causes.h:148
#define DEFAULT_TRUNKDATA
Definition: chan_iax2.c:624
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame)
Definition: chan_iax2.c:3029
char * ast_getformatname_multiple(char *buf, size_t size, format_t format)
Get the names of a set of formats.
Definition: frame.c:591
int ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
Check the authenticity of a message signature using a given public key.
Definition: res_crypto.c:440
struct ast_dnsmgr_entry * dnsmgr
Definition: chan_iax2.c:510
long min
Definition: jitterbuf.h:85
const ast_string_field accountcode
Definition: channel.h:787
#define IAX_IE_RR_PKTS
Definition: iax2.h:179
static char * handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:2638
Data structure associated with a single frame of data.
Definition: frame.h:142
static void jb_warning_output(const char *fmt,...)
Definition: chan_iax2.c:1143
#define AST_DATA_STRUCTURE(__struct, __name)
Definition: data.h:300
#define IAX_FLAG_FULL
Definition: iax2.h:40
int hangupcause
Definition: channel.h:849
struct callno_entry * callno_entry
Definition: chan_iax2.c:692
#define IAX_IE_CAUSE
Definition: iax2.h:152
Internal Asterisk hangup causes.
static char regcontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:275
static int authenticate_request(int call_num)
Definition: chan_iax2.c:7936
static int auth_reject(const void *data)
Definition: chan_iax2.c:9132
#define IAX_MAXAUTHREQ
Definition: chan_iax2.c:431
static int total
Definition: res_adsi.c:967
void ast_context_destroy(struct ast_context *con, const char *registrar)
Destroy a context (matches the specified context (or ANY context if NULL)
Definition: pbx.c:9875
#define IAX_IE_RSA_RESULT
Definition: iax2.h:147
#define AST_TEST_DEFINE(hdr)
Definition: test.h:126
void ast_codec_pref_convert(struct ast_codec_pref *pref, char *buf, size_t size, int right)
Shift an audio codec preference list up or down 65 bytes so that it becomes an ASCII string...
Definition: frame.c:1002
unsigned int ospblocklength[IAX_MAX_OSPBLOCK_NUM]
Definition: iax2-parser.h:80
static void encmethods_to_str(int e, struct ast_str **buf)
Definition: chan_iax2.c:1625
static void network_change_event_unsubscribe(void)
Definition: chan_iax2.c:1374
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2248
static uint16_t global_maxcallno
Definition: chan_iax2.c:903
static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
All frames other than that of type AST_FRAME_IAX must be held until we have received a destination ca...
Definition: chan_iax2.c:1926
char * password
Definition: iax2-parser.h:35
struct ast_ha * ha
Definition: chan_iax2.c:482
int(* ast_sched_cb)(const void *data)
callback for a cheops scheduler A cheops scheduler callback takes a pointer with callback data and ...
Definition: sched.h:160
static int iax2_do_register_s(const void *data)
Definition: chan_iax2.c:8415
IAX2 Provisioning protocol.
int ast_dnsmgr_changed(struct ast_dnsmgr_entry *entry)
Check is see if a dnsmgr entry has changed.
Definition: dnsmgr.c:238
format_t svoiceformat
Definition: chan_iax2.c:660
const ast_string_field cid_name
Definition: chan_iax2.c:508
#define IAX_IE_FWBLOCKDATA
Definition: iax2.h:166
static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
Definition: chan_iax2.c:5512
const char * name
Definition: pbx.h:96
static void stop_stuff(int callno)
Definition: chan_iax2.c:9107
char * calling_ani
Definition: iax2-parser.h:28
static int iax2_digit_begin(struct ast_channel *c, char digit)
Definition: chan_iax2.c:4381
struct ast_ha * ast_append_ha(const char *sense, const char *stuff, struct ast_ha *path, int *error)
Add a new rule to a list of HAs.
Definition: acl.c:399
int ast_db_put(const char *family, const char *key, const char *value)
Store value addressed by family/key.
Definition: db.c:260
#define IAX_IE_CALLED_CONTEXT
Definition: iax2.h:135
static int iax2_append_register(const char *hostname, const char *username, const char *secret, const char *porta)
Definition: chan_iax2.c:8633
#define IAX_AUTH_PLAINTEXT
Definition: iax2.h:195
struct timeval ast_tvsub(struct timeval a, struct timeval b)
Returns the difference of two timevals a - b.
Definition: utils.c:1601
Channels have this property if they can accept input with jitter; i.e. most VoIP channels.
Definition: channel.h:883
#define ast_sockaddr_to_sin(addr, sin)
Converts a struct ast_sockaddr to a struct sockaddr_in.
Definition: netsock2.h:629
#define ast_set_flags_to64(p, flag, value)
Definition: utils.h:161
unsigned short zeros
Definition: iax2.h:263
void iax_frame_free(struct iax_frame *fr)
Definition: iax2-parser.c:1241
int ast_sched_thread_add(struct ast_sched_thread *st, int when, ast_sched_cb cb, const void *data)
Add a scheduler entry.
Definition: sched.c:210
format_t peercapability
Definition: chan_iax2.c:702
static int pvt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:14675
int ast_parking_ext_valid(const char *exten_str, struct ast_channel *chan, const char *context)
Determine if parking extension exists in a given context.
Definition: features.c:844
#define AST_LIST_TRAVERSE_SAFE_BEGIN(head, var, field)
Loops safely over (traverses) the entries in a list.
Definition: linkedlists.h:528
enum ast_frame_type frametype
Definition: frame.h:144
struct ast_variable * next
Definition: config.h:82
#define DONT_RESCHEDULE
Definition: chan_iax2.c:367
#define IAX_ENCRYPT_AES128
Definition: iax2.h:199
static int __schedule_action(void(*func)(const void *data), const void *data, const char *funcname)
Definition: chan_iax2.c:1544
static struct adsi_event events[]
Definition: app_adsiprog.c:78
#define IAX_IE_APPARENT_ADDR
Definition: iax2.h:148
char context[AST_MAX_CONTEXT]
Definition: chan_iax2.c:4651
static int iax2_hangup(struct ast_channel *c)
Definition: chan_iax2.c:5317
#define ast_mutex_init(pmutex)
Definition: lock.h:152
long jitter
Definition: jitterbuf.h:84
const ast_string_field parkinglot
Definition: chan_iax2.c:508
ast_aes_encrypt_key tdcx
Definition: chan_iax2.c:804
#define ast_channel_trylock(chan)
Definition: channel.h:2468
#define ast_frfree(fr)
Definition: frame.h:583
static int get_encrypt_methods(const char *s)
Definition: chan_iax2.c:1641
unsigned char valid
TRUE if the name information is valid/present.
Definition: channel.h:229
static int attempt_transmit(const void *data)
Definition: chan_iax2.c:3651
int authmethods
Definition: chan_iax2.c:473
#define IAX_AUTH_MD5
Definition: iax2.h:196
static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame)
Definition: chan_iax2.c:3025
void jb_destroy(jitterbuf *jb)
destroy jitterbuf
Definition: jitterbuf.c:101
#define CONFIG_STATUS_FILEINVALID
Definition: config.h:52
static char context[AST_MAX_CONTEXT]
Definition: chan_alsa.c:107
int iax_ie_append_byte(struct iax_ie_data *ied, unsigned char ie, unsigned char dat)
Definition: iax2-parser.c:742
Call Parking and Pickup API Includes code and algorithms from the Zapata library. ...
const ast_string_field dbsecret
Definition: chan_iax2.c:508
int jitter
Definition: chan_iax2.c:641
#define ast_mutex_destroy(a)
Definition: lock.h:154
static int last_authmethod
Definition: chan_iax2.c:297
A query to the data API is specified in this structure.
Definition: data.h:263
unsigned short callno
Definition: chan_iax2.c:690
#define IAX_SENDCONNECTEDLINE
Definition: chan_iax2.c:435
struct ast_context * ast_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar)
Register a new context or find an existing one.
Definition: pbx.c:7726
const ast_string_field cid_name
Definition: chan_iax2.c:471
#define AST_LIST_INSERT_BEFORE_CURRENT(elm, field)
Inserts a list entry before the current entry during a traversal.
Definition: linkedlists.h:584
static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Part of the IAX2 switch interface.
Definition: chan_iax2.c:14020
static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
Definition: chan_iax2.c:5966
unsigned short refresh
Definition: iax2-parser.h:50
uint32_t buf[4]
Definition: md5.h:27
int adsi
Definition: chan_iax2.c:476
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
Definition: chan_iax2.c:7352
static int iax2_prov_app(struct ast_channel *chan, const char *data)
Definition: chan_iax2.c:12137
static unsigned int cos
Definition: chan_h323.c:147
const ast_string_field context
Definition: chan_iax2.c:769
static int peer_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:13169
unsigned int lastsent
Definition: chan_iax2.c:668
struct sockaddr_in sin
Definition: chan_iax2.c:1033
#define IAX_MAX_SHIFT
Definition: iax2.h:46
#define IAX_IE_TRANSFERID
Definition: iax2.h:157
void ast_shrink_phone_number(char *n)
Shrink a phone number in place to just digits (more accurately it just removes ()&#39;s, .&#39;s, and -&#39;s...
Definition: callerid.c:948
char * cause
Definition: iax2-parser.h:53
struct timeval rxtrunktime
Definition: chan_iax2.c:552
static int iax2_key_rotate(const void *vpvt)
Definition: chan_iax2.c:5479
static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
Definition: chan_iax2.c:9055
#define MIN_REUSE_TIME
Definition: chan_iax2.c:253
struct ast_iax2_firmware_header * fwh
Definition: chan_iax2.c:573
#define TRUNK_CALL_START
Definition: chan_iax2.c:1098
static format_t iax2_capability
Definition: chan_iax2.c:369
#define IAX_IE_FORMAT
Definition: iax2.h:139
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:38
#define AST_CAUSE_CALL_REJECTED
Definition: causes.h:110
static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
Definition: chan_iax2.c:9404
unsigned short dcallno
Definition: iax2-parser.h:99
#define manager_event(category, event, contents,...)
External routines may send asterisk manager events this way.
Definition: manager.h:219
const ast_string_field secret
Definition: chan_iax2.c:471
static struct ast_timer * timer
Definition: chan_iax2.c:313
#define RESULT_SUCCESS
Definition: cli.h:39
#define AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
Definition: causes.h:129
#define ast_malloc(a)
Definition: astmm.h:91
struct ast_data * ast_data_add_str(struct ast_data *root, const char *childname, const char *string)
Add a string node type.
Definition: data.c:2401
Asterisk module definitions.
const ast_string_field cid_num
Definition: chan_iax2.c:471
static struct hostent * hp
Definition: chan_skinny.c:1048
#define IAX_FLAG_RETRANS
Definition: iax2.h:42
int iax_ie_append_str(struct iax_ie_data *ied, unsigned char ie, const char *str)
Definition: iax2-parser.c:737
static void peercnt_remove(struct peercnt *peercnt)
Definition: chan_iax2.c:2484
MD5 digest functions.
int amaflags
Definition: channel.h:843
enum jb_return_code jb_getall(jitterbuf *jb, jb_frame *frameout)
unconditionally get frames from jitterbuf until empty
Definition: jitterbuf.c:803
static snd_pcm_format_t format
Definition: chan_alsa.c:93
union ast_frame::@172 data
static int trunk_nmaxmtu
Definition: chan_iax2.c:268
struct ast_channel_tech * tech
Definition: channel.h:743
static int global_rtautoclear
Definition: chan_iax2.c:439
static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
Definition: chan_iax2.c:2069
enum calltoken_peer_enum calltoken_required
Definition: chan_iax2.c:542
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
Add a datastore to a channel.
Definition: channel.c:2590
int iax_provision_unload(void)
format_t capability
Definition: chan_iax2.c:525
Persistant data storage (akin to *doze registry)
static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
Definition: chan_iax2.c:9559
struct ast_data * ast_data_add_int(struct ast_data *root, const char *childname, int value)
Add an integer node type.
Definition: data.c:2322
int frames_received
Definition: chan_iax2.c:834
static int(* iax2_regfunk)(const char *username, int onoff)
Definition: chan_iax2.c:319
#define ast_string_field_free_memory(x)
free all memory - to be called before destroying the object
Definition: stringfields.h:253
struct ast_event_sub * ast_event_unsubscribe(struct ast_event_sub *event_sub)
Un-subscribe from events.
Definition: event.c:987
iax_transfer_state
Definition: chan_iax2.c:587
ast_context: An extension context
Definition: pbx.c:955
static struct ao2_container * callno_limits
Definition: chan_iax2.c:894
long current
Definition: jitterbuf.h:86
static char * handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7280
#define IAX_MAX_OSPBUFF_SIZE
Definition: iax2.h:193
static struct ast_switch iax2_switch
Definition: chan_iax2.c:14289
unsigned char valid
TRUE if the number information is valid/present.
Definition: channel.h:247
long len
Definition: frame.h:170
unsigned char metacmd
Definition: iax2.h:257
static int peer_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:1738
#define ao2_unlink(arg1, arg2)
Definition: astobj2.h:817
#define ast_cond_timedwait(cond, mutex, time)
Definition: lock.h:172
static struct ast_custom_function iaxvar_function
Definition: chan_iax2.c:10024
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
Definition: chan_iax2.c:6142
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2262
int inet_aton(const char *cp, struct in_addr *pin)
int ast_data_search_match(const struct ast_data_search *search, struct ast_data *data)
Check the current generated node to know if it matches the search condition.
Definition: data.c:1458
#define ast_custom_function_register(acf)
Register a custom function.
Definition: pbx.h:1164
#define ACN_FORMAT2
const ast_string_field language
Definition: channel.h:787
#define IAX_RTUPDATE
Definition: chan_iax2.c:425
static int network_change_event_sched_id
Definition: chan_iax2.c:278
uint32_t version
Structure version.
Definition: data.h:247
static int iax2_do_register(struct iax2_registry *reg)
Definition: chan_iax2.c:12024
#define AST_CAUSE_CONGESTION
Definition: causes.h:152
struct ast_context * ast_context_find(const char *name)
Find a context.
Definition: pbx.c:2971
static void build_callno_limits(struct ast_variable *v)
Definition: chan_iax2.c:2542
#define IAX_IE_CAPABILITY
Definition: iax2.h:138
static struct ast_channel * ast_iax2_new(int callno, int state, format_t capability, const char *linkedid, unsigned int cachable)
Create new call, interface with the PBX core.
Definition: chan_iax2.c:5838
long max_contig_interp
Definition: jitterbuf.h:69
#define AST_KEY_PUBLIC
Definition: crypto.h:42
#define AST_BRIDGE_DTMF_CHANNEL_0
Report DTMF on channel 0.
Definition: channel.h:1932
int ast_do_masquerade(struct ast_channel *chan)
Start masquerading a channel.
Definition: channel.c:6546
char exten[AST_MAX_EXTENSION]
Definition: channel.h:869
Timing source management.
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
Definition: chan_iax2.c:1052
#define ast_register_application_xml(app, execute)
Register an application using XML documentation.
Definition: module.h:437
struct ast_key * ast_key_get(const char *key, int type)
Retrieve a key.
Definition: res_crypto.c:136
struct ast_variable * ast_variable_new(const char *name, const char *value, const char *filename)
Definition: config.c:278
int waiters[256]
Definition: chan_iax2.c:969
const ast_string_field peercontext
Definition: chan_iax2.c:508
int tm_min
Definition: localtime.h:37
Structure for mutex and tracking information.
Definition: lock.h:121
static int iax2_is_control_frame_allowed(int subtype)
Definition: chan_iax2.c:1284
#define RESULT_FAILURE
Definition: cli.h:41
static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
Definition: chan_iax2.c:6339
static char mailbox[AST_MAX_EXTENSION]
Definition: chan_mgcp.c:197
char * dnid
Definition: iax2-parser.h:42
format_t ast_translator_best_choice(format_t *dsts, format_t *srcs)
Chooses the best translation path.
Definition: translate.c:984
int ast_parse_allow_disallow(struct ast_codec_pref *pref, format_t *mask, const char *list, int allowing)
Parse an &quot;allow&quot; or &quot;deny&quot; line in a channel or device configuration and update the capabilities mask...
Definition: frame.c:1272
static format_t uncompress_subclass(unsigned char csub)
Definition: chan_iax2.c:1711
The structure of the node handler.
Definition: data.h:245
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2268
#define CALLTOKEN_IE_FORMAT
int ast_manager_unregister(char *action)
Unregister a registered manager command.
Definition: manager.c:5355
jack_status_t status
Definition: app_jack.c:143
unsigned int trunkdataalloc
Definition: chan_iax2.c:559
static int add_calltoken_ignore(const char *addr)
Definition: chan_iax2.c:2597
#define ASTERISK_FILE_VERSION(file, version)
Register/unregister a source code file with the core.
Definition: asterisk.h:180
static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:8230
#define AST_OPTION_TXGAIN
Definition: frame.h:458
int samples
Definition: frame.h:150
Mailbox name.
Definition: event_defs.h:83
static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14700
static char * ast_sockaddr_stringify_host(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return an address only, suitable for a URL (with brack...
Definition: netsock2.h:271
uint64_t flags
Definition: chan_iax2.c:4638
char * callerid
Definition: chan_iax2.c:9358
#define CONFIG_STATUS_FILEUNCHANGED
Definition: config.h:51
#define ast_mutex_unlock(a)
Definition: lock.h:156
unsigned int refresh
void ast_copy_ha(const struct ast_ha *from, struct ast_ha *to)
Copy the contents of one HA to another.
Definition: acl.c:234
static char hostname[MAXHOSTNAMELEN]
Definition: logger.c:91
unsigned int ts
Definition: iax2.h:225
void ast_codec_pref_prepend(struct ast_codec_pref *pref, format_t format, int only_if_existing)
Prepend an audio codec to a preference list, removing it first if it was already there.
Definition: frame.c:1125
static void peer_destructor(void *obj)
Definition: chan_iax2.c:12598
ast_bridge_result
Definition: channel.h:168
static force_inline int attribute_pure ast_str_hash(const char *str)
Compute a hash value on a string.
Definition: strings.h:949
#define AST_SCHED_DEL_SPINLOCK(sched, id, lock)
schedule task to get deleted releasing the lock between attempts
Definition: sched.h:86
static void __expire_registry(const void *data)
Definition: chan_iax2.c:8737
#define IAX_DPSTATUS_EXISTS
Definition: iax2.h:215
void jb_reset(jitterbuf *jb)
reset jitterbuf
Definition: jitterbuf.c:74
unsigned int outoforder
Definition: iax2-parser.h:111
#define ACN_FORMAT1
#define ast_string_field_set(x, field, data)
Set a field to a simple string value.
Definition: stringfields.h:344
#define IAX_TEMPONLY
Definition: chan_iax2.c:409
static struct ao2_container * peercnts
Definition: chan_iax2.c:891
static int reload(void)
Definition: chan_iax2.c:13809
#define DEFAULT_FREQ_NOTOK
Definition: chan_iax2.c:345
size_t len
Definition: chan_iax2.c:998
void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
Send ack in manager list transaction.
Definition: manager.c:2145
static char * handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7066
struct ast_module * ast_module_ref(struct ast_module *)
Definition: loader.c:1300
struct ast_data * ast_data_add_password(struct ast_data *root, const char *childname, const char *string)
Add a password node type.
Definition: data.c:2380
struct ast_party_number number
Subscriber phone number.
Definition: channel.h:292
static int auth_fail(int callno, int failcode)
Definition: chan_iax2.c:9146
#define ast_test_flag64(p, flag)
Definition: utils.h:120
int ast_park_call_exten(struct ast_channel *park_me, struct ast_channel *parker, const char *park_exten, const char *park_context, int timeout, int *extout)
Park a call and read back parked location.
Definition: features.c:1655
struct io_context * io_context_create(void)
Creates a context Create a context for I/O operations Basically mallocs an IO structure and sets up s...
Definition: io.c:76
static const char * ast_data_retrieve_string(struct ast_data *tree, const char *path)
Retrieve the string value of a node.
Definition: data.h:748
struct ast_channel * chan1
Definition: chan_iax2.c:9423