![]() |
Home page |
Mailing list |
Docs
Asterisk developer's documentation :: Codename Pineapple
chan_iax2.c
Go to the documentation of this file.
00001 /* 00002 * Asterisk -- An open source telephony toolkit. 00003 * 00004 * Copyright (C) 1999 - 2006, Digium, Inc. 00005 * 00006 * Mark Spencer <markster@digium.com> 00007 * 00008 * See http://www.asterisk.org for more information about 00009 * the Asterisk project. Please do not directly contact 00010 * any of the maintainers of this project for assistance; 00011 * the project provides a web site, mailing lists and IRC 00012 * channels for your use. 00013 * 00014 * This program is free software, distributed under the terms of 00015 * the GNU General Public License Version 2. See the LICENSE file 00016 * at the top of the source tree. 00017 */ 00018 00019 /*! \file 00020 * 00021 * \brief Implementation of Inter-Asterisk eXchange Version 2 00022 * 00023 * \author Mark Spencer <markster@digium.com> 00024 * 00025 * \par See also 00026 * \arg \ref Config_iax 00027 * 00028 * \ingroup channel_drivers 00029 */ 00030 00031 /*** MODULEINFO 00032 <use>zaptel</use> 00033 ***/ 00034 00035 #include "asterisk.h" 00036 00037 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 53128 $") 00038 00039 #include <stdlib.h> 00040 #include <stdio.h> 00041 #include <sys/types.h> 00042 #include <sys/mman.h> 00043 #include <dirent.h> 00044 #include <sys/socket.h> 00045 #include <netinet/in.h> 00046 #include <arpa/inet.h> 00047 #include <netinet/in_systm.h> 00048 #include <netinet/ip.h> 00049 #include <sys/time.h> 00050 #include <sys/signal.h> 00051 #include <signal.h> 00052 #include <string.h> 00053 #include <strings.h> 00054 #include <errno.h> 00055 #include <unistd.h> 00056 #include <netdb.h> 00057 #include <fcntl.h> 00058 #include <sys/stat.h> 00059 #include <regex.h> 00060 00061 #include "asterisk/zapata.h" 00062 00063 #include "asterisk/lock.h" 00064 #include "asterisk/frame.h" 00065 #include "asterisk/channel.h" 00066 #include "asterisk/logger.h" 00067 #include "asterisk/module.h" 00068 #include "asterisk/pbx.h" 00069 #include "asterisk/sched.h" 00070 #include "asterisk/io.h" 00071 #include "asterisk/config.h" 00072 #include "asterisk/options.h" 00073 #include "asterisk/cli.h" 00074 #include "asterisk/translate.h" 00075 #include "asterisk/md5.h" 00076 #include "asterisk/cdr.h" 00077 #include "asterisk/crypto.h" 00078 #include "asterisk/acl.h" 00079 #include "asterisk/manager.h" 00080 #include "asterisk/callerid.h" 00081 #include "asterisk/app.h" 00082 #include "asterisk/astdb.h" 00083 #include "asterisk/musiconhold.h" 00084 #include "asterisk/features.h" 00085 #include "asterisk/utils.h" 00086 #include "asterisk/causes.h" 00087 #include "asterisk/localtime.h" 00088 #include "asterisk/aes.h" 00089 #include "asterisk/dnsmgr.h" 00090 #include "asterisk/devicestate.h" 00091 #include "asterisk/netsock.h" 00092 #include "asterisk/stringfields.h" 00093 #include "asterisk/linkedlists.h" 00094 00095 #include "iax2.h" 00096 #include "iax2-parser.h" 00097 #include "iax2-provision.h" 00098 #include "jitterbuf.h" 00099 00100 /* Define SCHED_MULTITHREADED to run the scheduler in a special 00101 multithreaded mode. */ 00102 #define SCHED_MULTITHREADED 00103 00104 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each 00105 thread is actually doing. */ 00106 #define DEBUG_SCHED_MULTITHREAD 00107 00108 #ifndef IPTOS_MINCOST 00109 #define IPTOS_MINCOST 0x02 00110 #endif 00111 00112 #ifdef SO_NO_CHECK 00113 static int nochecksums = 0; 00114 #endif 00115 00116 00117 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a)) 00118 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a)) 00119 00120 #define DEFAULT_THREAD_COUNT 10 00121 #define DEFAULT_MAX_THREAD_COUNT 100 00122 #define DEFAULT_RETRY_TIME 1000 00123 #define MEMORY_SIZE 100 00124 #define DEFAULT_DROP 3 00125 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use 00126 but keeps the division between trunked and non-trunked better. */ 00127 #define TRUNK_CALL_START 0x4000 00128 00129 #define DEBUG_SUPPORT 00130 00131 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */ 00132 00133 /* Sample over last 100 units to determine historic jitter */ 00134 #define GAMMA (0.01) 00135 00136 static struct ast_codec_pref prefs; 00137 00138 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)"; 00139 00140 00141 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be 00142 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */ 00143 #define MAX_TRUNK_MTU 1240 00144 00145 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */ 00146 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */ 00147 00148 00149 static char context[80] = "default"; 00150 00151 static char language[MAX_LANGUAGE] = ""; 00152 static char regcontext[AST_MAX_CONTEXT] = ""; 00153 00154 static int maxauthreq = 3; 00155 static int max_retries = 4; 00156 static int ping_time = 20; 00157 static int lagrq_time = 10; 00158 static int maxtrunkcall = TRUNK_CALL_START; 00159 static int maxnontrunkcall = 1; 00160 static int maxjitterbuffer=1000; 00161 static int resyncthreshold=1000; 00162 static int maxjitterinterps=10; 00163 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */ 00164 00165 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */ 00166 00167 static int trunkfreq = 20; 00168 static int trunkmaxsize = MAX_TRUNKDATA; 00169 00170 static int authdebug = 1; 00171 static int autokill = 0; 00172 static int iaxcompat = 0; 00173 00174 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */ 00175 00176 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */ 00177 00178 static unsigned int tos = 0; 00179 00180 static int min_reg_expire; 00181 static int max_reg_expire; 00182 00183 static int srvlookup = 0; 00184 00185 static int timingfd = -1; /* Timing file descriptor */ 00186 00187 static struct ast_netsock_list *netsock; 00188 static int defaultsockfd = -1; 00189 00190 int (*iax2_regfunk)(const char *username, int onoff) = NULL; 00191 00192 /* Ethernet, etc */ 00193 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF 00194 /* T1, maybe ISDN */ 00195 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \ 00196 ~AST_FORMAT_SLINEAR & \ 00197 ~AST_FORMAT_ULAW & \ 00198 ~AST_FORMAT_ALAW & \ 00199 ~AST_FORMAT_G722) 00200 /* A modem */ 00201 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \ 00202 ~AST_FORMAT_G726 & \ 00203 ~AST_FORMAT_G726_AAL2 & \ 00204 ~AST_FORMAT_ADPCM) 00205 00206 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \ 00207 ~AST_FORMAT_G723_1) 00208 00209 00210 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */ 00211 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */ 00212 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */ 00213 00214 static struct io_context *io; 00215 static struct sched_context *sched; 00216 00217 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH; 00218 00219 static int iaxdebug = 0; 00220 00221 static int iaxtrunkdebug = 0; 00222 00223 static int test_losspct = 0; 00224 #ifdef IAXTESTS 00225 static int test_late = 0; 00226 static int test_resync = 0; 00227 static int test_jit = 0; 00228 static int test_jitpct = 0; 00229 #endif /* IAXTESTS */ 00230 00231 static char accountcode[AST_MAX_ACCOUNT_CODE]; 00232 static char mohinterpret[MAX_MUSICCLASS]; 00233 static char mohsuggest[MAX_MUSICCLASS]; 00234 static int amaflags = 0; 00235 static int adsi = 0; 00236 static int delayreject = 0; 00237 static int iax2_encryption = 0; 00238 00239 static struct ast_flags globalflags = { 0 }; 00240 00241 static pthread_t netthreadid = AST_PTHREADT_NULL; 00242 static pthread_t schedthreadid = AST_PTHREADT_NULL; 00243 AST_MUTEX_DEFINE_STATIC(sched_lock); 00244 static ast_cond_t sched_cond; 00245 00246 enum iax2_state { 00247 IAX_STATE_STARTED = (1 << 0), 00248 IAX_STATE_AUTHENTICATED = (1 << 1), 00249 IAX_STATE_TBD = (1 << 2), 00250 IAX_STATE_UNCHANGED = (1 << 3), 00251 }; 00252 00253 struct iax2_context { 00254 char context[AST_MAX_CONTEXT]; 00255 struct iax2_context *next; 00256 }; 00257 00258 enum iax2_flags { 00259 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */ 00260 IAX_DELME = (1 << 1), /*!< Needs to be deleted */ 00261 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */ 00262 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */ 00263 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */ 00264 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */ 00265 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */ 00266 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */ 00267 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */ 00268 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */ 00269 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */ 00270 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */ 00271 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */ 00272 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */ 00273 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */ 00274 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */ 00275 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/ 00276 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */ 00277 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */ 00278 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */ 00279 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */ 00280 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */ 00281 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */ 00282 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */ 00283 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */ 00284 }; 00285 00286 static int global_rtautoclear = 120; 00287 00288 static int reload_config(void); 00289 static int iax2_reload(int fd, int argc, char *argv[]); 00290 00291 00292 struct iax2_user { 00293 AST_DECLARE_STRING_FIELDS( 00294 AST_STRING_FIELD(name); 00295 AST_STRING_FIELD(secret); 00296 AST_STRING_FIELD(dbsecret); 00297 AST_STRING_FIELD(accountcode); 00298 AST_STRING_FIELD(mohinterpret); 00299 AST_STRING_FIELD(mohsuggest); 00300 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */ 00301 AST_STRING_FIELD(language); 00302 AST_STRING_FIELD(cid_num); 00303 AST_STRING_FIELD(cid_name); 00304 ); 00305 00306 int authmethods; 00307 int encmethods; 00308 int amaflags; 00309 int adsi; 00310 unsigned int flags; 00311 int capability; 00312 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */ 00313 int curauthreq; /*!< Current number of outstanding AUTHREQs */ 00314 struct ast_codec_pref prefs; 00315 struct ast_ha *ha; 00316 struct iax2_context *contexts; 00317 struct ast_variable *vars; 00318 AST_LIST_ENTRY(iax2_user) entry; 00319 }; 00320 00321 struct iax2_peer { 00322 AST_DECLARE_STRING_FIELDS( 00323 AST_STRING_FIELD(name); 00324 AST_STRING_FIELD(username); 00325 AST_STRING_FIELD(secret); 00326 AST_STRING_FIELD(dbsecret); 00327 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */ 00328 00329 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */ 00330 AST_STRING_FIELD(context); /*!< For transfers only */ 00331 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */ 00332 AST_STRING_FIELD(mailbox); /*!< Mailbox */ 00333 AST_STRING_FIELD(mohinterpret); 00334 AST_STRING_FIELD(mohsuggest); 00335 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */ 00336 /* Suggested caller id if registering */ 00337 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */ 00338 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */ 00339 AST_STRING_FIELD(zonetag); /*!< Time Zone */ 00340 ); 00341 struct ast_codec_pref prefs; 00342 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */ 00343 struct sockaddr_in addr; 00344 int formats; 00345 int sockfd; /*!< Socket to use for transmission */ 00346 struct in_addr mask; 00347 int adsi; 00348 unsigned int flags; 00349 00350 /* Dynamic Registration fields */ 00351 struct sockaddr_in defaddr; /*!< Default address if there is one */ 00352 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */ 00353 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */ 00354 00355 int expire; /*!< Schedule entry for expiry */ 00356 int expiry; /*!< How soon to expire */ 00357 int capability; /*!< Capability */ 00358 00359 /* Qualification */ 00360 int callno; /*!< Call number of POKE request */ 00361 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */ 00362 int lastms; /*!< How long last response took (in ms), or -1 for no response */ 00363 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */ 00364 00365 int pokefreqok; /*!< How often to check if the host is up */ 00366 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */ 00367 int historicms; /*!< How long recent average responses took */ 00368 int smoothing; /*!< Sample over how many units to determine historic ms */ 00369 00370 struct ast_ha *ha; 00371 AST_LIST_ENTRY(iax2_peer) entry; 00372 }; 00373 00374 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr)) 00375 00376 struct iax2_trunk_peer { 00377 ast_mutex_t lock; 00378 int sockfd; 00379 struct sockaddr_in addr; 00380 struct timeval txtrunktime; /*!< Transmit trunktime */ 00381 struct timeval rxtrunktime; /*!< Receive trunktime */ 00382 struct timeval lasttxtime; /*!< Last transmitted trunktime */ 00383 struct timeval trunkact; /*!< Last trunk activity */ 00384 unsigned int lastsent; /*!< Last sent time */ 00385 /* Trunk data and length */ 00386 unsigned char *trunkdata; 00387 unsigned int trunkdatalen; 00388 unsigned int trunkdataalloc; 00389 int trunkmaxmtu; 00390 int trunkerror; 00391 int calls; 00392 AST_LIST_ENTRY(iax2_trunk_peer) list; 00393 }; 00394 00395 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer); 00396 00397 struct iax_firmware { 00398 AST_LIST_ENTRY(iax_firmware) list; 00399 int fd; 00400 int mmaplen; 00401 int dead; 00402 struct ast_iax2_firmware_header *fwh; 00403 unsigned char *buf; 00404 }; 00405 00406 enum iax_reg_state { 00407 REG_STATE_UNREGISTERED = 0, 00408 REG_STATE_REGSENT, 00409 REG_STATE_AUTHSENT, 00410 REG_STATE_REGISTERED, 00411 REG_STATE_REJECTED, 00412 REG_STATE_TIMEOUT, 00413 REG_STATE_NOAUTH 00414 }; 00415 00416 enum iax_transfer_state { 00417 TRANSFER_NONE = 0, 00418 TRANSFER_BEGIN, 00419 TRANSFER_READY, 00420 TRANSFER_RELEASED, 00421 TRANSFER_PASSTHROUGH, 00422 TRANSFER_MBEGIN, 00423 TRANSFER_MREADY, 00424 TRANSFER_MRELEASED, 00425 TRANSFER_MPASSTHROUGH, 00426 TRANSFER_MEDIA, 00427 TRANSFER_MEDIAPASS 00428 }; 00429 00430 struct iax2_registry { 00431 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */ 00432 char username[80]; 00433 char secret[80]; /*!< Password or key name in []'s */ 00434 char random[80]; 00435 int expire; /*!< Sched ID of expiration */ 00436 int refresh; /*!< How often to refresh */ 00437 enum iax_reg_state regstate; 00438 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */ 00439 int callno; /*!< Associated call number if applicable */ 00440 struct sockaddr_in us; /*!< Who the server thinks we are */ 00441 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */ 00442 AST_LIST_ENTRY(iax2_registry) entry; 00443 }; 00444 00445 static AST_LIST_HEAD_STATIC(registrations, iax2_registry); 00446 00447 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */ 00448 #define MIN_RETRY_TIME 100 00449 #define MAX_RETRY_TIME 10000 00450 00451 #define MAX_JITTER_BUFFER 50 00452 #define MIN_JITTER_BUFFER 10 00453 00454 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */ 00455 00456 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */ 00457 00458 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */ 00459 #define TS_GAP_FOR_JB_RESYNC 5000 00460 00461 static int iaxthreadcount = DEFAULT_THREAD_COUNT; 00462 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT; 00463 static int iaxdynamicthreadcount = 0; 00464 00465 struct iax_rr { 00466 int jitter; 00467 int losspct; 00468 int losscnt; 00469 int packets; 00470 int delay; 00471 int dropped; 00472 int ooo; 00473 }; 00474 00475 struct chan_iax2_pvt { 00476 /*! Socket to send/receive on for this call */ 00477 int sockfd; 00478 /*! Last received voice format */ 00479 int voiceformat; 00480 /*! Last received video format */ 00481 int videoformat; 00482 /*! Last sent voice format */ 00483 int svoiceformat; 00484 /*! Last sent video format */ 00485 int svideoformat; 00486 /*! What we are capable of sending */ 00487 int capability; 00488 /*! Last received timestamp */ 00489 unsigned int last; 00490 /*! Last sent timestamp - never send the same timestamp twice in a single call */ 00491 unsigned int lastsent; 00492 /*! Next outgoing timestamp if everything is good */ 00493 unsigned int nextpred; 00494 /*! True if the last voice we transmitted was not silence/CNG */ 00495 unsigned int notsilenttx:1; 00496 /*! Ping time */ 00497 unsigned int pingtime; 00498 /*! Max time for initial response */ 00499 int maxtime; 00500 /*! Peer Address */ 00501 struct sockaddr_in addr; 00502 /*! Actual used codec preferences */ 00503 struct ast_codec_pref prefs; 00504 /*! Requested codec preferences */ 00505 struct ast_codec_pref rprefs; 00506 /*! Our call number */ 00507 unsigned short callno; 00508 /*! Peer callno */ 00509 unsigned short peercallno; 00510 /*! Peer selected format */ 00511 int peerformat; 00512 /*! Peer capability */ 00513 int peercapability; 00514 /*! timeval that we base our transmission on */ 00515 struct timeval offset; 00516 /*! timeval that we base our delivery on */ 00517 struct timeval rxcore; 00518 /*! The jitterbuffer */ 00519 jitterbuf *jb; 00520 /*! active jb read scheduler id */ 00521 int jbid; 00522 /*! LAG */ 00523 int lag; 00524 /*! Error, as discovered by the manager */ 00525 int error; 00526 /*! Owner if we have one */ 00527 struct ast_channel *owner; 00528 /*! What's our state? */ 00529 struct ast_flags state; 00530 /*! Expiry (optional) */ 00531 int expiry; 00532 /*! Next outgoing sequence number */ 00533 unsigned char oseqno; 00534 /*! Next sequence number they have not yet acknowledged */ 00535 unsigned char rseqno; 00536 /*! Next incoming sequence number */ 00537 unsigned char iseqno; 00538 /*! Last incoming sequence number we have acknowledged */ 00539 unsigned char aseqno; 00540 00541 AST_DECLARE_STRING_FIELDS( 00542 /*! Peer name */ 00543 AST_STRING_FIELD(peer); 00544 /*! Default Context */ 00545 AST_STRING_FIELD(context); 00546 /*! Caller ID if available */ 00547 AST_STRING_FIELD(cid_num); 00548 AST_STRING_FIELD(cid_name); 00549 /*! Hidden Caller ID (i.e. ANI) if appropriate */ 00550 AST_STRING_FIELD(ani); 00551 /*! DNID */ 00552 AST_STRING_FIELD(dnid); 00553 /*! RDNIS */ 00554 AST_STRING_FIELD(rdnis); 00555 /*! Requested Extension */ 00556 AST_STRING_FIELD(exten); 00557 /*! Expected Username */ 00558 AST_STRING_FIELD(username); 00559 /*! Expected Secret */ 00560 AST_STRING_FIELD(secret); 00561 /*! MD5 challenge */ 00562 AST_STRING_FIELD(challenge); 00563 /*! Public keys permitted keys for incoming authentication */ 00564 AST_STRING_FIELD(inkeys); 00565 /*! Private key for outgoing authentication */ 00566 AST_STRING_FIELD(outkey); 00567 /*! Preferred language */ 00568 AST_STRING_FIELD(language); 00569 /*! Hostname/peername for naming purposes */ 00570 AST_STRING_FIELD(host); 00571 00572 AST_STRING_FIELD(dproot); 00573 AST_STRING_FIELD(accountcode); 00574 AST_STRING_FIELD(mohinterpret); 00575 AST_STRING_FIELD(mohsuggest); 00576 ); 00577 00578 /*! permitted authentication methods */ 00579 int authmethods; 00580 /*! permitted encryption methods */ 00581 int encmethods; 00582 /*! Encryption AES-128 Key */ 00583 aes_encrypt_ctx ecx; 00584 /*! Decryption AES-128 Key */ 00585 aes_decrypt_ctx dcx; 00586 /*! 32 bytes of semi-random data */ 00587 unsigned char semirand[32]; 00588 /*! Associated registry */ 00589 struct iax2_registry *reg; 00590 /*! Associated peer for poking */ 00591 struct iax2_peer *peerpoke; 00592 /*! IAX_ flags */ 00593 unsigned int flags; 00594 int adsi; 00595 00596 /*! Transferring status */ 00597 enum iax_transfer_state transferring; 00598 /*! Transfer identifier */ 00599 int transferid; 00600 /*! Who we are IAX transferring to */ 00601 struct sockaddr_in transfer; 00602 /*! What's the new call number for the transfer */ 00603 unsigned short transfercallno; 00604 /*! Transfer decrypt AES-128 Key */ 00605 aes_encrypt_ctx tdcx; 00606 00607 /*! Status of knowledge of peer ADSI capability */ 00608 int peeradsicpe; 00609 00610 /*! Who we are bridged to */ 00611 unsigned short bridgecallno; 00612 00613 int pingid; /*!< Transmit PING request */ 00614 int lagid; /*!< Retransmit lag request */ 00615 int autoid; /*!< Auto hangup for Dialplan requestor */ 00616 int authid; /*!< Authentication rejection ID */ 00617 int authfail; /*!< Reason to report failure */ 00618 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */ 00619 int calling_ton; 00620 int calling_tns; 00621 int calling_pres; 00622 int amaflags; 00623 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries; 00624 struct ast_variable *vars; 00625 /*! last received remote rr */ 00626 struct iax_rr remote_rr; 00627 /*! Current base time: (just for stats) */ 00628 int min; 00629 /*! Dropped frame count: (just for stats) */ 00630 int frames_dropped; 00631 /*! received frame count: (just for stats) */ 00632 int frames_received; 00633 }; 00634 00635 static AST_LIST_HEAD_STATIC(queue, iax_frame); 00636 00637 static AST_LIST_HEAD_STATIC(users, iax2_user); 00638 00639 static AST_LIST_HEAD_STATIC(peers, iax2_peer); 00640 00641 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware); 00642 00643 enum { 00644 /*! Extension exists */ 00645 CACHE_FLAG_EXISTS = (1 << 0), 00646 /*! Extension is nonexistent */ 00647 CACHE_FLAG_NONEXISTENT = (1 << 1), 00648 /*! Extension can exist */ 00649 CACHE_FLAG_CANEXIST = (1 << 2), 00650 /*! Waiting to hear back response */ 00651 CACHE_FLAG_PENDING = (1 << 3), 00652 /*! Timed out */ 00653 CACHE_FLAG_TIMEOUT = (1 << 4), 00654 /*! Request transmitted */ 00655 CACHE_FLAG_TRANSMITTED = (1 << 5), 00656 /*! Timeout */ 00657 CACHE_FLAG_UNKNOWN = (1 << 6), 00658 /*! Matchmore */ 00659 CACHE_FLAG_MATCHMORE = (1 << 7), 00660 }; 00661 00662 struct iax2_dpcache { 00663 char peercontext[AST_MAX_CONTEXT]; 00664 char exten[AST_MAX_EXTENSION]; 00665 struct timeval orig; 00666 struct timeval expiry; 00667 int flags; 00668 unsigned short callno; 00669 int waiters[256]; 00670 AST_LIST_ENTRY(iax2_dpcache) cache_list; 00671 AST_LIST_ENTRY(iax2_dpcache) peer_list; 00672 }; 00673 00674 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache); 00675 00676 static void reg_source_db(struct iax2_peer *p); 00677 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin); 00678 00679 static void destroy_peer(struct iax2_peer *peer); 00680 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt); 00681 00682 enum iax2_thread_iostate { 00683 IAX_IOSTATE_IDLE, 00684 IAX_IOSTATE_READY, 00685 IAX_IOSTATE_PROCESSING, 00686 IAX_IOSTATE_SCHEDREADY, 00687 }; 00688 00689 enum iax2_thread_type { 00690 IAX_THREAD_TYPE_POOL, 00691 IAX_THREAD_TYPE_DYNAMIC, 00692 }; 00693 00694 struct iax2_thread { 00695 AST_LIST_ENTRY(iax2_thread) list; 00696 enum iax2_thread_type type; 00697 enum iax2_thread_iostate iostate; 00698 #ifdef SCHED_MULTITHREADED 00699 void (*schedfunc)(void *); 00700 void *scheddata; 00701 #endif 00702 #ifdef DEBUG_SCHED_MULTITHREAD 00703 char curfunc[80]; 00704 #endif 00705 int actions; 00706 pthread_t threadid; 00707 int threadnum; 00708 struct sockaddr_in iosin; 00709 unsigned char buf[4096]; 00710 int iores; 00711 int iofd; 00712 time_t checktime; 00713 ast_mutex_t lock; 00714 ast_cond_t cond; 00715 }; 00716 00717 /* Thread lists */ 00718 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread); 00719 static AST_LIST_HEAD_STATIC(active_list, iax2_thread); 00720 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread); 00721 00722 static void *iax2_process_thread(void *data); 00723 00724 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond) 00725 { 00726 ast_mutex_lock(lock); 00727 ast_cond_signal(cond); 00728 ast_mutex_unlock(lock); 00729 } 00730 00731 static void iax_debug_output(const char *data) 00732 { 00733 if (iaxdebug) 00734 ast_verbose("%s", data); 00735 } 00736 00737 static void iax_error_output(const char *data) 00738 { 00739 ast_log(LOG_WARNING, "%s", data); 00740 } 00741 00742 static void jb_error_output(const char *fmt, ...) 00743 { 00744 va_list args; 00745 char buf[1024]; 00746 00747 va_start(args, fmt); 00748 vsnprintf(buf, sizeof(buf), fmt, args); 00749 va_end(args); 00750 00751 ast_log(LOG_ERROR, buf); 00752 } 00753 00754 static void jb_warning_output(const char *fmt, ...) 00755 { 00756 va_list args; 00757 char buf[1024]; 00758 00759 va_start(args, fmt); 00760 vsnprintf(buf, sizeof(buf), fmt, args); 00761 va_end(args); 00762 00763 ast_log(LOG_WARNING, buf); 00764 } 00765 00766 static void jb_debug_output(const char *fmt, ...) 00767 { 00768 va_list args; 00769 char buf[1024]; 00770 00771 va_start(args, fmt); 00772 vsnprintf(buf, sizeof(buf), fmt, args); 00773 va_end(args); 00774 00775 ast_verbose(buf); 00776 } 00777 00778 /*! 00779 * \brief an array of iax2 pvt structures 00780 * 00781 * The container for active chan_iax2_pvt structures is implemented as an 00782 * array for extremely quick direct access to the correct pvt structure 00783 * based on the local call number. The local call number is used as the 00784 * index into the array where the associated pvt structure is stored. 00785 */ 00786 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS]; 00787 /*! 00788 * \brief chan_iax2_pvt structure locks 00789 * 00790 * These locks are used when accessing a pvt structure in the iaxs array. 00791 * The index used here is the same as used in the iaxs array. It is the 00792 * local call number for the associated pvt struct. 00793 */ 00794 static ast_mutex_t iaxsl[IAX_MAX_CALLS]; 00795 /*! 00796 * \brief The last time a call number was used 00797 * 00798 * It is important to know the last time that a call number was used locally so 00799 * that it is not used again too soon. The reason for this is the same as the 00800 * reason that the TCP protocol state machine requires a "TIME WAIT" state. 00801 * 00802 * For example, say that a call is up. Then, the remote side sends a HANGUP, 00803 * which we respond to with an ACK. However, there is no way to know whether 00804 * the ACK made it there successfully. If it were to get lost, the remote 00805 * side may retransmit the HANGUP. If in the meantime, this call number has 00806 * been reused locally, given the right set of circumstances, this retransmitted 00807 * HANGUP could potentially improperly hang up the new session. So, to avoid 00808 * this potential issue, we must wait a specified timeout period before reusing 00809 * a local call number. 00810 * 00811 * The specified time that we must wait before reusing a local call number is 00812 * defined as MIN_REUSE_TIME, with a default of 60 seconds. 00813 */ 00814 static struct timeval lastused[IAX_MAX_CALLS]; 00815 00816 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); 00817 static int expire_registry(void *data); 00818 static int iax2_answer(struct ast_channel *c); 00819 static int iax2_call(struct ast_channel *c, char *dest, int timeout); 00820 static int iax2_devicestate(void *data); 00821 static int iax2_digit_begin(struct ast_channel *c, char digit); 00822 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration); 00823 static int iax2_do_register(struct iax2_registry *reg); 00824 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan); 00825 static int iax2_hangup(struct ast_channel *c); 00826 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen); 00827 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall); 00828 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force); 00829 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final); 00830 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen); 00831 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img); 00832 static int iax2_sendtext(struct ast_channel *c, const char *text); 00833 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen); 00834 static int iax2_transfer(struct ast_channel *c, const char *dest); 00835 static int iax2_write(struct ast_channel *c, struct ast_frame *f); 00836 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now); 00837 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int); 00838 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int); 00839 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int); 00840 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int); 00841 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int); 00842 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause); 00843 static struct ast_frame *iax2_read(struct ast_channel *c); 00844 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly); 00845 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly); 00846 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime); 00847 static void destroy_user(struct iax2_user *user); 00848 static void prune_peers(void); 00849 00850 static const struct ast_channel_tech iax2_tech = { 00851 .type = "IAX2", 00852 .description = tdesc, 00853 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH, 00854 .properties = AST_CHAN_TP_WANTSJITTER, 00855 .requester = iax2_request, 00856 .devicestate = iax2_devicestate, 00857 .send_digit_begin = iax2_digit_begin, 00858 .send_digit_end = iax2_digit_end, 00859 .send_text = iax2_sendtext, 00860 .send_image = iax2_sendimage, 00861 .send_html = iax2_sendhtml, 00862 .call = iax2_call, 00863 .hangup = iax2_hangup, 00864 .answer = iax2_answer, 00865 .read = iax2_read, 00866 .write = iax2_write, 00867 .write_video = iax2_write, 00868 .indicate = iax2_indicate, 00869 .setoption = iax2_setoption, 00870 .bridge = iax2_bridge, 00871 .transfer = iax2_transfer, 00872 .fixup = iax2_fixup, 00873 }; 00874 00875 static void insert_idle_thread(struct iax2_thread *thread) 00876 { 00877 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) { 00878 AST_LIST_LOCK(&dynamic_list); 00879 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list); 00880 AST_LIST_UNLOCK(&dynamic_list); 00881 } else { 00882 AST_LIST_LOCK(&idle_list); 00883 AST_LIST_INSERT_TAIL(&idle_list, thread, list); 00884 AST_LIST_UNLOCK(&idle_list); 00885 } 00886 00887 return; 00888 } 00889 00890 static struct iax2_thread *find_idle_thread(void) 00891 { 00892 struct iax2_thread *thread = NULL; 00893 00894 /* Pop the head of the idle list off */ 00895 AST_LIST_LOCK(&idle_list); 00896 thread = AST_LIST_REMOVE_HEAD(&idle_list, list); 00897 AST_LIST_UNLOCK(&idle_list); 00898 00899 /* If we popped a thread off the idle list, just return it */ 00900 if (thread) 00901 return thread; 00902 00903 /* Pop the head of the dynamic list off */ 00904 AST_LIST_LOCK(&dynamic_list); 00905 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list); 00906 AST_LIST_UNLOCK(&dynamic_list); 00907 00908 /* If we popped a thread off the dynamic list, just return it */ 00909 if (thread) 00910 return thread; 00911 00912 /* If we can't create a new dynamic thread for any reason, return no thread at all */ 00913 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread)))) 00914 return NULL; 00915 00916 /* Set default values */ 00917 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1); 00918 thread->type = IAX_THREAD_TYPE_DYNAMIC; 00919 00920 /* Initialize lock and condition */ 00921 ast_mutex_init(&thread->lock); 00922 ast_cond_init(&thread->cond, NULL); 00923 00924 /* Create thread and send it on it's way */ 00925 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) { 00926 ast_cond_destroy(&thread->cond); 00927 ast_mutex_destroy(&thread->lock); 00928 free(thread); 00929 thread = NULL; 00930 } 00931 00932 return thread; 00933 } 00934 00935 #ifdef SCHED_MULTITHREADED 00936 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname) 00937 { 00938 struct iax2_thread *thread = NULL; 00939 static time_t lasterror; 00940 static time_t t; 00941 00942 thread = find_idle_thread(); 00943 00944 if (thread != NULL) { 00945 thread->schedfunc = func; 00946 thread->scheddata = data; 00947 thread->iostate = IAX_IOSTATE_SCHEDREADY; 00948 #ifdef DEBUG_SCHED_MULTITHREAD 00949 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc)); 00950 #endif 00951 signal_condition(&thread->lock, &thread->cond); 00952 return 0; 00953 } 00954 time(&t); 00955 if (t != lasterror) 00956 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n"); 00957 lasterror = t; 00958 00959 return -1; 00960 } 00961 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__) 00962 #endif 00963 00964 static int send_ping(void *data); 00965 00966 static void __send_ping(void *data) 00967 { 00968 int callno = (long)data; 00969 ast_mutex_lock(&iaxsl[callno]); 00970 if (iaxs[callno] && iaxs[callno]->pingid != -1) { 00971 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1); 00972 iaxs[callno]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, data); 00973 } 00974 ast_mutex_unlock(&iaxsl[callno]); 00975 } 00976 00977 static int send_ping(void *data) 00978 { 00979 #ifdef SCHED_MULTITHREADED 00980 if (schedule_action(__send_ping, data)) 00981 #endif 00982 __send_ping(data); 00983 return 0; 00984 } 00985 00986 static int get_encrypt_methods(const char *s) 00987 { 00988 int e; 00989 if (!strcasecmp(s, "aes128")) 00990 e = IAX_ENCRYPT_AES128; 00991 else if (ast_true(s)) 00992 e = IAX_ENCRYPT_AES128; 00993 else 00994 e = 0; 00995 return e; 00996 } 00997 00998 static int send_lagrq(void *data); 00999 01000 static void __send_lagrq(void *data) 01001 { 01002 int callno = (long)data; 01003 /* Ping only if it's real not if it's bridged */ 01004 ast_mutex_lock(&iaxsl[callno]); 01005 if (iaxs[callno] && iaxs[callno]->lagid != -1) { 01006 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1); 01007 iaxs[callno]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, data); 01008 } 01009 ast_mutex_unlock(&iaxsl[callno]); 01010 } 01011 01012 static int send_lagrq(void *data) 01013 { 01014 #ifdef SCHED_MULTITHREADED 01015 if (schedule_action(__send_lagrq, data)) 01016 #endif 01017 __send_lagrq(data); 01018 return 0; 01019 } 01020 01021 static unsigned char compress_subclass(int subclass) 01022 { 01023 int x; 01024 int power=-1; 01025 /* If it's 128 or smaller, just return it */ 01026 if (subclass < IAX_FLAG_SC_LOG) 01027 return subclass; 01028 /* Otherwise find its power */ 01029 for (x = 0; x < IAX_MAX_SHIFT; x++) { 01030 if (subclass & (1 << x)) { 01031 if (power > -1) { 01032 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass); 01033 return 0; 01034 } else 01035 power = x; 01036 } 01037 } 01038 return power | IAX_FLAG_SC_LOG; 01039 } 01040 01041 static int uncompress_subclass(unsigned char csub) 01042 { 01043 /* If the SC_LOG flag is set, return 2^csub otherwise csub */ 01044 if (csub & IAX_FLAG_SC_LOG) { 01045 /* special case for 'compressed' -1 */ 01046 if (csub == 0xff) 01047 return -1; 01048 else 01049 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT); 01050 } 01051 else 01052 return csub; 01053 } 01054 01055 static struct iax2_peer *find_peer(const char *name, int realtime) 01056 { 01057 struct iax2_peer *peer = NULL; 01058 01059 /* Grab peer from linked list */ 01060 AST_LIST_LOCK(&peers); 01061 AST_LIST_TRAVERSE(&peers, peer, entry) { 01062 if (!strcasecmp(peer->name, name)) { 01063 break; 01064 } 01065 } 01066 AST_LIST_UNLOCK(&peers); 01067 01068 /* Now go for realtime if applicable */ 01069 if(!peer && realtime) 01070 peer = realtime_peer(name, NULL); 01071 return peer; 01072 } 01073 01074 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer) 01075 { 01076 struct iax2_peer *peer = NULL; 01077 int res = 0; 01078 01079 if (lockpeer) 01080 AST_LIST_LOCK(&peers); 01081 AST_LIST_TRAVERSE(&peers, peer, entry) { 01082 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) && 01083 (peer->addr.sin_port == sin.sin_port)) { 01084 ast_copy_string(host, peer->name, len); 01085 res = 1; 01086 break; 01087 } 01088 } 01089 if (lockpeer) 01090 AST_LIST_UNLOCK(&peers); 01091 if (!peer) { 01092 peer = realtime_peer(NULL, &sin); 01093 if (peer) { 01094 ast_copy_string(host, peer->name, len); 01095 if (ast_test_flag(peer, IAX_TEMPONLY)) 01096 destroy_peer(peer); 01097 res = 1; 01098 } 01099 } 01100 01101 return res; 01102 } 01103 01104 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host) 01105 { 01106 struct chan_iax2_pvt *tmp; 01107 jb_conf jbconf; 01108 01109 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) 01110 return NULL; 01111 01112 if (ast_string_field_init(tmp, 32)) { 01113 free(tmp); 01114 tmp = NULL; 01115 return NULL; 01116 } 01117 01118 tmp->prefs = prefs; 01119 tmp->pingid = -1; 01120 tmp->lagid = -1; 01121 tmp->autoid = -1; 01122 tmp->authid = -1; 01123 tmp->initid = -1; 01124 01125 ast_string_field_set(tmp,exten, "s"); 01126 ast_string_field_set(tmp,host, host); 01127 01128 tmp->jb = jb_new(); 01129 tmp->jbid = -1; 01130 jbconf.max_jitterbuf = maxjitterbuffer; 01131 jbconf.resync_threshold = resyncthreshold; 01132 jbconf.max_contig_interp = maxjitterinterps; 01133 jbconf.target_extra = jittertargetextra; 01134 jb_setconf(tmp->jb,&jbconf); 01135 01136 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries); 01137 01138 return tmp; 01139 } 01140 01141 static struct iax_frame *iaxfrdup2(struct iax_frame *fr) 01142 { 01143 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable); 01144 if (new) { 01145 size_t mallocd_datalen = new->mallocd_datalen; 01146 memcpy(new, fr, sizeof(*new)); 01147 iax_frame_wrap(new, &fr->af); 01148 new->mallocd_datalen = mallocd_datalen; 01149 new->data = NULL; 01150 new->datalen = 0; 01151 new->direction = DIRECTION_INGRESS; 01152 new->retrans = -1; 01153 } 01154 return new; 01155 } 01156 01157 #define NEW_PREVENT 0 01158 #define NEW_ALLOW 1 01159 #define NEW_FORCE 2 01160 01161 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur) 01162 { 01163 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) && 01164 (cur->addr.sin_port == sin->sin_port)) { 01165 /* This is the main host */ 01166 if ((cur->peercallno == callno) || 01167 ((dcallno == cur->callno) && !cur->peercallno)) { 01168 /* That's us. Be sure we keep track of the peer call number */ 01169 return 1; 01170 } 01171 } 01172 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) && 01173 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) { 01174 /* We're transferring */ 01175 if (dcallno == cur->callno) 01176 return 1; 01177 } 01178 return 0; 01179 } 01180 01181 static void update_max_trunk(void) 01182 { 01183 int max = TRUNK_CALL_START; 01184 int x; 01185 /* XXX Prolly don't need locks here XXX */ 01186 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) { 01187 if (iaxs[x]) 01188 max = x + 1; 01189 } 01190 maxtrunkcall = max; 01191 if (option_debug && iaxdebug) 01192 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max); 01193 } 01194 01195 static void update_max_nontrunk(void) 01196 { 01197 int max = 1; 01198 int x; 01199 /* XXX Prolly don't need locks here XXX */ 01200 for (x=1;x<TRUNK_CALL_START - 1; x++) { 01201 if (iaxs[x]) 01202 max = x + 1; 01203 } 01204 maxnontrunkcall = max; 01205 if (option_debug && iaxdebug) 01206 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max); 01207 } 01208 01209 static int make_trunk(unsigned short callno, int locked) 01210 { 01211 int x; 01212 int res= 0; 01213 struct timeval now; 01214 if (iaxs[callno]->oseqno) { 01215 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n"); 01216 return -1; 01217 } 01218 if (callno & TRUNK_CALL_START) { 01219 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno); 01220 return -1; 01221 } 01222 gettimeofday(&now, NULL); 01223 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) { 01224 ast_mutex_lock(&iaxsl[x]); 01225 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) { 01226 iaxs[x] = iaxs[callno]; 01227 iaxs[x]->callno = x; 01228 iaxs[callno] = NULL; 01229 /* Update the two timers that should have been started */ 01230 if (iaxs[x]->pingid > -1) 01231 ast_sched_del(sched, iaxs[x]->pingid); 01232 if (iaxs[x]->lagid > -1) 01233 ast_sched_del(sched, iaxs[x]->lagid); 01234 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x); 01235 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x); 01236 if (locked) 01237 ast_mutex_unlock(&iaxsl[callno]); 01238 res = x; 01239 if (!locked) 01240 ast_mutex_unlock(&iaxsl[x]); 01241 break; 01242 } 01243 ast_mutex_unlock(&iaxsl[x]); 01244 } 01245 if (x >= IAX_MAX_CALLS - 1) { 01246 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n"); 01247 return -1; 01248 } 01249 if (option_debug) 01250 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x); 01251 /* We move this call from a non-trunked to a trunked call */ 01252 update_max_trunk(); 01253 update_max_nontrunk(); 01254 return res; 01255 } 01256 01257 /*! 01258 * \todo XXX Note that this function contains a very expensive operation that 01259 * happens for *every* incoming media frame. It iterates through every 01260 * possible call number, locking and unlocking each one, to try to match the 01261 * incoming frame to an active call. Call numbers can be up to 2^15, 32768. 01262 * So, for an call with a local call number of 20000, every incoming audio 01263 * frame would require 20000 mutex lock and unlock operations. Ouch. 01264 * 01265 * It's a shame that IAX2 media frames carry the source call number instead of 01266 * the destination call number. If they did, this lookup wouldn't be needed. 01267 * However, it's too late to change that now. Instead, we need to come up with 01268 * a better way of indexing active calls so that these frequent lookups are not 01269 * so expensive. 01270 */ 01271 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd) 01272 { 01273 int res = 0; 01274 int x; 01275 struct timeval now; 01276 char host[80]; 01277 if (new <= NEW_ALLOW) { 01278 /* Look for an existing connection first */ 01279 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) { 01280 ast_mutex_lock(&iaxsl[x]); 01281 if (iaxs[x]) { 01282 /* Look for an exact match */ 01283 if (match(sin, callno, dcallno, iaxs[x])) { 01284 res = x; 01285 } 01286 } 01287 ast_mutex_unlock(&iaxsl[x]); 01288 } 01289 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) { 01290 ast_mutex_lock(&iaxsl[x]); 01291 if (iaxs[x]) { 01292 /* Look for an exact match */ 01293 if (match(sin, callno, dcallno, iaxs[x])) { 01294 res = x; 01295 } 01296 } 01297 ast_mutex_unlock(&iaxsl[x]); 01298 } 01299 } 01300 if ((res < 1) && (new >= NEW_ALLOW)) { 01301 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer)) 01302 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port)); 01303 gettimeofday(&now, NULL); 01304 for (x=1;x<TRUNK_CALL_START;x++) { 01305 /* Find first unused call number that hasn't been used in a while */ 01306 ast_mutex_lock(&iaxsl[x]); 01307 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break; 01308 ast_mutex_unlock(&iaxsl[x]); 01309 } 01310 /* We've still got lock held if we found a spot */ 01311 if (x >= TRUNK_CALL_START) { 01312 ast_log(LOG_WARNING, "No more space\n"); 01313 return 0; 01314 } 01315 iaxs[x] = new_iax(sin, lockpeer, host); 01316 update_max_nontrunk(); 01317 if (iaxs[x]) { 01318 if (option_debug && iaxdebug) 01319 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x); 01320 iaxs[x]->sockfd = sockfd; 01321 iaxs[x]->addr.sin_port = sin->sin_port; 01322 iaxs[x]->addr.sin_family = sin->sin_family; 01323 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr; 01324 iaxs[x]->peercallno = callno; 01325 iaxs[x]->callno = x; 01326 iaxs[x]->pingtime = DEFAULT_RETRY_TIME; 01327 iaxs[x]->expiry = min_reg_expire; 01328 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x); 01329 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x); 01330 iaxs[x]->amaflags = amaflags; 01331 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF); 01332 01333 ast_string_field_set(iaxs[x], accountcode, accountcode); 01334 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret); 01335 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest); 01336 } else { 01337 ast_log(LOG_WARNING, "Out of resources\n"); 01338 ast_mutex_unlock(&iaxsl[x]); 01339 return 0; 01340 } 01341 ast_mutex_unlock(&iaxsl[x]); 01342 res = x; 01343 } 01344 return res; 01345 } 01346 01347 static void iax2_frame_free(struct iax_frame *fr) 01348 { 01349 if (fr->retrans > -1) 01350 ast_sched_del(sched, fr->retrans); 01351 iax_frame_free(fr); 01352 } 01353 01354 static int iax2_queue_frame(int callno, struct ast_frame *f) 01355 { 01356 /* Assumes lock for callno is already held... */ 01357 for (;;) { 01358 if (iaxs[callno] && iaxs[callno]->owner) { 01359 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) { 01360 /* Avoid deadlock by pausing and trying again */ 01361 ast_mutex_unlock(&iaxsl[callno]); 01362 usleep(1); 01363 ast_mutex_lock(&iaxsl[callno]); 01364 } else { 01365 ast_queue_frame(iaxs[callno]->owner, f); 01366 ast_mutex_unlock(&iaxs[callno]->owner->lock); 01367 break; 01368 } 01369 } else 01370 break; 01371 } 01372 return 0; 01373 } 01374 01375 static void destroy_firmware(struct iax_firmware *cur) 01376 { 01377 /* Close firmware */ 01378 if (cur->fwh) { 01379 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh))); 01380 } 01381 close(cur->fd); 01382 free(cur); 01383 } 01384 01385 static int try_firmware(char *s) 01386 { 01387 struct stat stbuf; 01388 struct iax_firmware *cur = NULL; 01389 int ifd, fd, res, len, chunk; 01390 struct ast_iax2_firmware_header *fwh, fwh2; 01391 struct MD5Context md5; 01392 unsigned char sum[16], buf[1024]; 01393 char *s2, *last; 01394 01395 if (!(s2 = alloca(strlen(s) + 100))) { 01396 ast_log(LOG_WARNING, "Alloca failed!\n"); 01397 return -1; 01398 } 01399 01400 last = strrchr(s, '/'); 01401 if (last) 01402 last++; 01403 else 01404 last = s; 01405 01406 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random()); 01407 01408 if ((res = stat(s, &stbuf) < 0)) { 01409 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno)); 01410 return -1; 01411 } 01412 01413 /* Make sure it's not a directory */ 01414 if (S_ISDIR(stbuf.st_mode)) 01415 return -1; 01416 ifd = open(s, O_RDONLY); 01417 if (ifd < 0) { 01418 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno)); 01419 return -1; 01420 } 01421 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE); 01422 if (fd < 0) { 01423 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno)); 01424 close(ifd); 01425 return -1; 01426 } 01427 /* Unlink our newly created file */ 01428 unlink(s2); 01429 01430 /* Now copy the firmware into it */ 01431 len = stbuf.st_size; 01432 while(len) { 01433 chunk = len; 01434 if (chunk > sizeof(buf)) 01435 chunk = sizeof(buf); 01436 res = read(ifd, buf, chunk); 01437 if (res != chunk) { 01438 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno)); 01439 close(ifd); 01440 close(fd); 01441 return -1; 01442 } 01443 res = write(fd, buf, chunk); 01444 if (res != chunk) { 01445 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno)); 01446 close(ifd); 01447 close(fd); 01448 return -1; 01449 } 01450 len -= chunk; 01451 } 01452 close(ifd); 01453 /* Return to the beginning */ 01454 lseek(fd, 0, SEEK_SET); 01455 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) { 01456 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s); 01457 close(fd); 01458 return -1; 01459 } 01460 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) { 01461 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s); 01462 close(fd); 01463 return -1; 01464 } 01465 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) { 01466 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s); 01467 close(fd); 01468 return -1; 01469 } 01470 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) { 01471 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s); 01472 close(fd); 01473 return -1; 01474 } 01475 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 01476 if (fwh == (void *) -1) { 01477 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno)); 01478 close(fd); 01479 return -1; 01480 } 01481 MD5Init(&md5); 01482 MD5Update(&md5, fwh->data, ntohl(fwh->datalen)); 01483 MD5Final(sum, &md5); 01484 if (memcmp(sum, fwh->chksum, sizeof(sum))) { 01485 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s); 01486 munmap(fwh, stbuf.st_size); 01487 close(fd); 01488 return -1; 01489 } 01490 01491 AST_LIST_TRAVERSE(&firmwares, cur, list) { 01492 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) { 01493 /* Found a candidate */ 01494 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version))) 01495 /* The version we have on loaded is older, load this one instead */ 01496 break; 01497 /* This version is no newer than what we have. Don't worry about it. 01498 We'll consider it a proper load anyhow though */ 01499 munmap(fwh, stbuf.st_size); 01500 close(fd); 01501 return 0; 01502 } 01503 } 01504 01505 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) { 01506 cur->fd = -1; 01507 AST_LIST_INSERT_TAIL(&firmwares, cur, list); 01508 } 01509 01510 if (cur) { 01511 if (cur->fwh) 01512 munmap(cur->fwh, cur->mmaplen); 01513 if (cur->fd > -1) 01514 close(cur->fd); 01515 cur->fwh = fwh; 01516 cur->fd = fd; 01517 cur->mmaplen = stbuf.st_size; 01518 cur->dead = 0; 01519 } 01520 01521 return 0; 01522 } 01523 01524 static int iax_check_version(char *dev) 01525 { 01526 int res = 0; 01527 struct iax_firmware *cur = NULL; 01528 01529 if (ast_strlen_zero(dev)) 01530 return 0; 01531 01532 AST_LIST_LOCK(&firmwares); 01533 AST_LIST_TRAVERSE(&firmwares, cur, list) { 01534 if (!strcmp(dev, (char *)cur->fwh->devname)) { 01535 res = ntohs(cur->fwh->version); 01536 break; 01537 } 01538 } 01539 AST_LIST_UNLOCK(&firmwares); 01540 01541 return res; 01542 } 01543 01544 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc) 01545 { 01546 int res = -1; 01547 unsigned int bs = desc & 0xff; 01548 unsigned int start = (desc >> 8) & 0xffffff; 01549 unsigned int bytes; 01550 struct iax_firmware *cur; 01551 01552 if (ast_strlen_zero((char *)dev) || !bs) 01553 return -1; 01554 01555 start *= bs; 01556 01557 AST_LIST_LOCK(&firmwares); 01558 AST_LIST_TRAVERSE(&firmwares, cur, list) { 01559 if (strcmp((char *)dev, (char *)cur->fwh->devname)) 01560 continue; 01561 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc); 01562 if (start < ntohl(cur->fwh->datalen)) { 01563 bytes = ntohl(cur->fwh->datalen) - start; 01564 if (bytes > bs) 01565 bytes = bs; 01566 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes); 01567 } else { 01568 bytes = 0; 01569 iax_ie_append(ied, IAX_IE_FWBLOCKDATA); 01570 } 01571 if (bytes == bs) 01572 res = 0; 01573 else 01574 res = 1; 01575 break; 01576 } 01577 AST_LIST_UNLOCK(&firmwares); 01578 01579 return res; 01580 } 01581 01582 01583 static void reload_firmware(void) 01584 { 01585 struct iax_firmware *cur = NULL; 01586 DIR *fwd; 01587 struct dirent *de; 01588 char dir[256], fn[256]; 01589 01590 AST_LIST_LOCK(&firmwares); 01591 01592 /* Mark all as dead */ 01593 AST_LIST_TRAVERSE(&firmwares, cur, list) 01594 cur->dead = 1; 01595 01596 /* Now that we have marked them dead... load new ones */ 01597 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR); 01598 fwd = opendir(dir); 01599 if (fwd) { 01600 while((de = readdir(fwd))) { 01601 if (de->d_name[0] != '.') { 01602 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name); 01603 if (!try_firmware(fn)) { 01604 if (option_verbose > 1) 01605 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name); 01606 } 01607 } 01608 } 01609 closedir(fwd); 01610 } else 01611 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno)); 01612 01613 /* Clean up leftovers */ 01614 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) { 01615 if (!cur->dead) 01616 continue; 01617 AST_LIST_REMOVE_CURRENT(&firmwares, list); 01618 destroy_firmware(cur); 01619 } 01620 AST_LIST_TRAVERSE_SAFE_END 01621 01622 AST_LIST_UNLOCK(&firmwares); 01623 } 01624 01625 static int __do_deliver(void *data) 01626 { 01627 /* Just deliver the packet by using queueing. This is called by 01628 the IAX thread with the iaxsl lock held. */ 01629 struct iax_frame *fr = data; 01630 fr->retrans = -1; 01631 fr->af.has_timing_info = 0; 01632 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE)) 01633 iax2_queue_frame(fr->callno, &fr->af); 01634 /* Free our iax frame */ 01635 iax2_frame_free(fr); 01636 /* And don't run again */ 01637 return 0; 01638 } 01639 01640 static int handle_error(void) 01641 { 01642 /* XXX Ideally we should figure out why an error occurred and then abort those 01643 rather than continuing to try. Unfortunately, the published interface does 01644 not seem to work XXX */ 01645 #if 0 01646 struct sockaddr_in *sin; 01647 int res; 01648 struct msghdr m; 01649 struct sock_extended_err e; 01650 m.msg_name = NULL; 01651 m.msg_namelen = 0; 01652 m.msg_iov = NULL; 01653 m.msg_control = &e; 01654 m.msg_controllen = sizeof(e); 01655 m.msg_flags = 0; 01656 res = recvmsg(netsocket, &m, MSG_ERRQUEUE); 01657 if (res < 0) 01658 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno)); 01659 else { 01660 if (m.msg_controllen) { 01661 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e); 01662 if (sin) 01663 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr)); 01664 else 01665 ast_log(LOG_WARNING, "No address detected??\n"); 01666 } else { 01667 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno)); 01668 } 01669 } 01670 #endif 01671 return 0; 01672 } 01673 01674 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd) 01675 { 01676 int res; 01677 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin, 01678 sizeof(*sin)); 01679 if (res < 0) { 01680 if (option_debug) 01681 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno)); 01682 handle_error(); 01683 } else 01684 res = 0; 01685 return res; 01686 } 01687 01688 static int send_packet(struct iax_frame *f) 01689 { 01690 int res; 01691 int callno = f->callno; 01692 01693 /* Don't send if there was an error, but return error instead */ 01694 if (!callno || !iaxs[callno] || iaxs[callno]->error) 01695 return -1; 01696 01697 /* Called with iaxsl held */ 01698 if (option_debug > 2 && iaxdebug) 01699 ast_log(LOG_DEBUG, "Sending %d 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)); 01700 if (f->transfer) { 01701 if (iaxdebug) 01702 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr)); 01703 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, 01704 sizeof(iaxs[callno]->transfer)); 01705 } else { 01706 if (iaxdebug) 01707 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr)); 01708 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, 01709 sizeof(iaxs[callno]->addr)); 01710 } 01711 if (res < 0) { 01712 if (option_debug && iaxdebug) 01713 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno)); 01714 handle_error(); 01715 } else 01716 res = 0; 01717 return res; 01718 } 01719 01720 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt) 01721 { 01722 struct iax2_user *user = NULL; 01723 01724 /* Decrement AUTHREQ count if needed */ 01725 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) { 01726 AST_LIST_LOCK(&users); 01727 AST_LIST_TRAVERSE(&users, user, entry) { 01728 if (!strcmp(user->name, pvt->username)) { 01729 user->curauthreq--; 01730 break; 01731 } 01732 } 01733 AST_LIST_UNLOCK(&users); 01734 ast_clear_flag(pvt, IAX_MAXAUTHREQ); 01735 } 01736 /* No more pings or lagrq's */ 01737 if (pvt->pingid > -1) 01738 ast_sched_del(sched, pvt->pingid); 01739 pvt->pingid = -1; 01740 if (pvt->lagid > -1) 01741 ast_sched_del(sched, pvt->lagid); 01742 pvt->lagid = -1; 01743 if (pvt->autoid > -1) 01744 ast_sched_del(sched, pvt->autoid); 01745 pvt->autoid = -1; 01746 if (pvt->authid > -1) 01747 ast_sched_del(sched, pvt->authid); 01748 pvt->authid = -1; 01749 if (pvt->initid > -1) 01750 ast_sched_del(sched, pvt->initid); 01751 pvt->initid = -1; 01752 if (pvt->jbid > -1) 01753 ast_sched_del(sched, pvt->jbid); 01754 pvt->jbid = -1; 01755 } 01756 01757 static int iax2_predestroy(int callno) 01758 { 01759 struct ast_channel *c = NULL; 01760 struct chan_iax2_pvt *pvt = iaxs[callno]; 01761 01762 if (!pvt) 01763 return -1; 01764 01765 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) { 01766 iax2_destroy_helper(pvt); 01767 ast_set_flag(pvt, IAX_ALREADYGONE); 01768 } 01769 01770 if ((c = pvt->owner)) { 01771 c->_softhangup |= AST_SOFTHANGUP_DEV; 01772 c->tech_pvt = NULL; 01773 ast_queue_hangup(c); 01774 pvt->owner = NULL; 01775 ast_module_unref(ast_module_info->self); 01776 } 01777 01778 return 0; 01779 } 01780 01781 static void iax2_destroy(int callno) 01782 { 01783 struct chan_iax2_pvt *pvt = NULL; 01784 struct iax_frame *cur = NULL; 01785 struct ast_channel *owner = NULL; 01786 01787 retry: 01788 pvt = iaxs[callno]; 01789 gettimeofday(&lastused[callno], NULL); 01790 01791 owner = pvt ? pvt->owner : NULL; 01792 01793 if (owner) { 01794 if (ast_mutex_trylock(&owner->lock)) { 01795 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n"); 01796 ast_mutex_unlock(&iaxsl[callno]); 01797 usleep(1); 01798 ast_mutex_lock(&iaxsl[callno]); 01799 goto retry; 01800 } 01801 } 01802 if (!owner) 01803 iaxs[callno] = NULL; 01804 if (pvt) { 01805 if (!owner) 01806 pvt->owner = NULL; 01807 iax2_destroy_helper(pvt); 01808 01809 /* Already gone */ 01810 ast_set_flag(pvt, IAX_ALREADYGONE); 01811 01812 if (owner) { 01813 /* If there's an owner, prod it to give up */ 01814 owner->_softhangup |= AST_SOFTHANGUP_DEV; 01815 ast_queue_hangup(owner); 01816 } 01817 01818 AST_LIST_LOCK(&queue); 01819 AST_LIST_TRAVERSE(&queue, cur, list) { 01820 /* Cancel any pending transmissions */ 01821 if (cur->callno == pvt->callno) 01822 cur->retries = -1; 01823 } 01824 AST_LIST_UNLOCK(&queue); 01825 01826 if (pvt->reg) 01827 pvt->reg->callno = 0; 01828 if (!owner) { 01829 jb_frame frame; 01830 if (pvt->vars) { 01831 ast_variables_destroy(pvt->vars); 01832 pvt->vars = NULL; 01833 } 01834 01835 while (jb_getall(pvt->jb, &frame) == JB_OK) 01836 iax2_frame_free(frame.data); 01837 jb_destroy(pvt->jb); 01838 /* gotta free up the stringfields */ 01839 ast_string_field_free_pools(pvt); 01840 free(pvt); 01841 } 01842 } 01843 if (owner) { 01844 ast_mutex_unlock(&owner->lock); 01845 } 01846 if (callno & 0x4000) 01847 update_max_trunk(); 01848 } 01849 01850 static int update_packet(struct iax_frame *f) 01851 { 01852 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */ 01853 struct ast_iax2_full_hdr *fh = f->data; 01854 /* Mark this as a retransmission */ 01855 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno); 01856 /* Update iseqno */ 01857 f->iseqno = iaxs[f->callno]->iseqno; 01858 fh->iseqno = f->iseqno; 01859 return 0; 01860 } 01861 01862 static int attempt_transmit(void *data); 01863 static void __attempt_transmit(void *data) 01864 { 01865 /* Attempt to transmit the frame to the remote peer... 01866 Called without iaxsl held. */ 01867 struct iax_frame *f = data; 01868 int freeme=0; 01869 int callno = f->callno; 01870 /* Make sure this call is still active */ 01871 if (callno) 01872 ast_mutex_lock(&iaxsl[callno]); 01873 if (callno && iaxs[callno]) { 01874 if ((f->retries < 0) /* Already ACK'd */ || 01875 (f->retries >= max_retries) /* Too many attempts */) { 01876 /* Record an error if we've transmitted too many times */ 01877 if (f->retries >= max_retries) { 01878 if (f->transfer) { 01879 /* Transfer timeout */ 01880 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1); 01881 } else if (f->final) { 01882 if (f->final) 01883 iax2_destroy(callno); 01884 } else { 01885 if (iaxs[callno]->owner) 01886 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno); 01887 iaxs[callno]->error = ETIMEDOUT; 01888 if (iaxs[callno]->owner) { 01889 struct ast_frame fr = { 0, }; 01890 /* Hangup the fd */ 01891 fr.frametype = AST_FRAME_CONTROL; 01892 fr.subclass = AST_CONTROL_HANGUP; 01893 iax2_queue_frame(callno, &fr); 01894 /* Remember, owner could disappear */ 01895 if (iaxs[callno]->owner) 01896 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER; 01897 } else { 01898 if (iaxs[callno]->reg) { 01899 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us)); 01900 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT; 01901 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE; 01902 } 01903 iax2_destroy(callno); 01904 } 01905 } 01906 01907 } 01908 freeme++; 01909 } else { 01910 /* Update it if it needs it */ 01911 update_packet(f); 01912 /* Attempt transmission */ 01913 send_packet(f); 01914 f->retries++; 01915 /* Try again later after 10 times as long */ 01916 f->retrytime *= 10; 01917 if (f->retrytime > MAX_RETRY_TIME) 01918 f->retrytime = MAX_RETRY_TIME; 01919 /* Transfer messages max out at one second */ 01920 if (f->transfer && (f->retrytime > 1000)) 01921 f->retrytime = 1000; 01922 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f); 01923 } 01924 } else { 01925 /* Make sure it gets freed */ 01926 f->retries = -1; 01927 freeme++; 01928 } 01929 if (callno) 01930 ast_mutex_unlock(&iaxsl[callno]); 01931 /* Do not try again */ 01932 if (freeme) { 01933 /* Don't attempt delivery, just remove it from the queue */ 01934 AST_LIST_LOCK(&queue); 01935 AST_LIST_REMOVE(&queue, f, list); 01936 AST_LIST_UNLOCK(&queue); 01937 f->retrans = -1; 01938 /* Free the IAX frame */ 01939 iax2_frame_free(f); 01940 } 01941 } 01942 01943 static int attempt_transmit(void *data) 01944 { 01945 #ifdef SCHED_MULTITHREADED 01946 if (schedule_action(__attempt_transmit, data)) 01947 #endif 01948 __attempt_transmit(data); 01949 return 0; 01950 } 01951 01952 static int iax2_prune_realtime(int fd, int argc, char *argv[]) 01953 { 01954 struct iax2_peer *peer; 01955 01956 if (argc != 4) 01957 return RESULT_SHOWUSAGE; 01958 if (!strcmp(argv[3],"all")) { 01959 reload_config(); 01960 ast_cli(fd, "OK cache is flushed.\n"); 01961 } else if ((peer = find_peer(argv[3], 0))) { 01962 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) { 01963 ast_set_flag(peer, IAX_RTAUTOCLEAR); 01964 expire_registry((void*)peer->name); 01965 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]); 01966 } else { 01967 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]); 01968 } 01969 } else { 01970 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]); 01971 } 01972 01973 return RESULT_SUCCESS; 01974 } 01975 01976 static int iax2_test_losspct(int fd, int argc, char *argv[]) 01977 { 01978 if (argc != 4) 01979 return RESULT_SHOWUSAGE; 01980 01981 test_losspct = atoi(argv[3]); 01982 01983 return RESULT_SUCCESS; 01984 } 01985 01986 #ifdef IAXTESTS 01987 static int iax2_test_late(int fd, int argc, char *argv[]) 01988 { 01989 if (argc != 4) 01990 return RESULT_SHOWUSAGE; 01991 01992 test_late = atoi(argv[3]); 01993 01994 return RESULT_SUCCESS; 01995 } 01996 01997 static int iax2_test_resync(int fd, int argc, char *argv[]) 01998 { 01999 if (argc != 4) 02000 return RESULT_SHOWUSAGE; 02001 02002 test_resync = atoi(argv[3]); 02003 02004 return RESULT_SUCCESS; 02005 } 02006 02007 static int iax2_test_jitter(int fd, int argc, char *argv[]) 02008 { 02009 if (argc < 4 || argc > 5) 02010 return RESULT_SHOWUSAGE; 02011 02012 test_jit = atoi(argv[3]); 02013 if (argc == 5) 02014 test_jitpct = atoi(argv[4]); 02015 02016 return RESULT_SUCCESS; 02017 } 02018 #endif /* IAXTESTS */ 02019 02020 /*! \brief peer_status: Report Peer status in character string */ 02021 /* returns 1 if peer is online, -1 if unmonitored */ 02022 static int peer_status(struct iax2_peer *peer, char *status, int statuslen) 02023 { 02024 int res = 0; 02025 if (peer->maxms) { 02026 if (peer->lastms < 0) { 02027 ast_copy_string(status, "UNREACHABLE", statuslen); 02028 } else if (peer->lastms > peer->maxms) { 02029 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms); 02030 res = 1; 02031 } else if (peer->lastms) { 02032 snprintf(status, statuslen, "OK (%d ms)", peer->lastms); 02033 res = 1; 02034 } else { 02035 ast_copy_string(status, "UNKNOWN", statuslen); 02036 } 02037 } else { 02038 ast_copy_string(status, "Unmonitored", statuslen); 02039 res = -1; 02040 } 02041 return res; 02042 } 02043 02044 /*! \brief Show one peer in detail */ 02045 static int iax2_show_peer(int fd, int argc, char *argv[]) 02046 { 02047 char status[30]; 02048 char cbuf[256]; 02049 struct iax2_peer *peer; 02050 char codec_buf[512]; 02051 int x = 0, codec = 0, load_realtime = 0; 02052 02053 if (argc < 4) 02054 return RESULT_SHOWUSAGE; 02055 02056 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0; 02057 02058 peer = find_peer(argv[3], load_realtime); 02059 if (peer) { 02060 ast_cli(fd,"\n\n"); 02061 ast_cli(fd, " * Name : %s\n", peer->name); 02062 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>"); 02063 ast_cli(fd, " Context : %s\n", peer->context); 02064 ast_cli(fd, " Mailbox : %s\n", peer->mailbox); 02065 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No"); 02066 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>")); 02067 ast_cli(fd, " Expire : %d\n", peer->expire); 02068 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No")); 02069 ast_cli(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)); 02070 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port)); 02071 ast_cli(fd, " Username : %s\n", peer->username); 02072 ast_cli(fd, " Codecs : "); 02073 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability); 02074 ast_cli(fd, "%s\n", codec_buf); 02075 02076 ast_cli(fd, " Codec Order : ("); 02077 for(x = 0; x < 32 ; x++) { 02078 codec = ast_codec_pref_index(&peer->prefs,x); 02079 if(!codec) 02080 break; 02081 ast_cli(fd, "%s", ast_getformatname(codec)); 02082 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1)) 02083 ast_cli(fd, "|"); 02084 } 02085 02086 if (!x) 02087 ast_cli(fd, "none"); 02088 ast_cli(fd, ")\n"); 02089 02090 ast_cli(fd, " Status : "); 02091 peer_status(peer, status, sizeof(status)); 02092 ast_cli(fd, "%s\n",status); 02093 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off"); 02094 ast_cli(fd,"\n"); 02095 if (ast_test_flag(peer, IAX_TEMPONLY)) 02096 destroy_peer(peer); 02097 } else { 02098 ast_cli(fd,"Peer %s not found.\n", argv[3]); 02099 ast_cli(fd,"\n"); 02100 } 02101 02102 return RESULT_SUCCESS; 02103 } 02104 02105 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state) 02106 { 02107 int which = 0; 02108 struct iax2_peer *p = NULL; 02109 char *res = NULL; 02110 int wordlen = strlen(word); 02111 02112 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */ 02113 if (pos == 3) { 02114 AST_LIST_LOCK(&peers); 02115 AST_LIST_TRAVERSE(&peers, p, entry) { 02116 if (!strncasecmp(p->name, word, wordlen) && ++which > state) { 02117 res = ast_strdup(p->name); 02118 break; 02119 } 02120 } 02121 AST_LIST_UNLOCK(&peers); 02122 } 02123 02124 return res; 02125 } 02126 02127 static int iax2_show_stats(int fd, int argc, char *argv[]) 02128 { 02129 struct iax_frame *cur; 02130 int cnt = 0, dead=0, final=0; 02131 02132 if (argc != 3) 02133 return RESULT_SHOWUSAGE; 02134 02135 AST_LIST_LOCK(&queue); 02136 AST_LIST_TRAVERSE(&queue, cur, list) { 02137 if (cur->retries < 0) 02138 dead++; 02139 if (cur->final) 02140 final++; 02141 cnt++; 02142 } 02143 AST_LIST_UNLOCK(&queue); 02144 02145 ast_cli(fd, " IAX Statistics\n"); 02146 ast_cli(fd, "---------------------\n"); 02147 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes()); 02148 ast_cli(fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed, 02149 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu); 02150 02151 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt); 02152 02153 trunk_timed = trunk_untimed = 0; 02154 if (trunk_maxmtu > trunk_nmaxmtu) 02155 trunk_nmaxmtu = trunk_maxmtu; 02156 02157 return RESULT_SUCCESS; 02158 } 02159 02160 /*! \brief Set trunk MTU from CLI */ 02161 static int iax2_set_mtu(int fd, int argc, char *argv[]) 02162 { 02163 int mtuv; 02164 02165 if (argc != 4) 02166 return RESULT_SHOWUSAGE; 02167 if (strncasecmp(argv[3], "default", strlen(argv[3])) == 0) 02168 mtuv = MAX_TRUNK_MTU; 02169 else 02170 mtuv = atoi(argv[3]); 02171 02172 if (mtuv == 0) { 02173 ast_cli(fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 02174 global_max_trunk_mtu = 0; 02175 return RESULT_SUCCESS; 02176 } 02177 if (mtuv < 172 || mtuv > 4000) { 02178 ast_cli(fd, "Trunk MTU must be between 172 and 4000\n"); 02179 return RESULT_SHOWUSAGE; 02180 } 02181 ast_cli(fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 02182 global_max_trunk_mtu = mtuv; 02183 return RESULT_SUCCESS; 02184 } 02185 02186 static int iax2_show_cache(int fd, int argc, char *argv[]) 02187 { 02188 struct iax2_dpcache *dp = NULL; 02189 char tmp[1024], *pc = NULL; 02190 int s, x, y; 02191 struct timeval tv; 02192 02193 gettimeofday(&tv, NULL); 02194 02195 AST_LIST_LOCK(&dpcache); 02196 02197 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags"); 02198 02199 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) { 02200 s = dp->expiry.tv_sec - tv.tv_sec; 02201 tmp[0] = '\0'; 02202 if (dp->flags & CACHE_FLAG_EXISTS) 02203 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1); 02204 if (dp->flags & CACHE_FLAG_NONEXISTENT) 02205 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1); 02206 if (dp->flags & CACHE_FLAG_CANEXIST) 02207 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1); 02208 if (dp->flags & CACHE_FLAG_PENDING) 02209 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1); 02210 if (dp->flags & CACHE_FLAG_TIMEOUT) 02211 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1); 02212 if (dp->flags & CACHE_FLAG_TRANSMITTED) 02213 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1); 02214 if (dp->flags & CACHE_FLAG_MATCHMORE) 02215 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1); 02216 if (dp->flags & CACHE_FLAG_UNKNOWN) 02217 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1); 02218 /* Trim trailing pipe */ 02219 if (!ast_strlen_zero(tmp)) 02220 tmp[strlen(tmp) - 1] = '\0'; 02221 else 02222 ast_copy_string(tmp, "(none)", sizeof(tmp)); 02223 y=0; 02224 pc = strchr(dp->peercontext, '@'); 02225 if (!pc) 02226 pc = dp->peercontext; 02227 else 02228 pc++; 02229 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++) 02230 if (dp->waiters[x] > -1) 02231 y++; 02232 if (s > 0) 02233 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp); 02234 else 02235 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp); 02236 } 02237 02238 AST_LIST_LOCK(&dpcache); 02239 02240 return RESULT_SUCCESS; 02241 } 02242 02243 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset); 02244 02245 static void unwrap_timestamp(struct iax_frame *fr) 02246 { 02247 int x; 02248 02249 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) { 02250 x = fr->ts - iaxs[fr->callno]->last; 02251 if (x < -50000) { 02252 /* Sudden big jump backwards in timestamp: 02253 What likely happened here is that miniframe timestamp has circled but we haven't 02254 gotten the update from the main packet. We'll just pretend that we did, and 02255 update the timestamp appropriately. */ 02256 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF); 02257 if (option_debug && iaxdebug) 02258 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n"); 02259 } 02260 if (x > 50000) { 02261 /* Sudden apparent big jump forwards in timestamp: 02262 What's likely happened is this is an old miniframe belonging to the previous 02263 top-16-bit timestamp that has turned up out of order. 02264 Adjust the timestamp appropriately. */ 02265 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF); 02266 if (option_debug && iaxdebug) 02267 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n"); 02268 } 02269 } 02270 } 02271 02272 static int get_from_jb(void *p); 02273 02274 static void update_jbsched(struct chan_iax2_pvt *pvt) 02275 { 02276 int when; 02277 02278 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore); 02279 02280 when = jb_next(pvt->jb) - when; 02281 02282 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid); 02283 02284 if(when <= 0) { 02285 /* XXX should really just empty until when > 0.. */ 02286 when = 1; 02287 } 02288 02289 pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno)); 02290 02291 /* Signal scheduler thread */ 02292 signal_condition(&sched_lock, &sched_cond); 02293 } 02294 02295 static void __get_from_jb(void *p) 02296 { 02297 int callno = PTR_TO_CALLNO(p); 02298 struct chan_iax2_pvt *pvt = NULL; 02299 struct iax_frame *fr; 02300 jb_frame frame; 02301 int ret; 02302 long now; 02303 long next; 02304 struct timeval tv; 02305 02306 /* Make sure we have a valid private structure before going on */ 02307 ast_mutex_lock(&iaxsl[callno]); 02308 pvt = iaxs[callno]; 02309 if (!pvt) { 02310 /* No go! */ 02311 ast_mutex_unlock(&iaxsl[callno]); 02312 return; 02313 } 02314 02315 pvt->jbid = -1; 02316 02317 gettimeofday(&tv,NULL); 02318 /* round up a millisecond since ast_sched_runq does; */ 02319 /* prevents us from spinning while waiting for our now */ 02320 /* to catch up with runq's now */ 02321 tv.tv_usec += 1000; 02322 02323 now = ast_tvdiff_ms(tv, pvt->rxcore); 02324 02325 if(now >= (next = jb_next(pvt->jb))) { 02326 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat)); 02327 switch(ret) { 02328 case JB_OK: 02329 fr = frame.data; 02330 __do_deliver(fr); 02331 break; 02332 case JB_INTERP: 02333 { 02334 struct ast_frame af; 02335 02336 /* create an interpolation frame */ 02337 af.frametype = AST_FRAME_VOICE; 02338 af.subclass = pvt->voiceformat; 02339 af.datalen = 0; 02340 af.samples = frame.ms * 8; 02341 af.mallocd = 0; 02342 af.src = "IAX2 JB interpolation"; 02343 af.data = NULL; 02344 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000)); 02345 af.offset=AST_FRIENDLY_OFFSET; 02346 02347 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame, 02348 * which we'd need to malloc, and then it would free it. That seems like a drag */ 02349 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) 02350 iax2_queue_frame(callno, &af); 02351 } 02352 break; 02353 case JB_DROP: 02354 iax2_frame_free(frame.data); 02355 break; 02356 case JB_NOFRAME: 02357 case JB_EMPTY: 02358 /* do nothing */ 02359 break; 02360 default: 02361 /* shouldn't happen */ 02362 break; 02363 } 02364 } 02365 update_jbsched(pvt); 02366 ast_mutex_unlock(&iaxsl[callno]); 02367 } 02368 02369 static int get_from_jb(void *data) 02370 { 02371 #ifdef SCHED_MULTITHREADED 02372 if (schedule_action(__get_from_jb, data)) 02373 #endif 02374 __get_from_jb(data); 02375 return 0; 02376 } 02377 02378 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout) 02379 { 02380 int type, len; 02381 int ret; 02382 int needfree = 0; 02383 02384 /* Attempt to recover wrapped timestamps */ 02385 unwrap_timestamp(fr); 02386 02387 02388 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */ 02389 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore)) 02390 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000)); 02391 else { 02392 #if 0 02393 if (option_debug) 02394 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n"); 02395 #endif 02396 fr->af.delivery = ast_tv(0,0); 02397 } 02398 02399 type = JB_TYPE_CONTROL; 02400 len = 0; 02401 02402 if(fr->af.frametype == AST_FRAME_VOICE) { 02403 type = JB_TYPE_VOICE; 02404 len = ast_codec_get_samples(&fr->af) / 8; 02405 } else if(fr->af.frametype == AST_FRAME_CNG) { 02406 type = JB_TYPE_SILENCE; 02407 } 02408 02409 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) { 02410 if (tsout) 02411 *tsout = fr->ts; 02412 __do_deliver(fr); 02413 return -1; 02414 } 02415 02416 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to 02417 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */ 02418 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && 02419 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) && 02420 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) { 02421 jb_frame frame; 02422 02423 /* deliver any frames in the jb */ 02424 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK) 02425 __do_deliver(frame.data); 02426 02427 jb_reset(iaxs[fr->callno]->jb); 02428 02429 if (iaxs[fr->callno]->jbid > -1) 02430 ast_sched_del(sched, iaxs[fr->callno]->jbid); 02431 02432 iaxs[fr->callno]->jbid = -1; 02433 02434 /* deliver this frame now */ 02435 if (tsout) 02436 *tsout = fr->ts; 02437 __do_deliver(fr); 02438 return -1; 02439 } 02440 02441 /* insert into jitterbuffer */ 02442 /* TODO: Perhaps we could act immediately if it's not droppable and late */ 02443 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts, 02444 calc_rxstamp(iaxs[fr->callno],fr->ts)); 02445 if (ret == JB_DROP) { 02446 needfree++; 02447 } else if (ret == JB_SCHED) { 02448 update_jbsched(iaxs[fr->callno]); 02449 } 02450 if (tsout) 02451 *tsout = fr->ts; 02452 if (needfree) { 02453 /* Free our iax frame */ 02454 iax2_frame_free(fr); 02455 return -1; 02456 } 02457 return 0; 02458 } 02459 02460 static int iax2_transmit(struct iax_frame *fr) 02461 { 02462 /* Lock the queue and place this packet at the end */ 02463 /* By setting this to 0, the network thread will send it for us, and 02464 queue retransmission if necessary */ 02465 fr->sentyet = 0; 02466 AST_LIST_LOCK(&queue); 02467 AST_LIST_INSERT_TAIL(&queue, fr, list); 02468 AST_LIST_UNLOCK(&queue); 02469 /* Wake up the network and scheduler thread */ 02470 pthread_kill(netthreadid, SIGURG); 02471 signal_condition(&sched_lock, &sched_cond); 02472 return 0; 02473 } 02474 02475 02476 02477 static int iax2_digit_begin(struct ast_channel *c, char digit) 02478 { 02479 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1); 02480 } 02481 02482 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration) 02483 { 02484 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1); 02485 } 02486 02487 static int iax2_sendtext(struct ast_channel *c, const char *text) 02488 { 02489 02490 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT, 02491 0, 0, (unsigned char *)text, strlen(text) + 1, -1); 02492 } 02493 02494 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img) 02495 { 02496 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1); 02497 } 02498 02499 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen) 02500 { 02501 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1); 02502 } 02503 02504 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan) 02505 { 02506 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt); 02507 ast_mutex_lock(&iaxsl[callno]); 02508 if (iaxs[callno]) 02509 iaxs[callno]->owner = newchan; 02510 else 02511 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n"); 02512 ast_mutex_unlock(&iaxsl[callno]); 02513 return 0; 02514 } 02515 02516 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin) 02517 { 02518 struct ast_variable *var; 02519 struct ast_variable *tmp; 02520 struct iax2_peer *peer=NULL; 02521 time_t regseconds = 0, nowtime; 02522 int dynamic=0; 02523 02524 if (peername) 02525 var = ast_load_realtime("iaxpeers", "name", peername, NULL); 02526 else { 02527 char porta[25]; 02528 sprintf(porta, "%d", ntohs(sin->sin_port)); 02529 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL); 02530 if (var) { 02531 /* We'll need the peer name in order to build the structure! */ 02532 for (tmp = var; tmp; tmp = tmp->next) { 02533 if (!strcasecmp(tmp->name, "name")) 02534 peername = tmp->value; 02535 } 02536 } 02537 } 02538 if (!var) 02539 return NULL; 02540 02541 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1); 02542 02543 if (!peer) 02544 return NULL; 02545 02546 for (tmp = var; tmp; tmp = tmp->next) { 02547 /* Make sure it's not a user only... */ 02548 if (!strcasecmp(tmp->name, "type")) { 02549 if (strcasecmp(tmp->value, "friend") && 02550 strcasecmp(tmp->value, "peer")) { 02551 /* Whoops, we weren't supposed to exist! */ 02552 destroy_peer(peer); 02553 peer = NULL; 02554 break; 02555 } 02556 } else if (!strcasecmp(tmp->name, "regseconds")) { 02557 ast_get_time_t(tmp->value, ®seconds, 0, NULL); 02558 } else if (!strcasecmp(tmp->name, "ipaddr")) { 02559 inet_aton(tmp->value, &(peer->addr.sin_addr)); 02560 } else if (!strcasecmp(tmp->name, "port")) { 02561 peer->addr.sin_port = htons(atoi(tmp->value)); 02562 } else if (!strcasecmp(tmp->name, "host")) { 02563 if (!strcasecmp(tmp->value, "dynamic")) 02564 dynamic = 1; 02565 } 02566 } 02567 if (!peer) 02568 return NULL; 02569 02570 ast_variables_destroy(var); 02571 02572 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) { 02573 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS); 02574 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) { 02575 if (peer->expire > -1) 02576 ast_sched_del(sched, peer->expire); 02577 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name); 02578 } 02579 AST_LIST_LOCK(&peers); 02580 AST_LIST_INSERT_HEAD(&peers, peer, entry); 02581 AST_LIST_UNLOCK(&peers); 02582 if (ast_test_flag(peer, IAX_DYNAMIC)) 02583 reg_source_db(peer); 02584 } else { 02585 ast_set_flag(peer, IAX_TEMPONLY); 02586 } 02587 02588 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) { 02589 time(&nowtime); 02590 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) { 02591 memset(&peer->addr, 0, sizeof(peer->addr)); 02592 realtime_update_peer(peer->name, &peer->addr, 0); 02593 if (option_debug) 02594 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n", 02595 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime); 02596 } 02597 else { 02598 if (option_debug) 02599 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n", 02600 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime); 02601 } 02602 } 02603 02604 return peer; 02605 } 02606 02607 static struct iax2_user *realtime_user(const char *username) 02608 { 02609 struct ast_variable *var; 02610 struct ast_variable *tmp; 02611 struct iax2_user *user=NULL; 02612 02613 var = ast_load_realtime("iaxusers", "name", username, NULL); 02614 if (!var) 02615 return NULL; 02616 02617 tmp = var; 02618 while(tmp) { 02619 /* Make sure it's not a peer only... */ 02620 if (!strcasecmp(tmp->name, "type")) { 02621 if (strcasecmp(tmp->value, "friend") && 02622 strcasecmp(tmp->value, "user")) { 02623 return NULL; 02624 } 02625 } 02626 tmp = tmp->next; 02627 } 02628 02629 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)); 02630 if (!user) 02631 return NULL; 02632 02633 ast_variables_destroy(var); 02634 02635 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) { 02636 ast_set_flag(user, IAX_RTCACHEFRIENDS); 02637 AST_LIST_LOCK(&users); 02638 AST_LIST_INSERT_HEAD(&users, user, entry); 02639 AST_LIST_UNLOCK(&users); 02640 } else { 02641 ast_set_flag(user, IAX_TEMPONLY); 02642 } 02643 02644 return user; 02645 } 02646 02647 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime) 02648 { 02649 char port[10]; 02650 char regseconds[20]; 02651 02652 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime); 02653 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port)); 02654 ast_update_realtime("iaxpeers", "name", peername, 02655 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port, 02656 "regseconds", regseconds, NULL); 02657 } 02658 02659 struct create_addr_info { 02660 int capability; 02661 unsigned int flags; 02662 int maxtime; 02663 int encmethods; 02664 int found; 02665 int sockfd; 02666 int adsi; 02667 char username[80]; 02668 char secret[80]; 02669 char outkey[80]; 02670 char timezone[80]; 02671 char prefs[32]; 02672 char context[AST_MAX_CONTEXT]; 02673 char peercontext[AST_MAX_CONTEXT]; 02674 char mohinterpret[MAX_MUSICCLASS]; 02675 char mohsuggest[MAX_MUSICCLASS]; 02676 }; 02677 02678 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai) 02679 { 02680 struct iax2_peer *peer; 02681 02682 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK); 02683 cai->sockfd = defaultsockfd; 02684 cai->maxtime = 0; 02685 sin->sin_family = AF_INET; 02686 02687 if (!(peer = find_peer(peername, 1))) { 02688 cai->found = 0; 02689 if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) { 02690 ast_log(LOG_WARNING, "No such host: %s\n", peername); 02691 return -1; 02692 } 02693 sin->sin_port = htons(IAX_DEFAULT_PORTNO); 02694 /* use global iax prefs for unknown peer/user */ 02695 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1); 02696 return 0; 02697 } 02698 02699 cai->found = 1; 02700 02701 /* if the peer has no address (current or default), return failure */ 02702 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) { 02703 if (ast_test_flag(peer, IAX_TEMPONLY)) 02704 destroy_peer(peer); 02705 return -1; 02706 } 02707 02708 /* if the peer is being monitored and is currently unreachable, return failure */ 02709 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) { 02710 if (ast_test_flag(peer, IAX_TEMPONLY)) 02711 destroy_peer(peer); 02712 return -1; 02713 } 02714 02715 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF); 02716 cai->maxtime = peer->maxms; 02717 cai->capability = peer->capability; 02718 cai->encmethods = peer->encmethods; 02719 cai->sockfd = peer->sockfd; 02720 cai->adsi = peer->adsi; 02721 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1); 02722 ast_copy_string(cai->context, peer->context, sizeof(cai->context)); 02723 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext)); 02724 ast_copy_string(cai->username, peer->username, sizeof(cai->username)); 02725 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone)); 02726 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey)); 02727 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret)); 02728 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest)); 02729 if (ast_strlen_zero(peer->dbsecret)) { 02730 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret)); 02731 } else { 02732 char *family; 02733 char *key = NULL; 02734 02735 family = ast_strdupa(peer->dbsecret); 02736 key = strchr(family, '/'); 02737 if (key) 02738 *key++ = '\0'; 02739 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) { 02740 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret); 02741 if (ast_test_flag(peer, IAX_TEMPONLY)) 02742 destroy_peer(peer); 02743 return -1; 02744 } 02745 } 02746 02747 if (peer->addr.sin_addr.s_addr) { 02748 sin->sin_addr = peer->addr.sin_addr; 02749 sin->sin_port = peer->addr.sin_port; 02750 } else { 02751 sin->sin_addr = peer->defaddr.sin_addr; 02752 sin->sin_port = peer->defaddr.sin_port; 02753 } 02754 02755 if (ast_test_flag(peer, IAX_TEMPONLY)) 02756 destroy_peer(peer); 02757 02758 return 0; 02759 } 02760 02761 static void __auto_congest(void *nothing) 02762 { 02763 int callno = PTR_TO_CALLNO(nothing); 02764 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION }; 02765 ast_mutex_lock(&iaxsl[callno]); 02766 if (iaxs[callno]) { 02767 iaxs[callno]->initid = -1; 02768 iax2_queue_frame(callno, &f); 02769 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n"); 02770 } 02771 ast_mutex_unlock(&iaxsl[callno]); 02772 } 02773 02774 static int auto_congest(void *data) 02775 { 02776 #ifdef SCHED_MULTITHREADED 02777 if (schedule_action(__auto_congest, data)) 02778 #endif 02779 __auto_congest(data); 02780 return 0; 02781 } 02782 02783 static unsigned int iax2_datetime(const char *tz) 02784 { 02785 time_t t; 02786 struct tm tm; 02787 unsigned int tmp; 02788 time(&t); 02789 localtime_r(&t, &tm); 02790 if (!ast_strlen_zero(tz)) 02791 ast_localtime(&t, &tm, tz); 02792 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */ 02793 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */ 02794 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */ 02795 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */ 02796 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */ 02797 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */ 02798 return tmp; 02799 } 02800 02801 struct parsed_dial_string { 02802 char *username; 02803 char *password; 02804 char *key; 02805 char *peer; 02806 char *port; 02807 char *exten; 02808 char *context; 02809 char *options; 02810 }; 02811 02812 /*! 02813 * \brief Parses an IAX dial string into its component parts. 02814 * \param data the string to be parsed 02815 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in 02816 * \return nothing 02817 * 02818 * This function parses the string and fills the structure 02819 * with pointers to its component parts. The input string 02820 * will be modified. 02821 * 02822 * \note This function supports both plaintext passwords and RSA 02823 * key names; if the password string is formatted as '[keyname]', 02824 * then the keyname will be placed into the key field, and the 02825 * password field will be set to NULL. 02826 * 02827 * \note The dial string format is: 02828 * [username[:password]@]peer[:port][/exten[@@context]][/options] 02829 */ 02830 static void parse_dial_string(char *data, struct parsed_dial_string *pds) 02831 { 02832 if (ast_strlen_zero(data)) 02833 return; 02834 02835 pds->peer = strsep(&data, "/"); 02836 pds->exten = strsep(&data, "/"); 02837 pds->options = data; 02838 02839 if (pds->exten) { 02840 data = pds->exten; 02841 pds->exten = strsep(&data, "@"); 02842 pds->context = data; 02843 } 02844 02845 if (strchr(pds->peer, '@')) { 02846 data = pds->peer; 02847 pds->username = strsep(&data, "@"); 02848 pds->peer = data; 02849 } 02850 02851 if (pds->username) { 02852 data = pds->username; 02853 pds->username = strsep(&data, ":"); 02854 pds->password = data; 02855 } 02856 02857 data = pds->peer; 02858 pds->peer = strsep(&data, ":"); 02859 pds->port = data; 02860 02861 /* check for a key name wrapped in [] in the secret position, if found, 02862 move it to the key field instead 02863 */ 02864 if (pds->password && (pds->password[0] == '[')) { 02865 pds->key = ast_strip_quoted(pds->password, "[", "]"); 02866 pds->password = NULL; 02867 } 02868 } 02869 02870 static int iax2_call(struct ast_channel *c, char *dest, int timeout) 02871 { 02872 struct sockaddr_in sin; 02873 char *l=NULL, *n=NULL, *tmpstr; 02874 struct iax_ie_data ied; 02875 char *defaultrdest = "s"; 02876 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt); 02877 struct parsed_dial_string pds; 02878 struct create_addr_info cai; 02879 struct ast_var_t *var; 02880 02881 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) { 02882 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name); 02883 return -1; 02884 } 02885 02886 memset(&cai, 0, sizeof(cai)); 02887 cai.encmethods = iax2_encryption; 02888 02889 memset(&pds, 0, sizeof(pds)); 02890 tmpstr = ast_strdupa(dest); 02891 parse_dial_string(tmpstr, &pds); 02892 02893 if (!pds.exten) 02894 pds.exten = defaultrdest; 02895 02896 if (create_addr(pds.peer, &sin, &cai)) { 02897 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer); 02898 return -1; 02899 } 02900 02901 if (!pds.username && !ast_strlen_zero(cai.username)) 02902 pds.username = cai.username; 02903 if (!pds.password && !ast_strlen_zero(cai.secret)) 02904 pds.password = cai.secret; 02905 if (!pds.key && !ast_strlen_zero(cai.outkey)) 02906 pds.key = cai.outkey; 02907 if (!pds.context && !ast_strlen_zero(cai.peercontext)) 02908 pds.context = cai.peercontext; 02909 02910 /* Keep track of the context for outgoing calls too */ 02911 ast_copy_string(c->context, cai.context, sizeof(c->context)); 02912 02913 if (pds.port) 02914 sin.sin_port = htons(atoi(pds.port)); 02915 02916 l = c->cid.cid_num; 02917 n = c->cid.cid_name; 02918 02919 /* Now build request */ 02920 memset(&ied, 0, sizeof(ied)); 02921 02922 /* On new call, first IE MUST be IAX version of caller */ 02923 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION); 02924 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten); 02925 if (pds.options && strchr(pds.options, 'a')) { 02926 /* Request auto answer */ 02927 iax_ie_append(&ied, IAX_IE_AUTOANSWER); 02928 } 02929 02930 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs); 02931 02932 if (l) { 02933 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l); 02934 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres); 02935 } else { 02936 if (n) 02937 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres); 02938 else 02939 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE); 02940 } 02941 02942 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton); 02943 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns); 02944 02945 if (n) 02946 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n); 02947 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani) 02948 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani); 02949 02950 if (!ast_strlen_zero(c->language)) 02951 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language); 02952 if (!ast_strlen_zero(c->cid.cid_dnid)) 02953 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid); 02954 if (!ast_strlen_zero(c->cid.cid_rdnis)) 02955 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis); 02956 02957 if (pds.context) 02958 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context); 02959 02960 if (pds.username) 02961 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username); 02962 02963 if (cai.encmethods) 02964 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods); 02965 02966 ast_mutex_lock(&iaxsl[callno]); 02967 02968 if (!ast_strlen_zero(c->context)) 02969 ast_string_field_set(iaxs[callno], context, c->context); 02970 02971 if (pds.username) 02972 ast_string_field_set(iaxs[callno], username, pds.username); 02973 02974 iaxs[callno]->encmethods = cai.encmethods; 02975 02976 iaxs[callno]->adsi = cai.adsi; 02977 02978 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret); 02979 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest); 02980 02981 if (pds.key) 02982 ast_string_field_set(iaxs[callno], outkey, pds.key); 02983 if (pds.password) 02984 ast_string_field_set(iaxs[callno], secret, pds.password); 02985 02986 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats); 02987 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability); 02988 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe); 02989 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone)); 02990 02991 if (iaxs[callno]->maxtime) { 02992 /* Initialize pingtime and auto-congest time */ 02993 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2; 02994 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno)); 02995 } else if (autokill) { 02996 iaxs[callno]->pingtime = autokill / 2; 02997 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno)); 02998 } 02999 03000 /* send the command using the appropriate socket for this peer */ 03001 iaxs[callno]->sockfd = cai.sockfd; 03002 03003 /* Add remote vars */ 03004 AST_LIST_TRAVERSE(&c->varshead, var, entries) { 03005 if (!strncmp(ast_var_name(var), "~IAX2~", strlen("~IAX2~"))) { 03006 char tmp[256]; 03007 int i; 03008 /* Automatically divide the value up into sized chunks */ 03009 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) - strlen("~IAX2~") + 1)) { 03010 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var) + strlen("~IAX2~"), ast_var_value(var) + i); 03011 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp); 03012 } 03013 } 03014 } 03015 03016 /* Transmit the string in a "NEW" request */ 03017 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1); 03018 03019 ast_mutex_unlock(&iaxsl[callno]); 03020 ast_setstate(c, AST_STATE_RINGING); 03021 03022 return 0; 03023 } 03024 03025 static int iax2_hangup(struct ast_channel *c) 03026 { 03027 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt); 03028 int alreadygone; 03029 struct iax_ie_data ied; 03030 memset(&ied, 0, sizeof(ied)); 03031 ast_mutex_lock(&iaxsl[callno]); 03032 if (callno && iaxs[callno]) { 03033 if (option_debug) 03034 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name); 03035 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE); 03036 /* Send the hangup unless we have had a transmission error or are already gone */ 03037 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause); 03038 if (!iaxs[callno]->error && !alreadygone) 03039 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1); 03040 /* Explicitly predestroy it */ 03041 iax2_predestroy(callno); 03042 /* If we were already gone to begin with, destroy us now */ 03043 if (alreadygone) { 03044 if (option_debug) 03045 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name); 03046 iax2_destroy(callno); 03047 } 03048 } 03049 ast_mutex_unlock(&iaxsl[callno]); 03050 if (option_verbose > 2) 03051 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name); 03052 return 0; 03053 } 03054 03055 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen) 03056 { 03057 struct ast_option_header *h; 03058 int res; 03059 03060 switch (option) { 03061 case AST_OPTION_TXGAIN: 03062 case AST_OPTION_RXGAIN: 03063 /* these two cannot be sent, because they require a result */ 03064 errno = ENOSYS; 03065 return -1; 03066 default: 03067 if (!(h = ast_malloc(datalen + sizeof(*h)))) 03068 return -1; 03069 03070 h->flag = AST_OPTION_FLAG_REQUEST; 03071 h->option = htons(option); 03072 memcpy(h->data, data, datalen); 03073 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL, 03074 AST_CONTROL_OPTION, 0, (unsigned char *) h, 03075 datalen + sizeof(*h), -1); 03076 free(h); 03077 return res; 03078 } 03079 } 03080 03081 static struct ast_frame *iax2_read(struct ast_channel *c) 03082 { 03083 ast_log(LOG_NOTICE, "I should never be called!\n"); 03084 return &ast_null_frame; 03085 } 03086 03087 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly) 03088 { 03089 int res; 03090 struct iax_ie_data ied0; 03091 struct iax_ie_data ied1; 03092 unsigned int transferid = (unsigned int)ast_random(); 03093 memset(&ied0, 0, sizeof(ied0)); 03094 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr); 03095 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno); 03096 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid); 03097 03098 memset(&ied1, 0, sizeof(ied1)); 03099 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr); 03100 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno); 03101 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid); 03102 03103 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1); 03104 if (res) 03105 return -1; 03106 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1); 03107 if (res) 03108 return -1; 03109 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN; 03110 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN; 03111 return 0; 03112 } 03113 03114 static void lock_both(unsigned short callno0, unsigned short callno1) 03115 { 03116 ast_mutex_lock(&iaxsl[callno0]); 03117 while (ast_mutex_trylock(&iaxsl[callno1])) { 03118 ast_mutex_unlock(&iaxsl[callno0]); 03119 usleep(10); 03120 ast_mutex_lock(&iaxsl[callno0]); 03121 } 03122 } 03123 03124 static void unlock_both(unsigned short callno0, unsigned short callno1) 03125 { 03126 ast_mutex_unlock(&iaxsl[callno1]); 03127 ast_mutex_unlock(&iaxsl[callno0]); 03128 } 03129 03130 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) 03131 { 03132 struct ast_channel *cs[3]; 03133 struct ast_channel *who, *other; 03134 int to = -1; 03135 int res = -1; 03136 int transferstarted=0; 03137 struct ast_frame *f; 03138 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt); 03139 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt); 03140 struct timeval waittimer = {0, 0}, tv; 03141 03142 lock_both(callno0, callno1); 03143 /* Put them in native bridge mode */ 03144 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) { 03145 iaxs[callno0]->bridgecallno = callno1; 03146 iaxs[callno1]->bridgecallno = callno0; 03147 } 03148 unlock_both(callno0, callno1); 03149 03150 /* If not, try to bridge until we can execute a transfer, if we can */ 03151 cs[0] = c0; 03152 cs[1] = c1; 03153 for (/* ever */;;) { 03154 /* Check in case we got masqueraded into */ 03155 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) { 03156 if (option_verbose > 2) 03157 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n"); 03158 /* Remove from native mode */ 03159 if (c0->tech == &iax2_tech) { 03160 ast_mutex_lock(&iaxsl[callno0]); 03161 iaxs[callno0]->bridgecallno = 0; 03162 ast_mutex_unlock(&iaxsl[callno0]); 03163 } 03164 if (c1->tech == &iax2_tech) { 03165 ast_mutex_lock(&iaxsl[callno1]); 03166 iaxs[callno1]->bridgecallno = 0; 03167 ast_mutex_unlock(&iaxsl[callno1]); 03168 } 03169 return AST_BRIDGE_FAILED_NOWARN; 03170 } 03171 if (c0->nativeformats != c1->nativeformats) { 03172 if (option_verbose > 2) { 03173 char buf0[255]; 03174 char buf1[255]; 03175 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats); 03176 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats); 03177 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1); 03178 } 03179 /* Remove from native mode */ 03180 lock_both(callno0, callno1); 03181 iaxs[callno0]->bridgecallno = 0; 03182 iaxs[callno1]->bridgecallno = 0; 03183 unlock_both(callno0, callno1); 03184 return AST_BRIDGE_FAILED_NOWARN; 03185 } 03186 /* check if transfered and if we really want native bridging */ 03187 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) { 03188 /* Try the transfer */ 03189 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) || 03190 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA))) 03191 ast_log(LOG_WARNING, "Unable to start the transfer\n"); 03192 transferstarted = 1; 03193 } 03194 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) { 03195 /* Call has been transferred. We're no longer involved */ 03196 gettimeofday(&tv, NULL); 03197 if (ast_tvzero(waittimer)) { 03198 waittimer = tv; 03199 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) { 03200 c0->_softhangup |= AST_SOFTHANGUP_DEV; 03201 c1->_softhangup |= AST_SOFTHANGUP_DEV; 03202 *fo = NULL; 03203 *rc = c0; 03204 res = AST_BRIDGE_COMPLETE; 03205 break; 03206 } 03207 } 03208 to = 1000; 03209 who = ast_waitfor_n(cs, 2, &to); 03210 if (timeoutms > -1) { 03211 timeoutms -= (1000 - to); 03212 if (timeoutms < 0) 03213 timeoutms = 0; 03214 } 03215 if (!who) { 03216 if (!timeoutms) { 03217 res = AST_BRIDGE_RETRY; 03218 break; 03219 } 03220 if (ast_check_hangup(c0) || ast_check_hangup(c1)) { 03221 res = AST_BRIDGE_FAILED; 03222 break; 03223 } 03224 continue; 03225 } 03226 f = ast_read(who); 03227 if (!f) { 03228 *fo = NULL; 03229 *rc = who; 03230 res = AST_BRIDGE_COMPLETE; 03231 break; 03232 } 03233 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) { 03234 *fo = f; 03235 *rc = who; 03236 res = AST_BRIDGE_COMPLETE; 03237 break; 03238 } 03239 other = (who == c0) ? c1 : c0; /* the 'other' channel */ 03240 if ((f->frametype == AST_FRAME_VOICE) || 03241 (f->frametype == AST_FRAME_TEXT) || 03242 (f->frametype == AST_FRAME_VIDEO) || 03243 (f->frametype == AST_FRAME_IMAGE) || 03244 (f->frametype == AST_FRAME_DTMF)) { 03245 /* monitored dtmf take out of the bridge. 03246 * check if we monitor the specific source. 03247 */ 03248 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1; 03249 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) { 03250 *rc = who; 03251 *fo = f; 03252 res = AST_BRIDGE_COMPLETE; 03253 /* Remove from native mode */ 03254 break; 03255 } 03256 /* everything else goes to the other side */ 03257 ast_write(other, f); 03258 } 03259 ast_frfree(f); 03260 /* Swap who gets priority */ 03261 cs[2] = cs[0]; 03262 cs[0] = cs[1]; 03263 cs[1] = cs[2]; 03264 } 03265 lock_both(callno0, callno1); 03266 if(iaxs[callno0]) 03267 iaxs[callno0]->bridgecallno = 0; 03268 if(iaxs[callno1]) 03269 iaxs[callno1]->bridgecallno = 0; 03270 unlock_both(callno0, callno1); 03271 return res; 03272 } 03273 03274 static int iax2_answer(struct ast_channel *c) 03275 { 03276 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt); 03277 if (option_debug) 03278 ast_log(LOG_DEBUG, "Answering IAX2 call\n"); 03279 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1); 03280 } 03281 03282 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen) 03283 { 03284 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt); 03285 03286 if (option_debug && iaxdebug) 03287 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition); 03288 03289 if (!strcasecmp(iaxs[callno]->mohinterpret, "passthrough")) 03290 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, data, datalen, -1); 03291 03292 switch (condition) { 03293 case AST_CONTROL_HOLD: 03294 ast_moh_start(c, data, iaxs[callno]->mohinterpret); 03295 return 0; 03296 case AST_CONTROL_UNHOLD: 03297 ast_moh_stop(c); 03298 return 0; 03299 default: 03300 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, data, datalen, -1); 03301 } 03302 } 03303 03304 static int iax2_transfer(struct ast_channel *c, const char *dest) 03305 { 03306 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt); 03307 struct iax_ie_data ied; 03308 char tmp[256], *context; 03309 ast_copy_string(tmp, dest, sizeof(tmp)); 03310 context = strchr(tmp, '@'); 03311 if (context) { 03312 *context = '\0'; 03313 context++; 03314 } 03315 memset(&ied, 0, sizeof(ied)); 03316 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp); 03317 if (context) 03318 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context); 03319 if (option_debug) 03320 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest); 03321 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1); 03322 } 03323 03324 static int iax2_getpeertrunk(struct sockaddr_in sin) 03325 { 03326 struct iax2_peer *peer = NULL; 03327 int res = 0; 03328 03329 AST_LIST_LOCK(&peers); 03330 AST_LIST_TRAVERSE(&peers, peer, entry) { 03331 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) && 03332 (peer->addr.sin_port == sin.sin_port)) { 03333 res = ast_test_flag(peer, IAX_TRUNK); 03334 break; 03335 } 03336 } 03337 AST_LIST_UNLOCK(&peers); 03338 03339 return res; 03340 } 03341 03342 /*! \brief Create new call, interface with the PBX core */ 03343 static struct ast_channel *ast_iax2_new(int callno, int state, int capability) 03344 { 03345 struct ast_channel *tmp; 03346 struct chan_iax2_pvt *i; 03347 struct ast_variable *v = NULL; 03348 03349 if (!(i = iaxs[callno])) { 03350 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno); 03351 return NULL; 03352 } 03353 03354 /* Don't hold call lock */ 03355 ast_mutex_unlock(&iaxsl[callno]); 03356 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "IAX2/%s-%d", i->host, i->callno); 03357 ast_mutex_lock(&iaxsl[callno]); 03358 if (!tmp) 03359 return NULL; 03360 tmp->tech = &iax2_tech; 03361 /* We can support any format by default, until we get restricted */ 03362 tmp->nativeformats = capability; 03363 tmp->readformat = ast_best_codec(capability); 03364 tmp->writeformat = ast_best_codec(capability); 03365 tmp->tech_pvt = CALLNO_TO_PTR(i->callno); 03366 03367 /* Don't use ast_set_callerid() here because it will 03368 * generate a NewCallerID event before the NewChannel event */ 03369 tmp->cid.cid_num = ast_strdup(i->cid_num); 03370 tmp->cid.cid_name = ast_strdup(i->cid_name); 03371 if (!ast_strlen_zero(i->ani)) 03372 tmp->cid.cid_ani = ast_strdup(i->ani); 03373 else 03374 tmp->cid.cid_ani = ast_strdup(i->cid_num); 03375 tmp->cid.cid_dnid = ast_strdup(i->dnid); 03376 tmp->cid.cid_rdnis = ast_strdup(i->rdnis); 03377 tmp->cid.cid_pres = i->calling_pres; 03378 tmp->cid.cid_ton = i->calling_ton; 03379 tmp->cid.cid_tns = i->calling_tns; 03380 if (!ast_strlen_zero(i->language)) 03381 ast_string_field_set(tmp, language, i->language); 03382 if (!ast_strlen_zero(i->accountcode)) 03383 ast_string_field_set(tmp, accountcode, i->accountcode); 03384 if (i->amaflags) 03385 tmp->amaflags = i->amaflags; 03386 ast_copy_string(tmp->context, i->context, sizeof(tmp->context)); 03387 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten)); 03388 if (i->adsi) 03389 tmp->adsicpe = i->peeradsicpe; 03390 else 03391 tmp->adsicpe = AST_ADSI_UNAVAILABLE; 03392 i->owner = tmp; 03393 i->capability = capability; 03394 if (state != AST_STATE_DOWN) { 03395 if (ast_pbx_start(tmp)) { 03396 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name); 03397 ast_hangup(tmp); 03398 i->owner = NULL; 03399 return NULL; 03400 } 03401 } 03402 03403 for (v = i->vars ; v ; v = v->next) 03404 pbx_builtin_setvar_helper(tmp, v->name, v->value); 03405 03406 ast_module_ref(ast_module_info->self); 03407 return tmp; 03408 } 03409 03410 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv) 03411 { 03412 unsigned long int mssincetx; /* unsigned to handle overflows */ 03413 long int ms, pred; 03414 03415 tpeer->trunkact = *tv; 03416 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime); 03417 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) { 03418 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */ 03419 tpeer->txtrunktime = *tv; 03420 tpeer->lastsent = 999999; 03421 } 03422 /* Update last transmit time now */ 03423 tpeer->lasttxtime = *tv; 03424 03425 /* Calculate ms offset */ 03426 ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime); 03427 /* Predict from last value */ 03428 pred = tpeer->lastsent + sampms; 03429 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW) 03430 ms = pred; 03431 03432 /* We never send the same timestamp twice, so fudge a little if we must */ 03433 if (ms == tpeer->lastsent) 03434 ms = tpeer->lastsent + 1; 03435 tpeer->lastsent = ms; 03436 return ms; 03437 } 03438 03439 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts) 03440 { 03441 long ms; /* NOT unsigned */ 03442 if (ast_tvzero(iaxs[callno]->rxcore)) { 03443 /* Initialize rxcore time if appropriate */ 03444 gettimeofday(&iaxs[callno]->rxcore, NULL); 03445 /* Round to nearest 20ms so traces look pretty */ 03446 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000; 03447 } 03448 /* Calculate difference between trunk and channel */ 03449 ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore); 03450 /* Return as the sum of trunk time and the difference between trunk and real time */ 03451 return ms + ts; 03452 } 03453 03454 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f) 03455 { 03456 int ms; 03457 int voice = 0; 03458 int genuine = 0; 03459 int adjust; 03460 struct timeval *delivery = NULL; 03461 03462 03463 /* What sort of frame do we have?: voice is self-explanatory 03464 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK 03465 non-genuine frames are CONTROL frames [ringing etc], DTMF 03466 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp, 03467 the others need a timestamp slaved to the voice frames so that they go in sequence 03468 */ 03469 if (f) { 03470 if (f->frametype == AST_FRAME_VOICE) { 03471 voice = 1; 03472 delivery = &f->delivery; 03473 } else if (f->frametype == AST_FRAME_IAX) { 03474 genuine = 1; 03475 } else if (f->frametype == AST_FRAME_CNG) { 03476 p->notsilenttx = 0; 03477 } 03478 } 03479 if (ast_tvzero(p->offset)) { 03480 gettimeofday(&p->offset, NULL); 03481 /* Round to nearest 20ms for nice looking traces */ 03482 p->offset.tv_usec -= p->offset.tv_usec % 20000; 03483 } 03484 /* If the timestamp is specified, just send it as is */ 03485 if (ts) 03486 return ts; 03487 /* If we have a time that the frame arrived, always use it to make our timestamp */ 03488 if (delivery && !ast_tvzero(*delivery)) { 03489 ms = ast_tvdiff_ms(*delivery, p->offset); 03490 if (option_debug > 2 && iaxdebug) 03491 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno); 03492 } else { 03493 ms = ast_tvdiff_ms(ast_tvnow(), p->offset); 03494 if (ms < 0) 03495 ms = 0; 03496 if (voice) { 03497 /* On a voice frame, use predicted values if appropriate */ 03498 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) { 03499 /* Adjust our txcore, keeping voice and non-voice synchronized */ 03500 /* AN EXPLANATION: 03501 When we send voice, we usually send "calculated" timestamps worked out 03502 on the basis of the number of samples sent. When we send other frames, 03503 we usually send timestamps worked out from the real clock. 03504 The problem is that they can tend to drift out of step because the 03505 source channel's clock and our clock may not be exactly at the same rate. 03506 We fix this by continuously "tweaking" p->offset. p->offset is "time zero" 03507 for this call. Moving it adjusts timestamps for non-voice frames. 03508 We make the adjustment in the style of a moving average. Each time we 03509 adjust p->offset by 10% of the difference between our clock-derived 03510 timestamp and the predicted timestamp. That's why you see "10000" 03511 below even though IAX2 timestamps are in milliseconds. 03512 The use of a moving average avoids offset moving too radically. 03513 Generally, "adjust" roams back and forth around 0, with offset hardly 03514 changing at all. But if a consistent different starts to develop it 03515 will be eliminated over the course of 10 frames (200-300msecs) 03516 */ 03517 adjust = (ms - p->nextpred); 03518 if (adjust < 0) 03519 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000)); 03520 else if (adjust > 0) 03521 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000)); 03522 03523 if (!p->nextpred) { 03524 p->nextpred = ms; /*f->samples / 8;*/ 03525 if (p->nextpred <= p->