Codename Pineapple

Home page | Mailing list | Docs

Last updated: Sat Feb 3 05:00:41 2007

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(