![]() |
Home page |
Mailing list |
Docs
Asterisk developer's documentation :: Codename Pineapple
chan_sip3.c
Go to the documentation of this file.
00001 /* CODENAME PINEAPPLE - THIS IS VERY EXPERIMENTAL. 00002 IF YOU USE THIS IN PRODUCTION, I WILL NOT SUPPORT YOU... 00003 * 00004 * -- Mail bugs to oej@edvina.net, do not file them in the bug tracker 00005 */ 00006 00007 /* To skip to source code, search for "-END-" */ 00008 00009 /* 00010 * Asterisk -- An open source telephony toolkit. 00011 * 00012 * Copyright (C) 1999 - 2007, Digium, Inc. 00013 * 00014 * Mark Spencer <markster@digium.com> 00015 * Chan_sip3 changes by Olle E. Johansson <oej@edvina.net> 00016 * 00017 * 00018 * 00019 * See http://www.asterisk.org for more information about 00020 * the Asterisk project. Please do not directly contact 00021 * any of the maintainers of this project for assistance; 00022 * the project provides a web site, mailing lists and IRC 00023 * channels for your use. 00024 * 00025 * This program is free software, distributed under the terms of 00026 * the GNU General Public License Version 2. See the LICENSE file 00027 * at the top of the source tree. 00028 */ 00029 00030 /*! 00031 * \file 00032 * \brief Implementation of Session Initiation Protocol 00033 * Version 3 of chan_sip 00034 * 00035 * \author Mark Spencer <markster@digium.com> 00036 * \author Olle E. Johansson <oej@edvina.net> (all the chan_sip3 changes) 00037 * 00038 * See Also: 00039 * \arg \ref AstCREDITS 00040 * 00041 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support 00042 * Configuration file \link Config_sip sip.conf \endlink 00043 * 00044 * 00045 * \todo SIP over TCP 00046 * \todo SIP over TLS 00047 * \todo Better support of forking 00048 * \todo VIA branch tag transaction checking 00049 * \todo Transaction support 00050 * 00051 * \ingroup channel_drivers 00052 */ 00053 00054 /*! \page chan_sip3_overview Chan_SIP3:: Overview 00055 * 00056 * \par Overview of the handling of SIP sessions 00057 * The SIP channel handles several types of SIP sessions, or dialogs, 00058 * not all of them being "telephone calls". 00059 * - Incoming calls that will be sent to the PBX core 00060 * - Outgoing calls, generated by the PBX 00061 * - SIP subscriptions and notifications of states and voicemail messages 00062 * - SIP registrations, both inbound and outbound 00063 * - SIP peer management (peerpoke, OPTIONS) 00064 * - SIP text messages 00065 * 00066 * In the SIP channel, there's a list of active SIP dialogs, which includes 00067 * all of these when they are active. "sip show channels" in the CLI will 00068 * show most of these, excluding subscriptions which are shown by 00069 * "sip show subscriptions" 00070 * 00071 * \par incoming packets 00072 * Incoming packets are received in the monitoring thread, then handled by 00073 * sipsock_read(). This function parses the packet and matches an existing 00074 * dialog or starts a new SIP dialog. 00075 * 00076 * sipsock_read sends the packet to handle_request(), that parses a bit more. 00077 * if it's a response to an outbound request, it's sent to handle_response(). 00078 * If it is a request, handle_request sends it to one of a list of functions 00079 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc 00080 * sipsock_read locks the ast_channel if it exists (an active call) and 00081 * unlocks it after we have processed the SIP message. 00082 * 00083 * A new INVITE is sent to handle_request_invite(), that will end up 00084 * starting a new channel in the PBX, the new channel after that executing 00085 * in a separate channel thread. This is an incoming "call". 00086 * When the call is answered, either by a bridged channel or the PBX itself 00087 * the sip_answer() function is called. 00088 * 00089 * The actual media - Video or Audio - is mostly handled by the RTP subsystem 00090 * in rtp.c 00091 * 00092 * \par Outbound calls 00093 * Outbound calls are set up by the PBX through the sip_request_call() 00094 * function. After that, they are activated by sip_call(). 00095 * 00096 * \par Hanging up 00097 * The PBX issues a hangup on both incoming and outgoing calls through 00098 * the sip_hangup() function 00099 * 00100 * \section SIP3dialog Dialogs, packets, transactions 00101 * 00102 * This version of chan_sip has a concept of a SIP dialog (\ref sip_dialog) that 00103 * lives throughut a session - a call (INVITE), a registration (REGISTER) 00104 * or a subscription for status (SUBSCRIBE)... We do save new requests we 00105 * send in a queue (sip_dialog->packets) until they're acknowledged by the 00106 * remote party, when we remove them (sip_ack() ) 00107 * 00108 * For requests and responses, we store them in a structure called \ref sip_request 00109 * and process them. The matching between a response or a new request and an 00110 * existing dialog is done in match_or_create_dialog(). 00111 * 00112 */ 00113 00114 /*! \page chan_sip3_00index Chan_sip3: Index over docs 00115 \title Chan_sip3 :: Index 00116 00117 - \ref chan_sip3_overview 00118 - \subpage chan_sip3_start 00119 - \subpage chan_sip3_security 00120 - \subpage chan_sip3_objects 00121 - \subpage chan_sip3_registrydb 00122 - \subpage chan_sip3_files 00123 - \subpage chan_sip3_auth 00124 - \subpage chan_sip3_dialogs 00125 - \subpage chan_sip3_transactions 00126 - \subpage sip3_timer_doc 00127 - \subpage sip3_dialog_match 00128 - \subpage chan_sip3_dialstring 00129 - \subpage chan_sip3_natsupport 00130 00131 \par todo Things to do, ideas 00132 - \subpage chan_sip3_todo 00133 - \subpage chan_sip3_subs 00134 00135 */ 00136 00137 /*! 00138 \page chan_sip3_start Chan_sip3: Welcome to Codename Pineapple ! 00139 00140 \title Chan_sip3: What's this? 00141 This is a re-work of the SIP channel in Asterisk. 00142 This channel will not be backwards compatible with the old 00143 sip channel. In order to be more SIP compatible, I will have 00144 to break the backwards compatibility. That's why the old channel 00145 will still be around for a while. 00146 00147 Chan_sip3 is the road towards security (see \ref chan_sip3_security). 00148 By adding a transaction layer and support for TCP connections, we can 00149 add TLS for the TCP connections and negotiate keys for secure media 00150 with SRTP. 00151 00152 ** This work is sponsored by voop.com - the Internet Dialtone. 00153 I am open for more sponsors - contact me on oej@edvina.net 00154 00155 \page chan_sip3_todo Chan_sip3: Things to do 00156 \b Done 00157 - Trying to reduce memory allocations for packets. 00158 - sipsock_read allocates a packet that stays in memory 00159 until the transaction is finished. If it's an initial 00160 request, it's flagged to stay in memory and kept until 00161 destruction of the dialog (or replacement of initreq). 00162 - The issue here is parsing, since parsing destroys the 00163 in-memory copy of the outbound message thus stopping 00164 proper re-transmits. Added flag for parsing of packet, 00165 trying to delay parsing until we send a response. 00166 - Added new CLI command "sip list configs" to list all configuration options 00167 Mostly for debugging 00168 00169 - Added new configuration engine 00170 - Add T1 timer configuration settings 00171 - Added configurable T2 timer, see \ref sip3_timer_doc 00172 - Added time to astdb registry storage, so that expired registrations 00173 won't be activated at restart 00174 - removed pedantic mode 00175 - added config option for qualify frequency timers 00176 - merged peermatch and sipregister branches 00177 - removed "type=user" 00178 - change "sip nodebug" to "sip debug off" and "sip debug" to "sip debug on" - done 00179 - change "sip history" and "nohistory" to "on/off" - done 00180 - "sip show/list peers" is now "sip show/list phones" 00181 - manager command renamed - SIPdevices and SIPshowdevice 00182 - Added "authuser" configuration option for trunks and services 00183 - Added "domain" configuration option for all devices 00184 - Fixed handling of too short registration times (sending 423) 00185 - T38 does no longer depend on canreinvite settings 00186 - removed userconf support (in favour of astum) 00187 00188 \b Larger changes required outside of chan_sip 00189 - dnsmgr needs to follow DNS ttl 00190 - dnsmgr needs to handle SRV, NAPTR 00191 00192 \b Halfdone 00193 - Added separate TOS setting for presence. Need to run setsockopt 00194 in a locked socket for that to work on the SIP interface. 00195 00196 \par Todo - architecture 00197 - check if the "defaultport" and "port" settings are working - port for remote peer? 00198 - dnsmgr needs to be integrated and updated 00199 - netsock? 00200 - thread and separate port for outbound registrations 00201 - receive queue between sipsock_read and handle_request 00202 - inbound call authentication 00203 00204 \par Todo - ideas 00205 - Implement support for a:rtcp sdp (needs changes in the rtp interface) 00206 - Implement "busylimit" for signalling busy, but not enforcing a call limit 00207 - Use "accept-language" to set language tags in error messages etc 00208 - Implement "holdaction = music | sendhold" 00209 - Handle 423 Interval too brief on registrations 00210 - Accept-language to language tag. 00211 - Fix T4 implementation 00212 - Configuration setting implemented in global 00213 - Check if usereqphone is a global flag 00214 - Fix compact headers per peer 00215 - Always enable "alwaysauthreject" and remove that option 00216 - Check "insecure" option - do we still need it? 00217 - Only check for pickup code if callgroup/pickupgroups are specified in config 00218 - check resp 491 to INVITE processing 00219 - Make show devices and the completion support domains too 00220 - Fix realtime caching and optional loading 00221 - Clean up the authuser/username/peername mess! 00222 - authuser as a separate config option, please, please 00223 - Split up source code file 00224 - Add astum 00225 - Add auto-nat for RFC 1918 networks 00226 - Add type=device for peers 00227 - Add type=service for register= replacement 00228 - Add type=trunk definition, based on domain routing 00229 - Implement state engine for dialogs 00230 - Implement transactions 00231 - Implement state engine for transactions 00232 - Implement real realtime caching 00233 - Implement realtime static loading for MWI and qualify support 00234 - Implement remote MWI notification 00235 - Implement remote subscriptions 00236 - Implement improved SIP domain support 00237 - Document these ideas! 00238 - Prove transaction engine by implementing PRACK 00239 - Implement netsock API in this channel 00240 - Add File's multithreading code 00241 - Make debugaddr a ha list instead of one address and move it out of sipnet 00242 - Save the last sent request/response for re-transmits 00243 - RTP keepalives (STUN) for video 00244 - Clean up 302 redirect - remove "promisredir" setting 00245 00246 \b Maybe 00247 - add support for Path header 00248 the Path is arriving with Register requests, saved in location 00249 and used as a Route: header in the outbound request 00250 - Add support for the "norefersub" option 00251 - Add support for GRUU 00252 00253 - ... And much more 00254 */ 00255 /*! 00256 \page chan_sip3_security Chan_sip3: The road to SIP security 00257 00258 Codename pineapple is the road towards SIP security. 00259 00260 - SIP/TLS is the way to secure signalling 00261 - In order to get there, we need TCP 00262 - In order to get TCP, we need a transaction state engine 00263 - We also need a separation of network transmission over 00264 reliable and unreliable transports and the SIP 00265 core 00266 - When we have that, we can add SRTP 00267 00268 */ 00269 /*! 00270 \page chan_sip3_objects Chan_sip3: Devices, trunks and services 00271 - \b phones are devices that connect to Asterisk. They register with 00272 Asterisk acting as a SIP location server/registrar and use Asterisk 00273 as the outbound SIP proxy. They get calls from Asterisk and place 00274 calls to Asterisk. The phone use one of the SIP domains that are hosted 00275 within your Asterisk server. (this is like the 00276 current "friend") 00277 00278 - \b service is when Asterisk is the UA, acting as a phone towards 00279 another SIP server - we register with a SIP location server/registrar 00280 to get incoming calls. We place 00281 calls, masquerading as a phone (using the registrars domain). 00282 Currently, this is a mixture between a peer (matched on IP for 00283 incoming calls) and a register= statement. In some cases, two 00284 peers and a register= statement. Very confusing. 00285 00286 - \b trunk is when we exchange traffic with another server. We send 00287 calls to their SIP domain and receive calls to our SIP domain. We may 00288 use realm based authentication for the incoming part of the trunk 00289 (not based on caller ID/From: header) and a combination of SIP domain and ACLs. 00290 This is currently handled by defining sip peers for outbound calls and 00291 separate SIP peers for inbound calls - where we match on IP. The 00292 problem with the IP matching is when a trunking partner use several 00293 SIP servers to connect to us, we need to define one peer per server 00294 instead of just matching on domain and then authenticate. 00295 00296 */ 00297 00298 /*! 00299 \page chan_sip3_subs Chan_sip3: Subscriptions 00300 00301 \title Ideas for a new subscription system 00302 00303 We need to move out the active subsriptions to a list 00304 of their own, like the registry. Do not keep them in 00305 the active dialog list, they're active subscriptions. 00306 00307 Add a list of internal and external subscriptions. 00308 We need one object that "watches" URIs or extensions 00309 that is connected to subscribers. For several subscribers, 00310 we have only one internal or external subscription. 00311 00312 Should the external subscription system be directly 00313 connected or go through the hint subsystem? Will this 00314 cause un-needed overhead? 00315 00316 exten => johnny,hint,sipsubscribe::sip:johnny@johnnysdomain.com 00317 00318 */ 00319 00320 /*! 00321 \page chan_sip3_files Chan_sip3: Source code files 00322 \title Chan_sip3: Source Code Files 00323 00324 \b \\channels 00325 00326 - \b chan_sip3.c The main source code file for the channel 00327 PBX interface 00328 00329 \b \\channels\\sip3 00330 00331 - \b sip3.h The include file for structures and enums 00332 - \b sip3funcs.h The include file for functions 00333 - \b sip3_cliami.c Manager and CLI functions 00334 - \b sip3_sdprtp.c SDP handling and RTP interface 00335 - \b sip3_callerid.c CallerID, pres and RPID handling 00336 - \b sip3_monitor.c The monitor thread (housekeeping) 00337 - \b sip3_dialog.c SIP dialog support 00338 - \b sip3_auth.c SIP authentication 00339 - \b sip3_config.c Configuration 00340 - \b sip3_domain.c SIP domain support 00341 - \b sip3_subscribe.c SIP subscription support 00342 - \b sip3_parse.c Parsing stuff 00343 - \b sip3_compose.c Composing new requests and responses 00344 - \b sip3_refer.c SIP transfer and parking support 00345 - \b sip3_network.c Networks interface (UDP today) 00346 - \b sip3_services.c Outbound registrations (services) 00347 - \b sip3_pokedevice.c Peer management (health checks) 00348 00349 */ 00350 /*! 00351 * \page chan_sip3_transactions Chan_sip3: Implementing transactions 00352 * 00353 * A SIP transaction is a request and one or several responses. 00354 * The INVITE transaction is special, it's a three-way handshake 00355 * request - response - ack 00356 * 00357 * Responses are divided into temporary responses and final responses. 00358 * A final response closes the transaction, temporary responses 00359 * just updates the transaction. 00360 * 00361 * Some transactions will open a new SIP dialog, some will not. 00362 * Some transactions are allowed within an active dialog, some 00363 * are not. 00364 * 00365 * \title Transactions and chan_sip 00366 * The current version of chan_sip.c does not have much notion 00367 * of a SIP transaction or a dialog. Each transaction will update 00368 * the dialog, so only the last request is remembered and the 00369 * direction of the last request. 00370 * 00371 * While this can be seen as effective, it does not allow 00372 * for situations with multiple concurrent transactions. 00373 * Most importantly, the INVITE transaction can be open for 00374 * a long time (Ringing) and other things may happen at 00375 * the same time. 00376 * 00377 * We do need to change chan_sip3 so that the transaction 00378 * state engine works properly. 00379 00380 * \title Random thoughts 00381 * - Integrate sip_pkt and sip_request - done 00382 * - Mark the UNACKed packets in dialog->packets with a flag 00383 * Maybe two lists of packets, to keep it simple for do_monitor? 00384 * Or a flag when we have no open transactions? 00385 * - Use sip-request as "transaction holders" within sip_dialog 00386 * - Keep them in Cseq order 00387 * - Add transaction state 00388 * - When do you delete them - 32 secs after first transmit 00389 * - Then we finally can fix the "ignore" ignorant stuff and resend last response 00390 * - The first transaction that opened in a dialog needs to be saved for the 00391 * CANCEL/BYE (in an INVITE transaction) 00392 * - For SUBSCRIBE dialogs, we need to keep the initial SUBSCRIBE 00393 * Then unacknowledged NOTIFY transactions. Keep the transaction 00394 * until timer expires 00395 * - Queue system for incoming packets? 00396 * 00397 * SIP_dialog 00398 * - sip_trans 00399 * Request (our or remote) 00400 * response (our or remote) 00401 * - sip_trans 00402 * 00403 */ 00404 /* -END- documentation pages */ 00405 00406 #define CHAN_SIP3_MAIN 00407 00408 /* GNURK is a temporary marker of functions that are exposed outside of this code file 00409 and possibly needs to move out */ 00410 #define GNURK 00411 00412 #include "asterisk.h" 00413 00414 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 53128 $") 00415 00416 #include <stdio.h> 00417 #include <ctype.h> 00418 #include <string.h> 00419 #include <unistd.h> 00420 #include <sys/socket.h> 00421 #include <sys/ioctl.h> 00422 #include <net/if.h> 00423 #include <errno.h> 00424 #include <stdlib.h> 00425 #include <fcntl.h> 00426 #include <netdb.h> 00427 #include <signal.h> 00428 #include <sys/signal.h> 00429 #include <netinet/in.h> 00430 #include <netinet/in_systm.h> 00431 #include <arpa/inet.h> 00432 #include <netinet/ip.h> 00433 #include <regex.h> 00434 00435 #include "asterisk/lock.h" 00436 #include "asterisk/channel.h" 00437 #include "asterisk/config.h" 00438 #include "asterisk/logger.h" 00439 #include "asterisk/module.h" 00440 #include "asterisk/pbx.h" 00441 #include "asterisk/options.h" 00442 #include "asterisk/sched.h" 00443 #include "asterisk/io.h" 00444 #include "asterisk/rtp.h" 00445 #include "asterisk/udptl.h" 00446 #include "asterisk/acl.h" 00447 #include "asterisk/manager.h" 00448 #include "asterisk/translate.h" 00449 #include "asterisk/callerid.h" 00450 #include "asterisk/cli.h" 00451 #include "asterisk/app.h" 00452 #include "asterisk/musiconhold.h" 00453 #include "asterisk/dsp.h" 00454 #include "asterisk/features.h" 00455 #include "asterisk/srv.h" 00456 #include "asterisk/astdb.h" 00457 #include "asterisk/causes.h" 00458 #include "asterisk/utils.h" 00459 #include "asterisk/file.h" 00460 #include "asterisk/astobj.h" 00461 #include "asterisk/dnsmgr.h" 00462 #include "asterisk/devicestate.h" 00463 #include "asterisk/linkedlists.h" 00464 #include "asterisk/stringfields.h" 00465 #include "asterisk/monitor.h" 00466 #include "asterisk/localtime.h" 00467 #include "asterisk/abstract_jb.h" 00468 #include "asterisk/compiler.h" 00469 00470 #include "sip3/sip3.h" 00471 #include "sip3/sip3funcs.h" 00472 00473 #define SIPLABEL sip3 00474 00475 /*------- GLOBAL VARIABLES ------------------------------------ */ 00476 00477 /*! \brief various expiry times for registrations */ 00478 struct expiry_times expiry = { 00479 .min_expiry = DEFAULT_MIN_EXPIRY, /*!< Minimum accepted registration time */ 00480 .max_expiry = DEFAULT_MAX_EXPIRY, /*!< Maximum accepted registration time */ 00481 .default_expiry = DEFAULT_DEFAULT_EXPIRY, 00482 .expiry = DEFAULT_EXPIRY, /*!< Is this ever used ??? */ 00483 }; 00484 00485 /* Default setttings are used as a channel setting and as a default when 00486 configuring devices */ 00487 /*! Global settings only apply to the channel */ 00488 struct sip_globals global; 00489 00490 /* Object counters */ 00491 struct channel_counters sipcounters = { 0, 0, 0, 0, 0, 0, 0, 0}; 00492 00493 /*! \brief Make sure we don't reload twice at the same time */ 00494 AST_MUTEX_DEFINE_STATIC(sip_reload_lock); 00495 00496 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */ 00497 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */ 00498 00499 struct sched_context *sched; /*!< The scheduling context */ 00500 struct io_context *io; /*!< The IO context */ 00501 00502 /* --- Linked lists of various objects --------*/ 00503 00504 struct sip_dialog *dialoglist = NULL; /*!< List of concurrent SIP dialogs */ 00505 struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */ 00506 00507 /*---------------------------- Forward declarations of functions in chan_sip3.c */ 00508 00509 /*--- PBX interface functions - stays in this source code file */ 00510 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause); 00511 static int sip_devicestate(void *data); 00512 static int sip_sendtext(struct ast_channel *ast, const char *text); 00513 static int sip_call(struct ast_channel *ast, char *dest, int timeout); 00514 static int sip_hangup(struct ast_channel *ast); 00515 static int sip_answer(struct ast_channel *ast); 00516 static int sip_write(struct ast_channel *ast, struct ast_frame *frame); 00517 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen); 00518 static int sip_transfer(struct ast_channel *ast, const char *dest); 00519 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan); 00520 static int sip_senddigit_begin(struct ast_channel *ast, char digit); 00521 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration); 00522 00523 static void receive_message(struct sip_dialog *p, struct sip_request *req); 00524 00525 /*--- Dialog management */ 00526 static int auto_congest(void *nothing); 00527 static void list_route(struct sip_route *route); 00528 static void build_route(struct sip_dialog *p, struct sip_request *req, int backwards); 00529 static enum check_auth_result register_verify(struct sip_dialog *p, struct sockaddr_in *sin, 00530 struct sip_request *req, char *uri); 00531 static void check_pendings(struct sip_dialog *p); 00532 static int sip_sipredirect(struct sip_dialog *p, const char *dest); 00533 00534 /*--- Codec handling / SDP */ 00535 GNURK void try_suggested_sip_codec(struct sip_dialog *p); 00536 00537 /*--- Authentication stuff */ 00538 static enum check_auth_result check_user_full(struct sip_dialog *p, struct sip_request *req, 00539 int sipmethod, char *uri, enum xmittype reliable, 00540 struct sockaddr_in *sin, struct sip_device **authpeer); 00541 static int check_user(struct sip_dialog *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin); 00542 00543 /*--- Misc functions */ 00544 static int sip_sipredirect(struct sip_dialog *p, const char *dest); 00545 00546 /*--- Device monitoring and Device/extension state handling */ 00547 static int cb_extensionstate(char *context, char* exten, int state, void *data); 00548 static int sip_devicestate(void *data); 00549 00550 /*--- Applications, functions, CLI and manager command helpers */ 00551 GNURK int sip_notify(int fd, int argc, char *argv[]); 00552 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len); 00553 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len); 00554 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len); 00555 static int sip_dtmfmode(struct ast_channel *chan, void *data); 00556 static int sip_addheader(struct ast_channel *chan, void *data); 00557 00558 /*--- Debugging 00559 Functions for enabling debug per IP or fully, or enabling history logging for 00560 a SIP dialog 00561 */ 00562 GNURK void sip_dump_history(struct sip_dialog *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */ 00563 GNURK inline int sip_debug_test_pvt(struct sip_dialog *p); 00564 00565 /*--- Device object handling */ 00566 static enum parse_register_result parse_register_contact(struct sip_dialog *pvt, struct sip_device *p, struct sip_request *req); 00567 00568 /*--- Parsing SIP requests and responses */ 00569 static int get_also_info(struct sip_dialog *p, struct sip_request *oreq); 00570 static int parse_ok_contact(struct sip_dialog *pvt, struct sip_request *req); 00571 static int set_address_from_contact(struct sip_dialog *pvt); 00572 static void check_via(struct sip_dialog *p, struct sip_request *req); 00573 static int get_msg_text(char *buf, int len, struct sip_request *req); 00574 00575 /*--- Constructing requests and responses */ 00576 static int create_addr_from_peer(struct sip_dialog *r, struct sip_device *peer); 00577 static int add_vidupdate(struct sip_request *req); 00578 00579 /*------Request handling functions */ 00580 static int handle_request_invite(struct sip_dialog *p, struct sip_request *req, int debug, struct sockaddr_in *sin, int *recount, char *e); 00581 static int handle_request_bye(struct sip_dialog *p, struct sip_request *req); 00582 static int handle_request_register(struct sip_dialog *p, struct sip_request *req, struct sockaddr_in *sin, char *e); 00583 static int handle_request_cancel(struct sip_dialog *p, struct sip_request *req); 00584 static int handle_request_message(struct sip_dialog *p, struct sip_request *req); 00585 static int handle_request_subscribe(struct sip_dialog *p, struct sip_request *req, struct sockaddr_in *sin, char *e); 00586 static void handle_request_info(struct sip_dialog *p, struct sip_request *req); 00587 static int handle_request_options(struct sip_dialog *p, struct sip_request *req); 00588 static int handle_invite_replaces(struct sip_dialog *p, struct sip_request *req, int debug, struct sockaddr_in *sin); 00589 static int handle_request_notify(struct sip_dialog *p, struct sip_request *req, struct sockaddr_in *sin, char *e); 00590 00591 /*------Response handling functions */ 00592 static void handle_response_invite(struct sip_dialog *p, int resp, char *rest, struct sip_request *req); 00593 static void handle_response_refer(struct sip_dialog *p, int resp, char *rest, struct sip_request *req); 00594 static void handle_response(struct sip_dialog *p, int resp, char *rest, struct sip_request *req); 00595 00596 /*------ T38 Support --------- */ 00597 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_dialog *pvt, int reinvite); /*!< T38 negotiation helper function */ 00598 00599 /*! \brief Definition of this channel for PBX channel registration */ 00600 static const struct ast_channel_tech sip_tech = { 00601 .type = "SIP", 00602 .description = "Session Initiation Protocol (SIP)", 00603 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1), 00604 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, 00605 .requester = sip_request_call, /*!< Where we set up a call, but don't actually activate it */ 00606 .devicestate = sip_devicestate, /*!< Checking the status of a known SIP device */ 00607 .call = sip_call, /*!< Try calling Bob, says Alice */ 00608 .hangup = sip_hangup, /*!< Alice does not want to talk to Bob any more */ 00609 .answer = sip_answer, /*!< Bob answers the call */ 00610 .read = sip_read, /*!< Deliver media to the PBX */ 00611 .write = sip_write, /*!< Get media from the PBX side */ 00612 .write_video = sip_write, /*!< Get video media from the PBX side */ 00613 .indicate = sip_indicate, /*!< Get indications from the PBX side */ 00614 .transfer = sip_transfer, /*!< Transfer a call, severely broken */ 00615 .fixup = sip_fixup, 00616 .send_digit_begin = sip_senddigit_begin, /*!< DTMF support */ 00617 .send_digit_end = sip_senddigit_end, /*!< DTMF support */ 00618 .bridge = ast_rtp_bridge, 00619 .early_bridge = ast_rtp_early_bridge, 00620 .send_text = sip_sendtext, /*!< Get text from the PBX to send out */ 00621 }; 00622 00623 /*! \brief This version of the sip channel tech has no send_digit_begin 00624 * callback. This is for use with channels using SIP INFO DTMF so that 00625 * the core knows that the channel doesn't want DTMF BEGIN frames. */ 00626 static const struct ast_channel_tech sip_tech_info = { 00627 .type = "SIP", 00628 .description = "Session Initiation Protocol (SIP)", 00629 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1), 00630 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, 00631 .requester = sip_request_call, /*!< Where we set up a call, but don't actually activate it */ 00632 .devicestate = sip_devicestate, /*!< Checking the status of a known SIP device */ 00633 .call = sip_call, /*!< Try calling Bob, says Alice */ 00634 .hangup = sip_hangup, /*!< Alice does not want to talk to Bob any more */ 00635 .answer = sip_answer, /*!< Bob answers the call */ 00636 .read = sip_read, /*!< Deliver media to the PBX */ 00637 .write = sip_write, /*!< Get media from the PBX side */ 00638 .write_video = sip_write, /*!< Get video media from the PBX side */ 00639 .indicate = sip_indicate, /*!< Get indications from the PBX side */ 00640 .transfer = sip_transfer, /*!< Transfer a call, severely broken */ 00641 .fixup = sip_fixup, 00642 .send_digit_end = sip_senddigit_end, /*!< DTMF support */ 00643 .bridge = ast_rtp_bridge, 00644 .early_bridge = ast_rtp_early_bridge, 00645 .send_text = sip_sendtext, /*!< Get text from the PBX to send out */ 00646 }; 00647 00648 00649 /*! \brief Send SIP MESSAGE text within a call 00650 Called from PBX core sendtext() application */ 00651 static int sip_sendtext(struct ast_channel *ast, const char *text) 00652 { 00653 struct sip_dialog *dialog = ast->tech_pvt; 00654 int debug = sip_debug_test_pvt(dialog); 00655 00656 if (!dialog) 00657 return -1; 00658 if (ast_strlen_zero(text)) 00659 return 0; 00660 if (debug) 00661 ast_verbose("Really sending text %s on %s\n", text, ast->name); 00662 transmit_message_with_text(dialog, text); 00663 return 0; 00664 } 00665 00666 00667 /*! \brief Set nat mode on the various media streams */ 00668 GNURK void do_setnat(struct sip_dialog *dialog, int natflags) 00669 { 00670 const char *mode = natflags ? "On" : "Off"; 00671 00672 if (dialog->rtp) { 00673 if (option_debug) 00674 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode); 00675 ast_rtp_setnat(dialog->rtp, natflags); 00676 } 00677 if (dialog->vrtp) { 00678 if (option_debug) 00679 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode); 00680 ast_rtp_setnat(dialog->vrtp, natflags); 00681 } 00682 if (dialog->udptl) { 00683 if (option_debug) 00684 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode); 00685 ast_udptl_setnat(dialog->udptl, natflags); 00686 } 00687 } 00688 00689 /*! \brief Create address structure from device reference. 00690 * return -1 on error, 0 on success. 00691 */ 00692 static int create_addr_from_peer(struct sip_dialog *dialog, struct sip_device *device) 00693 { 00694 if ((device->addr.sin_addr.s_addr || device->defaddr.sin_addr.s_addr) && 00695 (!device->maxms || ((device->lastms >= 0) && (device->lastms <= device->maxms)))) { 00696 dialog->sa = (device->addr.sin_addr.s_addr) ? device->addr : device->defaddr; 00697 dialog->recv = dialog->sa; 00698 } else 00699 return -1; 00700 00701 ast_copy_flags(&dialog->flags[0], &device->flags[0], SIP_FLAGS_TO_COPY); 00702 ast_copy_flags(&dialog->flags[1], &device->flags[1], SIP_PAGE2_FLAGS_TO_COPY); 00703 dialog->capability = device->capability; 00704 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && dialog->vrtp) { 00705 ast_rtp_destroy(dialog->vrtp); 00706 dialog->vrtp = NULL; 00707 } 00708 dialog->prefs = device->prefs; 00709 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) { 00710 dialog->t38.capability = global.t38_capability; 00711 if (dialog->udptl) { 00712 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC ) 00713 dialog->t38.capability |= T38FAX_UDP_EC_FEC; 00714 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY ) 00715 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY; 00716 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE ) 00717 dialog->t38.capability |= T38FAX_UDP_EC_NONE; 00718 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF; 00719 if (option_debug > 1) 00720 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability); 00721 } 00722 dialog->t38.jointcapability = dialog->t38.capability; 00723 } else if (dialog->udptl) { 00724 ast_udptl_destroy(dialog->udptl); 00725 dialog->udptl = NULL; 00726 } 00727 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE ); 00728 00729 if (dialog->rtp) { 00730 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) != SIP_DTMF_INFO); 00731 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE)); 00732 } 00733 if (dialog->vrtp) { 00734 ast_rtp_setdtmf(dialog->vrtp, 0); 00735 ast_rtp_setdtmfcompensate(dialog->vrtp, 0); 00736 } 00737 00738 /* Set Frame packetization */ 00739 if (dialog->rtp) { 00740 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs); 00741 dialog->autoframing = device->autoframing; 00742 } 00743 00744 /* XXX Why use username for all of this? */ 00745 //ast_string_field_set(dialog, peername, device->defaultuser); 00746 00747 ast_string_field_set(dialog, peername, device->name); 00748 /* Authuser is fromuser, and if that not is set, it's the defaultuser, if that's set */ 00749 00750 if (ast_strlen_zero(device->extra.fromuser)) 00751 ast_string_field_set(dialog, authname, device->defaultuser); 00752 else 00753 ast_string_field_set(dialog, authname, device->extra.fromuser); 00754 ast_string_field_set(dialog, defaultuser, device->defaultuser); 00755 ast_string_field_set(dialog, peersecret, device->secret); 00756 ast_string_field_set(dialog, peermd5secret, device->md5secret); 00757 ast_string_field_set(dialog, tohost, device->extra.tohost); 00758 ast_string_field_set(dialog, mohinterpret, device->extra.mohinterpret); 00759 ast_string_field_set(dialog, mohsuggest, device->extra.mohsuggest); 00760 ast_string_field_set(dialog, fullcontact, device->fullcontact); 00761 if (!dialog->initreq && !ast_strlen_zero(device->extra.fromdomain)) { 00762 char *tmpcall; 00763 char *c; 00764 tmpcall = ast_strdupa(dialog->callid); 00765 c = strchr(tmpcall, '@'); 00766 if (c) { 00767 *c = '\0'; 00768 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, device->extra.fromdomain); 00769 } 00770 } 00771 if (ast_strlen_zero(dialog->tohost)) 00772 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr)); 00773 if (!ast_strlen_zero(device->extra.fromdomain)) 00774 ast_string_field_set(dialog, fromdomain, device->extra.fromdomain); 00775 if (!ast_strlen_zero(device->extra.fromuser)) 00776 ast_string_field_set(dialog, fromuser, device->extra.fromuser); 00777 dialog->callgroup = device->callgroup; 00778 dialog->pickupgroup = device->pickupgroup; 00779 dialog->allowtransfer = device->allowtransfer; 00780 /* Set timer T1 to RTT for this peer (if known by qualify=) */ 00781 /* Minimum is settable or default to 100 ms */ 00782 if (device->maxms && device->lastms) 00783 dialog->timer_t1 = device->lastms < global.t1min ? global.t1min : device->lastms; 00784 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) || 00785 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) 00786 dialog->noncodeccapability |= AST_RTP_DTMF; 00787 else 00788 dialog->noncodeccapability &= ~AST_RTP_DTMF; 00789 ast_string_field_set(dialog, context, device->extra.context); 00790 ast_rtp_set_rtptimeout(dialog->rtp, device->rtptimer.rtptimeout); 00791 ast_rtp_set_rtpholdtimeout(dialog->rtp, device->rtptimer.rtpholdtimeout); 00792 ast_rtp_set_rtpkeepalive(dialog->rtp, device->rtptimer.rtpkeepalive); 00793 if (dialog->vrtp) { 00794 ast_rtp_set_rtptimeout(dialog->vrtp, device->rtptimer.rtptimeout); 00795 ast_rtp_set_rtpholdtimeout(dialog->vrtp, device->rtptimer.rtpholdtimeout); 00796 ast_rtp_set_rtpkeepalive(dialog->vrtp, device->rtptimer.rtpkeepalive); 00797 } 00798 if (device->call_limit) 00799 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT); 00800 dialog->maxcallbitrate = device->maxcallbitrate; 00801 00802 return 0; 00803 } 00804 00805 /*! \brief create address structure from peer name 00806 * Or, if peer not found, find it in the global DNS 00807 * returns TRUE (-1) on failure, FALSE on success */ 00808 GNURK int create_addr(struct sip_dialog *dialog, const char *username, char *domain, const char *device) 00809 { 00810 struct hostent *hp; 00811 struct ast_hostent ahp; 00812 struct sip_device *p = NULL; 00813 char *port; 00814 int portno; 00815 char host[MAXHOSTNAMELEN], *hostn; 00816 char peername[256]; 00817 char todomain[256]; 00818 int srvcheck = TRUE; 00819 00820 00821 dialog->sa.sin_family = AF_INET; 00822 dialog->timer_t1 = global.t1default; /* Default SIP retransmission timer T1 (RFC 3261) */ 00823 if (!ast_strlen_zero(device)) { 00824 int res; 00825 00826 p = find_device(device, NULL, 1); 00827 00828 if (p) { 00829 res = create_addr_from_peer(dialog, p); 00830 device_unref(p); 00831 return res; 00832 } else { 00833 if (option_verbose > 1) 00834 ast_verbose("Can't find peer %s\n", device); 00835 00836 return -1; /* Can't find peer */ 00837 } 00838 } 00839 00840 /* See if we have a port. If we have a given port, 00841 disable SRV lookups */ 00842 if (!ast_strlen_zero(domain)) { 00843 ast_copy_string(todomain, domain, sizeof(todomain)); 00844 port = strchr(todomain, ':'); 00845 } 00846 if (port) { 00847 *port++ = '\0'; 00848 srvcheck = FALSE; 00849 } 00850 00851 hostn = domain; 00852 portno = port ? atoi(port) : STANDARD_SIP_PORT; 00853 00854 if (global.srvlookup && srvcheck) { 00855 char service[MAXHOSTNAMELEN]; 00856 int tportno; 00857 int ret; 00858 00859 snprintf(service, sizeof(service), "_sip._udp.%s", domain); 00860 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service); 00861 if (ret > 0) { 00862 hostn = host; 00863 portno = tportno; 00864 if (option_debug > 2) 00865 ast_log(LOG_DEBUG, "Resolved domain %s to host %s in SRV \n", domain, hostn); 00866 } 00867 } 00868 hp = ast_gethostbyname(hostn, &ahp); 00869 if (!hp) { 00870 ast_log(LOG_WARNING, "No such host: %s\n", peername); 00871 return -2; 00872 } 00873 ast_string_field_set(dialog, tohost, domain); 00874 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr)); 00875 dialog->sa.sin_port = htons(portno); 00876 dialog->recv = dialog->sa; 00877 return 0; 00878 } 00879 00880 /*! \brief Scheduled congestion on a call */ 00881 static int auto_congest(void *nothing) 00882 { 00883 struct sip_dialog *dialog = nothing; 00884 00885 dialog_lock(dialog, TRUE); 00886 dialog->initid = -1; 00887 if (dialog->owner) { 00888 /* XXX fails on possible deadlock */ 00889 if (!ast_channel_trylock(dialog->owner)) { 00890 ast_log(LOG_NOTICE, "Auto-congesting %s\n", dialog->owner->name); 00891 append_history(dialog, "Cong", "Auto-congesting (timer)"); 00892 ast_queue_control(dialog->owner, AST_CONTROL_CONGESTION); 00893 ast_channel_unlock(dialog->owner); 00894 } 00895 } 00896 dialog_lock(dialog, FALSE); 00897 return 0; 00898 } 00899 00900 00901 /*! \brief Initiate SIP call from PBX 00902 * used from the dial() application */ 00903 static int sip_call(struct ast_channel *ast, char *dest, int timeout) 00904 { 00905 int res; 00906 struct sip_dialog *p; 00907 struct varshead *headp; 00908 struct ast_var_t *current; 00909 const char *referer = NULL; /* SIP refererer */ 00910 00911 p = ast->tech_pvt; 00912 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) { 00913 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name); 00914 return -1; 00915 } 00916 00917 /* Check whether there is vxml_url, distinctive ring variables */ 00918 headp=&ast->varshead; 00919 AST_LIST_TRAVERSE(headp,current,entries) { 00920 /* Check whether there is a VXML_URL variable */ 00921 if (!p->inviteoptions->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) { 00922 p->inviteoptions->vxml_url = ast_var_value(current); 00923 } else if (!p->inviteoptions->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) { 00924 p->inviteoptions->uri_options = ast_var_value(current); 00925 } else if (!p->inviteoptions->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) { 00926 /* Check whether there is a variable with a name starting with SIPADDHEADER */ 00927 p->inviteoptions->addsipheaders = 1; 00928 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) { 00929 /* This is a transfered call */ 00930 p->inviteoptions->transfer = 1; 00931 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) { 00932 /* This is the referer */ 00933 referer = ast_var_value(current); 00934 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) { 00935 /* We're replacing a call. */ 00936 p->inviteoptions->replaces = ast_var_value(current); 00937 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) { 00938 p->t38.state = T38_LOCAL_DIRECT; 00939 if (option_debug) 00940 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name); 00941 } 00942 00943 } 00944 00945 res = 0; 00946 ast_set_flag(&p->flags[0], SIP_OUTGOING); 00947 00948 if (p->inviteoptions->transfer) { 00949 char buf[BUFSIZ/2]; 00950 00951 if (referer) { 00952 if (sipdebug && option_debug > 2) 00953 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->peername, referer); 00954 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer); 00955 } else 00956 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name); 00957 ast_string_field_set(p, cid_name, buf); 00958 } 00959 if (option_debug) 00960 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->peername); 00961 00962 res = update_call_counter(p, INC_CALL_RINGING); 00963 if ( res != -1 ) { 00964 p->callingpres = ast->cid.cid_pres; 00965 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec); 00966 p->jointnoncodeccapability = p->noncodeccapability; 00967 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) { 00968 ast_log(LOG_WARNING, "No audio formats found to offer. Cancelling call to %s\n", p->username); 00969 res = -1; 00970 } else { 00971 p->t38.jointcapability = p->t38.capability; 00972 if (option_debug) 00973 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability); 00974 transmit_invite(p, SIP_INVITE, TRUE, 2); 00975 /* SIP timer B - Invite transaction timeout time */ 00976 p->initid = ast_sched_add(sched, global.siptimer_b, auto_congest, p); 00977 } 00978 } 00979 return res; 00980 } 00981 00982 /*! \brief update_call_counter: Handle call_limit for SIP users 00983 * Setting a call-limit will cause calls above the limit not to be accepted. 00984 * 00985 * Remember that for a type=friend, there's one limit for the user and 00986 * another for the peer, not a combined call limit. 00987 * This will cause unexpected behaviour in subscriptions, since a "friend" 00988 * is *two* devices in Asterisk, not one. 00989 * 00990 * Thought: For realtime, we should propably update storage with inuse counter... 00991 * 00992 * \return 0 if call is ok (no call limit, below treshold) 00993 * -1 on rejection of call 00994 * 00995 */ 00996 GNURK int update_call_counter(struct sip_dialog *fup, int event) 00997 { 00998 char name[256]; 00999 int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING); 01000 struct sip_device *device = NULL; 01001 01002 if (option_debug > 2) 01003 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming"); 01004 /* Test if we need to check call limits, in order to avoid 01005 realtime lookups if we do not need it */ 01006 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT)) 01007 return 0; 01008 01009 ast_copy_string(name, fup->peername, sizeof(name)); 01010 01011 /* Check the list of devices */ 01012 device = find_device(fup->peername, NULL, 1); 01013 if (!device) { 01014 if (option_debug > 1) 01015 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name); 01016 return 0; 01017 } 01018 01019 switch(event) { 01020 /* incoming and outgoing affects the inUse counter */ 01021 case DEC_CALL_LIMIT: 01022 if ( device->inUse > 0 ) { 01023 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) 01024 device->inUse--; 01025 } else { 01026 device->inUse= 0; 01027 } 01028 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) { 01029 if (device->inRinging > 0) 01030 (device->inRinging)--; 01031 else 01032 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername); 01033 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING); 01034 } 01035 if (option_debug > 1 || sipdebug) { 01036 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", device->type & SIP_USER ? "user":"peer", name, device->call_limit); 01037 } 01038 break; 01039 case INC_CALL_RINGING: 01040 case INC_CALL_LIMIT: 01041 if (device->call_limit > 0 ) { 01042 if (device->inUse >= device->call_limit) { 01043 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", device->type & SIP_USER ? "user":"peer", name, device->call_limit); 01044 device_unref(device); 01045 return -1; 01046 } 01047 } 01048 if (event == INC_CALL_RINGING) { 01049 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) { 01050 device->inRinging++; 01051 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING); 01052 } 01053 } 01054 /* Continue */ 01055 device->inUse++; 01056 ast_set_flag(&fup->flags[0], SIP_INC_COUNT); 01057 if (option_debug > 1 || sipdebug) { 01058 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", device->type & SIP_USER ? "user" : "peer", name, device->inUse, device->call_limit); 01059 } 01060 break; 01061 case DEC_CALL_RINGING: 01062 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) { 01063 if (device->inRinging > 0) 01064 device->inRinging--; 01065 else 01066 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", device->name); 01067 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING); 01068 } 01069 break; 01070 default: 01071 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event); 01072 } 01073 ast_device_state_changed("SIP/%s", device->name); 01074 device_unref(device); 01075 return 0; 01076 } 01077 01078 /*! \brief sip_hangup: Hangup SIP call 01079 * Part of PBX interface, called from ast_hangup */ 01080 static int sip_hangup(struct ast_channel *ast) 01081 { 01082 struct sip_dialog *p = ast->tech_pvt; 01083 int needcancel = FALSE; 01084 int needdestroy = 0; 01085 struct ast_channel *oldowner = ast; 01086 01087 if (!p) { 01088 if (option_debug) 01089 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n"); 01090 return 0; 01091 } 01092 01093 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) { 01094 if (option_debug >3) 01095 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid); 01096 if (p->autokillid > -1) 01097 sip_cancel_destroy(p); 01098 dialogstatechange(p, DIALOG_STATE_TERMINATED); 01099 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* This does not issue BYE - fix needed */ 01100 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */ 01101 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY); 01102 p->owner->tech_pvt = NULL; 01103 p->owner = NULL; /* Owner will be gone after we return, so take it away */ 01104 return 0; 01105 } 01106 if (option_debug > 1) { 01107 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug) 01108 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid); 01109 else 01110 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid); 01111 } 01112 if (option_debug > 1 && ast_test_flag(ast, AST_FLAG_ZOMBIE)) 01113 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n"); 01114 01115 dialog_lock(p, TRUE); 01116 if (option_debug && sipdebug) 01117 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->peername); 01118 update_call_counter(p, DEC_CALL_LIMIT); /* Fix call limit counter */ 01119 01120 /* Determine how to disconnect */ 01121 if (p->owner != ast) { 01122 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n"); 01123 dialog_lock(p, FALSE); 01124 return 0; 01125 } 01126 /* If the call is not UP, we need to send CANCEL instead of BYE */ 01127 /*! \note XXX This need to check invitestate to handle early media !!!*/ 01128 /* The p-owner check is for re-invites. We have to separate transaction and 01129 dialog state! */ 01130 if (p->state < INV_STATE_COMPLETED && p->owner->_state != AST_STATE_UP) { 01131 needcancel = TRUE; 01132 if (option_debug > 3) { 01133 ast_log(LOG_DEBUG, "Hanging up channel in AST state %s (not UP)\n", ast_state2str(ast->_state)); 01134 ast_log(LOG_DEBUG, "Hanging up channel in SIP state %s\n", dialogstate2str(p->state)); 01135 } 01136 } 01137 01138 /* Disconnect */ 01139 if (p->vad) 01140 ast_dsp_free(p->vad); 01141 01142 /* Disconnect us from the owner */ 01143 p->owner = NULL; 01144 ast->tech_pvt = NULL; 01145 01146 ast_module_unref(ast_module_info->self); 01147 01148 /* Do not destroy this pvt until we have timeout or 01149 get an answer to the BYE or INVITE/CANCEL 01150 If we get no answer during retransmit period, drop the call anyway. 01151 (Sorry, mother-in-law, you can't deny a hangup by sending 01152 603 declined to BYE...) 01153 */ 01154 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) 01155 needdestroy = 1; /* Set destroy flag at end of this function */ 01156 else /* ONLY do this if we're in UP state */ 01157 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); 01158 01159 /* Start the process if it's not already started */ 01160 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq->data)) { 01161 if (needcancel) { /* Outgoing call, not up */ 01162 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) { 01163 /* stop retransmitting an INVITE that has not received a response */ 01164 __sip_pretend_ack(p); 01165 01166 /* if we can't send right now, mark it pending */ 01167 if (p->state == DIALOG_STATE_TRYING) { 01168 ast_set_flag(&p->flags[0], SIP_PENDINGBYE); 01169 /* Do we need a timer here if we don't hear from them at all? */ 01170 } else { 01171 /* Send a new request: CANCEL */ 01172 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE); 01173 /* Actually don't destroy us yet, wait for the 487 on our original 01174 INVITE, but do set an autodestruct just in case we never get it. */ 01175 needdestroy = 0; 01176 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); 01177 dialogstatechange(p, DIALOG_STATE_TERMINATED); 01178 } 01179 if ( p->initid != -1 ) { 01180 /* channel still up - reverse dec of inUse counter 01181 only if the channel is not auto-congested */ 01182 update_call_counter(p, INC_CALL_LIMIT); 01183 } 01184 } else { /* Incoming call, not up */ 01185 const char *res; 01186 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause))) 01187 transmit_response_reliable(p, res, p->initreq); 01188 else 01189 transmit_response_reliable(p, "603 Declined", p->initreq); 01190 dialogstatechange(p, DIALOG_STATE_TERMINATED); 01191 } 01192 } else { /* Call is in UP state, send BYE */ 01193 if (!p->pendinginvite) { 01194 char *audioqos = ""; 01195 char *videoqos = ""; 01196 if (p->rtp) 01197 audioqos = ast_rtp_get_quality(p->rtp); 01198 if (p->vrtp) 01199 videoqos = ast_rtp_get_quality(p->vrtp); 01200 01201 /* Get RTCP quality before end of call */ 01202 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) { 01203 if (p->rtp) 01204 append_history(p, "RTCPaudio", "Quality:%s", audioqos); 01205 if (p->vrtp) 01206 append_history(p, "RTCPvideo", "Quality:%s", videoqos); 01207 } 01208 if (p->rtp && oldowner) 01209 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos); 01210 if (p->vrtp && oldowner) 01211 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos); 01212 dialogstatechange(p, DIALOG_STATE_TERMINATED); 01213 01214 /* Send a hangup */ 01215 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1); 01216 } else { 01217 /* Note we will need a BYE when this all settles out 01218 but we can't send one while we have "INVITE" outstanding. */ 01219 ast_set_flag(&p->flags[0], SIP_PENDINGBYE); 01220 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 01221 sip_cancel_destroy(p); 01222 } 01223 } 01224 } 01225 if (needdestroy) 01226 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); 01227 01228 if(!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) 01229 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* If we don't get answer in 32 secs, destroy */ 01230 dialog_lock(p, FALSE); 01231 return 0; 01232 } 01233 01234 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */ 01235 GNURK void try_suggested_sip_codec(struct sip_dialog *p) 01236 { 01237 int fmt; 01238 const char *codec; 01239 01240 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC"); 01241 if (!codec) 01242 return; 01243 01244 fmt = ast_getformatbyname(codec); 01245 if (fmt) { 01246 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec); 01247 if (p->jointcapability & fmt) { 01248 p->jointcapability &= fmt; 01249 p->capability &= fmt; 01250 } else 01251 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n"); 01252 } else 01253 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec); 01254 return; 01255 } 01256 01257 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite 01258 * Part of PBX interface */ 01259 static int sip_answer(struct ast_channel *ast) 01260 { 01261 int res = 0; 01262 struct sip_dialog *dialog = ast->tech_pvt; 01263 01264 dialog_lock(dialog, TRUE); 01265 if (ast->_state != AST_STATE_UP) { 01266 try_suggested_sip_codec(dialog); 01267 01268 ast_setstate(ast, AST_STATE_UP); 01269 if (option_debug) 01270 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name); 01271 if (dialog->t38.state == T38_PEER_DIRECT) { 01272 dialog->t38.state = T38_ENABLED; 01273 if (option_debug > 1) 01274 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", dialog->t38.state, ast->name); 01275 res = transmit_response_with_attachment(WITH_T38_SDP, dialog, "200 OK", dialog->initreq, XMIT_CRITICAL); 01276 } else 01277 res = transmit_response_with_attachment(WITH_SDP, dialog, "200 OK", dialog->initreq, XMIT_CRITICAL); 01278 dialogstatechange(dialog, DIALOG_STATE_CONFIRMED); 01279 } 01280 dialog_lock(dialog, FALSE); 01281 return res; 01282 } 01283 01284 /*! Write a media frame (audio, video, text) to the dialogs RTP stream. 01285 * If needed, issue early media with 183 01286 */ 01287 static int write_media_frame(struct ast_channel *ast, struct sip_dialog *p, struct ast_frame *frame, struct ast_rtp *mediartp) 01288 { 01289 int res = 0; 01290 if (!p) 01291 return AST_FAILURE; 01292 01293 dialog_lock(p, TRUE); 01294 if (mediartp) { 01295 /* If channel is not up, activate early media session */ 01296 if ((ast->_state != AST_STATE_UP) && 01297 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) && 01298 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) { 01299 transmit_response_with_attachment(WITH_SDP, p, "183 Session Progress", p->initreq, XMIT_UNRELIABLE); 01300 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT); 01301 } 01302 p->lastrtptx = time(NULL); 01303 res = ast_rtp_write(mediartp, frame); 01304 } 01305 dialog_lock(p, FALSE); 01306 return res; 01307 } 01308 01309 /*! \brief Send frame to media channel (rtp) :: PBX interface */ 01310 static int sip_write(struct ast_channel *ast, struct ast_frame *frame) 01311 { 01312 struct sip_dialog *p = ast->tech_pvt; 01313 int res = 0; 01314 01315 switch (frame->frametype) { 01316 case AST_FRAME_VOICE: 01317 if (!(frame->subclass & ast->nativeformats)) { 01318 char s1[512], s2[512], s3[512]; 01319 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n", 01320 frame->subclass, 01321 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK), 01322 ast->nativeformats & AST_FORMAT_AUDIO_MASK, 01323 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat), 01324 ast->readformat, 01325 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat), 01326 ast->writeformat); 01327 return 0; 01328 } 01329 if (p && p->rtp) 01330 res = write_media_frame(ast, p, frame, p->rtp); 01331 break; 01332 case AST_FRAME_VIDEO: 01333 if (p && p->vrtp) 01334 res = write_media_frame(ast, p, frame, p->vrtp); 01335 break; 01336 case AST_FRAME_IMAGE: 01337 return 0; 01338 break; 01339 case AST_FRAME_MODEM: 01340 if (p) { 01341 dialog_lock(p, TRUE); 01342 if (p->udptl && ast->_state == AST_STATE_UP) 01343 res = ast_udptl_write(p->udptl, frame); 01344 dialog_lock(p, FALSE); 01345 } 01346 break; 01347 default: 01348 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype); 01349 return 0; 01350 } 01351 01352 return res; 01353 } 01354 01355 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called. 01356 Basically update any ->owner links :: PBX interface */ 01357 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan) 01358 { 01359 int ret = -1; 01360 struct sip_dialog *p; 01361 01362 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug) 01363 ast_log(LOG_DEBUG, "New channel is zombie\n"); 01364 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug) 01365 ast_log(LOG_DEBUG, "Old channel is zombie\n"); 01366 01367 if (!newchan || !newchan->tech_pvt) { 01368 if (!newchan) 01369 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name); 01370 else 01371 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name); 01372 return -1; 01373 } 01374 p = newchan->tech_pvt; 01375 01376 dialog_lock(p, TRUE); 01377 append_history(p, "Masq", "Old channel: %s\n", oldchan->name); 01378 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name); 01379 if (p->owner != oldchan) 01380 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner); 01381 else { 01382 p->owner = newchan; 01383 ret = 0; 01384 } 01385 if (option_debug > 2) 01386 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name); 01387 01388 dialog_lock(p, FALSE); 01389 return ret; 01390 } 01391 01392 /*! \brief Start sending DTMF character on SIP channel 01393 within one call, we're able to transmit in many methods simultaneously */ 01394 static int sip_senddigit_begin(struct ast_channel *ast, char digit) 01395 { 01396 struct sip_dialog *p = ast->tech_pvt; 01397 int res = 0; 01398 01399 dialog_lock(p, TRUE); 01400 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) { 01401 case SIP_DTMF_INBAND: 01402 res = -1; /* Tell Asterisk to generate inband indications */ 01403 break; 01404 case SIP_DTMF_RFC2833: 01405 if (p->rtp) 01406 ast_rtp_senddigit_begin(p->rtp, digit); 01407 break; 01408 default: 01409 break; 01410 } 01411 dialog_lock(p, FALSE); 01412 01413 return res; 01414 } 01415 01416 /*! \brief Send DTMF character on SIP channel 01417 within one call, we're able to transmit in many methods simultaneously */ 01418 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration) 01419 { 01420 struct sip_dialog *p = ast->tech_pvt; 01421 int res = 0; 01422 01423 dialog_lock(p, TRUE); 01424 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) { 01425 case SIP_DTMF_INFO: 01426 transmit_info_with_digit(p, digit, duration); 01427 break; 01428 case SIP_DTMF_RFC2833: 01429 if (p->rtp) 01430 ast_rtp_senddigit_end(p->rtp, digit); 01431 break; 01432 case SIP_DTMF_INBAND: 01433 res = -1; /* Tell Asterisk to stop inband indications */ 01434 break; 01435 } 01436 dialog_lock(p, FALSE); 01437 01438 return res; 01439 } 01440 01441 /*! \brief Transfer SIP call :: PBX interface */ 01442 static int sip_transfer(struct ast_channel *ast, const char *dest) 01443 { 01444 struct sip_dialog *p = ast->tech_pvt; 01445 int res; 01446 01447 if (dest == NULL) 01448 dest = ""; 01449 dialog_lock(p, TRUE); 01450 if (ast->_state == AST_STATE_RING) 01451 res = sip_sipredirect(p, dest); 01452 else 01453 res = transmit_refer(p, dest); 01454 dialog_lock(p, FALSE); 01455 return res; 01456 } 01457 01458 /*! \brief Play indication to user :: PBX interface 01459 * With SIP a lot of indications is sent as messages, letting the device play 01460 the indication - busy signal, congestion etc 01461 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message 01462 */ 01463 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen) 01464 { 01465 struct sip_dialog *p = ast->tech_pvt; 01466 int res = 0; 01467 01468 dialog_lock(p, TRUE); 01469 switch(condition) { 01470 case AST_CONTROL_RINGING: 01471 if (ast->_state == AST_STATE_RING) { 01472 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) || 01473 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) { 01474 /* Send 180 ringing if out-of-band seems reasonable */ 01475 transmit_response(p, "180 Ringing", p->initreq); 01476 ast_set_flag(&p->flags[0], SIP_RINGING); 01477 dialogstatechange(p, DIALOG_STATE_PROCEEDING); 01478 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES) 01479 break; 01480 } else { 01481 /* Well, if it's not reasonable, just send in-band */ 01482 } 01483 } 01484 res = -1; 01485 break; 01486 case AST_CONTROL_BUSY: 01487 if (ast->_state != AST_STATE_UP) { 01488 transmit_final_response(p, "486 Busy Here", p->initreq, XMIT_RELIABLE); 01489 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV); 01490 dialogstatechange(p, DIALOG_STATE_CONFIRMED); 01491 break; 01492 } 01493 res = -1; 01494 break; 01495 case AST_CONTROL_CONGESTION: 01496 if (ast->_state != AST_STATE_UP) { 01497 transmit_final_response(p, "503 Service Unavailable", p->initreq, XMIT_RELIABLE); 01498 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV); 01499 dialogstatechange(p, DIALOG_STATE_CONFIRMED); 01500 break; 01501 } 01502 res = -1; 01503 break; 01504 case AST_CONTROL_PROCEEDING: 01505 if ((ast->_state != AST_STATE_UP) && 01506 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) && 01507 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) { 01508 transmit_response(p, "100 Trying", p->initreq); 01509 dialogstatechange(p, DIALOG_STATE_PROCEEDING); 01510 break; 01511 } 01512 res = -1; 01513 break; 01514 case AST_CONTROL_PROGRESS: 01515 if ((ast->_state != AST_STATE_UP) && 01516 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) && 01517 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) { 01518 transmit_response_with_attachment(WITH_SDP, p, "183 Session Progress", p->initreq, XMIT_UNRELIABLE); 01519 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT); 01520 dialogstatechange(p, DIALOG_STATE_PROCEEDING); 01521 break; 01522 } 01523 res = -1; 01524 break; 01525 case AST_CONTROL_HOLD: 01526 ast_moh_start(ast, data, p->mohinterpret); 01527 break; 01528 case AST_CONTROL_UNHOLD: 01529 ast_moh_stop(ast); 01530 break; 01531 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */ 01532 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) { 01533 transmit_info_with_vidupdate(p); 01534 /* ast_rtcp_send_h261fur(p->vrtp); */ 01535 } else 01536 res = -1; 01537 break; 01538 case -1: 01539 res = -1; 01540 break; 01541 default: 01542 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition); 01543 res = -1; 01544 break; 01545 } 01546 dialog_lock(p, FALSE); 01547 return res; 01548 } 01549 01550 01551 01552 /*! \brief Initiate a call in the SIP channel :: PBX interface 01553 01554 called from sip_request_call (calls from the pbx ) for outbound channels 01555 and from handle_request_invite for inbound channels 01556 01557 */ 01558 static struct ast_channel *sip_new(struct sip_dialog *dialog, int state, const char *title) 01559 { 01560 struct ast_channel *tmp; 01561 struct ast_variable *v = NULL; 01562 int fmt; 01563 int what; 01564 int needvideo = 0; 01565 01566 { 01567 const char *my_name; /* pick a good name */ 01568 01569 if (title) 01570 my_name = title; 01571 else if ( (my_name = strchr(dialog->fromdomain,':')) ) 01572 my_name++; /* skip ':' */ 01573 else 01574 my_name = dialog->fromdomain; 01575 01576 dialog_lock(dialog, FALSE); 01577 /* Don't hold a sip pvt lock while we allocate a channel */ 01578 01579 tmp = ast_channel_alloc(1, state, dialog->cid_num, dialog->cid_name, "SIP/%s-%08x", my_name, (int)(long) dialog); 01580 01581 } 01582 /* Lock the channel */ 01583 dialog_lock(dialog, TRUE); 01584 if (!tmp) { 01585 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n"); 01586 return NULL; 01587 } 01588 if (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_INFO) 01589 tmp->tech = &sip_tech_info; 01590 else 01591 tmp->tech = &sip_tech; 01592 01593 /* Select our native format based on codec preference until we receive 01594 something from another device to the contrary. */ 01595 if (dialog->jointcapability) /* The joint capabilities of us and peer */ 01596 what = dialog->jointcapability; 01597 else 01598 what = dialog->capability ? dialog->capability : global.capability; 01599 01600 /* Set the native formats for audio and merge in video */ 01601 tmp->nativeformats = ast_codec_choose(&dialog->prefs, what, 1) | (dialog->jointcapability & AST_FORMAT_VIDEO_MASK); 01602 if (option_debug > 2) { 01603 char buf[BUFSIZ]; 01604 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, tmp->nativeformats)); 01605 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, dialog->jointcapability)); 01606 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, dialog->capability)); 01607 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, ast_codec_choose(&dialog->prefs, what, 1))); 01608 if (dialog->prefcodec) 01609 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, BUFSIZ, dialog->prefcodec)); 01610 } 01611 01612 /* XXX Why are we choosing a codec from the native formats?? */ 01613 fmt = ast_best_codec(tmp->nativeformats); 01614 01615 /* If we have a prefcodec setting, we have an inbound channel that set a 01616 preferred format for this call. Otherwise, we check the jointcapability 01617 We also check for vrtp. If it's not there, we are not allowed do any video anyway. 01618 */ 01619 if (dialog->vrtp) { 01620 if (dialog->prefcodec) 01621 needvideo = dialog->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */ 01622 else 01623 needvideo = dialog->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */ 01624 } 01625 01626 if (option_debug > 2) { 01627 if (needvideo) 01628 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n"); 01629 else 01630 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n"); 01631 } 01632 01633 /* Turn on dsp if we have inband DTMF (mixed in the audio stream) */ 01634 if (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) { 01635 dialog->vad = ast_dsp_new(); 01636 ast_dsp_set_features(dialog->vad, DSP_FEATURE_DTMF_DETECT); 01637 if (global.relaxdtmf) 01638 ast_dsp_digitmode(dialog->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF); 01639 } 01640 01641 /* Set file descriptors for this channel */ 01642 if (dialog->rtp) { 01643 tmp->fds[0] = ast_rtp_fd(dialog->rtp); 01644 tmp->fds[1] = ast_rtcp_fd(dialog->rtp); 01645 } 01646 if (needvideo && dialog->vrtp) { 01647 tmp->fds[2] = ast_rtp_fd(dialog->vrtp); 01648 tmp->fds[3] = ast_rtcp_fd(dialog->vrtp); 01649 } 01650 if (dialog->udptl) 01651 tmp->fds[5] = ast_udptl_fd(dialog->udptl); 01652 01653 if (state == AST_STATE_RING) 01654 tmp->rings = 1; 01655 tmp->adsicpe = AST_ADSI_UNAVAILABLE; 01656 tmp->writeformat = fmt; 01657 tmp->rawwriteformat = fmt; 01658 tmp->readformat = fmt; 01659 tmp->rawreadformat = fmt; 01660 tmp->tech_pvt = dialog; 01661 01662 tmp->callgroup = dialog->callgroup; 01663 tmp->pickupgroup = dialog->pickupgroup; 01664 tmp->cid.cid_pres = dialog->callingpres; 01665 if (!ast_strlen_zero(dialog->accountcode)) 01666 ast_string_field_set(tmp, accountcode, dialog->accountcode); 01667 if (dialog->amaflags) 01668 tmp->amaflags = dialog->amaflags; 01669 if (!ast_strlen_zero(dialog->language)) 01670 ast_string_field_set(tmp, language, dialog->language); 01671 dialog->owner = tmp; 01672 ast_module_ref(ast_module_info->self); 01673 ast_copy_string(tmp->context, dialog->context, sizeof(tmp->context)); 01674 ast_copy_string(tmp->exten, dialog->exten, sizeof(tmp->exten)); 01675 01676 /* Don't use ast_set_callerid() here because it will 01677 * generate a NewCallerID event before the NewChannel event */ 01678 tmp->cid.cid_num = ast_strdup(dialog->cid_num); 01679 tmp->cid.cid_ani = ast_strdup(dialog->cid_num); 01680 tmp->cid.cid_name = ast_strdup(dialog->cid_name); 01681 if (!ast_strlen_zero(dialog->rdnis)) 01682 tmp->cid.cid_rdnis = ast_strdup(dialog->rdnis); 01683 01684 if (!ast_strlen_zero(dialog->exten) && strcmp(dialog->exten, "s")) 01685 tmp->cid.cid_dnid = ast_strdup(dialog->exten); 01686 01687 tmp->priority = 1; 01688 if (!ast_strlen_zero(dialog->uri)) 01689 pbx_builtin_setvar_helper(tmp, "SIPURI", dialog->uri); 01690 if (!ast_strlen_zero(dialog->domain)) 01691 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", dialog->domain); 01692 if (!ast_strlen_zero(dialog->callid)) 01693 pbx_builtin_setvar_helper(tmp, "SIPCALLID", dialog->callid); 01694 if (dialog->rtp) 01695 ast_jb_configure(tmp, &global.jbconf); 01696 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) { 01697 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name); 01698 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION; 01699 ast_hangup(tmp); 01700 tmp = NULL; 01701 } 01702 /* Set channel variables for this call from configuration */ 01703 for (v = dialog->chanvars ; v ; v = v->next) 01704 pbx_builtin_setvar_helper(tmp,v->name,v->value); 01705 01706 if (!ast_test_flag(&dialog->flags[0], SIP_NO_HISTORY)) 01707 append_history(dialog, "NewChan", "Channel %s - from %s", tmp->name, dialog->callid); 01708 01709 return tmp; 01710 } 01711 01712 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */ 01713 static int t38_get_rate(int t38cap) 01714 { 01715 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400)); 01716 01717 if (maxrate & T38FAX_RATE_14400) { 01718 if (option_debug > 1) 01719 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n"); 01720 return 14400; 01721 } else if (maxrate & T38FAX_RATE_12000) { 01722 if (option_debug > 1) 01723 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n"); 01724 return 12000; 01725 } else if (maxrate & T38FAX_RATE_9600) { 01726 if (option_debug > 1) 01727 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n"); 01728 return 9600; 01729 } else if (maxrate & T38FAX_RATE_7200) { 01730 if (option_debug > 1) 01731 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n"); 01732 return 7200; 01733 } else if (maxrate & T38FAX_RATE_4800) { 01734 if (option_debug > 1) 01735 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n"); 01736 return 4800; 01737 } else if (maxrate & T38FAX_RATE_2400) { 01738 if (option_debug > 1) 01739 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n"); 01740 return 2400; 01741 } else { 01742 if (option_debug > 1) 01743 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n"); 01744 return 0; 01745 } 01746 } 01747 01748 /*! \brief Add T.38 Session Description Protocol message */ 01749 GNURK int add_t38_sdp(struct sip_request *resp, struct sip_dialog *p) 01750 { 01751 int len = 0; 01752 int x = 0; 01753 struct sockaddr_in udptlsin; 01754 char v[256] = ""; 01755 char s[256] = ""; 01756 char o[256] = ""; 01757 char c[256] = ""; 01758 char t[256] = ""; 01759 char m_modem[256]; 01760 char a_modem[1024]; 01761 char *m_modem_next = m_modem; 01762 size_t m_modem_left = sizeof(m_modem); 01763 char *a_modem_next = a_modem; 01764 size_t a_modem_left = sizeof(a_modem); 01765 struct sockaddr_in udptldest = { 0, }; 01766 int debug; 01767 01768 debug = sip_debug_test_pvt(p); 01769 len = 0; 01770 if (!p->udptl) { 01771 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n"); 01772 return -1; 01773 } 01774 01775 if (!p->sessionid) { 01776 p->sessionid = getpid(); 01777 p->sessionversion = p->sessionid; 01778 } else 01779 p->sessionversion++; 01780 01781 /* Our T.38 end is */ 01782 ast_udptl_get_us(p->udptl, &udptlsin); 01783 01784 /* Determine T.38 UDPTL destination */ 01785 if (p->udptlredirip.sin_addr.s_addr) { 01786 udptldest.sin_port = p->udptlredirip.sin_port; 01787 udptldest.sin_addr = p->udptlredirip.sin_addr; 01788 } else { 01789 udptldest.sin_addr = p->ourip; 01790 udptldest.sin_port = udptlsin.sin_port; 01791 } 01792 01793 if (debug) 01794 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port)); 01795 01796 /* We break with the "recommendation" and send our IP, in order that our 01797 peer doesn't have to ast_gethostbyname() us */ 01798 01799 if (debug) { 01800 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n", 01801 p->t38.capability, 01802 p->t38.peercapability, 01803 p->t38.jointcapability); 01804 } 01805 snprintf(v, sizeof(v), "v=0\r\n"); 01806 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr)); 01807 snprintf(s, sizeof(s), "s=session\r\n"); 01808 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr)); 01809 snprintf(t, sizeof(t), "t=0 0\r\n"); 01810 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port)); 01811 01812 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0) 01813 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n"); 01814 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1) 01815 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n"); 01816 if ((x = t38_get_rate(p->t38.jointcapability))) 01817 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x); 01818 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0); 01819 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0); 01820 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0); 01821 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF"); 01822 x = ast_udptl_get_local_max_datagram(p->udptl); 01823 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x); 01824 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x); 01825 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE) 01826 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC"); 01827 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem); 01828 add_header(resp, "Content-Type", "application/sdp"); 01829 add_header_contentLength(resp, len); 01830 add_line(resp, v); 01831 add_line(resp, o); 01832 add_line(resp, s); 01833 add_line(resp, c); 01834 add_line(resp, t); 01835 add_line(resp, m_modem); 01836 add_line(resp, a_modem); 01837 01838 /* Update lastrtprx when we send our SDP */ 01839 p->lastrtprx = p->lastrtptx = time(NULL); 01840 01841 return 0; 01842 } 01843 01844 /*! \brief Save contact header for 200 OK on INVITE */ 01845 static int parse_ok_contact(struct sip_dialog *pvt, struct sip_request *req) 01846 { 01847 char contact[250]; 01848 char *c; 01849 01850 /* Look for brackets */ 01851 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact)); 01852 c = get_in_brackets(contact); 01853 01854 /* Save full contact to call pvt for later bye or re-invite */ 01855 ast_string_field_set(pvt, fullcontact, c); 01856 01857 /* Save URI for later ACKs, BYE or RE-invites */ 01858 ast_string_field_set(pvt, okcontacturi, c); 01859 01860 /*! \todo We should return false for URI:s we can't handle, 01861 like sips:, tel:, mailto:,ldap: etc */ 01862 return TRUE; 01863 } 01864 01865 /*! \brief Change the other partys IP address based on given contact */ 01866 static int set_address_from_contact(struct sip_dialog *pvt) 01867 { 01868 struct hostent *hp; 01869 struct ast_hostent ahp; 01870 int port; 01871 char *c, *host, *pt; 01872 char *contact; 01873 01874 01875 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) { 01876 /* NAT: Don't trust the contact field. Just use what they came to us 01877 with. */ 01878 pvt->sa = pvt->recv; 01879 return 0; 01880 } 01881 01882 01883 /* Work on a copy */ 01884 contact = ast_strdupa(pvt->fullcontact); 01885 01886 /* XXX this code is repeated all over */ 01887 /* Make sure it's a SIP URL */ 01888 if (strncasecmp(contact, "sip:", 4)) { 01889 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact); 01890 } else 01891 contact += 4; 01892 01893 /* Ditch arguments */ 01894 /* XXX this code is replicated also shortly below */ 01895 contact = strsep(&contact, ";"); /* trim ; and beyond */ 01896 01897 /* Grab host */ 01898 host = strchr(contact, '@'); 01899 if (!host) { /* No username part */ 01900 host = contact; 01901 c = NULL; 01902 } else { 01903 *host++ = '\0'; 01904 } 01905 pt = strchr(host, ':'); 01906 if (pt) { 01907 *pt++ = '\0'; 01908 port = atoi(pt); 01909 } else 01910 port = STANDARD_SIP_PORT; 01911 01912 /* XXX This could block for a long time XXX */ 01913 /* We should only do this if it's a name, not an IP */ 01914 hp = ast_gethostbyname(host, &ahp); 01915 if (!hp) { 01916 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host); 01917 return -1; 01918 } 01919 pvt->sa.sin_family = AF_INET; 01920 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr)); 01921 pvt->sa.sin_port = htons(port); 01922 01923 return 0; 01924 } 01925 01926 01927 /*! \brief Parse contact header and save registration (peer registration) */ 01928 static enum parse_register_result parse_register_contact(struct sip_dialog *pvt, struct sip_device *peer, struct sip_request *req) 01929 { 01930 char contact[BUFSIZ]; 01931 char data[BUFSIZ]; 01932 const char *expires = get_header(req, "Expires"); 01933 int localexpiry = atoi(expires); 01934 char *curi, *n, *pt; 01935 int port; 01936 const char *useragent; 01937 struct hostent *hp; 01938 struct ast_hostent ahp; 01939 struct sockaddr_in oldsin; 01940 time_t expirytime; 01941 01942 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact)); 01943 01944 if (ast_strlen_zero(expires)) { /* No expires header */ 01945 expires = strcasestr(contact, ";expires="); 01946 if (expires) { 01947 /* XXX bug here, we overwrite the string */ 01948 expires = strsep((char **) &expires, ";"); /* trim ; and beyond */ 01949 if (sscanf(expires + 9, "%d", &localexpiry) != 1) 01950 localexpiry = expiry.default_expiry; 01951 } else { 01952 /* Nothing has been specified */ 01953 localexpiry = expiry.default_expiry; 01954 } 01955 } 01956 if (localexpiry < expiry.min_expiry && localexpiry > 0) 01957 return PARSE_REGISTER_FAILED_MINEXPIRY; 01958 01959 /* Look for brackets */ 01960 curi = contact; 01961 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */ 01962 strsep(&curi, ";"); /* This is Header options, not URI options */ 01963 curi = get_in_brackets(contact); 01964 01965 /* if they did not specify Contact: or Expires:, they are querying 01966 what we currently have stored as their contact address, so return 01967 it 01968 */ 01969 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) { 01970 /* If we have an active registration, tell them when the registration is going to expire */ 01971 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) 01972 pvt->expiry = ast_sched_when(sched, peer->expire); 01973 return PARSE_REGISTER_QUERY; 01974 } else if (!strcasecmp(curi, "*") || !localexpiry) { /* Unregister this peer */ 01975 /* This means remove all registrations and return OK */ 01976 memset(&peer->addr, 0, sizeof(peer->addr)); 01977 if (peer->expire > -1) 01978 ast_sched_del(sched, peer->expire); 01979 peer->expire = -1; 01980 01981 destroy_association(peer); 01982 01983 register_peer_exten(peer, 0); /* Add extension from regexten= setting in sip.conf */ 01984 ast_string_field_free(peer, fullcontact); 01985 ast_string_field_free(peer, useragent); 01986 peer->sipoptions = 0; 01987 peer->lastms = 0; 01988 01989 if (option_verbose > 2) 01990 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name); 01991 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name); 01992 return PARSE_REGISTER_UPDATE; 01993 } 01994 01995 /* Store whatever we got as a contact from the client */ 01996 ast_string_field_set(peer, fullcontact, curi); 01997 01998 /* For the 200 OK, we should use the received contact */ 01999 ast_string_field_build(pvt, our_contact, "<%s>", curi); 02000 02001 /* Make sure it's a SIP URL */ 02002 if (strncasecmp(curi, "sip:", 4)) { 02003 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi); 02004 } else 02005 curi += 4; 02006 /* Ditch q */ 02007 curi = strsep(&curi, ";"); 02008 /* Grab host */ 02009 n = strchr(curi, '@'); 02010 if (!n) { 02011 n = curi; 02012 curi = NULL; 02013 } else 02014 *n++ = '\0'; 02015 pt = strchr(n, ':'); 02016 if (pt) { 02017 *pt++ = '\0'; 02018 port = atoi(pt); 02019 } else 02020 port = STANDARD_SIP_PORT; 02021 oldsin = peer->addr; 02022 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) { 02023 /* XXX This could block for a long time XXX */ 02024 hp = ast_gethostbyname(n, &ahp); 02025 if (!hp) { 02026 ast_log(LOG_WARNING, "Invalid host '%s'\n", n); 02027 return PARSE_REGISTER_FAILED; 02028 } 02029 peer->addr.sin_family = AF_INET; 02030 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr)); 02031 peer->addr.sin_port = htons(port); 02032 } else { 02033 /* Don't trust the contact field. Just use what they came to us 02034 with */ 02035 peer->addr = pvt->recv; 02036 } 02037 02038 /* Save SIP options profile */ 02039 peer->sipoptions = pvt->sipoptions; 02040 02041 if (curi) { /* Overwrite the default username from config at registration */ 02042 ast_string_field_set(peer, defaultuser, curi); 02043 //ast_copy_string(peer->defaultuser, curi, sizeof(peer->defaultuser)); 02044 } else 02045 ast_string_field_set(peer, defaultuser, ""); 02046 //peer->defaultuser[0] = '\0'; 02047 02048 if (peer->expire > -1) 02049 ast_sched_del(sched, peer->expire); 02050 if (localexpiry > expiry.max_expiry) 02051 localexpiry = expiry.max_expiry; 02052 //if (localexpiry < expiry.min_expiry) 02053 //localexpiry = expiry.min_expiry; 02054 peer->expire = ast_test_flag(&peer->flags[0], SIP_REALTIME) ? -1 : 02055 ast_sched_add(sched, (localexpiry + 10) * 1000, expire_register, peer); 02056 pvt->expiry = localexpiry; 02057 02058 /* Store registration data in the registry */ 02059 expirytime = time(NULL) + localexpiry + 10; 02060 snprintf(data, sizeof(data), "%d|%s|%d|%d|%s", (int) expirytime, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), localexpiry, peer->fullcontact); 02061 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT)) 02062 ast_db_put("SIP3-Registry", peer->name, data); 02063 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name); 02064 02065 /* Is this a new IP address for us? */ 02066 if (inaddrcmp(&peer->addr, &oldsin)) { 02067 sip_poke_peer(peer); 02068 if (option_verbose > 2) 02069 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), localexpiry); 02070 register_peer_exten(peer, 1); 02071 } 02072 02073 /* Save User agent */ 02074 useragent = get_header(req, "User-Agent"); 02075 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */ 02076 ast_string_field_set(peer, useragent, useragent); 02077 if (option_verbose > 3) 02078 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name); 02079 } 02080 return PARSE_REGISTER_UPDATE; 02081 } 02082 02083 /*! \brief Remove route from route list */ 02084 void free_old_route(struct sip_route *route) 02085 { 02086 struct sip_route *next; 02087 02088 while (route) { 02089 next = route->next; 02090 free(route); 02091 route = next; 02092 } 02093 } 02094 02095 /*! \brief List all routes - mostly for debugging */ 02096 static void list_route(struct sip_route *route) 02097 { 02098 if (!route) 02099 ast_verbose("list_route: no route\n"); 02100 else { 02101 for (;route; route = route->next) 02102 ast_verbose("list_route: hop: <%s>\n", route->hop); 02103 } 02104 } 02105 02106 /*! \brief Build route list from Record-Route header */ 02107 static void build_route(struct sip_dialog *p, struct sip_request *req, int backwards) 02108 { 02109 struct sip_route *thishop, *head, *tail; 02110 int start = 0; 02111 int len; 02112 const char *rr, *contact, *c; 02113 02114 /* Once a persistant route is set, don't fool with it */ 02115 if (p->route && p->route_persistant) { 02116 if (option_debug) 02117 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop); 02118 return; 02119 } 02120 02121 if (p->route) { 02122 free_old_route(p->route); 02123 p->route = NULL; 02124 } 02125 02126 p->route_persistant = backwards; 02127 02128 /* Build a tailq, then assign it to p->route when done. 02129 * If backwards, we add entries from the head so they end up 02130 * in reverse order. However, we do need to maintain a correct 02131 * tail pointer because the contact is always at the end. 02132 */ 02133 head = NULL; 02134 tail = head; 02135 /* 1st we pass through all the hops in any Record-Route headers */ 02136 for (;;) { 02137 /* Each Record-Route header */ 02138 rr = __get_header(req, "Record-Route", &start); 02139 if (*rr == '\0') 02140 break; 02141 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */ 02142 ++rr; 02143 len = strcspn(rr, ">") + 1; 02144 /* Make a struct route */ 02145 if ((thishop = ast_malloc(sizeof(*thishop) + len))) { 02146 /* ast_calloc is not needed because all fields are initialized in this block */ 02147 ast_copy_string(thishop->hop, rr, len); 02148 if (option_debug > 1) 02149 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop); 02150 /* Link in */ 02151 if (backwards) { 02152 /* Link in at head so they end up in reverse order */ 02153 thishop->next = head; 02154 head = thishop; 02155 /* If this was the first then it'll be the tail */ 02156 if (!tail) 02157 tail = thishop; 02158 } else { 02159 thishop->next = NULL; 02160 /* Link in at the end */ 02161 if (tail) 02162 tail->next = thishop; 02163 else 02164 head = thishop; 02165 tail = thishop; 02166 } 02167 } 02168 } 02169 } 02170 02171 /* Only append the contact if we are dealing with a strict router */ 02172 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) { 02173 /* 2nd append the Contact: if there is one */ 02174 /* Can be multiple Contact headers, comma separated values - we just take the first */ 02175 contact = get_header(req, "Contact"); 02176 if (!ast_strlen_zero(contact)) { 02177 if (option_debug > 1) 02178 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact); 02179 /* Look for <: delimited address */ 02180 c = strchr(contact, '<'); 02181 if (c) { 02182 /* Take to > */ 02183 ++c; 02184 len = strcspn(c, ">") + 1; 02185 } else { 02186 /* No <> - just take the lot */ 02187 c = contact; 02188 len = strlen(contact) + 1; 02189 } 02190 if ((thishop = ast_malloc(sizeof(*thishop) + len))) { 02191 /* ast_calloc is not needed because all fields are initialized in this block */ 02192 ast_copy_string(thishop->hop, c, len); 02193 thishop->next = NULL; 02194 /* Goes at the end */ 02195 if (tail) 02196 tail->next = thishop; 02197 else 02198 head = thishop; 02199 } 02200 } 02201 } 02202 02203 /* Store as new route */ 02204 p->route = head; 02205 02206 /* For debugging dump what we ended up with */ 02207 if (sip_debug_test_pvt(p)) 02208 list_route(p->route); 02209 } 02210 02211 /*! \brief Change onhold state of a peer using a pvt structure */ 02212 GNURK void sip_peer_hold(struct sip_dialog *p, int hold) 02213 { 02214 struct sip_device *peer = find_device(p->peername, NULL, 1); 02215 02216 if (!peer) 02217 return; 02218 02219 /* If they put someone on hold, increment the value... otherwise decrement it */ 02220 if (hold) 02221 peer->onHold++; 02222 else if (hold > 0) 02223 peer->onHold--; 02224 02225 /* Request device state update */ 02226 ast_device_state_changed("SIP/%s", peer->name); 02227 02228 return; 02229 } 02230 02231 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem 02232 \note If you add an "hint" priority to the extension in the dial plan, 02233 you will get notifications on device state changes */ 02234 static int cb_extensionstate(char *context, char* exten, int state, void *data) 02235 { 02236 struct sip_dialog *p = data; 02237 02238 switch(state) { 02239 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */ 02240 case AST_EXTENSION_REMOVED: /* Extension is gone */ 02241 if (p->autokillid > -1) 02242 sip_cancel_destroy(p); /* Remove subscription expiry for renewals */ 02243 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */ 02244 ast_verbose(VERBOSE_PREFIX_2 "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->peername); 02245 p->stateid = -1; 02246 p->subscribed = NONE; 02247 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated"); 02248 break; 02249 default: /* Tell user */ 02250 p->laststate = state; 02251 break; 02252 } 02253 transmit_state_notify(p, state, 1, FALSE); 02254 02255 if (option_verbose > 1) 02256 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->peername); 02257 return 0; 02258 } 02259 02260 /*! 02261 * Terminate the uri at the first ';' or space. 02262 * Technically we should ignore escaped space per RFC3261 (19.1.1 etc) 02263 * but don't do it for the time being. Remember the uri format is: 02264 * 02265 * sip:user:password@host:port;uri-parameters?headers 02266 * sips:user:password@host:port;uri-parameters?headers 02267 * 02268 */ 02269 static char *terminate_uri(char *uri) 02270 { 02271 char *t = uri; 02272 while (*t && *t > ' ' && *t != ';') 02273 t++; 02274 *t = '\0'; 02275 return uri; 02276 } 02277 02278 /*! \brief Verify registration of user 02279 - Registration is done in several steps, first a REGISTER without auth 02280 to get a challenge (nonce) then a second one with auth 02281 - Registration requests are only matched with peers that are marked as "dynamic" 02282 */ 02283 static enum check_auth_result register_verify(struct sip_dialog *p, struct sockaddr_in *sin, 02284 struct sip_request *req, char *uri) 02285 { 02286 enum check_auth_result res = AUTH_NOT_FOUND; 02287 struct sip_device *peer; 02288 char tmp[256]; 02289 char *name, *c; 02290 char *domain; 02291 02292 terminate_uri(uri); /*! \bug XXX warning, overwrite the string */ 02293 02294 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp)); 02295 ast_uri_decode(tmp); 02296 02297 c = get_in_brackets(tmp); 02298 c = strsep(&c, ";"); /* Ditch ;user=phone */ 02299 02300 if (!strncmp(c, "sip:", 4)) { 02301 name = c + 4; 02302 } else { 02303 name = c; 02304 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr)); 02305 } 02306 02307 /* Strip off the domain name */ 02308 if ((c = strchr(name, '@'))) { 02309 *c++ = '\0'; 02310 domain = c; 02311 if ((c = strchr(domain, ':'))) /* Remove :port */ 02312 *c = '\0'; 02313 if (domains_configured()) { 02314 if (!check_sip_domain(domain, NULL, 0)) { 02315 transmit_response(p, "404 Not found (unknown domain)", p->initreq); 02316 return AUTH_UNKNOWN_DOMAIN; 02317 } 02318 } 02319 } 02320 02321 ast_string_field_set(p, exten, name); 02322 build_contact(p); 02323 peer = find_device(name, NULL, 1); 02324 if (!(peer && ast_apply_ha(peer->ha, sin))) { 02325 /* Peer fails ACL check */ 02326 if (peer) 02327 device_unref(peer); 02328 peer = NULL; 02329 } 02330 if (peer) { 02331 /* Set Frame packetization */ 02332 if (p->rtp) { 02333 ast_rtp_codec_setpref(p->rtp, &peer->prefs); 02334 p->autoframing = peer->autoframing; 02335 } 02336 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) { 02337 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name); 02338 } else { 02339 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT); 02340 transmit_response(p, "100 Trying", req); 02341 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) { 02342 sip_cancel_destroy(p); 02343 02344 /* We have a succesful registration attemp with proper authentication, 02345 now, update the peer */ 02346 switch (parse_register_contact(p, peer, req)) { 02347 case PARSE_REGISTER_FAILED_MINEXPIRY: 02348 transmit_response_with_attachment(WITH_MINEXPIRY, p, "423 Interval too small", req, XMIT_UNRELIABLE); 02349 peer->mailbox.lastmsgssent = -1; 02350 res = 0; 02351 break; 02352 case PARSE_REGISTER_FAILED: 02353 ast_log(LOG_WARNING, "Failed to parse contact info\n"); 02354 transmit_response_with_attachment(WITH_DATE, p, "400 Bad Request", req, XMIT_UNRELIABLE); 02355 peer->mailbox.lastmsgssent = -1; 02356 res = 0; 02357 break; 02358 case PARSE_REGISTER_QUERY: 02359 transmit_response_with_attachment(WITH_DATE, p, "200 OK", req, XMIT_UNRELIABLE); 02360 peer->mailbox.lastmsgssent = -1; 02361 res = 0; 02362 break; 02363 case PARSE_REGISTER_UPDATE: 02364 update_peer(peer, p->expiry); 02365 /* Say OK and ask subsystem to retransmit msg counter */ 02366 transmit_response_with_attachment(WITH_DATE, p, "200 OK", req, XMIT_UNRELIABLE); 02367 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY)) 02368 peer->mailbox.lastmsgssent = -1; 02369 res = 0; 02370 break; 02371 } 02372 } 02373 } 02374 } 02375 if (!peer && global.autocreatepeer) { 02376 /* Create peer if we have autocreate mode enabled */ 02377 peer = temp_device(name); 02378 if (peer) { 02379 ASTOBJ_CONTAINER_LINK(&devicelist, peer); 02380 sip_cancel_destroy(p); 02381 switch (parse_register_contact(p, peer, req)) { 02382 case PARSE_REGISTER_FAILED_MINEXPIRY: 02383 transmit_response_with_attachment(WITH_MINEXPIRY, p, "423 Interval too small", req, XMIT_UNRELIABLE); 02384 peer->mailbox.lastmsgssent = -1; 02385 res = 0; 02386 case PARSE_REGISTER_FAILED: 02387 ast_log(LOG_WARNING, "Failed to parse contact info\n"); 02388 transmit_response_with_attachment(WITH_DATE, p, "400 Bad Request", req, XMIT_UNRELIABLE); 02389 peer->mailbox.lastmsgssent = -1; 02390 res = 0; 02391 break; 02392 case PARSE_REGISTER_QUERY: 02393 transmit_response_with_attachment(WITH_DATE, p, "200 OK", req, XMIT_UNRELIABLE); 02394 peer->mailbox.lastmsgssent = -1; 02395 res = 0; 02396 break; 02397 case PARSE_REGISTER_UPDATE: 02398 /* Say OK and ask subsystem to retransmit msg counter */ 02399 transmit_response_with_attachment(WITH_DATE, p, "200 OK", req, XMIT_UNRELIABLE); 02400 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name); 02401 peer->mailbox.lastmsgssent = -1; 02402 res = 0; 02403 break; 02404 } 02405 } 02406 } 02407 if (!res) { 02408 ast_device_state_changed("SIP/%s", peer->name); 02409 } 02410 if (res < 0) { 02411 switch (res) { 02412 case AUTH_SECRET_FAILED: 02413 /* Wrong password in authentication. Go away, don't try again until you fixed it */ 02414 transmit_response(p, "403 Forbidden (Bad auth)", p->initreq); 02415 break; 02416 case AUTH_USERNAME_MISMATCH: 02417 /* Username and digest username does not match. 02418 Asterisk uses the From: username for authentication. We need the 02419 users to use the same authentication user name until we support 02420 proper authentication by digest auth name */ 02421 transmit_response(p, "403 Authentication user name does not match account name", p->initreq); 02422 break; 02423 case AUTH_NOT_FOUND: 02424 if (global.alwaysauthreject) { 02425 transmit_fake_auth_response(p, p->initreq, 1); 02426 } else { 02427 /* URI not found */ 02428 transmit_response(p, "404 Not found", p->initreq); 02429 } 02430 break; 02431 default: 02432 break; 02433 } 02434 if (option_debug > 1) { 02435 const char *reason = ""; 02436 02437 switch (res) { 02438 case AUTH_SECRET_FAILED: 02439 reason = "Bad password"; 02440 break; 02441 case AUTH_USERNAME_MISMATCH: 02442 reason = "Bad digest user"; 02443 break; 02444 case AUTH_NOT_FOUND: 02445 reason = "Peer not found"; 02446 break; 02447 default: 02448 break; 02449 } 02450 ast_log(LOG_DEBUG, "SIP REGISTER attempt failed for %s : %s\n", 02451 peer->name, reason); 02452 } 02453 } 02454 device_unref(peer); 02455 02456 return res; 02457 } 02458 02459 /*! \brief Lock dialog list lock and find matching pvt lock 02460 - Their tag is fromtag, our tag is to-tag 02461 - This means that in some transactions, totag needs to be their tag :-) 02462 depending upon the direction 02463 */ 02464 GNURK struct sip_dialog *get_sip_dialog_byid_locked(const char *callid, const char *totag, const char *fromtag) 02465 { 02466 struct sip_dialog *sip_dialog_ptr; 02467 02468 dialoglist_lock(); 02469 02470 if (option_debug > 3 && totag) 02471 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>"); 02472 02473 /* Search interfaces and find the match */ 02474 for (sip_dialog_ptr = dialoglist; sip_dialog_ptr; sip_dialog_ptr = sip_dialog_ptr->next) { 02475 if (!strcmp(sip_dialog_ptr->callid, callid)) { 02476 int match = 1; 02477 char *ourtag = sip_dialog_ptr->tag; 02478 02479 /* Go ahead and lock it (and its owner) before returning */ 02480 dialog_lock(sip_dialog_ptr, TRUE); 02481 02482 /* Check if tags match. If not, this is not the call we want 02483 (With a forking SIP proxy, several call legs share the 02484 call id, but have different tags) 02485 */ 02486 if (strcmp(fromtag, sip_dialog_ptr->theirtag) || strcmp(totag, ourtag)) 02487 match = 0; 02488 02489 if (!match) { 02490 dialog_lock(sip_dialog_ptr, FALSE); 02491 continue; 02492 } 02493 02494 if (option_debug > 3 && totag) 02495 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n", 02496 ast_test_flag(&sip_dialog_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING", 02497 sip_dialog_ptr->theirtag, sip_dialog_ptr->tag); 02498 02499 /* deadlock avoidance... */ 02500 while (sip_dialog_ptr->owner && ast_channel_trylock(sip_dialog_ptr->owner)) { 02501 dialog_lock(sip_dialog_ptr, FALSE); 02502 usleep(1); 02503 dialog_lock(sip_dialog_ptr, TRUE); 02504 } 02505 break; 02506 } 02507 } 02508 dialoglist_unlock(); 02509 if (option_debug > 3 && !sip_dialog_ptr) 02510 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag); 02511 return sip_dialog_ptr; 02512 } 02513 02514 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/ 02515 static int get_also_info(struct sip_dialog *p, struct sip_request *oreq) 02516 { 02517 char tmp[256] = "", *c, *a; 02518 struct sip_request *req = oreq ? oreq : p->initreq; 02519 struct sip_refer *referdata = p->refer; 02520 const char *transfer_context = NULL; 02521 02522 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp)); 02523 c = get_in_brackets(tmp); 02524 02525 ast_uri_decode(c); 02526 02527 if (strncmp(c, "sip:", 4)) { 02528 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c); 02529 return -1; 02530 } 02531 c += 4; 02532 02533 if ((a = strchr(c, ';'))) /* Remove arguments */ 02534 *a = '\0'; 02535 02536 if ((a = strchr(c, '@'))) { /* Separate Domain */ 02537 *a++ = '\0'; 02538 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain)); 02539 } 02540 02541 02542 if (sip_debug_test_pvt(p)) 02543 ast_verbose("Looking for %s in %s\n", c, p->context); 02544 02545 if (p->owner) /* Mimic behaviour in res_features.c */ 02546 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT"); 02547 02548 /* By default, use the context in the channel sending the REFER */ 02549 if (ast_strlen_zero(transfer_context)) { 02550 transfer_context = S_OR(p->owner->macrocontext, 02551 S_OR(p->context, global.default_context)); 02552 } 02553 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) { 02554 /* This is a blind transfer */ 02555 if (option_debug) 02556 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context); 02557 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to)); 02558 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by)); 02559 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact)); 02560 referdata->refer_call = NULL; 02561 /* Set new context */ 02562 ast_string_field_set(p, context, transfer_context); 02563 return 0; 02564 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) { 02565 return 1; 02566 } 02567 02568 return -1; 02569 } 02570 /*! \brief check Via: header for hostname, port and rport request/answer */ 02571 static void check_via(struct sip_dialog *p, struct sip_request *req) 02572 { 02573 char via[256]; 02574 char *c, *pt; 02575 struct hostent *hp; 02576 struct ast_hostent ahp; 02577 02578 ast_copy_string(via, get_header(req, "Via"), sizeof(via)); 02579 if (strlen(via) == 0) 02580 ast_log(LOG_DEBUG, "Empty VIA string found \n"); 02581 02582 /* Work on the leftmost value of the topmost Via header */ 02583 c = strchr(via, ','); 02584 if (c) 02585 *c = '\0'; 02586 02587 /* Check for rport */ 02588 c = strstr(via, ";rport"); 02589 if (c && (c[6] != '=')) /* rport query, not answer */ 02590 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE); 02591 02592 c = strchr(via, ';'); 02593 if (c) 02594 *c = '\0'; 02595 02596 c = strchr(via, ' '); 02597 if (c) { 02598 *c = '\0'; 02599 c = ast_skip_blanks(c+1); 02600 if (strcasecmp(via, "SIP/2.0/UDP")) { 02601 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via); 02602 return; 02603 } 02604 pt = strchr(c, ':'); 02605 if (pt) 02606 *pt++ = '\0'; /* remember port pointer */ 02607 02608 /* Set sender's address to the IP address in via for replies */ 02609 memset(&p->sa, 0, sizeof(p->sa)); 02610 p->sa.sin_family = AF_INET; 02611 02612 if (!inet_aton(c, &p->sa.sin_addr)) { /* Check if this is an IP address, not a host name */ 02613 /* resolve host name */ 02614 hp = ast_gethostbyname(c, &ahp); 02615 if (!hp) { 02616 ast_log(LOG_WARNING, "'%s' is not a valid DNS host name\n", c); 02617 return; 02618 } 02619 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr)); 02620 } 02621 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT); 02622 02623 if (sip_debug_test_pvt(p)) { 02624 const struct sockaddr_in *dst = sip_real_dst(p); 02625 02626 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p)); 02627 ast_verbose("Sender's address %s : %d (%s)\n", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), sip_nat_mode(p)); 02628 } 02629 } 02630 } 02631 02632 /*! \brief Check if matching user or peer is defined 02633 Match user on From: user name and peer on IP/port 02634 This is used on first invite (not re-invites) and subscribe requests 02635 \return 0 on success, non-zero on failure 02636 */ 02637 static enum check_auth_result check_user_full(struct sip_dialog *p, struct sip_request *req, 02638 int sipmethod, char *uri, enum xmittype reliable, 02639 struct sockaddr_in *sin, struct sip_device **authpeer) 02640 { 02641 struct sip_device *device = NULL; 02642 char from[256], *c; 02643 char *of; 02644 char rpid_num[50]; 02645 const char *rpid; 02646 enum check_auth_result res = AUTH_SUCCESSFUL; 02647 char *t; 02648 char calleridname[50]; 02649 int debug = sip_debug_test_addr(sin); 02650 struct ast_variable *tmpvar = NULL, *v = NULL; 02651 enum objecttype devicematch = SIP_UNKNOWN; 02652 char *uri2 = ast_strdupa(uri); 02653 02654 /* Terminate URI */ 02655 t = uri2; 02656 while (*t && *t > 32 && *t != ';') 02657 t++; 02658 *t = '\0'; 02659 ast_copy_string(from, get_header(req, "From"), sizeof(from)); /* XXX bug in original code, overwrote string */ 02660 ast_uri_decode(from); 02661 /* XXX here tries to map the username for invite things */ 02662 memset(calleridname, 0, sizeof(calleridname)); 02663 get_calleridname(from, calleridname, sizeof(calleridname)); 02664 if (calleridname[0]) 02665 ast_string_field_set(p, cid_name, calleridname); 02666 02667 rpid = get_header(req, "Remote-Party-ID"); 02668 memset(rpid_num, 0, sizeof(rpid_num)); 02669 if (!ast_strlen_zero(rpid)) 02670 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num)); 02671 02672 of = get_in_brackets(from); 02673 if (ast_strlen_zero(p->exten)) { 02674 char *t = uri2; 02675 if (!strncmp(t, "sip:", 4)) 02676 t+= 4; 02677 ast_string_field_set(p, exten, t); 02678 t = strchr(p->exten, '@'); 02679 if (t) 02680 *t = '\0'; 02681 if (ast_strlen_zero(p->our_contact)) 02682 build_contact(p); 02683 } 02684 /* save the URI part of the From header */ 02685 ast_string_field_set(p, from, of); 02686 if (strncmp(of, "sip:", 4)) 02687 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n"); 02688 else 02689 of += 4; 02690 /* Get just the username part */ 02691 if ((c = strchr(of, '@'))) { 02692 char *tmp; 02693 *c = '\0'; 02694 if ((c = strchr(of, ':'))) 02695 *c = '\0'; 02696 tmp = ast_strdupa(of); 02697 if (ast_is_shrinkable_phonenumber(tmp)) 02698 ast_shrink_phone_number(tmp); 02699 ast_string_field_set(p, cid_num, tmp); 02700 } 02701 if (ast_strlen_zero(of)) 02702 return AUTH_SUCCESSFUL; 02703 02704 if (p->registry && p->registry->peer) /* We already know this device from registry */ 02705 device = p->registry->peer; 02706 else 02707 /* Find device in device list */ 02708 device = find_device(of, NULL, 1); 02709 if (device && !ast_apply_ha(device->ha, sin)) { 02710 device_unref(device); 02711 device = NULL; 02712 } 02713 /* Secondly match on IP/port (will in the future only be applied to trunks, not devices */ 02714 if (!device) { 02715 /* Look for peer based on the IP address we received data from */ 02716 /* If peer is registered from this IP address or have this as a default 02717 IP address, this call is from the peer 02718 */ 02719 device = find_device(NULL, &p->recv, 1); 02720 } 02721 if (device && !ast_apply_ha(device->ha, sin)) { 02722 device_unref(device); 02723 device = NULL; 02724 } 02725 if (device) 02726 devicematch = SIP_PEER; /* We matched on a peer */ 02727 /* No device found */ 02728 if (!device) { 02729 if (debug) 02730 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port)); 02731 02732 /* do we allow guests? */ 02733 if (!global.allowguest) 02734 res = -1; /* we don't want any guests, authentication will fail */ 02735 return res; 02736 } 02737 02738 /* Ok, we have a device, let's check authentication if needed */ 02739 ast_copy_flags(&p->flags[0], &device->flags[0], SIP_FLAGS_TO_COPY); 02740 ast_copy_flags(&p->flags[1], &device->flags[1], SIP_PAGE2_FLAGS_TO_COPY); 02741 02742 /* Copy SIP extensions profile to peer */ 02743 if (p->sipoptions) 02744 device->sipoptions = p->sipoptions; 02745 02746 /* copy channel vars */ 02747 for (v = device->chanvars ; v ; v = v->next) { 02748 if ((tmpvar = ast_variable_new(v->name, v->value))) { 02749 tmpvar->next = p->chanvars; 02750 p->chanvars = tmpvar; 02751 } 02752 } 02753 p->prefs = device->prefs; 02754 /* Set Frame packetization */ 02755 if (p->rtp) { 02756 ast_rtp_codec_setpref(p->rtp, &p->prefs); 02757 p->autoframing = device->autoframing; 02758 } 02759 02760 replace_cid(p, rpid_num, calleridname); 02761 02762 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE)); 02763 02764 if (device->maxms && device->lastms) 02765 p->timer_t1 = device->lastms; 02766 if (ast_test_flag(&device->flags[0], SIP_INSECURE_INVITE)) { 02767 /* Pretend there is no required authentication */ 02768 ast_string_field_free(p, peersecret); 02769 ast_string_field_free(p, peermd5secret); 02770 } 02771 /* Now, check auth */ 02772 if (!(res = check_auth(p, req, device->name, device->secret, device->md5secret, sipmethod, uri, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) { 02773 /* We have positive authentication, let's configure this SIP session */ 02774 sip_cancel_destroy(p); 02775 ast_copy_flags(&p->flags[0], &device->flags[0], SIP_FLAGS_TO_COPY); 02776 ast_copy_flags(&p->flags[1], &device->flags[1], SIP_PAGE2_FLAGS_TO_COPY); 02777 /* Copy SIP extensions profile from INVITE */ 02778 if (p->sipoptions) 02779 device->sipoptions = p->sipoptions; 02780 /* If we have a call limit, set flag */ 02781 if (device->call_limit) 02782 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT); 02783 if (!ast_strlen_zero(device->extra.context)) 02784 ast_string_field_set(p, context, device->extra.context); 02785 if (!ast_strlen_zero(device->extra.cid_num) && !ast_strlen_zero(p->cid_num)) { 02786 char *tmp = ast_strdupa(device->extra.cid_num); 02787 if (tmp) { 02788 if (ast_is_shrinkable_phonenumber(tmp)) 02789 ast_shrink_phone_number(tmp); 02790 ast_string_field_set(p, cid_num, tmp); 02791 } else { 02792 ast_string_field_set(p, cid_num, device->extra.cid_num); 02793 } 02794 } 02795 if (!ast_strlen_zero(device->extra.cid_name) && !ast_strlen_zero(p->cid_num)) 02796 ast_string_field_set(p, cid_name, device->extra.cid_name); 02797 ast_string_field_set(p, peersecret, device->secret); 02798 ast_string_field_set(p, peermd5secret, device->md5secret); 02799 ast_string_field_set(p, fullcontact, device->fullcontact); 02800 ast_string_field_set(p, peername, device->name); 02801 ast_string_field_set(p, authname, device->name); 02802 if (!ast_strlen_zero(device->defaultuser)) { 02803 ast_string_field_set(p, peername, device->defaultuser); 02804 /* Use the default username for authentication on outbound calls */ 02805 if(!ast_strlen_zero(device->authuser)) 02806 ast_string_field_set(p, authname, device->authuser); 02807 } 02808 if (p->t38.peercapability) 02809 p->t38.jointcapability &= p->t38.peercapability; 02810 p->maxcallbitrate = device->maxcallbitrate; 02811 /* If we do not support video, remove video from call structure */ 02812 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && p->vrtp) { 02813 ast_rtp_destroy(p->vrtp); 02814 p->vrtp = NULL; 02815 } 02816 ast_string_field_set(p, subscribecontext, device->extra.subscribecontext); 02817 ast_string_field_set(p, accountcode, device->extra.accountcode); 02818 ast_string_field_set(p, language, device->language); 02819 ast_string_field_set(p, mohsuggest, device->extra.mohsuggest); 02820 ast_string_field_set(p, mohinterpret, device->extra.mohinterpret); 02821 p->allowtransfer = device->allowtransfer; 02822 p->amaflags = device->extra.amaflags; 02823 p->callgroup = device->callgroup; 02824 p->pickupgroup = device->pickupgroup; 02825 p->callingpres = device->callingpres; 02826 p->capability = device->capability; 02827 p->jointcapability = device->capability; 02828 p->prefs = device->prefs; 02829 if (p->peercapability) 02830 p->jointcapability &= p->peercapability; 02831 p->maxcallbitrate = device->maxcallbitrate; 02832 if (!ast_test_flag((&p->flags[1]), SIP_PAGE2_VIDEOSUPPORT) && p->vrtp) { 02833 ast_rtp_destroy(p->vrtp); 02834 p->vrtp = NULL; 02835 } 02836 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) 02837 p->noncodeccapability |= AST_RTP_DTMF; 02838 else 02839 p->noncodeccapability &= ~AST_RTP_DTMF; 02840 02841 /* copy channel vars */ 02842 for (v = device->chanvars ; v ; v = v->next) { 02843 if ((tmpvar = ast_variable_new(v->name, v->value))) { 02844 tmpvar->next = p->chanvars; 02845 p->chanvars = tmpvar; 02846 } 02847 } 02848 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE)); 02849 ast_string_field_set(p, peersecret, device->secret); 02850 ast_string_field_set(p, peermd5secret, device->md5secret); 02851 ast_string_field_set(p, subscribecontext, device->extra.subscribecontext); 02852 ast_string_field_set(p, mohinterpret, device->extra.mohinterpret); 02853 ast_string_field_set(p, mohsuggest, device->extra.mohsuggest); 02854 if (device->callingpres) /* Peer calling pres setting will override RPID */ 02855 p->callingpres = device->callingpres; 02856 } 02857 if (device && debug) 02858 ast_verbose("Found %s '%s'\n", device->type & SIP_USER ? "user" : "peer", device->name); 02859 02860 device_unref(device); 02861 02862 return res; 02863 } 02864 02865 /*! \brief Find user 02866 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced 02867 */ 02868 static int check_user(struct sip_dialog *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin) 02869 { 02870 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL); 02871 } 02872 02873 /*! \brief Get text out of a SIP MESSAGE packet */ 02874 static int get_msg_text(char *buf, int len, struct sip_request *req) 02875 { 02876 int x; 02877 int y; 02878 02879 buf[0] = '\0'; 02880 y = len - strlen(buf) - 5; 02881 if (y < 0) 02882 y = 0; 02883 for (x=0;x<req->lines;x++) { 02884 strncat(buf, req->line[x], y); /* safe */ 02885 y -= strlen(req->line[x]) + 1; 02886 if (y < 0) 02887 y = 0; 02888 if (y != 0) 02889 strcat(buf, "\n"); /* safe */ 02890 } 02891 return 0; 02892 } 02893 02894 02895 /*! \brief Receive SIP MESSAGE method messages 02896 \note We only handle messages within current calls currently 02897 Reference: RFC 3428 */ 02898 static void receive_message(struct sip_dialog *p, struct sip_request *req) 02899 { 02900 char buf[1024]; 02901 struct ast_frame f; 02902 const char *content_type = get_header(req, "Content-Type"); 02903 02904 if (strcmp(content_type, "text/plain")) { /* No text/plain attachment */ 02905 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */ 02906 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); 02907 return; 02908 } 02909 02910 if (get_msg_text(buf, sizeof(buf), req)) { 02911 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid); 02912 transmit_response(p, "202 Accepted", req); 02913 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); 02914 return; 02915 } 02916 02917 if (p->owner) { 02918 if (sip_debug_test_pvt(p)) 02919 ast_verbose("Message received: '%s'\n", buf); 02920 memset(&f, 0, sizeof(f)); 02921 f.frametype = AST_FRAME_TEXT; 02922 f.subclass = 0; 02923 f.offset = 0; 02924 f.data = buf; 02925 f.datalen = strlen(buf); 02926 ast_queue_frame(p->owner, &f); 02927 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */ 02928 } else { /* Message outside of a call, we do not support that */ 02929 ast_log(LOG_WARNING,"Received message to %s from %s, dropped it...\n Content-Type:%s\n Message: %s\n", get_header(req,"To"), get_header(req,"From"), content_type, buf); 02930 transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */ 02931 } 02932 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); 02933 return; 02934 } 02935 02936 /*! \brief Remove temporary realtime objects from memory (CLI) */ 02937 GNURK int sip_prune_realtime(int fd, int argc, char *argv[]) 02938 { 02939 struct sip_device *device; 02940 int prunepeer = FALSE; 02941 int multi = FALSE; 02942 char *name = NULL; 02943 regex_t regexbuf; 02944 02945 switch (argc) { 02946 case 4: 02947 if (!strcasecmp(argv[3], "peer")) 02948 return RESULT_SHOWUSAGE; 02949 if (!strcasecmp(argv[3], "like")) 02950 return RESULT_SHOWUSAGE; 02951 if (!strcasecmp(argv[3], "all")) { 02952 multi = TRUE; 02953 prunepeer = TRUE; 02954 } else { 02955 prunepeer = TRUE; 02956 name = argv[3]; 02957 } 02958 break; 02959 case 5: 02960 if (!strcasecmp(argv[4], "like")) 02961 return RESULT_SHOWUSAGE; 02962 if (!strcasecmp(argv[3], "all")) 02963 return RESULT_SHOWUSAGE; 02964 if (!strcasecmp(argv[3], "like")) { 02965 multi = TRUE; 02966 name = argv[4]; 02967 prunepeer = TRUE; 02968 } else if (!strcasecmp(argv[3], "peer")) { 02969 prunepeer = TRUE; 02970 if (!strcasecmp(argv[4], "all")) 02971 multi = TRUE; 02972 else 02973 name = argv[4]; 02974 } else 02975 return RESULT_SHOWUSAGE; 02976 break; 02977 case 6: 02978 if (strcasecmp(argv[4], "like")) 02979 return RESULT_SHOWUSAGE; 02980 if (!strcasecmp(argv[3], "peer")) { 02981 prunepeer = TRUE; 02982 name = argv[5]; 02983 } else 02984 return RESULT_SHOWUSAGE; 02985 break; 02986 default: 02987 return RESULT_SHOWUSAGE; 02988 } 02989 02990 if (multi && name) { 02991 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB)) 02992 return RESULT_SHOWUSAGE; 02993 } 02994 02995 if (multi) { 02996 if (prunepeer) { 02997 int pruned = 0; 02998 02999 ASTOBJ_CONTAINER_WRLOCK(&devicelist); 03000 ASTOBJ_CONTAINER_TRAVERSE(&devicelist, 1, do { 03001 ASTOBJ_RDLOCK(iterator); 03002 if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) { 03003 ASTOBJ_UNLOCK(iterator); 03004 continue; 03005 }; 03006 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) { 03007 ASTOBJ_MARK(iterator); 03008 pruned++; 03009 } 03010 ASTOBJ_UNLOCK(iterator); 03011 } while (0) ); 03012 if (pruned) { 03013 ASTOBJ_CONTAINER_PRUNE_MARKED(&devicelist, sip_destroy_device); 03014 ast_cli(fd, "%d peers pruned.\n", pruned); 03015 } else 03016 ast_cli(fd, "No peers found to prune.\n"); 03017 ASTOBJ_CONTAINER_UNLOCK(&devicelist); 03018 } 03019 } else { 03020 if (prunepeer) { 03021 if ((device = ASTOBJ_CONTAINER_FIND_UNLINK(&devicelist, name))) { 03022 if (!ast_test_flag((&device->flags[1]), SIP_PAGE2_RTCACHEFRIENDS)) { 03023 ast_cli(fd, "Device '%s' is not a Realtime peer, cannot be pruned.\n", name); 03024 ASTOBJ_CONTAINER_LINK(&devicelist, device); 03025 } else 03026 ast_cli(fd, "Peer '%s' pruned.\n", name); 03027 device_unref(device); 03028 } else 03029 ast_cli(fd, "Device '%s' not found.\n", name); 03030 } 03031 } 03032 03033 return RESULT_SUCCESS; 03034 } 03035 03036 /*! \brief Receive SIP INFO Message 03037 \note Doesn't read the duration of the DTMF signal */ 03038 static void handle_request_info(struct sip_dialog *p, struct sip_request *req) 03039 { 03040 char buf[1024]; 03041 unsigned int event; 03042 const char *c = get_header(req, "Content-Type"); 03043 03044 if (ast_test_flag(req, SIP_PKT_IGNORE)) { 03045 transmit_response(p, "200 OK", req); 03046 return; 03047 } 03048 03049 /* All replies to INFO are final */ 03050 dialogstatechange(p, DIALOG_STATE_TERMINATED); 03051 03052 /* Need to check the media/type */ 03053 if (!strcasecmp(c, "application/dtmf-relay") || 03054 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) { 03055 unsigned int duration = 0; 03056 03057 if (p->state == DIALOG_STATE_TRYING) { /* INFO outside of a dialog */ 03058 transmit_final_response(p, "481 Call leg/transaction does not exist", req, XMIT_UNRELIABLE); /* Should return error */ 03059 return; 03060 } 03061 03062 /* Try getting the "signal=" part */ 03063 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) { 03064 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid); 03065 transmit_response(p, "200 OK", req); /* Should return error */ 03066 return; 03067 } else 03068 ast_copy_string(buf, c, sizeof(buf)); 03069 03070 if (!ast_strlen_zero((c = get_body(req, "Duration")))) 03071 duration = atoi(c); 03072 if (!duration) 03073 duration = 100; /* 100 ms */ 03074 03075 03076 03077 if (ast_strlen_zero(buf)) { 03078 /* Nothing there folks, move on. */ 03079 transmit_response(p, "200 OK", req); 03080 return; 03081 } 03082 /* We have a DTMF code in the attachment */ 03083 03084 if (buf[0] == '*') 03085 event = 10; 03086 else if (buf[0] == '#') 03087 event = 11; 03088 else if ((buf[0] >= 'A') && (buf[0] <= 'D')) 03089 event = 12 + buf[0] - 'A'; 03090 else 03091 event = atoi(buf); 03092 if (event == 16) { 03093 /* send a FLASH event */ 03094 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, }; 03095 ast_queue_frame(p->owner, &f); 03096 if (sipdebug) 03097 ast_verbose("* DTMF-relay event received: FLASH\n"); 03098 } else { 03099 /* send a DTMF event */ 03100 struct ast_frame f = { AST_FRAME_DTMF, }; 03101 if (event < 10) { 03102 f.subclass = '0' + event; 03103 } else if (event < 11) { 03104 f.subclass = '*'; 03105 } else if (event < 12) { 03106 f.subclass = '#'; 03107 } else if (event < 16) { 03108 f.subclass = 'A' + (event - 12); 03109 } 03110 f.len = duration; 03111 ast_queue_frame(p->owner, &f); 03112 if (sipdebug) 03113 ast_verbose("* DTMF-relay event received: %c\n", f.subclass); 03114 } 03115 transmit_response(p, "200 OK", req); 03116 return; 03117 } else if (!strcasecmp(c, "application/media_control+xml")) { 03118 /* Eh, we'll just assume it's a fast picture update for now */ 03119 if (p->owner) 03120 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE); 03121 transmit_response(p, "200 OK", req); 03122 return; 03123 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) { 03124 /* Client code (from SNOM phone) */ 03125 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) { 03126 if (p->owner && p->owner->cdr) 03127 ast_cdr_setuserfield(p->owner, c); 03128 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr) 03129 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c); 03130 transmit_response(p, "200 OK", req); 03131 } else { 03132 transmit_response(p, "415 Unsupported media type", req); 03133 } 03134 return; 03135 } 03136 /* Other type of INFO message, not really understood by Asterisk */ 03137 /* if (get_msg_text(buf, sizeof(buf), req)) { */ 03138 03139 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf); 03140 transmit_response(p, "415 Unsupported media type", req); 03141 return; 03142 } 03143 03144 /*! \brief Cli command to send SIP notify to peer */ 03145 GNURK int sip_notify(int fd, int argc, char *argv[]) 03146 { 03147 struct ast_variable *varlist; 03148 int i; 03149 03150 if (argc < 4) 03151 return RESULT_SHOWUSAGE; 03152 03153 if (!notify_types) { 03154 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config); 03155 return RESULT_FAILURE; 03156 } 03157 03158 varlist = ast_variable_browse(notify_types, argv[2]); 03159 03160 if (!varlist) { 03161 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]); 03162 return RESULT_FAILURE; 03163 } 03164 03165 for (i = 3; i < argc; i++) { 03166 struct sip_dialog *dialog; 03167 struct sip_request *req; 03168 struct ast_variable *var; 03169 struct sip_device *peer; 03170 03171 if (!(dialog = sip_alloc(NULL, NULL, FALSE, SIP_NOTIFY))) { 03172 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n"); 03173 return RESULT_FAILURE; 03174 } 03175 03176 peer = find_device(argv[i], NULL, 1); 03177 03178 if (peer && create_addr_from_peer(dialog, peer)) { 03179 /* Maybe they're not registered, etc. */ 03180 sip_destroy(dialog); 03181 ast_cli(fd, "Could not create address for '%s'\n", argv[i]); 03182 continue; 03183 } 03184 if (peer) 03185 device_unref(peer); 03186 req = siprequest_alloc(SIP_MAX_PACKET, &sipnet); 03187 if (!req) { 03188 ast_log(LOG_WARNING, "Unable to build sip request data for notify (memory/socket error)\n"); 03189 return RESULT_FAILURE; 03190 } 03191 03192 initreqprep(req, dialog, SIP_NOTIFY); 03193 03194 for (var = varlist; var; var = var->next) 03195 add_header(req, var->name, var->value); 03196 03197 /* Recalculate our side, and recalculate Call ID */ 03198 if (sip_ouraddrfor(&dialog->sa.sin_addr, &dialog->ourip)) 03199 dialog->ourip = sipnet.__ourip; 03200 build_via(dialog, FALSE); 03201 build_callid_pvt(dialog); 03202 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]); 03203 transmit_sip_request(dialog, req); 03204 siprequest_free(req); 03205 sip_scheddestroy(dialog, -1); 03206 } 03207 03208 return RESULT_SUCCESS; 03209 } 03210 03211 /*! \brief Read SIP header (dialplan function) */ 03212 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 03213 { 03214 struct sip_dialog *p; 03215 const char *content = NULL; 03216 AST_DECLARE_APP_ARGS(args, 03217 AST_APP_ARG(header); 03218 AST_APP_ARG(number); 03219 ); 03220 int i, number, start = 0; 03221 03222 if (ast_strlen_zero(data)) { 03223 ast_log(LOG_WARNING, "This function requires a header name.\n"); 03224 return -1; 03225 } 03226 03227 ast_channel_lock(chan); 03228 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) { 03229 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n"); 03230 ast_channel_unlock(chan); 03231 return -1; 03232 } 03233 03234 AST_STANDARD_APP_ARGS(args, data); 03235 if (!args.number) { 03236 number = 1; 03237 } else { 03238 sscanf(args.number, "%d", &number); 03239 if (number < 1) 03240 number = 1; 03241 } 03242 03243 p = chan->tech_pvt; 03244 03245 /* If there is no private structure, this channel is no longer alive */ 03246 if (!p) { 03247 ast_channel_unlock(chan); 03248 return -1; 03249 } 03250 03251 for (i = 0; i < number; i++) 03252 content = __get_header(p->initreq, args.header, &start); 03253 03254 if (ast_strlen_zero(content)) { 03255 ast_channel_unlock(chan); 03256 return -1; 03257 } 03258 03259 ast_copy_string(buf, content, len); 03260 ast_channel_unlock(chan); 03261 03262 return 0; 03263 } 03264 03265 static struct ast_custom_function sip_header_function = { 03266 .name = "SIP_HEADER", 03267 .synopsis = "Gets the specified SIP header from the INVITE", 03268 .syntax = "SIP_HEADER(<name>[,<number>])", 03269 .desc = "Since there are several headers (such as Via) which can occur multiple\n" 03270 "times, SIP_HEADER takes an optional second argument to specify which header with\n" 03271 "that name to retrieve. Headers start at offset 1.\n", 03272 .read = func_header_read, 03273 }; 03274 03275 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */ 03276 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) 03277 { 03278 struct sip_device *peer; 03279 char *colname; 03280 03281 if ((colname = strchr(data, '|'))) 03282 *colname++ = '\0'; 03283 else 03284 colname = "ip"; 03285 03286 if (!(peer = find_device(data, NULL, 1))) 03287 return -1; 03288 03289 if (!strcasecmp(colname, "ip")) { 03290 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len); 03291 } else if (!strcasecmp(colname, "status")) { 03292 device_status(peer, buf, len); 03293 } else if (!strcasecmp(colname, "language")) { 03294 ast_copy_string(buf, peer->language, len); 03295 } else if (!strcasecmp(colname, "regexten")) { 03296 ast_copy_string(buf, peer->extra.regexten, len); 03297 } else if (!strcasecmp(colname, "limit")) { 03298 snprintf(buf, len, "%d", peer->call_limit); 03299 } else if (!strcasecmp(colname, "curcalls")) { 03300 snprintf(buf, len, "%d", peer->inUse); 03301 } else if (!strcasecmp(colname, "accountcode")) { 03302 ast_copy_string(buf, peer->extra.accountcode, len); 03303 } else if (!strcasecmp(colname, "useragent")) { 03304 ast_copy_string(buf, peer->useragent, len); 03305 } else if (!strcasecmp(colname, "mailbox")) { 03306 ast_copy_string(buf, peer->mailbox.mailbox, len); 03307 } else if (!strcasecmp(colname, "context")) { 03308 ast_copy_string(buf, peer->extra.context, len); 03309 } else if (!strcasecmp(colname, "expire")) { 03310 snprintf(buf, len, "%d", peer->expire); 03311 } else if (!strcasecmp(colname, "dynamic")) { 03312 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len); 03313 } else if (!strcasecmp(colname, "callerid_name")) { 03314 ast_copy_string(buf, peer->extra.cid_name, len); 03315 } else if (!strcasecmp(colname, "callerid_num")) { 03316 ast_copy_string(buf, peer->extra.cid_num, len); 03317 } else if (!strcasecmp(colname, "codecs")) { 03318 ast_getformatname_multiple(buf, len -1, peer->capability); 03319 } else if (!strncasecmp(colname, "codec[", 6)) { 03320 char *codecnum; 03321 int index = 0, codec = 0; 03322 03323 codecnum = colname + 6; /* move past the '[' */ 03324 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */ 03325 index = atoi(codecnum); 03326 if((codec = ast_codec_pref_index(&peer->prefs, index))) { 03327 ast_copy_string(buf, ast_getformatname(codec), len); 03328 } 03329 } 03330 03331 device_unref(peer); 03332 03333 return 0; 03334 } 03335 03336 /*! \brief Structure to declare a dialplan function: SIPPEER */ 03337 struct ast_custom_function sippeer_function = { 03338 .name = "SIPPEER", 03339 .synopsis = "Gets SIP peer information", 03340 .syntax = "SIPPEER(<peername>[|item])", 03341 .read = function_sippeer, 03342 .desc = "Valid items are:\n" 03343 "- ip (default) The IP address.\n" 03344 "- mailbox The configured mailbox.\n" 03345 "- context The configured context.\n" 03346 "- expire The epoch time of the next expire.\n" 03347 "- dynamic Is it dynamic? (yes/no).\n" 03348 "- callerid_name The configured Caller ID name.\n" 03349 "- callerid_num The configured Caller ID number.\n" 03350 "- codecs The configured codecs.\n" 03351 "- status Status (if qualify=yes).\n" 03352 "- regexten Registration extension\n" 03353 "- limit Call limit (call-limit)\n" 03354 "- curcalls Current amount of calls \n" 03355 " Only available if call-limit is set\n" 03356 "- language Default language for peer\n" 03357 "- accountcode Account code for this peer\n" 03358 "- useragent Current user agent id for peer\n" 03359 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n" 03360 "\n" 03361 }; 03362 03363 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */ 03364 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) 03365 { 03366 struct sip_dialog *p; 03367 03368 *buf = 0; 03369 03370 if (!data) { 03371 ast_log(LOG_WARNING, "This function requires a parameter name.\n"); 03372 return -1; 03373 } 03374 03375 ast_channel_lock(chan); 03376 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) { 03377 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n"); 03378 ast_channel_unlock(chan); 03379 return -1; 03380 } 03381 03382 p = chan->tech_pvt; 03383 03384 /* If there is no private structure, this channel is no longer alive */ 03385 if (!p) { 03386 ast_channel_unlock(chan); 03387 return -1; 03388 } 03389 03390 if (!strcasecmp(data, "peerip")) { 03391 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len); 03392 } else if (!strcasecmp(data, "recvip")) { 03393 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len); 03394 } else if (!strcasecmp(data, "from")) { 03395 ast_copy_string(buf, p->from, len); 03396 } else if (!strcasecmp(data, "uri")) { 03397 ast_copy_string(buf, p->uri, len); 03398 } else if (!strcasecmp(data, "useragent")) { 03399 ast_copy_string(buf, p->useragent, len); 03400 } else if (!strcasecmp(data, "peername")) { 03401 ast_copy_string(buf, p->peername, len); 03402 } else if (!strcasecmp(data, "t38passthrough")) { 03403 if (p->t38.state == T38_DISABLED) 03404 ast_copy_string(buf, "0", sizeof("0")); 03405 else /* T38 is offered or enabled in this call */ 03406 ast_copy_string(buf, "1", sizeof("1")); 03407 } else { 03408 ast_channel_unlock(chan); 03409 return -1; 03410 } 03411 ast_channel_unlock(chan); 03412 03413 return 0; 03414 } 03415 03416 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */ 03417 static struct ast_custom_function sipchaninfo_function = { 03418 .name = "SIPCHANINFO", 03419 .synopsis = "Gets the specified SIP parameter from the current channel", 03420 .syntax = "SIPCHANINFO(item)", 03421 .read = function_sipchaninfo_read, 03422 .desc = "Valid items are:\n" 03423 "- peerip The IP address of the peer.\n" 03424 "- recvip The source IP address of the peer.\n" 03425 "- from The URI from the From: header.\n" 03426 "- uri The URI from the Contact: header.\n" 03427 "- useragent The useragent.\n" 03428 "- peername The name of the peer.\n" 03429 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n" 03430 }; 03431 03432 /*! \brief Check pending actions on SIP call */ 03433 static void check_pendings(struct sip_dialog *p) 03434 { 03435 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) { 03436 /* if we can't BYE, then this is really a pending CANCEL */ 03437 if (!ast_test_flag(&p->flags[0], SIP_CAN_BYE)) 03438 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0); 03439 /* Actually don't destroy us yet, wait for the 487 on our original 03440 INVITE, but do set an autodestruct just in case we never get it. */ 03441 else 03442 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1); 03443 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE); 03444 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); 03445 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) { 03446 if (option_debug) 03447 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid); 03448 /* Didn't get to reinvite yet, so do it now */ 03449 transmit_reinvite_with_sdp(p, FALSE); 03450 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 03451 } 03452 } 03453 03454 /*! \brief Handle a positive response to an INVITE - 200 OK */ 03455 static void handle_response_answer(struct sip_dialog *dialog, struct sip_request *req, int outgoing, int reinvite) 03456 { 03457 int res; /*! \note XXX Not used now, but somehow we need to handle response from process_sdp */ 03458 struct ast_channel *bridgepeer = NULL; 03459 03460 /* If we have SDP in the 200 OK, then process it */ 03461 if (find_sdp(req)) { 03462 if ((res = process_sdp(dialog, req)) && !ast_test_flag(req, SIP_PKT_IGNORE)) 03463 if (!reinvite) 03464 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */ 03465 /* For re-invites, we try to recover */ 03466 ast_set_flag(&dialog->flags[0], SIP_PENDINGBYE); 03467 } else 03468 ast_log(LOG_NOTICE, "200 OK on INVITE without SDP??? Call-ID: %s\n", dialog->callid); 03469 03470 /* Parse contact header for continued conversation */ 03471 /* When we get 200 OK, we know which device (and IP) to contact for this call */ 03472 /* This is important when we have a SIP proxy between us and the phone */