00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 #include <stdio.h>
00033 #include <ctype.h>
00034 #include <string.h>
00035 #include <unistd.h>
00036 #include <sys/socket.h>
00037 #include <sys/ioctl.h>
00038 #include <net/if.h>
00039 #include <errno.h>
00040 #include <stdlib.h>
00041 #include <fcntl.h>
00042 #include <netdb.h>
00043 #include <signal.h>
00044 #include <sys/signal.h>
00045 #include <netinet/in.h>
00046 #include <netinet/in_systm.h>
00047 #include <arpa/inet.h>
00048 #include <netinet/ip.h>
00049 #include <regex.h>
00050
00051 #include "asterisk.h"
00052
00053 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 211526 $")
00054
00055 #include "asterisk/lock.h"
00056 #include "asterisk/channel.h"
00057 #include "asterisk/config.h"
00058 #include "asterisk/logger.h"
00059 #include "asterisk/module.h"
00060 #include "asterisk/pbx.h"
00061 #include "asterisk/options.h"
00062 #include "asterisk/lock.h"
00063 #include "asterisk/sched.h"
00064 #include "asterisk/io.h"
00065 #include "asterisk/rtp.h"
00066 #include "asterisk/acl.h"
00067 #include "asterisk/manager.h"
00068 #include "asterisk/callerid.h"
00069 #include "asterisk/cli.h"
00070 #include "asterisk/app.h"
00071 #include "asterisk/musiconhold.h"
00072 #include "asterisk/dsp.h"
00073 #include "asterisk/features.h"
00074 #include "asterisk/acl.h"
00075 #include "asterisk/srv.h"
00076 #include "asterisk/astdb.h"
00077 #include "asterisk/causes.h"
00078 #include "asterisk/utils.h"
00079 #include "asterisk/file.h"
00080 #include "asterisk/astobj.h"
00081 #include "asterisk/devicestate.h"
00082 #include "asterisk/linkedlists.h"
00083
00084 #ifdef OSP_SUPPORT
00085 #include "asterisk/astosp.h"
00086 #endif
00087
00088 #ifndef DEFAULT_USERAGENT
00089 #define DEFAULT_USERAGENT "Asterisk PBX"
00090 #endif
00091
00092 #define VIDEO_CODEC_MASK 0x1fc0000
00093 #ifndef IPTOS_MINCOST
00094 #define IPTOS_MINCOST 0x02
00095 #endif
00096
00097
00098
00099 #define SIPDUMPER
00100 #define DEFAULT_DEFAULT_EXPIRY 120
00101 #define DEFAULT_MAX_EXPIRY 3600
00102 #define DEFAULT_REGISTRATION_TIMEOUT 20
00103 #define DEFAULT_MAX_FORWARDS "70"
00104
00105
00106
00107 #define EXPIRY_GUARD_SECS 15
00108 #define EXPIRY_GUARD_LIMIT 30
00109
00110 #define EXPIRY_GUARD_MIN 500
00111
00112
00113
00114 #define EXPIRY_GUARD_PCT 0.20
00115
00116
00117 #define SIP_LEN_CONTACT 256
00118
00119 static int max_expiry = DEFAULT_MAX_EXPIRY;
00120 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00121
00122 #ifndef MAX
00123 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00124 #endif
00125
00126 #define CALLERID_UNKNOWN "Unknown"
00127
00128
00129
00130 #define DEFAULT_MAXMS 2000
00131 #define DEFAULT_FREQ_OK 60 * 1000
00132 #define DEFAULT_FREQ_NOTOK 10 * 1000
00133
00134 #define DEFAULT_RETRANS 1000
00135
00136 #define MAX_RETRANS 6
00137 #define MAX_AUTHTRIES 3
00138
00139
00140 #define DEBUG_READ 0
00141 #define DEBUG_SEND 1
00142
00143 static const char desc[] = "Session Initiation Protocol (SIP)";
00144 static const char channeltype[] = "SIP";
00145 static const char config[] = "sip.conf";
00146 static const char notify_config[] = "sip_notify.conf";
00147
00148 #define RTP 1
00149 #define NO_RTP 0
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159 enum subscriptiontype {
00160 NONE = 0,
00161 XPIDF_XML,
00162 DIALOG_INFO_XML,
00163 CPIM_PIDF_XML,
00164 PIDF_XML
00165 };
00166
00167 static const struct cfsubscription_types {
00168 enum subscriptiontype type;
00169 const char * const event;
00170 const char * const mediatype;
00171 const char * const text;
00172 } subscription_types[] = {
00173 { NONE, "-", "unknown", "unknown" },
00174
00175 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00176 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00177 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00178 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }
00179 };
00180
00181 enum sipmethod {
00182 SIP_UNKNOWN,
00183 SIP_RESPONSE,
00184 SIP_REGISTER,
00185 SIP_OPTIONS,
00186 SIP_NOTIFY,
00187 SIP_INVITE,
00188 SIP_ACK,
00189 SIP_PRACK,
00190 SIP_BYE,
00191 SIP_REFER,
00192 SIP_SUBSCRIBE,
00193 SIP_MESSAGE,
00194 SIP_UPDATE,
00195 SIP_INFO,
00196 SIP_CANCEL,
00197 SIP_PUBLISH,
00198 } sip_method_list;
00199
00200 enum sip_auth_type {
00201 PROXY_AUTH,
00202 WWW_AUTH,
00203 };
00204
00205
00206 static const struct cfsip_methods {
00207 enum sipmethod id;
00208 int need_rtp;
00209 char * const text;
00210 int can_create;
00211 } sip_methods[] = {
00212 { SIP_UNKNOWN, RTP, "-UNKNOWN-", 2 },
00213 { SIP_RESPONSE, NO_RTP, "SIP/2.0", 0 },
00214 { SIP_REGISTER, NO_RTP, "REGISTER", 1 },
00215 { SIP_OPTIONS, NO_RTP, "OPTIONS", 1 },
00216 { SIP_NOTIFY, NO_RTP, "NOTIFY", 2 },
00217 { SIP_INVITE, RTP, "INVITE", 1 },
00218 { SIP_ACK, NO_RTP, "ACK", 0 },
00219 { SIP_PRACK, NO_RTP, "PRACK", 2 },
00220 { SIP_BYE, NO_RTP, "BYE", 0 },
00221 { SIP_REFER, NO_RTP, "REFER", 2 },
00222 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", 1 },
00223 { SIP_MESSAGE, NO_RTP, "MESSAGE", 1 },
00224 { SIP_UPDATE, NO_RTP, "UPDATE", 0 },
00225 { SIP_INFO, NO_RTP, "INFO", 0 },
00226 { SIP_CANCEL, NO_RTP, "CANCEL", 0 },
00227 { SIP_PUBLISH, NO_RTP, "PUBLISH", 1 }
00228 };
00229
00230
00231 static const struct cfalias {
00232 char * const fullname;
00233 char * const shortname;
00234 } aliases[] = {
00235 { "Content-Type", "c" },
00236 { "Content-Encoding", "e" },
00237 { "From", "f" },
00238 { "Call-ID", "i" },
00239 { "Contact", "m" },
00240 { "Content-Length", "l" },
00241 { "Subject", "s" },
00242 { "To", "t" },
00243 { "Supported", "k" },
00244 { "Refer-To", "r" },
00245 { "Referred-By", "b" },
00246 { "Allow-Events", "u" },
00247 { "Event", "o" },
00248 { "Via", "v" },
00249 { "Accept-Contact", "a" },
00250 { "Reject-Contact", "j" },
00251 { "Request-Disposition", "d" },
00252 { "Session-Expires", "x" },
00253 };
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263
00264
00265 #define SUPPORTED 1
00266 #define NOT_SUPPORTED 0
00267
00268 #define SIP_OPT_REPLACES (1 << 0)
00269 #define SIP_OPT_100REL (1 << 1)
00270 #define SIP_OPT_TIMER (1 << 2)
00271 #define SIP_OPT_EARLY_SESSION (1 << 3)
00272 #define SIP_OPT_JOIN (1 << 4)
00273 #define SIP_OPT_PATH (1 << 5)
00274 #define SIP_OPT_PREF (1 << 6)
00275 #define SIP_OPT_PRECONDITION (1 << 7)
00276 #define SIP_OPT_PRIVACY (1 << 8)
00277 #define SIP_OPT_SDP_ANAT (1 << 9)
00278 #define SIP_OPT_SEC_AGREE (1 << 10)
00279 #define SIP_OPT_EVENTLIST (1 << 11)
00280 #define SIP_OPT_GRUU (1 << 12)
00281 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00282
00283
00284
00285 static const struct cfsip_options {
00286 int id;
00287 int supported;
00288 char * const text;
00289 } sip_options[] = {
00290
00291 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
00292
00293 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
00294
00295 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
00296
00297 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
00298
00299 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
00300
00301 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
00302
00303 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
00304
00305 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00306
00307 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
00308
00309 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
00310
00311 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00312
00313 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00314
00315 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
00316
00317 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
00318 };
00319
00320
00321
00322 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
00323
00324
00325 #define SUPPORTED_EXTENSIONS "replaces"
00326
00327 #define DEFAULT_SIP_PORT 5060
00328 #define SIP_MAX_PACKET 4096
00329
00330 static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
00331
00332 #define DEFAULT_CONTEXT "default"
00333 static char default_context[AST_MAX_CONTEXT] = DEFAULT_CONTEXT;
00334 static char default_subscribecontext[AST_MAX_CONTEXT];
00335
00336 #define DEFAULT_VMEXTEN "asterisk"
00337 static char global_vmexten[AST_MAX_EXTENSION] = DEFAULT_VMEXTEN;
00338
00339 static char default_language[MAX_LANGUAGE] = "";
00340
00341 #define DEFAULT_CALLERID "asterisk"
00342 static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
00343
00344 static char default_fromdomain[AST_MAX_EXTENSION] = "";
00345
00346 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
00347 static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
00348
00349 static int global_notifyringing = 1;
00350
00351 static int global_alwaysauthreject = 0;
00352
00353 static int default_qualify = 0;
00354
00355 static struct ast_flags global_flags = {0};
00356 static struct ast_flags global_flags_page2 = {0};
00357
00358 static int srvlookup = 0;
00359
00360 static int pedanticsipchecking = 0;
00361
00362 static int autocreatepeer = 0;
00363
00364 static int relaxdtmf = 0;
00365
00366 static int global_rtptimeout = 0;
00367
00368 static int global_rtpholdtimeout = 0;
00369
00370 static int global_rtpkeepalive = 0;
00371
00372 static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
00373 static int global_regattempts_max = 0;
00374
00375
00376 static int suserobjs = 0;
00377 static int ruserobjs = 0;
00378 static int speerobjs = 0;
00379 static int rpeerobjs = 0;
00380 static int apeerobjs = 0;
00381 static int regobjs = 0;
00382
00383 static int global_allowguest = 1;
00384
00385 #define DEFAULT_MWITIME 10
00386 static int global_mwitime = DEFAULT_MWITIME;
00387
00388 static int usecnt =0;
00389 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
00390
00391 AST_MUTEX_DEFINE_STATIC(rand_lock);
00392
00393
00394 AST_MUTEX_DEFINE_STATIC(iflock);
00395
00396
00397
00398 AST_MUTEX_DEFINE_STATIC(netlock);
00399
00400 AST_MUTEX_DEFINE_STATIC(monlock);
00401
00402
00403
00404 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00405
00406 static int restart_monitor(void);
00407
00408
00409 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00410
00411 static struct in_addr __ourip;
00412 static struct sockaddr_in outboundproxyip;
00413 static int ourport;
00414
00415 #define SIP_DEBUG_CONFIG 1 << 0
00416 #define SIP_DEBUG_CONSOLE 1 << 1
00417 static int sipdebug = 0;
00418 static struct sockaddr_in debugaddr;
00419
00420 static int tos = 0;
00421
00422 static int videosupport = 0;
00423
00424 static int compactheaders = 0;
00425
00426 static int recordhistory = 0;
00427 static int dumphistory = 0;
00428
00429 static char global_musicclass[MAX_MUSICCLASS] = "";
00430 #define DEFAULT_REALM "asterisk"
00431 static char global_realm[MAXHOSTNAMELEN] = DEFAULT_REALM;
00432 static char regcontext[AST_MAX_CONTEXT] = "";
00433
00434 #define DEFAULT_EXPIRY 900
00435 static int expiry = DEFAULT_EXPIRY;
00436
00437 #define DEFAULT_T1MIN 100
00438
00439 static struct sched_context *sched;
00440 static struct io_context *io;
00441 static int *sipsock_read_id;
00442
00443 #define SIP_MAX_HEADERS 64
00444 #define SIP_MAX_LINES 64
00445
00446 #define DEC_CALL_LIMIT 0
00447 #define INC_CALL_LIMIT 1
00448
00449 static struct ast_codec_pref prefs;
00450
00451
00452
00453 struct sip_request {
00454 char *rlPart1;
00455 char *rlPart2;
00456 int len;
00457 int headers;
00458 int method;
00459 char *header[SIP_MAX_HEADERS];
00460 int lines;
00461 char *line[SIP_MAX_LINES];
00462 char data[SIP_MAX_PACKET];
00463 int debug;
00464 unsigned int flags;
00465 unsigned int sdp_start;
00466 unsigned int sdp_end;
00467 };
00468
00469 struct sip_pkt;
00470
00471
00472 struct sip_invite_param {
00473 char *distinctive_ring;
00474 char *osptoken;
00475 int addsipheaders;
00476 char *uri_options;
00477 char *vxml_url;
00478 char *auth;
00479 char *authheader;
00480 enum sip_auth_type auth_type;
00481 };
00482
00483 struct sip_route {
00484 struct sip_route *next;
00485 char hop[0];
00486 };
00487
00488 enum domain_mode {
00489 SIP_DOMAIN_AUTO,
00490 SIP_DOMAIN_CONFIG,
00491 };
00492
00493 struct domain {
00494 char domain[MAXHOSTNAMELEN];
00495 char context[AST_MAX_EXTENSION];
00496 enum domain_mode mode;
00497 AST_LIST_ENTRY(domain) list;
00498 };
00499
00500 static AST_LIST_HEAD_STATIC(domain_list, domain);
00501
00502 int allow_external_domains;
00503
00504
00505 struct sip_history {
00506 char event[80];
00507 struct sip_history *next;
00508 };
00509
00510
00511 struct sip_auth {
00512 char realm[AST_MAX_EXTENSION];
00513 char username[256];
00514 char secret[256];
00515 char md5secret[256];
00516 struct sip_auth *next;
00517 };
00518
00519 #define SIP_ALREADYGONE (1 << 0)
00520 #define SIP_NEEDDESTROY (1 << 1)
00521 #define SIP_NOVIDEO (1 << 2)
00522 #define SIP_RINGING (1 << 3)
00523 #define SIP_PROGRESS_SENT (1 << 4)
00524 #define SIP_NEEDREINVITE (1 << 5)
00525 #define SIP_PENDINGBYE (1 << 6)
00526 #define SIP_GOTREFER (1 << 7)
00527 #define SIP_PROMISCREDIR (1 << 8)
00528 #define SIP_TRUSTRPID (1 << 9)
00529 #define SIP_USEREQPHONE (1 << 10)
00530 #define SIP_REALTIME (1 << 11)
00531 #define SIP_USECLIENTCODE (1 << 12)
00532 #define SIP_OUTGOING (1 << 13)
00533 #define SIP_SELFDESTRUCT (1 << 14)
00534 #define SIP_CAN_BYE (1 << 15)
00535
00536 #define SIP_DTMF (3 << 16)
00537 #define SIP_DTMF_RFC2833 (0 << 16)
00538 #define SIP_DTMF_INBAND (1 << 16)
00539 #define SIP_DTMF_INFO (2 << 16)
00540 #define SIP_DTMF_AUTO (3 << 16)
00541
00542 #define SIP_NAT (3 << 18)
00543 #define SIP_NAT_NEVER (0 << 18)
00544 #define SIP_NAT_RFC3581 (1 << 18)
00545 #define SIP_NAT_ROUTE (2 << 18)
00546 #define SIP_NAT_ALWAYS (3 << 18)
00547
00548 #define SIP_REINVITE (3 << 20)
00549 #define SIP_CAN_REINVITE (1 << 20)
00550 #define SIP_REINVITE_UPDATE (2 << 20)
00551
00552 #define SIP_INSECURE_PORT (1 << 22)
00553 #define SIP_INSECURE_INVITE (1 << 23)
00554
00555 #define SIP_PROG_INBAND (3 << 24)
00556 #define SIP_PROG_INBAND_NEVER (0 << 24)
00557 #define SIP_PROG_INBAND_NO (1 << 24)
00558 #define SIP_PROG_INBAND_YES (2 << 24)
00559
00560 #define SIP_OSPAUTH (3 << 26)
00561 #define SIP_OSPAUTH_NO (0 << 26)
00562 #define SIP_OSPAUTH_GATEWAY (1 << 26)
00563 #define SIP_OSPAUTH_PROXY (2 << 26)
00564 #define SIP_OSPAUTH_EXCLUSIVE (3 << 26)
00565
00566 #define SIP_CALL_ONHOLD (1 << 28)
00567 #define SIP_CALL_LIMIT (1 << 29)
00568
00569 #define SIP_SENDRPID (1 << 30)
00570 #define SIP_INC_COUNT (1 << 31)
00571
00572 #define SIP_FLAGS_TO_COPY \
00573 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
00574 SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
00575 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
00576
00577
00578 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
00579 #define SIP_PAGE2_RTUPDATE (1 << 1)
00580 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
00581 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 3)
00582 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
00583 #define SIP_PAGE2_DYNAMIC (1 << 5)
00584
00585
00586 #define SIP_PKT_DEBUG (1 << 0)
00587 #define SIP_PKT_WITH_TOTAG (1 << 1)
00588
00589 static int global_rtautoclear;
00590
00591
00592 static struct sip_pvt {
00593 ast_mutex_t lock;
00594 int method;
00595 char callid[128];
00596 char randdata[80];
00597 struct ast_codec_pref prefs;
00598 unsigned int ocseq;
00599 unsigned int icseq;
00600 ast_group_t callgroup;
00601 ast_group_t pickupgroup;
00602 int lastinvite;
00603 unsigned int flags;
00604 int timer_t1;
00605 unsigned int sipoptions;
00606 int capability;
00607 int jointcapability;
00608 int peercapability;
00609 int prefcodec;
00610 int noncodeccapability;
00611 int jointnoncodeccapability;
00612 int callingpres;
00613 int authtries;
00614 int expiry;
00615 int branch;
00616 char tag[11];
00617 int sessionid;
00618 int sessionversion;
00619 struct sockaddr_in sa;
00620 struct sockaddr_in redirip;
00621 struct sockaddr_in vredirip;
00622 int redircodecs;
00623 struct sockaddr_in recv;
00624 struct in_addr ourip;
00625 struct ast_channel *owner;
00626 char exten[AST_MAX_EXTENSION];
00627 char refer_to[AST_MAX_EXTENSION];
00628 char referred_by[AST_MAX_EXTENSION];
00629 char refer_contact[SIP_LEN_CONTACT];
00630 struct sip_pvt *refer_call;
00631 struct sip_route *route;
00632 int route_persistant;
00633 char from[256];
00634 char useragent[256];
00635 char context[AST_MAX_CONTEXT];
00636 char subscribecontext[AST_MAX_CONTEXT];
00637 char fromdomain[MAXHOSTNAMELEN];
00638 char fromuser[AST_MAX_EXTENSION];
00639 char fromname[AST_MAX_EXTENSION];
00640 char tohost[MAXHOSTNAMELEN];
00641 char language[MAX_LANGUAGE];
00642 char musicclass[MAX_MUSICCLASS];
00643 char rdnis[256];
00644 char theirtag[256];
00645 char username[256];
00646 char peername[256];
00647 char authname[256];
00648 char uri[256];
00649 char okcontacturi[SIP_LEN_CONTACT];
00650 char peersecret[256];
00651 char peermd5secret[256];
00652 struct sip_auth *peerauth;
00653 char cid_num[256];
00654 char cid_name[256];
00655 char via[256];
00656 char fullcontact[SIP_LEN_CONTACT];
00657 char accountcode[AST_MAX_ACCOUNT_CODE];
00658 char our_contact[SIP_LEN_CONTACT];
00659 char *rpid;
00660 char *rpid_from;
00661 char realm[MAXHOSTNAMELEN];
00662 char nonce[256];
00663 int noncecount;
00664 char opaque[256];
00665 char qop[80];
00666 char domain[MAXHOSTNAMELEN];
00667 char lastmsg[256];
00668 int amaflags;
00669 int pendinginvite;
00670 #ifdef OSP_SUPPORT
00671 int osphandle;
00672 time_t ospstart;
00673 unsigned int osptimelimit;
00674 #endif
00675 struct sip_request initreq;
00676
00677 int maxtime;
00678 int initid;
00679 int autokillid;
00680 time_t lastrtprx;
00681 time_t lastrtptx;
00682 int rtptimeout;
00683 int rtpholdtimeout;
00684 int rtpkeepalive;
00685 enum subscriptiontype subscribed;
00686 int stateid;
00687 int laststate;
00688 int dialogver;
00689
00690 struct ast_dsp *vad;
00691
00692 struct sip_peer *peerpoke;
00693 struct sip_registry *registry;
00694 struct ast_rtp *rtp;
00695 struct ast_rtp *vrtp;
00696 struct sip_pkt *packets;
00697 struct sip_history *history;
00698 struct ast_variable *chanvars;
00699 struct sip_pvt *next;
00700 struct sip_invite_param *options;
00701 } *iflist = NULL;
00702
00703 #define FLAG_RESPONSE (1 << 0)
00704 #define FLAG_FATAL (1 << 1)
00705
00706
00707 struct sip_pkt {
00708 struct sip_pkt *next;
00709 int retrans;
00710 int method;
00711 int seqno;
00712 unsigned int flags;
00713 struct sip_pvt *owner;
00714 int retransid;
00715 int timer_a;
00716 int timer_t1;
00717 int packetlen;
00718 char data[0];
00719 };
00720
00721
00722 struct sip_user {
00723
00724 ASTOBJ_COMPONENTS(struct sip_user);
00725 char secret[80];
00726 char md5secret[80];
00727 char context[AST_MAX_CONTEXT];
00728 char subscribecontext[AST_MAX_CONTEXT];
00729 char cid_num[80];
00730 char cid_name[80];
00731 char accountcode[AST_MAX_ACCOUNT_CODE];
00732 char language[MAX_LANGUAGE];
00733 char musicclass[MAX_MUSICCLASS];
00734 char useragent[256];
00735 struct ast_codec_pref prefs;
00736 ast_group_t callgroup;
00737 ast_group_t pickupgroup;
00738 unsigned int flags;
00739 unsigned int sipoptions;
00740 struct ast_flags flags_page2;
00741 int amaflags;
00742 int callingpres;
00743 int capability;
00744 int inUse;
00745 int call_limit;
00746 struct ast_ha *ha;
00747 struct ast_variable *chanvars;
00748 };
00749
00750
00751 struct sip_peer {
00752 ASTOBJ_COMPONENTS(struct sip_peer);
00753
00754 char secret[80];
00755 char md5secret[80];
00756 struct sip_auth *auth;
00757 char context[AST_MAX_CONTEXT];
00758 char subscribecontext[AST_MAX_CONTEXT];
00759 char username[80];
00760 char accountcode[AST_MAX_ACCOUNT_CODE];
00761 int amaflags;
00762 char tohost[MAXHOSTNAMELEN];
00763 char regexten[AST_MAX_EXTENSION];
00764 char fromuser[80];
00765 char fromdomain[MAXHOSTNAMELEN];
00766 char fullcontact[SIP_LEN_CONTACT];
00767 char cid_num[80];
00768 char cid_name[80];
00769 int callingpres;
00770 int inUse;
00771 int call_limit;
00772 char vmexten[AST_MAX_EXTENSION];
00773 char mailbox[AST_MAX_EXTENSION];
00774 char language[MAX_LANGUAGE];
00775 char musicclass[MAX_MUSICCLASS];
00776 char useragent[256];
00777 struct ast_codec_pref prefs;
00778 int lastmsgssent;
00779 time_t lastmsgcheck;
00780 unsigned int flags;
00781 unsigned int sipoptions;
00782 struct ast_flags flags_page2;
00783 int expire;
00784 int capability;
00785 int rtptimeout;
00786 int rtpholdtimeout;
00787 int rtpkeepalive;
00788 ast_group_t callgroup;
00789 ast_group_t pickupgroup;
00790 struct sockaddr_in addr;
00791
00792
00793 struct sip_pvt *call;
00794 int pokeexpire;
00795 int lastms;
00796 int maxms;
00797 struct timeval ps;
00798
00799 struct sockaddr_in defaddr;
00800 struct ast_ha *ha;
00801 struct ast_variable *chanvars;
00802 int lastmsg;
00803 };
00804
00805 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00806 static int sip_reloading = 0;
00807
00808
00809 #define REG_STATE_UNREGISTERED 0
00810 #define REG_STATE_REGSENT 1
00811 #define REG_STATE_AUTHSENT 2
00812 #define REG_STATE_REGISTERED 3
00813 #define REG_STATE_REJECTED 4
00814 #define REG_STATE_TIMEOUT 5
00815 #define REG_STATE_NOAUTH 6
00816 #define REG_STATE_FAILED 7
00817
00818
00819
00820 struct sip_registry {
00821 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
00822 int portno;
00823 char username[80];
00824 char authuser[80];
00825 char hostname[MAXHOSTNAMELEN];
00826 char secret[80];
00827 char md5secret[80];
00828 char contact[SIP_LEN_CONTACT];
00829 char random[80];
00830 int expire;
00831 int regattempts;
00832 int timeout;
00833 int refresh;
00834 struct sip_pvt *call;
00835 int regstate;
00836 int callid_valid;
00837 char callid[128];
00838 unsigned int ocseq;
00839 struct sockaddr_in us;
00840
00841
00842 char realm[MAXHOSTNAMELEN];
00843 char nonce[256];
00844 char domain[MAXHOSTNAMELEN];
00845 char opaque[256];
00846 char qop[80];
00847 int noncecount;
00848
00849 char lastmsg[256];
00850 };
00851
00852
00853 static struct ast_user_list {
00854 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
00855 } userl;
00856
00857
00858 static struct ast_peer_list {
00859 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
00860 } peerl;
00861
00862
00863 static struct ast_register_list {
00864 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
00865 int recheck;
00866 } regl;
00867
00868
00869 static int __sip_do_register(struct sip_registry *r);
00870
00871 static int sipsock = -1;
00872
00873
00874 static struct sockaddr_in bindaddr = { 0, };
00875 static struct sockaddr_in externip;
00876 static char externhost[MAXHOSTNAMELEN] = "";
00877 static time_t externexpire = 0;
00878 static int externrefresh = 10;
00879 static struct ast_ha *localaddr;
00880
00881
00882 struct ast_config *notify_types;
00883
00884 static struct sip_auth *authl;
00885
00886 static int transmit_response_using_temp(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, struct sip_request *req, char *msg);
00887 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
00888 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
00889 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
00890 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header, int stale);
00891 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
00892 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
00893 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
00894 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
00895 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
00896 static int transmit_info_with_vidupdate(struct sip_pvt *p);
00897 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
00898 static int transmit_refer(struct sip_pvt *p, const char *dest);
00899 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
00900 static struct sip_peer *temp_peer(const char *name);
00901 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
00902 static void free_old_route(struct sip_route *route);
00903 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
00904 static int update_call_counter(struct sip_pvt *fup, int event);
00905 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
00906 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
00907 static int sip_do_reload(void);
00908 static int expire_register(void *data);
00909 static int callevents = 0;
00910
00911 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
00912 static int sip_devicestate(void *data);
00913 static int sip_sendtext(struct ast_channel *ast, const char *text);
00914 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
00915 static int sip_hangup(struct ast_channel *ast);
00916 static int sip_answer(struct ast_channel *ast);
00917 static struct ast_frame *sip_read(struct ast_channel *ast);
00918 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
00919 static int sip_indicate(struct ast_channel *ast, int condition);
00920 static int sip_transfer(struct ast_channel *ast, const char *dest);
00921 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
00922 static int sip_senddigit(struct ast_channel *ast, char digit);
00923 static int clear_realm_authentication(struct sip_auth *authlist);
00924 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
00925 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm);
00926 static int check_sip_domain(const char *domain, char *context, size_t len);
00927 static void append_date(struct sip_request *req);
00928 static int determine_firstline_parts(struct sip_request *req);
00929 static void sip_dump_history(struct sip_pvt *dialog);
00930 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
00931 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate, int timeout);
00932 static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
00933
00934
00935 static const struct ast_channel_tech sip_tech = {
00936 .type = channeltype,
00937 .description = "Session Initiation Protocol (SIP)",
00938 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
00939 .properties = AST_CHAN_TP_WANTSJITTER,
00940 .requester = sip_request_call,
00941 .devicestate = sip_devicestate,
00942 .call = sip_call,
00943 .hangup = sip_hangup,
00944 .answer = sip_answer,
00945 .read = sip_read,
00946 .write = sip_write,
00947 .write_video = sip_write,
00948 .indicate = sip_indicate,
00949 .transfer = sip_transfer,
00950 .fixup = sip_fixup,
00951 .send_digit = sip_senddigit,
00952 .bridge = ast_rtp_bridge,
00953 .send_text = sip_sendtext,
00954 };
00955
00956 #ifdef __AST_DEBUG_MALLOC
00957 static void FREE(void *ptr)
00958 {
00959 free(ptr);
00960 }
00961 #else
00962 #define FREE free
00963 #endif
00964
00965
00966
00967
00968
00969
00970
00971
00972 static force_inline int thread_safe_rand(void)
00973 {
00974 int val;
00975
00976 ast_mutex_lock(&rand_lock);
00977 val = rand();
00978 ast_mutex_unlock(&rand_lock);
00979
00980 return val;
00981 }
00982
00983
00984
00985
00986 static int find_sip_method(char *msg)
00987 {
00988 int i, res = 0;
00989
00990 if (ast_strlen_zero(msg))
00991 return 0;
00992
00993 for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
00994 if (!strcasecmp(sip_methods[i].text, msg))
00995 res = sip_methods[i].id;
00996 }
00997 return res;
00998 }
00999
01000
01001 static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
01002 {
01003 char *next = NULL;
01004 char *sep = NULL;
01005 char *temp = ast_strdupa(supported);
01006 int i;
01007 unsigned int profile = 0;
01008
01009 if (ast_strlen_zero(supported) )
01010 return 0;
01011
01012 if (option_debug > 2 && sipdebug)
01013 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
01014
01015 next = temp;
01016 while (next) {
01017 char res=0;
01018 if ( (sep = strchr(next, ',')) != NULL) {
01019 *sep = '\0';
01020 sep++;
01021 }
01022 while (*next == ' ')
01023 next++;
01024 if (option_debug > 2 && sipdebug)
01025 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
01026 for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
01027 if (!strcasecmp(next, sip_options[i].text)) {
01028 profile |= sip_options[i].id;
01029 res = 1;
01030 if (option_debug > 2 && sipdebug)
01031 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
01032 }
01033 }
01034 if (!res)
01035 if (option_debug > 2 && sipdebug)
01036 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
01037 next = sep;
01038 }
01039 if (pvt) {
01040 pvt->sipoptions = profile;
01041 if (option_debug)
01042 ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
01043 }
01044 return profile;
01045 }
01046
01047
01048 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
01049 {
01050 if (sipdebug == 0)
01051 return 0;
01052 if (debugaddr.sin_addr.s_addr) {
01053 if (((ntohs(debugaddr.sin_port) != 0)
01054 && (debugaddr.sin_port != addr->sin_port))
01055 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
01056 return 0;
01057 }
01058 return 1;
01059 }
01060
01061
01062 static inline int sip_debug_test_pvt(struct sip_pvt *p)
01063 {
01064 if (sipdebug == 0)
01065 return 0;
01066 return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
01067 }
01068
01069
01070
01071 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
01072 {
01073 int res;
01074 char iabuf[INET_ADDRSTRLEN];
01075
01076 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
01077 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
01078 else
01079 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
01080
01081 if (res != len) {
01082 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), res, strerror(errno));
01083 }
01084 return res;
01085 }
01086
01087 static void sip_destroy(struct sip_pvt *p);
01088
01089
01090 static void build_via(struct sip_pvt *p, char *buf, int len)
01091 {
01092 char iabuf[INET_ADDRSTRLEN];
01093
01094
01095 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581)
01096 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
01097 else
01098 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
01099 }
01100
01101
01102
01103 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
01104 {
01105
01106
01107
01108
01109
01110 struct sockaddr_in theirs;
01111 theirs.sin_addr = *them;
01112 if (localaddr && externip.sin_addr.s_addr &&
01113 ast_apply_ha(localaddr, &theirs)) {
01114 char iabuf[INET_ADDRSTRLEN];
01115 if (externexpire && (time(NULL) >= externexpire)) {
01116 struct ast_hostent ahp;
01117 struct hostent *hp;
01118 time(&externexpire);
01119 externexpire += externrefresh;
01120 if ((hp = ast_gethostbyname(externhost, &ahp))) {
01121 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
01122 } else
01123 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
01124 }
01125 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
01126 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
01127 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
01128 }
01129 else if (bindaddr.sin_addr.s_addr)
01130 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
01131 else
01132 return ast_ouraddrfor(them, us);
01133 return 0;
01134 }
01135
01136
01137
01138 static int append_history(struct sip_pvt *p, const char *event, const char *data)
01139 {
01140 struct sip_history *hist, *prev;
01141 char *c;
01142
01143 if (!recordhistory || !p)
01144 return 0;
01145 if(!(hist = malloc(sizeof(struct sip_history)))) {
01146 ast_log(LOG_WARNING, "Can't allocate memory for history\n");
01147 return 0;
01148 }
01149 memset(hist, 0, sizeof(struct sip_history));
01150 snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
01151
01152 c = hist->event;
01153 while(*c) {
01154 if ((*c == '\r') || (*c == '\n')) {
01155 *c = '\0';
01156 break;
01157 }
01158 c++;
01159 }
01160
01161 prev = p->history;
01162 if (prev) {
01163 while(prev->next)
01164 prev = prev->next;
01165 prev->next = hist;
01166 } else {
01167 p->history = hist;
01168 }
01169 return 0;
01170 }
01171
01172
01173 static int retrans_pkt(void *data)
01174 {
01175 struct sip_pkt *pkt=data, *prev, *cur = NULL;
01176 char iabuf[INET_ADDRSTRLEN];
01177 int reschedule = DEFAULT_RETRANS;
01178
01179
01180 ast_mutex_lock(&pkt->owner->lock);
01181
01182 if (pkt->retrans < MAX_RETRANS) {
01183 char buf[80];
01184
01185 pkt->retrans++;
01186 if (!pkt->timer_t1) {
01187 if (sipdebug && option_debug > 3)
01188 ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
01189 } else {
01190 int siptimer_a;
01191
01192 if (sipdebug && option_debug > 3)
01193 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
01194 if (!pkt->timer_a)
01195 pkt->timer_a = 2 ;
01196 else
01197 pkt->timer_a = 2 * pkt->timer_a;
01198
01199
01200 siptimer_a = pkt->timer_t1 * pkt->timer_a;
01201 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
01202 siptimer_a = 4000;
01203
01204
01205 reschedule = siptimer_a;
01206 if (option_debug > 3)
01207 ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
01208 }
01209
01210 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
01211 if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
01212 ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
01213 else
01214 ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
01215 }
01216 snprintf(buf, sizeof(buf), "ReTx %d", reschedule);
01217
01218 append_history(pkt->owner, buf, pkt->data);
01219 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
01220 ast_mutex_unlock(&pkt->owner->lock);
01221 return reschedule;
01222 }
01223
01224 if (pkt->owner && pkt->method != SIP_OPTIONS) {
01225 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug)
01226 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
01227 } else {
01228 if (pkt->method == SIP_OPTIONS && sipdebug)
01229 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
01230 }
01231 append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
01232
01233 pkt->retransid = -1;
01234
01235 if (ast_test_flag(pkt, FLAG_FATAL)) {
01236 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
01237 ast_mutex_unlock(&pkt->owner->lock);
01238 usleep(1);
01239 ast_mutex_lock(&pkt->owner->lock);
01240 }
01241 if (pkt->owner->owner) {
01242 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
01243 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
01244 ast_queue_hangup(pkt->owner->owner);
01245 ast_mutex_unlock(&pkt->owner->owner->lock);
01246 } else {
01247
01248
01249 if (pkt->method != SIP_OPTIONS)
01250 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
01251 }
01252 }
01253
01254 prev = NULL;
01255 cur = pkt->owner->packets;
01256 while(cur) {
01257 if (cur == pkt)
01258 break;
01259 prev = cur;
01260 cur = cur->next;
01261 }
01262 if (cur) {
01263 if (prev)
01264 prev->next = cur->next;
01265 else
01266 pkt->owner->packets = cur->next;
01267 ast_mutex_unlock(&pkt->owner->lock);
01268 free(cur);
01269 pkt = NULL;
01270 } else
01271 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
01272 if (pkt)
01273 ast_mutex_unlock(&pkt->owner->lock);
01274 return 0;
01275 }
01276
01277
01278 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
01279 {
01280 struct sip_pkt *pkt;
01281 int siptimer_a = DEFAULT_RETRANS;
01282
01283 pkt = malloc(sizeof(struct sip_pkt) + len + 1);
01284 if (!pkt)
01285 return -1;
01286 memset(pkt, 0, sizeof(struct sip_pkt));
01287 memcpy(pkt->data, data, len);
01288 pkt->method = sipmethod;
01289 pkt->packetlen = len;
01290 pkt->next = p->packets;
01291 pkt->owner = p;
01292 pkt->seqno = seqno;
01293 if (resp)
01294 ast_set_flag(pkt, FLAG_RESPONSE);
01295 pkt->data[len] = '\0';
01296 pkt->timer_t1 = p->timer_t1;
01297 if (fatal)
01298 ast_set_flag(pkt, FLAG_FATAL);
01299 if (pkt->timer_t1)
01300 siptimer_a = pkt->timer_t1 * 2;
01301
01302
01303 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
01304 if (option_debug > 3 && sipdebug)
01305 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
01306 pkt->next = p->packets;
01307 p->packets = pkt;
01308
01309 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
01310 if (sipmethod == SIP_INVITE) {
01311
01312 p->pendinginvite = seqno;
01313 }
01314 return 0;
01315 }
01316
01317
01318 static int __sip_autodestruct(void *data)
01319 {
01320 struct sip_pvt *p = data;
01321
01322
01323
01324 if (p->subscribed) {
01325 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, 1, 1);
01326 p->subscribed = NONE;
01327 append_history(p, "Subscribestatus", "timeout");
01328 return 10000;
01329 }
01330
01331
01332 p->autokillid = -1;
01333
01334 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
01335 append_history(p, "AutoDestroy", "");
01336 if (p->owner) {
01337 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
01338 ast_queue_hangup(p->owner);
01339 } else {
01340 sip_destroy(p);
01341 }
01342 return 0;
01343 }
01344
01345
01346 static int sip_scheddestroy(struct sip_pvt *p, int ms)
01347 {
01348 char tmp[80];
01349 if (sip_debug_test_pvt(p))
01350 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
01351 if (recordhistory) {
01352 snprintf(tmp, sizeof(tmp), "%d ms", ms);
01353 append_history(p, "SchedDestroy", tmp);
01354 }
01355
01356 if (p->autokillid > -1)
01357 ast_sched_del(sched, p->autokillid);
01358 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
01359 return 0;
01360 }
01361
01362
01363 static int sip_cancel_destroy(struct sip_pvt *p)
01364 {
01365 if (p->autokillid > -1)
01366 ast_sched_del(sched, p->autokillid);
01367 append_history(p, "CancelDestroy", "");
01368 p->autokillid = -1;
01369 return 0;
01370 }
01371
01372
01373 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
01374 {
01375 struct sip_pkt *cur, *prev = NULL;
01376 int res = -1;
01377 int resetinvite = 0;
01378
01379 char *msg;
01380
01381 msg = sip_methods[sipmethod].text;
01382
01383 ast_mutex_lock(&p->lock);
01384 cur = p->packets;
01385 while(cur) {
01386 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
01387 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
01388 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
01389 if (!resp && (seqno == p->pendinginvite)) {
01390 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
01391 p->pendinginvite = 0;
01392 resetinvite = 1;
01393 }
01394
01395 if (prev)
01396 prev->next = cur->next;
01397 else
01398 p->packets = cur->next;
01399 if (cur->retransid > -1) {
01400 if (sipdebug && option_debug > 3)
01401 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
01402 ast_sched_del(sched, cur->retransid);
01403 cur->retransid = -1;
01404 }
01405 free(cur);
01406 res = 0;
01407 break;
01408 }
01409 prev = cur;
01410 cur = cur->next;
01411 }
01412 ast_mutex_unlock(&p->lock);
01413 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
01414 return res;
01415 }
01416
01417
01418 static int __sip_pretend_ack(struct sip_pvt *p)
01419 {
01420 struct sip_pkt *cur=NULL;
01421
01422 while(p->packets) {
01423 if (cur == p->packets) {
01424 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
01425 return -1;
01426 }
01427 cur = p->packets;
01428 if (cur->method)
01429 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
01430 else {
01431 char *c;
01432 char method[128];
01433 ast_copy_string(method, p->packets->data, sizeof(method));
01434 c = ast_skip_blanks(method);
01435 *c = '\0';
01436 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
01437 }
01438 }
01439 return 0;
01440 }
01441
01442
01443 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
01444 {
01445 struct sip_pkt *cur;
01446 int res = -1;
01447 char *msg = sip_methods[sipmethod].text;
01448
01449 cur = p->packets;
01450 while(cur) {
01451 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
01452 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
01453 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
01454
01455 if (cur->retransid > -1) {
01456 if (option_debug > 3 && sipdebug)
01457 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
01458 ast_sched_del(sched, cur->retransid);
01459 cur->retransid = -1;
01460 }
01461 res = 0;
01462 break;
01463 }
01464 cur = cur->next;
01465 }
01466 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
01467 return res;
01468 }
01469
01470 static void parse_request(struct sip_request *req);
01471 static char *get_header(struct sip_request *req, char *name);
01472 static void copy_request(struct sip_request *dst,struct sip_request *src);
01473
01474
01475 static void parse_copy(struct sip_request *dst, struct sip_request *src)
01476 {
01477 memset(dst, 0, sizeof(*dst));
01478 memcpy(dst->data, src->data, sizeof(dst->data));
01479 dst->len = src->len;
01480 parse_request(dst);
01481 }
01482
01483
01484 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
01485 {
01486 int res;
01487 char iabuf[INET_ADDRSTRLEN];
01488 struct sip_request tmp;
01489 char tmpmsg[80];
01490
01491 if (sip_debug_test_pvt(p)) {
01492 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
01493 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
01494 else
01495 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
01496 }
01497 if (reliable) {
01498 if (recordhistory) {
01499 parse_copy(&tmp, req);
01500 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
01501 append_history(p, "TxRespRel", tmpmsg);
01502 }
01503 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1), req->method);
01504 } else {
01505 if (recordhistory) {
01506 parse_copy(&tmp, req);
01507 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
01508 append_history(p, "TxResp", tmpmsg);
01509 }
01510 res = __sip_xmit(p, req->data, req->len);
01511 }
01512 if (res > 0)
01513 return 0;
01514 return res;
01515 }
01516
01517
01518 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
01519 {
01520 int res;
01521 char iabuf[INET_ADDRSTRLEN];
01522 struct sip_request tmp;
01523 char tmpmsg[80];
01524
01525 if (sip_debug_test_pvt(p)) {
01526 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
01527 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
01528 else
01529 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
01530 }
01531 if (reliable) {
01532 if (recordhistory) {
01533 parse_copy(&tmp, req);
01534 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
01535 append_history(p, "TxReqRel", tmpmsg);
01536 }
01537 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method);
01538 } else {
01539 if (recordhistory) {
01540 parse_copy(&tmp, req);
01541 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
01542 append_history(p, "TxReq", tmpmsg);
01543 }
01544 res = __sip_xmit(p, req->data, req->len);
01545 }
01546 return res;
01547 }
01548
01549
01550
01551 static char *get_in_brackets(char *tmp)
01552 {
01553 char *parse;
01554 char *first_quote;
01555 char *first_bracket;
01556 char *second_bracket;
01557 char last_char;
01558
01559 parse = tmp;
01560 while (1) {
01561 first_quote = strchr(parse, '"');
01562 first_bracket = strchr(parse, '<');
01563 if (first_quote && first_bracket && (first_quote < first_bracket)) {
01564 last_char = '\0';
01565 for (parse = first_quote + 1; *parse; parse++) {
01566 if ((*parse == '"') && (last_char != '\\'))
01567 break;
01568 last_char = *parse;
01569 }
01570 if (!*parse) {
01571 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
01572 return tmp;
01573 }
01574 parse++;
01575 continue;
01576 }
01577 if (first_bracket) {
01578 second_bracket = strchr(first_bracket + 1, '>');
01579 if (second_bracket) {
01580 *second_bracket = '\0';
01581 return first_bracket + 1;
01582 } else {
01583 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
01584 return tmp;
01585 }
01586 }
01587 return tmp;
01588 }
01589 }
01590
01591
01592
01593 static int sip_sendtext(struct ast_channel *ast, const char *text)
01594 {
01595 struct sip_pvt *p = ast->tech_pvt;
01596 int debug=sip_debug_test_pvt(p);
01597
01598 if (debug)
01599 ast_verbose("Sending text %s on %s\n", text, ast->name);
01600 if (!p)
01601 return -1;
01602 if (ast_strlen_zero(text))
01603 return 0;
01604 if (debug)
01605 ast_verbose("Really sending text %s on %s\n", text, ast->name);
01606 transmit_message_with_text(p, text);
01607 return 0;
01608 }
01609
01610
01611 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
01612 {
01613 char port[10];
01614 char ipaddr[20];
01615 char regseconds[20];
01616 time_t nowtime;
01617
01618 time(&nowtime);
01619 nowtime += expirey;
01620 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
01621 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
01622 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
01623
01624 if (fullcontact)
01625 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL);
01626 else
01627 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
01628 }
01629
01630
01631 static void register_peer_exten(struct sip_peer *peer, int onoff)
01632 {
01633 char multi[256];
01634 char *stringp, *ext;
01635 if (!ast_strlen_zero(regcontext)) {
01636 ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
01637 stringp = multi;
01638 while((ext = strsep(&stringp, "&"))) {
01639 if (onoff)
01640 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), FREE, channeltype);
01641 else
01642 ast_context_remove_extension(regcontext, ext, 1, NULL);
01643 }
01644 }
01645 }
01646
01647
01648 static void sip_destroy_peer(struct sip_peer *peer)
01649 {
01650
01651 if (peer->call)
01652 sip_destroy(peer->call);
01653 if (peer->chanvars) {
01654 ast_variables_destroy(peer->chanvars);
01655 peer->chanvars = NULL;
01656 }
01657 if (peer->expire > -1)
01658 ast_sched_del(sched, peer->expire);
01659
01660 if (peer->pokeexpire > -1)
01661 ast_sched_del(sched, peer->pokeexpire);
01662 register_peer_exten(peer, 0);
01663 ast_free_ha(peer->ha);
01664 if (ast_test_flag(peer, SIP_SELFDESTRUCT))
01665 apeerobjs--;
01666 else if (ast_test_flag(peer, SIP_REALTIME))
01667 rpeerobjs--;
01668 else
01669 speerobjs--;
01670 clear_realm_authentication(peer->auth);
01671 peer->auth = (struct sip_auth *) NULL;
01672 free(peer);
01673 }
01674
01675
01676 static void update_peer(struct sip_peer *p, int expiry)
01677 {
01678 int rtcachefriends = ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
01679 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) &&
01680 (ast_test_flag(p, SIP_REALTIME) || rtcachefriends)) {
01681 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
01682 }
01683 }
01684
01685
01686
01687
01688 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
01689 {
01690 struct sip_peer *peer=NULL;
01691 struct ast_variable *var = NULL;
01692 struct ast_variable *tmp;
01693 char *newpeername = (char *) peername;
01694 char iabuf[80];
01695
01696
01697 if (newpeername) {
01698 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
01699 if (!var && sin)
01700 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), NULL);
01701 if (!var) {
01702 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
01703
01704
01705
01706
01707
01708
01709 if (var) {
01710 for (tmp = var; tmp; tmp = tmp->next) {
01711 if (!strcasecmp(var->name, "host")) {
01712 struct hostent *hp;
01713 struct ast_hostent ahp;
01714 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
01715
01716 ast_variables_destroy(var);
01717 var = NULL;
01718 }
01719 break;
01720 }
01721 }
01722 }
01723 }
01724 }
01725
01726 if (!var && sin) {
01727 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
01728 var = ast_load_realtime("sippeers", "host", iabuf, NULL);
01729 if (!var)
01730 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);
01731 }
01732
01733 if (!var)
01734 return NULL;
01735
01736 tmp = var;
01737
01738 while(tmp) {
01739 if (!strcasecmp(tmp->name, "type") &&
01740 !strcasecmp(tmp->value, "user")) {
01741 ast_variables_destroy(var);
01742 return NULL;
01743 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
01744 newpeername = tmp->value;
01745 }
01746 tmp = tmp->next;
01747 }
01748
01749 if (!newpeername) {
01750 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
01751 ast_variables_destroy(var);
01752 return (struct sip_peer *) NULL;
01753 }
01754
01755
01756 peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
01757 if (!peer) {
01758 ast_variables_destroy(var);
01759 return (struct sip_peer *) NULL;
01760 }
01761
01762 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
01763
01764 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
01765 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
01766 if (peer->expire > -1) {
01767 ast_sched_del(sched, peer->expire);
01768 }
01769 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
01770 }
01771 ASTOBJ_CONTAINER_LINK(&peerl,peer);
01772 } else {
01773 ast_set_flag(peer, SIP_REALTIME);
01774 }
01775 ast_variables_destroy(var);
01776
01777 return peer;
01778 }
01779
01780
01781 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
01782 {
01783
01784 struct sip_peer *p = (struct sip_peer *)name;
01785 return !(!inaddrcmp(&p->addr, sin) ||
01786 (ast_test_flag(p, SIP_INSECURE_PORT) &&
01787 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
01788 }
01789
01790
01791
01792
01793 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
01794 {
01795 struct sip_peer *p = NULL;
01796
01797 if (peer)
01798 p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
01799 else
01800 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
01801
01802 if (!p && realtime) {
01803 p = realtime_peer(peer, sin);
01804 }
01805
01806 return p;
01807 }
01808
01809
01810 static void sip_destroy_user(struct sip_user *user)
01811 {
01812 ast_free_ha(user->ha);
01813 if (user->chanvars) {
01814 ast_variables_destroy(user->chanvars);
01815 user->chanvars = NULL;
01816 }
01817 if (ast_test_flag(user, SIP_REALTIME))
01818 ruserobjs--;
01819 else
01820 suserobjs--;
01821 free(user);
01822 }
01823
01824
01825
01826
01827 static struct sip_user *realtime_user(const char *username)
01828 {
01829 struct ast_variable *var;
01830 struct ast_variable *tmp;
01831 struct sip_user *user = NULL;
01832
01833 var = ast_load_realtime("sipusers", "name", username, NULL);
01834
01835 if (!var)
01836 return NULL;
01837
01838 tmp = var;
01839 while (tmp) {
01840 if (!strcasecmp(tmp->name, "type") &&
01841 !strcasecmp(tmp->value, "peer")) {
01842 ast_variables_destroy(var);
01843 return NULL;
01844 }
01845 tmp = tmp->next;
01846 }
01847
01848
01849
01850 user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
01851
01852 if (!user) {
01853 ast_variables_destroy(var);
01854 return NULL;
01855 }
01856
01857 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
01858 ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
01859 suserobjs++;
01860 ASTOBJ_CONTAINER_LINK(&userl,user);
01861 } else {
01862
01863 suserobjs--;
01864 ruserobjs++;
01865 ast_set_flag(user, SIP_REALTIME);
01866 }
01867 ast_variables_destroy(var);
01868 return user;
01869 }
01870
01871
01872
01873
01874
01875 static struct sip_user *find_user(const char *name, int realtime)
01876 {
01877 struct sip_user *u = NULL;
01878 u = ASTOBJ_CONTAINER_FIND(&userl,name);
01879 if (!u && realtime) {
01880 u = realtime_user(name);
01881 }
01882 return u;
01883 }
01884
01885
01886 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
01887 {
01888 char *callhost;
01889
01890 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
01891 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
01892 if (peer->addr.sin_addr.s_addr) {
01893 r->sa.sin_family = peer->addr.sin_family;
01894 r->sa.sin_addr = peer->addr.sin_addr;
01895 r->sa.sin_port = peer->addr.sin_port;
01896 } else {
01897 r->sa.sin_family = peer->defaddr.sin_family;
01898 r->sa.sin_addr = peer->defaddr.sin_addr;
01899 r->sa.sin_port = peer->defaddr.sin_port;
01900 }
01901 memcpy(&r->recv, &r->sa, sizeof(r->recv));
01902 } else {
01903 return -1;
01904 }
01905
01906 ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY);
01907 r->capability = peer->capability;
01908 r->prefs = peer->prefs;
01909 if (r->rtp) {
01910 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
01911 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
01912 }
01913 if (r->vrtp) {
01914 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
01915 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
01916 }
01917 ast_copy_string(r->peername, peer->name, sizeof(r->peername));
01918 ast_copy_string(r->authname, peer->username, sizeof(r->authname));
01919 ast_copy_string(r->username, peer->username, sizeof(r->username));
01920 ast_copy_string(r->peersecret, peer->secret, sizeof(r->peersecret));
01921 ast_copy_string(r->peermd5secret, peer->md5secret, sizeof(r->peermd5secret));
01922 ast_copy_string(r->tohost, peer->tohost, sizeof(r->tohost));
01923 ast_copy_string(r->fullcontact, peer->fullcontact, sizeof(r->fullcontact));
01924 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
01925 if ((callhost = strchr(r->callid, '@'))) {
01926 strncpy(callhost + 1, peer->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
01927 }
01928 }
01929 if (ast_strlen_zero(r->tohost)) {
01930 if (peer->addr.sin_addr.s_addr)
01931 ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->addr.sin_addr);
01932 else
01933 ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->defaddr.sin_addr);
01934 }
01935 if (!ast_strlen_zero(peer->fromdomain))
01936 ast_copy_string(r->fromdomain, peer->fromdomain, sizeof(r->fromdomain));
01937 if (!ast_strlen_zero(peer->fromuser))
01938 ast_copy_string(r->fromuser, peer->fromuser, sizeof(r->fromuser));
01939 if (!ast_strlen_zero(peer->language))
01940 ast_copy_string(r->language, peer->language, sizeof(r->language));
01941 r->maxtime = peer->maxms;
01942 r->callgroup = peer->callgroup;
01943 r->pickupgroup = peer->pickupgroup;
01944
01945 if (peer->maxms && peer->lastms)
01946 r->timer_t1 = peer->lastms < DEFAULT_T1MIN ? DEFAULT_T1MIN : peer->lastms;
01947 if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO))
01948 r->noncodeccapability |= AST_RTP_DTMF;
01949 else
01950 r->noncodeccapability &= ~AST_RTP_DTMF;
01951 ast_copy_string(r->context, peer->context,sizeof(r->context));
01952 r->rtptimeout = peer->rtptimeout;
01953 r->rtpholdtimeout = peer->rtpholdtimeout;
01954 r->rtpkeepalive = peer->rtpkeepalive;
01955 if (peer->call_limit)
01956 ast_set_flag(r, SIP_CALL_LIMIT);
01957
01958 return 0;
01959 }
01960
01961
01962
01963
01964 static int create_addr(struct sip_pvt *dialog, char *opeer)
01965 {
01966 struct hostent *hp;
01967 struct ast_hostent ahp;
01968 struct sip_peer *p;
01969 int found=0;
01970 char *port;
01971 int portno;
01972 char host[MAXHOSTNAMELEN], *hostn;
01973 char peer[256];
01974
01975 ast_copy_string(peer, opeer, sizeof(peer));
01976 port = strchr(peer, ':');
01977 if (port) {
01978 *port = '\0';
01979 port++;
01980 }
01981 dialog->sa.sin_family = AF_INET;
01982 dialog->timer_t1 = 500;
01983 p = find_peer(peer, NULL, 1);
01984
01985 if (p) {
01986 found++;
01987 if (create_addr_from_peer(dialog, p))
01988 ASTOBJ_UNREF(p, sip_destroy_peer);
01989 }
01990 if (!p) {
01991 if (found)
01992 return -1;
01993
01994 hostn = peer;
01995 if (port)
01996 portno = atoi(port);
01997 else
01998 portno = DEFAULT_SIP_PORT;
01999 if (srvlookup) {
02000 char service[MAXHOSTNAMELEN];
02001 int tportno;
02002 int ret;
02003 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
02004 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
02005 if (ret > 0) {
02006 hostn = host;
02007 portno = tportno;
02008 }
02009 }
02010 hp = ast_gethostbyname(hostn, &ahp);
02011 if (hp) {
02012 ast_copy_string(dialog->tohost, peer, sizeof(dialog->tohost));
02013 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
02014 dialog->sa.sin_port = htons(portno);
02015 memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
02016 return 0;
02017 } else {
02018 ast_log(LOG_WARNING, "No such host: %s\n", peer);
02019 return -1;
02020 }
02021 } else {
02022 ASTOBJ_UNREF(p, sip_destroy_peer);
02023 return 0;
02024 }
02025 }
02026
02027
02028 static int auto_congest(void *nothing)
02029 {
02030 struct sip_pvt *p = nothing;
02031 ast_mutex_lock(&p->lock);
02032 p->initid = -1;
02033 if (p->owner) {
02034 if (!ast_mutex_trylock(&p->owner->lock)) {
02035 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
02036 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
02037 ast_mutex_unlock(&p->owner->lock);
02038 }
02039 }
02040 ast_mutex_unlock(&p->lock);
02041 return 0;
02042 }
02043
02044
02045
02046
02047
02048
02049 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
02050 {
02051 int res;
02052 struct sip_pvt *p;
02053 #ifdef OSP_SUPPORT
02054 char *osphandle = NULL;
02055 #endif
02056 struct varshead *headp;
02057 struct ast_var_t *current;
02058
02059
02060
02061 p = ast->tech_pvt;
02062 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
02063 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
02064 return -1;
02065 }
02066
02067
02068
02069
02070 headp=&ast->varshead;
02071 AST_LIST_TRAVERSE(headp,current,entries) {
02072
02073 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
02074 p->options->vxml_url = ast_var_value(current);
02075 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
02076 p->options->uri_options = ast_var_value(current);
02077 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
02078
02079 p->options->distinctive_ring = ast_var_value(current);
02080 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
02081
02082 p->options->addsipheaders = 1;
02083 }
02084
02085
02086 #ifdef OSP_SUPPORT
02087 else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
02088 p->options->osptoken = ast_var_value(current);
02089 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
02090 osphandle = ast_var_value(current);
02091 }
02092 #endif
02093 }
02094
02095 res = 0;
02096 ast_set_flag(p, SIP_OUTGOING);
02097 #ifdef OSP_SUPPORT
02098 if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%30d", &p->osphandle) != 1)) {
02099
02100 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
02101 p->options->osptoken = NULL;
02102 osphandle = NULL;
02103 p->osphandle = -1;
02104 }
02105 #endif
02106 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
02107 res = update_call_counter(p, INC_CALL_LIMIT);
02108 if ( res != -1 ) {
02109 p->callingpres = ast->cid.cid_pres;
02110 p->jointcapability = p->capability;
02111 p->jointnoncodeccapability = p->noncodeccapability;
02112 transmit_invite(p, SIP_INVITE, 1, 2);
02113 if (p->maxtime) {
02114
02115 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
02116 }
02117 }
02118 return res;
02119 }
02120
02121
02122
02123 static void sip_registry_destroy(struct sip_registry *reg)
02124 {
02125
02126 if (reg->call) {
02127
02128
02129 reg->call->registry = NULL;
02130 sip_destroy(reg->call);
02131 }
02132 if (reg->expire > -1)
02133 ast_sched_del(sched, reg->expire);
02134 if (reg->timeout > -1)
02135 ast_sched_del(sched, reg->timeout);
02136 regobjs--;
02137 free(reg);
02138
02139 }
02140
02141
02142 static void __sip_destroy(struct sip_pvt *p, int lockowner)
02143 {
02144 struct sip_pvt *cur, *prev = NULL;
02145 struct sip_pkt *cp;
02146 struct sip_history *hist;
02147
02148 if (sip_debug_test_pvt(p))
02149 ast_verbose("Destroying call '%s'\n", p->callid);
02150
02151 if (ast_test_flag(p, SIP_INC_COUNT)) {
02152 update_call_counter(p, DEC_CALL_LIMIT);
02153 if (option_debug)
02154 ast_log(LOG_DEBUG, "Call did not properly clean up call counter. Call ID %s\n", p->callid);
02155 }
02156
02157 if (dumphistory)
02158 sip_dump_history(p);
02159
02160 if (p->options)
02161 free(p->options);
02162
02163 if (p->stateid > -1)
02164 ast_extension_state_del(p->stateid, NULL);
02165 if (p->initid > -1)
02166 ast_sched_del(sched, p->initid);
02167 if (p->autokillid > -1)
02168 ast_sched_del(sched, p->autokillid);
02169
02170 if (p->rtp) {
02171 ast_rtp_destroy(p->rtp);
02172 }
02173 if (p->vrtp) {
02174 ast_rtp_destroy(p->vrtp);
02175 }
02176 if (p->route) {
02177 free_old_route(p->route);
02178 p->route = NULL;
02179 }
02180 if (p->registry) {
02181 if (p->registry->call == p)
02182 p->registry->call = NULL;
02183 ASTOBJ_UNREF(p->registry,sip_registry_destroy);
02184 }
02185
02186 if (p->rpid)
02187 free(p->rpid);
02188
02189 if (p->rpid_from)
02190 free(p->rpid_from);
02191
02192
02193 if (p->owner) {
02194 if (lockowner)
02195 ast_mutex_lock(&p->owner->lock);
02196 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
02197 p->owner->tech_pvt = NULL;
02198 if (lockowner)
02199 ast_mutex_unlock(&p->owner->lock);
02200 }
02201
02202 while(p->history) {
02203 hist = p->history;
02204 p->history = p->history->next;
02205 free(hist);
02206 }
02207
02208 cur = iflist;
02209 while(cur) {
02210 if (cur == p) {
02211 if (prev)
02212 prev->next = cur->next;
02213 else
02214 iflist = cur->next;
02215 break;
02216 }
02217 prev = cur;
02218 cur = cur->next;
02219 }
02220 if (!cur) {
02221 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
02222 return;
02223 }
02224 while((cp = p->packets)) {
02225 p->packets = p->packets->next;
02226 if (cp->retransid > -1) {
02227 ast_sched_del(sched, cp->retransid);
02228 }
02229 free(cp);
02230 }
02231 if (p->chanvars) {
02232 ast_variables_destroy(p->chanvars);
02233 p->chanvars = NULL;
02234 }
02235 ast_mutex_destroy(&p->lock);
02236 free(p);
02237 }
02238
02239
02240
02241
02242 static int update_call_counter(struct sip_pvt *fup, int event)
02243 {
02244 char name[256];
02245 int *inuse, *call_limit;
02246 int outgoing = ast_test_flag(fup, SIP_OUTGOING);
02247 struct sip_user *u = NULL;
02248 struct sip_peer *p = NULL;
02249
02250 if (option_debug > 2)
02251 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
02252
02253
02254 if (!ast_test_flag(fup, SIP_CALL_LIMIT))
02255 return 0;
02256
02257 ast_copy_string(name, fup->username, sizeof(name));
02258
02259
02260 if (!outgoing && (u = find_user(name, 1))) {
02261 inuse = &u->inUse;
02262 call_limit = &u->call_limit;
02263 p = NULL;
02264 } else {
02265
02266 if (!p)
02267 p = find_peer(fup->peername, NULL, 1);
02268 if (p) {
02269 inuse = &p->inUse;
02270 call_limit = &p->call_limit;
02271 ast_copy_string(name, fup->peername, sizeof(name));
02272 } else {
02273 if (option_debug > 1)
02274 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
02275 return 0;
02276 }
02277 }
02278 switch(event) {
02279
02280 case DEC_CALL_LIMIT:
02281 if ( *inuse > 0 ) {
02282 if (ast_test_flag(fup, SIP_INC_COUNT)) {
02283 (*inuse)--;
02284 ast_clear_flag(fup, SIP_INC_COUNT);
02285 }
02286 } else {
02287 *inuse = 0;
02288 }
02289 if (option_debug > 1 || sipdebug) {
02290 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
02291 }
02292 break;
02293 case INC_CALL_LIMIT:
02294 if (*call_limit > 0 ) {
02295 if (*inuse >= *call_limit) {
02296 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
02297 if (u)
02298 ASTOBJ_UNREF(u,sip_destroy_user);
02299 else
02300 ASTOBJ_UNREF(p,sip_destroy_peer);
02301 return -1;
02302 }
02303 }
02304 (*inuse)++;
02305 ast_set_flag(fup,SIP_INC_COUNT);
02306 if (option_debug > 1 || sipdebug) {
02307 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
02308 }
02309 break;
02310 default:
02311 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
02312 }
02313 if (u)
02314 ASTOBJ_UNREF(u,sip_destroy_user);
02315 else
02316 ASTOBJ_UNREF(p,sip_destroy_peer);
02317 return 0;
02318 }
02319
02320
02321 static void sip_destroy(struct sip_pvt *p)
02322 {
02323 ast_mutex_lock(&iflock);
02324 __sip_destroy(p, 1);
02325 ast_mutex_unlock(&iflock);
02326 }
02327
02328
02329 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
02330
02331
02332 static int hangup_sip2cause(int cause)
02333 {
02334
02335
02336 switch(cause) {
02337 case 603:
02338 case 403:
02339 case 487:
02340 return AST_CAUSE_CALL_REJECTED;
02341 case 404:
02342 return AST_CAUSE_UNALLOCATED;
02343 case 408:
02344 return AST_CAUSE_NO_USER_RESPONSE;
02345 case 480:
02346 return AST_CAUSE_NO_ANSWER;
02347 case 483:
02348 return AST_CAUSE_NO_ANSWER;
02349 case 486:
02350 return AST_CAUSE_BUSY;
02351 case 488:
02352 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
02353 case 500:
02354 return AST_CAUSE_FAILURE;
02355 case 501:
02356 return AST_CAUSE_FACILITY_REJECTED;
02357 case 502:
02358 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
02359 case 503:
02360 case 504:
02361 return AST_CAUSE_CONGESTION;
02362 default:
02363 return AST_CAUSE_NORMAL;
02364 }
02365
02366 return 0;
02367 }
02368
02369
02370
02371
02372
02373
02374
02375
02376
02377
02378
02379
02380
02381
02382
02383
02384
02385
02386
02387
02388
02389
02390
02391
02392
02393
02394
02395
02396
02397
02398
02399
02400
02401
02402 static char *hangup_cause2sip(int cause)
02403 {
02404 switch(cause)
02405 {
02406 case AST_CAUSE_UNALLOCATED:
02407 case AST_CAUSE_NO_ROUTE_DESTINATION:
02408 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
02409 return "404 Not Found";
02410 case AST_CAUSE_CONGESTION:
02411 case AST_CAUSE_SWITCH_CONGESTION:
02412 return "503 Service Unavailable";
02413 case AST_CAUSE_NO_USER_RESPONSE:
02414 return "408 Request Timeout";
02415 case AST_CAUSE_NO_ANSWER:
02416 return "480 Temporarily unavailable";
02417 case AST_CAUSE_CALL_REJECTED:
02418 return "403 Forbidden";
02419 case AST_CAUSE_NUMBER_CHANGED:
02420 return "410 Gone";
02421 case AST_CAUSE_NORMAL_UNSPECIFIED:
02422 return "480 Temporarily unavailable";
02423 case AST_CAUSE_INVALID_NUMBER_FORMAT:
02424 return "484 Address incomplete";
02425 case AST_CAUSE_USER_BUSY:
02426 return "486 Busy here";
02427 case AST_CAUSE_FAILURE:
02428 return "500 Server internal failure";
02429 case AST_CAUSE_FACILITY_REJECTED:
02430 return "501 Not Implemented";
02431 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
02432 return "503 Service Unavailable";
02433
02434 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
02435 return "502 Bad Gateway";
02436 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
02437 return "488 Not Acceptable Here";
02438
02439 case AST_CAUSE_NOTDEFINED:
02440 default:
02441 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
02442 return NULL;
02443 }
02444
02445
02446 return 0;
02447 }
02448
02449
02450
02451
02452 static int sip_hangup(struct ast_channel *ast)
02453 {
02454 struct sip_pvt *p = ast->tech_pvt;
02455 int needcancel = 0;
02456 int needdestroy = 0;
02457
02458 if (!p) {
02459 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
02460 return 0;
02461 }
02462 if (option_debug)
02463 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
02464
02465 ast_mutex_lock(&p->lock);
02466 #ifdef OSP_SUPPORT
02467 if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
02468 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
02469 }
02470 #endif
02471 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter\n", p->username);
02472 update_call_counter(p, DEC_CALL_LIMIT);
02473
02474 if (p->owner != ast) {
02475 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
02476 ast_mutex_unlock(&p->lock);
02477 return 0;
02478 }
02479
02480 if (ast->_state != AST_STATE_UP)
02481 needcancel = 1;
02482
02483
02484 if (p->vad) {
02485 ast_dsp_free(p->vad);
02486 }
02487 p->owner = NULL;
02488 ast->tech_pvt = NULL;
02489
02490 ast_mutex_lock(&usecnt_lock);
02491 usecnt--;
02492 ast_mutex_unlock(&usecnt_lock);
02493 ast_update_use_count();
02494
02495
02496
02497
02498
02499
02500
02501 if (ast_test_flag(p, SIP_ALREADYGONE))
02502 needdestroy = 1;
02503 else
02504 sip_scheddestroy(p, 32000);
02505
02506
02507 if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
02508 if (needcancel) {
02509 if (ast_test_flag(p, SIP_OUTGOING)) {
02510
02511 __sip_pretend_ack(p);
02512
02513
02514
02515 if (!ast_test_flag(p, SIP_CAN_BYE)) {
02516 ast_set_flag(p, SIP_PENDINGBYE);
02517
02518 } else {
02519
02520 transmit_request(p, SIP_CANCEL, p->ocseq, 1, 0);
02521
02522
02523 }
02524 if ( p->initid != -1 ) {
02525
02526
02527 update_call_counter(p, INC_CALL_LIMIT);
02528 }
02529 } else {
02530 char *res;
02531 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
02532 transmit_response_reliable(p, res, &p->initreq, 1);
02533 } else
02534 transmit_response_reliable(p, "603 Declined", &p->initreq, 1);
02535 }
02536 } else {
02537 if (!p->pendinginvite) {
02538
02539 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
02540 } else {
02541
02542
02543 ast_set_flag(p, SIP_PENDINGBYE);
02544 ast_clear_flag(p, SIP_NEEDREINVITE);
02545 }
02546 }
02547 }
02548 if (needdestroy)
02549 ast_set_flag(p, SIP_NEEDDESTROY);
02550 ast_mutex_unlock(&p->lock);
02551 return 0;
02552 }
02553
02554
02555 static void try_suggested_sip_codec(struct sip_pvt *p)
02556 {
02557 int fmt;
02558 char *codec;
02559
02560 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
02561 if (!codec)
02562 return;
02563
02564 fmt = ast_getformatbyname(codec);
02565 if (fmt) {
02566 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
02567 if (p->jointcapability & fmt) {
02568 p->jointcapability &= fmt;
02569 p->capability &= fmt;
02570 } else
02571 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
02572 } else
02573 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
02574 return;
02575 }
02576
02577
02578
02579 static int sip_answer(struct ast_channel *ast)
02580 {
02581 int res = 0;
02582 struct sip_pvt *p = ast->tech_pvt;
02583
02584 ast_mutex_lock(&p->lock);
02585 if (ast->_state != AST_STATE_UP) {
02586 #ifdef OSP_SUPPORT
02587 time(&p->ospstart);
02588 #endif
02589 try_suggested_sip_codec(p);
02590
02591 ast_setstate(ast, AST_STATE_UP);
02592 if (option_debug)
02593 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
02594 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 2);
02595 }
02596 ast_mutex_unlock(&p->lock);
02597 return res;
02598 }
02599
02600
02601 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
02602 {
02603 struct sip_pvt *p = ast->tech_pvt;
02604 int res = 0;
02605 switch (frame->frametype) {
02606 case AST_FRAME_VOICE:
02607 if (!(frame->subclass & ast->nativeformats)) {
02608 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
02609 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
02610 return 0;
02611 }
02612 if (p) {
02613 ast_mutex_lock(&p->lock);
02614 if (p->rtp) {
02615
02616 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
02617 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
02618 ast_set_flag(p, SIP_PROGRESS_SENT);
02619 }
02620 time(&p->lastrtptx);
02621 res = ast_rtp_write(p->rtp, frame);
02622 }
02623 ast_mutex_unlock(&p->lock);
02624 }
02625 break;
02626 case AST_FRAME_VIDEO:
02627 if (p) {
02628 ast_mutex_lock(&p->lock);
02629 if (p->vrtp) {
02630
02631 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
02632 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
02633 ast_set_flag(p, SIP_PROGRESS_SENT);
02634 }
02635 time(&p->lastrtptx);
02636 res = ast_rtp_write(p->vrtp, frame);
02637 }
02638 ast_mutex_unlock(&p->lock);
02639 }
02640 break;
02641 case AST_FRAME_IMAGE:
02642 return 0;
02643 break;
02644 default:
02645 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
02646 return 0;
02647 }
02648
02649 return res;
02650 }
02651
02652
02653
02654 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
02655 {
02656 struct sip_pvt *p = newchan->tech_pvt;
02657 if (!p) {
02658 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
02659 return -1;
02660 }
02661
02662 ast_mutex_lock(&p->lock);
02663 if (p->owner != oldchan) {
02664 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
02665 ast_mutex_unlock(&p->lock);
02666 return -1;
02667 }
02668 p->owner = newchan;
02669 ast_mutex_unlock(&p->lock);
02670 return 0;
02671 }
02672
02673
02674
02675 static int sip_senddigit(struct ast_channel *ast, char digit)
02676 {
02677 struct sip_pvt *p = ast->tech_pvt;
02678 int res = 0;
02679 ast_mutex_lock(&p->lock);
02680 switch (ast_test_flag(p, SIP_DTMF)) {
02681 case SIP_DTMF_INFO:
02682 transmit_info_with_digit(p, digit);
02683 break;
02684 case SIP_DTMF_RFC2833:
02685 if (p->rtp)
02686 ast_rtp_senddigit(p->rtp, digit);
02687 break;
02688 case SIP_DTMF_INBAND:
02689 res = -1;
02690 break;
02691 }
02692 ast_mutex_unlock(&p->lock);
02693 return res;
02694 }
02695
02696
02697
02698
02699 static int sip_transfer(struct ast_channel *ast, const char *dest)
02700 {
02701 struct sip_pvt *p = ast->tech_pvt;
02702 int res;
02703
02704 ast_mutex_lock(&p->lock);
02705 if (ast->_state == AST_STATE_RING)
02706 res = sip_sipredirect(p, dest);
02707 else
02708 res = transmit_refer(p, dest);
02709 ast_mutex_unlock(&p->lock);
02710 return res;
02711 }
02712
02713
02714
02715
02716 static int sip_indicate(struct ast_channel *ast, int condition)
02717 {
02718 struct sip_pvt *p = ast->tech_pvt;
02719 int res = 0;
02720
02721 ast_mutex_lock(&p->lock);
02722 switch(condition) {
02723 case AST_CONTROL_RINGING:
02724 if (ast->_state == AST_STATE_RING) {
02725 if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
02726 (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
02727
02728 transmit_response(p, "180 Ringing", &p->initreq);
02729 ast_set_flag(p, SIP_RINGING);
02730 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
02731 break;
02732 } else {
02733
02734 }
02735 }
02736 res = -1;
02737 break;
02738 case AST_CONTROL_BUSY:
02739 if (ast->_state != AST_STATE_UP) {
02740 transmit_response(p, "486 Busy Here", &p->initreq);
02741 ast_set_flag(p, SIP_ALREADYGONE);
02742 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
02743 break;
02744 }
02745 res = -1;
02746 break;
02747 case AST_CONTROL_CONGESTION:
02748 if (ast->_state != AST_STATE_UP) {
02749 transmit_response(p, "503 Service Unavailable", &p->initreq);
02750 ast_set_flag(p, SIP_ALREADYGONE);
02751 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
02752 break;
02753 }
02754 res = -1;
02755 break;
02756 case AST_CONTROL_PROCEEDING:
02757 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
02758 transmit_response(p, "100 Trying", &p->initreq);
02759 break;
02760 }
02761 res = -1;
02762 break;
02763 case AST_CONTROL_PROGRESS:
02764 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
02765 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
02766 ast_set_flag(p, SIP_PROGRESS_SENT);
02767 break;
02768 }
02769 res = -1;
02770 break;
02771 case AST_CONTROL_HOLD:
02772 if (sipdebug)
02773 ast_log(LOG_DEBUG, "Bridged channel now on hold%s\n", p->callid);
02774 res = -1;
02775 break;
02776 case AST_CONTROL_UNHOLD:
02777 if (sipdebug)
02778 ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
02779 res = -1;
02780 break;
02781 case AST_CONTROL_VIDUPDATE:
02782 if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) {
02783 transmit_info_with_vidupdate(p);
02784 res = 0;
02785 } else
02786 res = -1;
02787 break;
02788 case -1:
02789 res = -1;
02790 break;
02791 default:
02792 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
02793 res = -1;
02794 break;
02795 }
02796 ast_mutex_unlock(&p->lock);
02797 return res;
02798 }
02799
02800
02801
02802
02803
02804 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
02805 {
02806 struct ast_channel *tmp;
02807 struct ast_variable *v = NULL;
02808 int fmt;
02809 #ifdef OSP_SUPPORT
02810 char iabuf[INET_ADDRSTRLEN];
02811 char peer[MAXHOSTNAMELEN];
02812 #endif
02813
02814 ast_mutex_unlock(&i->lock);
02815
02816 tmp = ast_channel_alloc(1);
02817 if (!tmp) {
02818 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
02819 return NULL;
02820 }
02821 ast_mutex_lock(&i->lock);
02822 tmp->tech = &sip_tech;
02823
02824
02825 if (i->jointcapability)
02826 tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
02827 else if (i->capability)
02828 tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
02829 else
02830 tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
02831 fmt = ast_best_codec(tmp->nativeformats);
02832
02833 if (title)
02834 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", title, (int)(long) i);
02835 else if (strchr(i->fromdomain,':'))
02836 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':') + 1, (int)(long) i);
02837 else
02838 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long) i);
02839
02840 tmp->type = channeltype;
02841 if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
02842 i->vad = ast_dsp_new();
02843 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
02844 if (relaxdtmf)
02845 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
02846 }
02847 if (i->rtp) {
02848 tmp->fds[0] = ast_rtp_fd(i->rtp);
02849 tmp->fds[1] = ast_rtcp_fd(i->rtp);
02850 }
02851 if (i->vrtp) {
02852 tmp->fds[2] = ast_rtp_fd(i->vrtp);
02853 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
02854 }
02855 if (state == AST_STATE_RING)
02856 tmp->rings = 1;
02857 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
02858 tmp->writeformat = fmt;
02859 tmp->rawwriteformat = fmt;
02860 tmp->readformat = fmt;
02861 tmp->rawreadformat = fmt;
02862 tmp->tech_pvt = i;
02863
02864 tmp->callgroup = i->callgroup;
02865 tmp->pickupgroup = i->pickupgroup;
02866 tmp->cid.cid_pres = i->callingpres;
02867 if (!ast_strlen_zero(i->accountcode))
02868 ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
02869 if (i->amaflags)
02870 tmp->amaflags = i->amaflags;
02871 if (!ast_strlen_zero(i->language))
02872 ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
02873 if (!ast_strlen_zero(i->musicclass))
02874 ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
02875 i->owner = tmp;
02876 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
02877 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
02878
02879 if (!ast_strlen_zero(i->cid_num))
02880 tmp->cid.cid_num = strdup(i->cid_num);
02881 if (!ast_strlen_zero(i->cid_name))
02882 tmp->cid.cid_name = strdup(i->cid_name);
02883 if (!ast_strlen_zero(i->rdnis))
02884 tmp->cid.cid_rdnis = strdup(i->rdnis);
02885 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
02886 tmp->cid.cid_dnid = strdup(i->exten);
02887
02888 tmp->priority = 1;
02889 if (!ast_strlen_zero(i->uri)) {
02890 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
02891 }
02892 if (!ast_strlen_zero(i->domain)) {
02893 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
02894 }
02895 if (!ast_strlen_zero(i->useragent)) {
02896 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
02897 }
02898 if (!ast_strlen_zero(i->callid)) {
02899 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
02900 }
02901 #ifdef OSP_SUPPORT
02902 snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
02903 pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
02904 #endif
02905 ast_setstate(tmp, state);
02906
02907
02908 for (v = i->chanvars ; v ; v = v->next)
02909 pbx_builtin_setvar_helper(tmp, v->name, v->value);
02910
02911 if (state != AST_STATE_DOWN) {
02912 if (ast_pbx_start(tmp)) {
02913 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
02914 ast_hangup(tmp);
02915 tmp = NULL;
02916 }
02917 }
02918
02919 ast_mutex_lock(&usecnt_lock);
02920 usecnt++;
02921 ast_mutex_unlock(&usecnt_lock);
02922 ast_update_use_count();
02923
02924 return tmp;
02925 }
02926
02927
02928 static char *get_body_by_line(char *line, char *name, int nameLen)
02929 {
02930 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
02931 return ast_skip_blanks(line + nameLen + 1);
02932 }
02933 return "";
02934 }
02935
02936
02937 static char *get_sdp(struct sip_request *req, char *name)
02938 {
02939 int x;
02940 int len = strlen(name);
02941 char *r;
02942
02943 for (x = req->sdp_start; x < req->sdp_end; x++) {
02944 r = get_body_by_line(req->line[x], name, len);
02945 if (r[0] != '\0')
02946 return r;
02947 }
02948 return "";
02949 }
02950
02951 static void sdpLineNum_iterator_init(int *iterator, struct sip_request *req)
02952 {
02953 *iterator = req->sdp_start;
02954 }
02955
02956 static char *get_sdp_iterate(int *iterator,
02957 struct sip_request *req, char *name)
02958 {
02959 int len = strlen(name);
02960 char *r;
02961
02962 while (*iterator < req->sdp_end) {
02963 r = get_body_by_line(req->line[(*iterator)++], name, len);
02964 if (r[0] != '\0')
02965 return r;
02966 }
02967 return "";
02968 }
02969
02970
02971 static char *get_body(struct sip_request *req, char *name)
02972 {
02973 int x;
02974 int len = strlen(name);
02975 char *r;
02976
02977 for (x = 0; x < req->lines; x++) {
02978 r = get_body_by_line(req->line[x], name, len);
02979 if (r[0] != '\0')
02980 return r;
02981 }
02982 return "";
02983 }
02984
02985 static char *find_alias(const char *name, char *_default)
02986 {
02987 int x;
02988 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
02989 if (!strcasecmp(aliases[x].fullname, name))
02990 return aliases[x].shortname;
02991 return _default;
02992 }
02993
02994 static char *__get_header(struct sip_request *req, char *name, int *start)
02995 {
02996 int pass;
02997
02998
02999
03000
03001
03002
03003
03004
03005
03006
03007 for (pass = 0; name && pass < 2;pass++) {
03008 int x, len = strlen(name);
03009 for (x=*start; x<req->headers; x++) {
03010 if (!strncasecmp(req->header[x], name, len)) {
03011 char *r = req->header[x] + len;
03012 if (pedanticsipchecking)
03013 r = ast_skip_blanks(r);
03014
03015 if (*r == ':') {
03016 *start = x+1;
03017 return ast_skip_blanks(r+1);
03018 }
03019 }
03020 }
03021 if (pass == 0)
03022 name = find_alias(name, NULL);
03023 }
03024
03025
03026 return "";
03027 }
03028
03029
03030 static char *get_header(struct sip_request *req, char *name)
03031 {
03032 int start = 0;
03033 return __get_header(req, name, &start);
03034 }
03035
03036
03037 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
03038 {
03039
03040 struct ast_frame *f;
03041 static struct ast_frame null_frame = { AST_FRAME_NULL, };
03042
03043 if (!p->rtp) {
03044
03045 return &null_frame;
03046 }
03047
03048 switch(ast->fdno) {
03049 case 0:
03050 f = ast_rtp_read(p->rtp);
03051 break;
03052 case 1:
03053 f = ast_rtcp_read(p->rtp);
03054 break;
03055 case 2:
03056 f = ast_rtp_read(p->vrtp);
03057 break;
03058 case 3:
03059 f = ast_rtcp_read(p->vrtp);
03060 break;
03061 default:
03062 f = &null_frame;
03063 }
03064
03065 if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
03066 return &null_frame;
03067 if (p->owner) {
03068
03069 if (f && f->frametype == AST_FRAME_VOICE) {
03070 if (f->subclass != p->owner->nativeformats) {
03071 if (!(f->subclass & p->jointcapability)) {
03072 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
03073 ast_getformatname(f->subclass), p->owner->name);
03074 return &null_frame;
03075 }
03076 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
03077 p->owner->nativeformats = f->subclass;
03078 ast_set_read_format(p->owner, p->owner->readformat);
03079 ast_set_write_format(p->owner, p->owner->writeformat);
03080 }
03081 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
03082 f = ast_dsp_process(p->owner, p->vad, f);
03083 if (f && (f->frametype == AST_FRAME_DTMF))
03084 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
03085 }
03086 }
03087 }
03088 return f;
03089 }
03090
03091
03092 static struct ast_frame *sip_read(struct ast_channel *ast)
03093 {
03094 struct ast_frame *fr;
03095 struct sip_pvt *p = ast->tech_pvt;
03096 ast_mutex_lock(&p->lock);
03097 fr = sip_rtp_read(ast, p);
03098 time(&p->lastrtprx);
03099 ast_mutex_unlock(&p->lock);
03100 return fr;
03101 }
03102
03103
03104 static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
03105 {
03106 int res;
03107 int val;
03108 int x;
03109 char iabuf[INET_ADDRSTRLEN];
03110 for (x=0; x<4; x++) {
03111 val = thread_safe_rand();
03112 res = snprintf(callid, len, "%08x", val);
03113 len -= res;
03114 callid += res;
03115 }
03116 if (!ast_strlen_zero(fromdomain))
03117 snprintf(callid, len, "@%s", fromdomain);
03118 else
03119
03120 snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
03121 }
03122
03123 static void make_our_tag(char *tagbuf, size_t len)
03124 {
03125 snprintf(tagbuf, len, "as%08x", thread_safe_rand());
03126 }
03127
03128
03129 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method)
03130 {
03131 struct sip_pvt *p;
03132
03133 if (!(p = calloc(1, sizeof(*p))))
03134 return NULL;
03135
03136 ast_mutex_init(&p->lock);
03137
03138 p->method = intended_method;
03139 p->initid = -1;
03140 p->autokillid = -1;
03141 p->subscribed = NONE;
03142 p->stateid = -1;
03143 p->prefs = prefs;
03144 if (intended_method != SIP_OPTIONS)
03145 p->timer_t1 = 500;
03146 #ifdef OSP_SUPPORT
03147 p->osphandle = -1;
03148 p->osptimelimit = 0;
03149 #endif
03150 if (sin) {
03151 memcpy(&p->sa, sin, sizeof(p->sa));
03152 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
03153 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
03154 } else {
03155 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
03156 }
03157
03158 p->branch = thread_safe_rand();
03159 make_our_tag(p->tag, sizeof(p->tag));
03160
03161 p->ocseq = 101;
03162
03163 if (sip_methods[intended_method].need_rtp) {
03164 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
03165 if (videosupport)
03166 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
03167 if (!p->rtp || (videosupport && !p->vrtp)) {
03168 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n", videosupport ? "and video" : "", strerror(errno));
03169 ast_mutex_destroy(&p->lock);
03170 if (p->chanvars) {
03171 ast_variables_destroy(p->chanvars);
03172 p->chanvars = NULL;
03173 }
03174 free(p);
03175 return NULL;
03176 }
03177 ast_rtp_settos(p->rtp, tos);
03178 if (p->vrtp)
03179 ast_rtp_settos(p->vrtp, tos);
03180 p->rtptimeout = global_rtptimeout;
03181 p->rtpholdtimeout = global_rtpholdtimeout;
03182 p->rtpkeepalive = global_rtpkeepalive;
03183 }
03184
03185 if (useglobal_nat && sin) {
03186
03187 ast_copy_flags(p, &global_flags, SIP_NAT);
03188 memcpy(&p->recv, sin, sizeof(p->recv));
03189 if (p->rtp)
03190 ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
03191 if (p->vrtp)
03192 ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
03193 }
03194
03195 if (p->method != SIP_REGISTER)
03196 ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
03197 build_via(p, p->via, sizeof(p->via));
03198 if (!callid)
03199 build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
03200 else
03201 ast_copy_string(p->callid, callid, sizeof(p->callid));
03202 ast_copy_flags(p, &global_flags, SIP_FLAGS_TO_COPY);
03203
03204 strcpy(p->musicclass, global_musicclass);
03205 p->capability = global_capability;
03206 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
03207 p->noncodeccapability |= AST_RTP_DTMF;
03208 p->jointnoncodeccapability = p->noncodeccapability;
03209 strcpy(p->context, default_context);
03210
03211
03212 ast_mutex_lock(&iflock);
03213 p->next = iflist;
03214 iflist = p;
03215 ast_mutex_unlock(&iflock);
03216 if (option_debug)
03217 ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
03218 return p;
03219 }
03220
03221
03222
03223 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
03224 {
03225 struct sip_pvt *p = NULL;
03226 char *callid;
03227 char *tag = "";
03228 char totag[128];
03229 char fromtag[128];
03230
03231 callid = get_header(req, "Call-ID");
03232
03233 if (pedanticsipchecking) {
03234
03235
03236
03237
03238
03239
03240 if (gettag(req, "To", totag, sizeof(totag)))
03241 ast_set_flag(req, SIP_PKT_WITH_TOTAG);
03242 gettag(req, "From", fromtag, sizeof(fromtag));
03243
03244 if (req->method == SIP_RESPONSE)
03245 tag = totag;
03246 else
03247 tag = fromtag;
03248
03249
03250 if (option_debug > 4 )
03251 ast_log(LOG_DEBUG, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
03252 }
03253
03254 ast_mutex_lock(&iflock);
03255 p = iflist;
03256 while(p) {
03257 int found = 0;
03258 if (req->method == SIP_REGISTER)
03259 found = (!strcmp(p->callid, callid));
03260 else
03261 found = (!strcmp(p->callid, callid) &&
03262 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
03263
03264 if (option_debug > 4)
03265 ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
03266
03267
03268 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) {
03269 if (p->tag[0] == '\0' && totag[0]) {
03270
03271 found = 0;
03272 } else if (totag[0]) {
03273 if (strcmp(totag, p->tag)) {
03274 found = 0;
03275 }
03276 }
03277 if (!found && option_debug > 4)
03278 ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
03279 }
03280
03281
03282 if (found) {
03283
03284 ast_mutex_lock(&p->lock);
03285 ast_mutex_unlock(&iflock);
03286 return p;
03287 }
03288 p = p->next;
03289 }
03290 ast_mutex_unlock(&iflock);
03291
03292
03293
03294 if (!sip_methods[intended_method].can_create) {
03295
03296 if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK)
03297 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
03298 } else if (sip_methods[intended_method].can_create == 2) {
03299 char *response = "481 Call leg/transaction does not exist";
03300
03301 if (intended_method == SIP_PRACK || intended_method == SIP_UNKNOWN)
03302 response = "501 Method not implemented";
03303 else if(intended_method == SIP_REFER)
03304 response = "603 Declined (no dialog)";
03305 else if(intended_method == SIP_NOTIFY)
03306 response = "489 Bad event";
03307
03308 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
03309
03310 } else {
03311 p = sip_alloc(callid, sin, 1, intended_method);
03312 if (p)
03313 ast_mutex_lock(&p->lock);
03314 else {
03315
03316
03317
03318
03319
03320
03321
03322
03323 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
03324 if (option_debug > 3)
03325 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
03326 }
03327 }
03328
03329 return p;
03330 }
03331
03332
03333 static int sip_register(char *value, int lineno)
03334 {
03335 struct sip_registry *reg;
03336 char copy[256];
03337 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
03338 char *porta=NULL;
03339 char *contact=NULL;
03340 char *stringp=NULL;
03341
03342 if (!value)
03343 return -1;
03344 ast_copy_string(copy, value, sizeof(copy));
03345 stringp=copy;
03346 username = stringp;
03347 hostname = strrchr(stringp, '@');
03348 if (hostname) {
03349 *hostname = '\0';
03350 hostname++;
03351 }
03352 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
03353 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
03354 return -1;
03355 }
03356 stringp=username;
03357 username = strsep(&stringp, ":");
03358 if (username) {
03359 secret = strsep(&stringp, ":");
03360 if (secret)
03361 authuser = strsep(&stringp, ":");
03362 }
03363 stringp = hostname;
03364 hostname = strsep(&stringp, "/");
03365 if (hostname)
03366 contact = strsep(&stringp, "/");
03367 if (ast_strlen_zero(contact))
03368 contact = "s";
03369 stringp=hostname;
03370 hostname = strsep(&stringp, ":");
03371 porta = strsep(&stringp, ":");
03372
03373 if (porta && !atoi(porta)) {
03374 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
03375 return -1;
03376 }
03377 reg = malloc(sizeof(struct sip_registry));
03378 if (!reg) {
03379 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
03380 return -1;
03381 }
03382 memset(reg, 0, sizeof(struct sip_registry));
03383 regobjs++;
03384 ASTOBJ_INIT(reg);
03385 ast_copy_string(reg->contact, contact, sizeof(reg->contact));
03386 if (username)
03387 ast_copy_string(reg->username, username, sizeof(reg->username));
03388 if (hostname)
03389 ast_copy_string(reg->hostname, hostname, sizeof(reg->hostname));
03390 if (authuser)
03391 ast_copy_string(reg->authuser, authuser, sizeof(reg->authuser));
03392 if (secret)
03393 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
03394 reg->expire = -1;
03395 reg->timeout = -1;
03396 reg->refresh = default_expiry;
03397 reg->portno = porta ? atoi(porta) : 0;
03398 reg->callid_valid = 0;
03399 reg->ocseq = 101;
03400 ASTOBJ_CONTAINER_LINK(®l, reg);
03401 ASTOBJ_UNREF(reg,sip_registry_destroy);
03402 return 0;
03403 }
03404
03405
03406
03407 static int lws2sws(char *msgbuf, int len)
03408 {
03409 int h = 0, t = 0;
03410 int lws = 0;
03411
03412 for (; h < len;) {
03413
03414 if (msgbuf[h] == '\r') {
03415 h++;
03416 continue;
03417 }
03418
03419 if (msgbuf[h] == '\n') {
03420
03421 if (h + 1 == len)
03422 break;
03423
03424 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
03425
03426 h++;
03427 continue;
03428 }
03429
03430 msgbuf[t++] = msgbuf[h++];
03431 lws = 0;
03432 continue;
03433 }
03434 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
03435 if (lws) {
03436 h++;
03437 continue;
03438 }
03439 msgbuf[t++] = msgbuf[h++];
03440 lws = 1;
03441 continue;
03442 }
03443 msgbuf[t++] = msgbuf[h++];
03444 if (lws)
03445 lws = 0;
03446 }
03447 msgbuf[t] = '\0';
03448 return t;
03449 }
03450
03451
03452 static void parse_request(struct sip_request *req)
03453 {
03454
03455 char *c;
03456 int f = 0;
03457
03458 c = req->data;
03459
03460
03461 req->header[f] = c;
03462 while(*c) {
03463 if (*c == '\n') {
03464
03465 *c = 0;
03466
03467 if (sipdebug && option_debug > 3)
03468 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
03469 if (ast_strlen_zero(req->header[f])) {
03470
03471 c++;
03472 break;
03473 }
03474 if (f >= SIP_MAX_HEADERS - 1) {
03475 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
03476 } else
03477 f++;
03478 req->header[f] = c + 1;
03479 } else if (*c == '\r') {
03480
03481 *c = 0;
03482 }
03483 c++;
03484 }
03485
03486 if (!ast_strlen_zero(req->header[f])) {
03487 if (sipdebug && option_debug > 3)
03488 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
03489 f++;
03490 }
03491 req->headers = f;
03492
03493 f = 0;
03494 req->line[f] = c;
03495 while(*c) {
03496 if (*c == '\n') {
03497
03498 *c = 0;
03499 if (sipdebug && option_debug > 3)
03500 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
03501 if (f >= SIP_MAX_LINES - 1) {
03502 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
03503 } else
03504 f++;
03505 req->line[f] = c + 1;
03506 } else if (*c == '\r') {
03507
03508 *c = 0;
03509 }
03510 c++;
03511 }
03512
03513 if (!ast_strlen_zero(req->line[f]))
03514 f++;
03515 req->lines = f;
03516 if (*c)
03517 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
03518
03519 determine_firstline_parts(req);
03520 }
03521
03522
03523
03524
03525
03526
03527
03528
03529
03530 static int find_sdp(struct sip_request *req)
03531 {
03532 char *content_type;
03533 char *search;
03534 char *boundary;
03535 unsigned int x;
03536
03537 content_type = get_header(req, "Content-Type");
03538
03539
03540 if (!strcasecmp(content_type, "application/sdp")) {
03541 req->sdp_start = 0;
03542 req->sdp_end = req->lines;
03543 return 1;
03544 }
03545
03546
03547 if (strncasecmp(content_type, "multipart/mixed", 15))
03548 return 0;
03549
03550
03551 if (!(search = strcasestr(content_type, ";boundary=")))
03552 return 0;
03553
03554 search += 10;
03555
03556 if (ast_strlen_zero(search))
03557 return 0;
03558
03559
03560
03561 boundary = ast_strdupa(search - 2);
03562 boundary[0] = boundary[1] = '-';
03563
03564
03565
03566
03567 for (x = 0; x < (req->lines - 2); x++) {
03568 if (!strncasecmp(req->line[x], boundary, strlen(boundary)) &&
03569 !strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) {
03570 x += 2;
03571 req->sdp_start = x;
03572
03573
03574 for ( ; x < req->lines; x++) {
03575 if (!strncasecmp(req->line[x], boundary, strlen(boundary)))
03576 break;
03577 }
03578 req->sdp_end = x;
03579 return 1;
03580 }
03581 }
03582
03583 return 0;
03584 }
03585
03586
03587 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
03588 {
03589 char *m;
03590 char *c;
03591 char *a;
03592 char host[258];
03593 char iabuf[INET_ADDRSTRLEN];
03594 int len = -1;
03595 int portno = -1;
03596 int vportno = -1;
03597 int peercapability, peernoncodeccapability;
03598 int vpeercapability=0, vpeernoncodeccapability=0;
03599 struct sockaddr_in sin;
03600 char *codecs;
03601 struct hostent *hp;
03602 struct ast_hostent ahp;
03603 int codec;
03604 int destiterator = 0;
03605 int iterator;
03606 int sendonly = 0;
03607 int x,y;
03608 int debug=sip_debug_test_pvt(p);
03609 struct ast_channel *bridgepeer = NULL;
03610
03611 if (!p->rtp) {
03612 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
03613 return -1;
03614 }
03615
03616
03617 time(&p->lastrtprx);
03618 time(&p->lastrtptx);
03619
03620 m = get_sdp(req, "m");
03621 sdpLineNum_iterator_init(&destiterator, req);
03622 c = get_sdp_iterate(&destiterator, req, "c");
03623 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
03624 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
03625 return -1;
03626 }
03627 if (sscanf(c, "IN IP4 %256s", host) != 1) {
03628 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
03629 return -1;
03630 }
03631
03632 hp = ast_gethostbyname(host, &ahp);
03633 if (!hp) {
03634 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
03635 return -1;
03636 }
03637 sdpLineNum_iterator_init(&iterator, req);
03638 ast_set_flag(p, SIP_NOVIDEO);
03639 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
03640 int found = 0;
03641 if ((sscanf(m, "audio %30d/%30d RTP/AVP %n", &x, &y, &len) == 2) ||
03642 (sscanf(m, "audio %30d RTP/AVP %n", &x, &len) == 1)) {
03643 found = 1;
03644 portno = x;
03645
03646 ast_rtp_pt_clear(p->rtp);
03647 codecs = m + len;
03648 while(!ast_strlen_zero(codecs)) {
03649 if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
03650 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
03651 return -1;
03652 }
03653 if (debug)
03654 ast_verbose("Found RTP audio format %d\n", codec);
03655 ast_rtp_set_m_type(p->rtp, codec);
03656 codecs = ast_skip_blanks(codecs + len);
03657 }
03658 }
03659 if (p->vrtp)
03660 ast_rtp_pt_clear(p->vrtp);
03661
03662 if (p->vrtp && (sscanf(m, "video %30d RTP/AVP %n", &x, &len) == 1)) {
03663 found = 1;
03664 ast_clear_flag(p, SIP_NOVIDEO);
03665 vportno = x;
03666
03667 codecs = m + len;
03668 while(!ast_strlen_zero(codecs)) {
03669 if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
03670 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
03671 return -1;
03672 }
03673 if (debug)
03674 ast_verbose("Found RTP video format %d\n", codec);
03675 ast_rtp_set_m_type(p->vrtp, codec);
03676 codecs = ast_skip_blanks(codecs + len);
03677 }
03678 }
03679 if (!found )
03680 ast_log(LOG_WARNING, "Unknown SDP media type in offer: %s\n", m);
03681 }
03682 if (portno == -1 && vportno == -1) {
03683
03684 return -2;
03685 }
03686
03687 c = get_sdp_iterate(&destiterator, req, "c");
03688 if (!ast_strlen_zero(c)) {
03689 if (sscanf(c, "IN IP4 %256s", host) != 1) {
03690 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
03691 } else {
03692
03693 hp = ast_gethostbyname(host, &ahp);
03694 if (!hp) {
03695 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
03696 return -1;
03697 }
03698 }
03699 }
03700
03701 sin.sin_family = AF_INET;
03702 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
03703
03704
03705 sin.sin_port = htons(portno);
03706 if (p->rtp && sin.sin_port) {
03707 ast_rtp_set_peer(p->rtp, &sin);
03708 if (debug) {
03709 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
03710 ast_log(LOG_DEBUG,"Peer audio RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
03711 }
03712 }
03713
03714 c = get_sdp_iterate(&destiterator, req, "c");
03715 if (!ast_strlen_zero(c)) {
03716 if (sscanf(c, "IN IP4 %256s", host) != 1) {
03717 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
03718 } else {
03719
03720 hp = ast_gethostbyname(host, &ahp);
03721 if (!hp) {
03722 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
03723 return -1;
03724 }
03725 }
03726 }
03727
03728 sin.sin_port = htons(vportno);
03729 if (p->vrtp && sin.sin_port) {
03730 ast_rtp_set_peer(p->vrtp, &sin);
03731 if (debug) {
03732 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
03733 ast_log(LOG_DEBUG,"Peer video RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
03734 }
03735 }
03736
03737
03738
03739
03740 sdpLineNum_iterator_init(&iterator, req);
03741 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
03742 char* mimeSubtype = ast_strdupa(a);
03743 if (!strcasecmp(a, "sendonly") || !strcasecmp(a, "inactive")) {
03744 sendonly = 1;
03745 continue;
03746 }
03747 if (!strcasecmp(a, "sendrecv")) {
03748 sendonly = 0;
03749 }
03750 if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) != 2) continue;
03751 if (debug)
03752 ast_verbose("Found description format %s\n", mimeSubtype);
03753
03754 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
03755 if (p->vrtp)
03756 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
03757 }
03758
03759
03760 ast_rtp_get_current_formats(p->rtp,
03761 &peercapability, &peernoncodeccapability);
03762 if (p->vrtp)
03763 ast_rtp_get_current_formats(p->vrtp,
03764 &vpeercapability, &vpeernoncodeccapability);
03765 p->jointcapability = p->capability & (peercapability | vpeercapability);
03766 p->peercapability = (peercapability | vpeercapability);
03767 p->jointnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
03768
03769 if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO) {
03770 ast_clear_flag(p, SIP_DTMF);
03771 if (p->jointnoncodeccapability & AST_RTP_DTMF) {
03772
03773 ast_set_flag(p, SIP_DTMF_RFC2833);
03774 } else {
03775 ast_set_flag(p, SIP_DTMF_INBAND);
03776 }
03777 }
03778
03779 if (debug) {
03780
03781 const unsigned slen=512;
03782 char s1[slen], s2[slen], s3[slen], s4[slen];
03783
03784 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
03785 ast_getformatname_multiple(s1, slen, p->capability),
03786 ast_getformatname_multiple(s2, slen, peercapability),
03787 ast_getformatname_multiple(s3, slen, vpeercapability),
03788 ast_getformatname_multiple(s4, slen, p->jointcapability));
03789
03790 ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
03791 ast_rtp_lookup_mime_multiple(s1, slen, p->noncodeccapability, 0),
03792 ast_rtp_lookup_mime_multiple(s2, slen, peernoncodeccapability, 0),
03793 ast_rtp_lookup_mime_multiple(s3, slen, p->jointnoncodeccapability, 0));
03794 }
03795 if (!p->jointcapability) {
03796 ast_log(LOG_NOTICE, "No compatible codecs!\n");
03797 return -1;
03798 }
03799
03800 if (!p->owner)
03801 return 0;
03802
03803 if (!(p->owner->nativeformats & p->jointcapability)) {
03804 const unsigned slen=512;
03805 char s1[slen], s2[slen];
03806 ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n",
03807 ast_getformatname_multiple(s1, slen, p->jointcapability),
03808 ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
03809 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1);
03810 ast_set_read_format(p->owner, p->owner->readformat);
03811 ast_set_write_format(p->owner, p->owner->writeformat);
03812 }
03813 if ((bridgepeer=ast_bridged_channel(p->owner))) {
03814
03815
03816 struct ast_frame af = { AST_FRAME_NULL, };
03817 if (sin.sin_addr.s_addr && !sendonly) {
03818 ast_moh_stop(bridgepeer);
03819
03820
03821 ast_queue_frame(p->owner, &af);
03822 } else {
03823
03824
03825 ast_moh_start(bridgepeer, NULL);
03826 if (sendonly)
03827 ast_rtp_stop(p->rtp);
03828
03829 ast_queue_frame(p->owner, &af);
03830 }
03831 }
03832
03833
03834 if (sin.sin_addr.s_addr && !sendonly) {
03835 append_history(p, "Unhold", req->data);
03836
03837 if (callevents && ast_test_flag(p, SIP_CALL_ONHOLD)) {
03838 manager_event(EVENT_FLAG_CALL, "Unhold",
03839 "Channel: %s\r\n"
03840 "Uniqueid: %s\r\n",
03841 p->owner->name,
03842 p->owner->uniqueid);
03843
03844 }
03845 ast_clear_flag(p, SIP_CALL_ONHOLD);
03846 } else {
03847
03848 append_history(p, "Hold", req->data);
03849
03850 if (callevents && !ast_test_flag(p, SIP_CALL_ONHOLD)) {
03851 manager_event(EVENT_FLAG_CALL, "Hold",
03852 "Channel: %s\r\n"
03853 "Uniqueid: %s\r\n",
03854 p->owner->name,
03855 p->owner->uniqueid);
03856 }
03857 ast_set_flag(p, SIP_CALL_ONHOLD);
03858 }
03859
03860 return 0;
03861 }
03862
03863
03864 static int add_header(struct sip_request *req, const char *var, const char *value)
03865 {
03866 int x = 0;
03867
03868 if (req->headers == SIP_MAX_HEADERS) {
03869 ast_log(LOG_WARNING, "Out of SIP header space\n");
03870 return -1;
03871 }
03872
03873 if (req->lines) {
03874 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
03875 return -1;
03876 }
03877
03878 if (req->len >= sizeof(req->data) - 4) {
03879 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
03880 return -1;
03881 }
03882
03883 req->header[req->headers] = req->data + req->len;
03884
03885 if (compactheaders) {
03886 for (x = 0; x < (sizeof(aliases) / sizeof(aliases[0])); x++)
03887 if (!strcasecmp(aliases[x].fullname, var))
03888 var = aliases[x].shortname;
03889 }
03890
03891 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
03892 req->len += strlen(req->header[req->headers]);
03893 req->headers++;
03894
03895 return 0;
03896 }
03897
03898
03899 static int add_header_contentLength(struct sip_request *req, int len)
03900 {
03901 char clen[10];
03902
03903 snprintf(clen, sizeof(clen), "%d", len);
03904 return add_header(req, "Content-Length", clen);
03905 }
03906
03907
03908 static int add_blank_header(struct sip_request *req)
03909 {
03910 if (req->headers == SIP_MAX_HEADERS) {
03911 ast_log(LOG_WARNING, "Out of SIP header space\n");
03912 return -1;
03913 }
03914 if (req->lines) {
03915 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
03916 return -1;
03917 }
03918 if (req->len >= sizeof(req->data) - 4) {
03919 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
03920 return -1;
03921 }
03922 req->header[req->headers] = req->data + req->len;
03923 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
03924 req->len += strlen(req->header[req->headers]);
03925 req->headers++;
03926 return 0;
03927 }
03928
03929
03930 static int add_line(struct sip_request *req, const char *line)
03931 {
03932 if (req->lines == SIP_MAX_LINES) {
03933 ast_log(LOG_WARNING, "Out of SIP line space\n");
03934 return -1;
03935 }
03936 if (!req->lines) {
03937
03938 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
03939 req->len += strlen(req->data + req->len);
03940 }
03941 if (req->len >= sizeof(req->data) - 4) {
03942 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
03943 return -1;
03944 }
03945 req->line[req->lines] = req->data + req->len;
03946 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
03947 req->len += strlen(req->line[req->lines]);
03948 req->lines++;
03949 return 0;
03950 }
03951
03952
03953 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
03954 {
03955 char *tmp;
03956 tmp = get_header(orig, field);
03957 if (!ast_strlen_zero(tmp)) {
03958
03959 return add_header(req, field, tmp);
03960 }
03961 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
03962 return -1;
03963 }
03964
03965
03966 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
03967 {
03968 char *tmp;
03969 int start = 0;
03970 int copied = 0;
03971 for (;;) {
03972 tmp = __get_header(orig, field, &start);
03973 if (!ast_strlen_zero(tmp)) {
03974
03975 add_header(req, field, tmp);
03976 copied++;
03977 } else
03978 break;
03979 }
03980 return copied ? 0 : -1;
03981 }
03982
03983
03984
03985
03986
03987
03988
03989 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
03990 {
03991 char tmp[256], *oh, *end;
03992 int start = 0;
03993 int copied = 0;
03994 char iabuf[INET_ADDRSTRLEN];
03995
03996 for (;;) {
03997 oh = __get_header(orig, field, &start);
03998 if (!ast_strlen_zero(oh)) {
03999 if (!copied) {
04000 char *rport;
04001 char new[256];
04002
04003
04004 rport = strstr(oh, ";rport");
04005 if (rport && *(rport+6) == '=')
04006 rport = NULL;
04007
04008 if (rport && ((ast_test_flag(p, SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(p, SIP_NAT) == SIP_NAT_RFC3581))) {
04009
04010 ast_copy_string(tmp, oh, sizeof(tmp));
04011
04012 rport = strstr(tmp, ";rport");
04013
04014 if (rport) {
04015 end = strchr(rport + 1, ';');
04016 if (end)
04017 memmove(rport, end, strlen(end) + 1);
04018 else
04019 *rport = '\0';
04020 }
04021
04022
04023
04024
04025
04026 snprintf(new, sizeof(new), "%s;received=%s;rport=%d", tmp, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
04027 } else {
04028
04029 snprintf(new, sizeof(new), "%s;received=%s", oh, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
04030 }
04031 add_header(req, field, new);
04032 } else {
04033
04034 add_header(req, field, oh);
04035 }
04036 copied++;
04037 } else
04038 break;
04039 }
04040 if (!copied) {
04041 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
04042 return -1;
04043 }
04044 return 0;
04045 }
04046
04047
04048 static void add_route(struct sip_request *req, struct sip_route *route)
04049 {
04050 char r[BUFSIZ*2], *p;
04051 int n, rem = sizeof(r);
04052
04053 if (!route) return;
04054
04055 p = r;
04056 while (route) {
04057 n = strlen(route->hop);
04058 if ((n+3)>rem) break;
04059 if (p != r) {
04060 *p++ = ',';
04061 --rem;
04062 }
04063 *p++ = '<';
04064 ast_copy_string(p, route->hop, rem); p += n;
04065 *p++ = '>';
04066 rem -= (n+2);
04067 route = route->next;
04068 }
04069 *p = '\0';
04070 add_header(req, "Route", r);
04071 }
04072
04073
04074 static void set_destination(struct sip_pvt *p, char *uri)
04075 {
04076 char *h, *maddr, hostname[256];
04077 char iabuf[INET_ADDRSTRLEN];
04078 int port, hn;
04079 struct hostent *hp;
04080 struct ast_hostent ahp;
04081 int debug=sip_debug_test_pvt(p);
04082
04083
04084
04085
04086 if (debug)
04087 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
04088
04089
04090 h = strchr(uri, '@');
04091 if (h)
04092 ++h;
04093 else {
04094 h = uri;
04095 if (strncasecmp(h, "sip:", 4) == 0)
04096 h += 4;
04097 else if (strncasecmp(h, "sips:", 5) == 0)
04098 h += 5;
04099 }
04100 hn = strcspn(h, ":;>") + 1;
04101 if (hn > sizeof(hostname))
04102 hn = sizeof(hostname);
04103 ast_copy_string(hostname, h, hn);
04104 h += hn - 1;
04105
04106
04107 if (*h == ':') {
04108
04109 ++h;
04110 port = strtol(h, &h, 10);
04111 }
04112 else
04113 port = DEFAULT_SIP_PORT;
04114
04115
04116 maddr = strstr(h, "maddr=");
04117 if (maddr) {
04118 maddr += 6;
04119 hn = strspn(maddr, "0123456789.") + 1;
04120 if (hn > sizeof(hostname)) hn = sizeof(hostname);
04121 ast_copy_string(hostname, maddr, hn);
04122 }
04123
04124 hp = ast_gethostbyname(hostname, &ahp);
04125 if (hp == NULL) {
04126 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
04127 return;
04128 }
04129 p->sa.sin_family = AF_INET;
04130 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
04131 p->sa.sin_port = htons(port);
04132 if (debug)
04133 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), port);
04134 }
04135
04136
04137 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
04138 {
04139
04140 if (req->headers || req->len) {
04141 ast_log(LOG_WARNING, "Request already initialized?!?\n");
04142 return -1;
04143 }
04144 req->method = SIP_RESPONSE;
04145 req->header[req->headers] = req->data + req->len;
04146 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
04147 req->len += strlen(req->header[req->headers]);
04148 req->headers++;
04149 return 0;
04150 }
04151
04152
04153 static int init_req(struct sip_request *req, int sipmethod, char *recip)
04154 {
04155
04156 if (req->headers || req->len) {
04157 ast_log(LOG_WARNING, "Request already initialized?!?\n");
04158 return -1;
04159 }
04160 req->header[req->headers] = req->data + req->len;
04161 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
04162 req->len += strlen(req->header[req->headers]);
04163 req->headers++;
04164 req->method = sipmethod;
04165 return 0;
04166 }
04167
04168
04169
04170 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
04171 {
04172 char newto[256], *ot;
04173
04174 memset(resp, 0, sizeof(*resp));
04175 init_resp(resp, msg, req);
04176 copy_via_headers(p, resp, req, "Via");
04177 if (msg[0] == '2')
04178 copy_all_header(resp, req, "Record-Route");
04179 copy_header(resp, req, "From");
04180 ot = get_header(req, "To");
04181 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
04182
04183
04184 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(p, SIP_OUTGOING))
04185 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
04186 else if (p->tag && !ast_test_flag(p, SIP_OUTGOING))
04187 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
04188 else {
04189 ast_copy_string(newto, ot, sizeof(newto));
04190 newto[sizeof(newto) - 1] = '\0';
04191 }
04192 ot = newto;
04193 }
04194 add_header(resp, "To", ot);
04195 copy_header(resp, req, "Call-ID");
04196 copy_header(resp, req, "CSeq");
04197 if (!ast_strlen_zero(default_useragent))
04198 add_header(resp, "User-Agent", default_useragent);
04199 add_header(resp, "Allow", ALLOWED_METHODS);
04200 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
04201
04202
04203 char tmp[256];
04204
04205 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
04206 add_header(resp, "Expires", tmp);
04207 if (p->expiry) {
04208 char contact[SIP_LEN_CONTACT];
04209 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
04210 add_header(resp, "Contact", contact);
04211 }
04212 } else if (msg[0] != '4' && p->our_contact[0]) {
04213 add_header(resp, "Contact", p->our_contact);
04214 }
04215 return 0;
04216 }
04217
04218
04219 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
04220 {
04221 struct sip_request *orig = &p->initreq;
04222 char stripped[80];
04223 char tmp[80];
04224 char newto[256];
04225 char *c, *n;
04226 char *ot, *of;
04227 int is_strict = 0;
04228
04229 memset(req, 0, sizeof(struct sip_request));
04230
04231 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
04232
04233 if (!seqno) {
04234 p->ocseq++;
04235 seqno = p->ocseq;
04236 }
04237
04238 if (newbranch) {
04239 p->branch ^= thread_safe_rand();
04240 build_via(p, p->via, sizeof(p->via));
04241 }
04242
04243
04244 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL)
04245 is_strict = 1;
04246
04247 if (sipmethod == SIP_CANCEL) {
04248 c = p->initreq.rlPart2;
04249 } else if (sipmethod == SIP_ACK) {
04250
04251
04252 if (!ast_strlen_zero(p->okcontacturi))
04253 c = is_strict ? p->route->hop : p->okcontacturi;
04254 else
04255 c = p->initreq.rlPart2;
04256 } else if (!ast_strlen_zero(p->okcontacturi)) {
04257 c = is_strict ? p->route->hop : p->okcontacturi;
04258 } else if (!ast_strlen_zero(p->uri)) {
04259 c = p->uri;
04260 } else {
04261
04262 c = get_header(orig, (ast_test_flag(p, SIP_OUTGOING)) ? "To" : "From");
04263 ast_copy_string(stripped, c, sizeof(stripped));
04264 c = get_in_brackets(stripped);
04265 n = strchr(c, ';');
04266 if (n)
04267 *n = '\0';
04268 }
04269 init_req(req, sipmethod, c);
04270
04271 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
04272
04273 add_header(req, "Via", p->via);
04274 if (p->route) {
04275 set_destination(p, p->route->hop);
04276 if (is_strict)
04277 add_route(req, p->route->next);
04278 else
04279 add_route(req, p->route);
04280 }
04281
04282 ot = get_header(orig, "To");
04283 of = get_header(orig, "From");
04284
04285
04286
04287 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
04288
04289
04290 if (ast_test_flag(p, SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
04291 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
04292 else if (!ast_test_flag(p, SIP_OUTGOING))
04293 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
04294 else
04295 snprintf(newto, sizeof(newto), "%s", ot);
04296 ot = newto;
04297 }
04298
04299 if (ast_test_flag(p, SIP_OUTGOING)) {
04300 add_header(req, "From", of);
04301 add_header(req, "To", ot);
04302 } else {
04303 add_header(req, "From", ot);
04304 add_header(req, "To", of);
04305 }
04306 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
04307 add_header(req, "Contact", p->our_contact);
04308 copy_header(req, orig, "Call-ID");
04309 add_header(req, "CSeq", tmp);
04310
04311 if (!ast_strlen_zero(default_useragent))
04312 add_header(req, "User-Agent", default_useragent);
04313 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
04314
04315 if (p->rpid)
04316 add_header(req, "Remote-Party-ID", p->rpid);
04317
04318 return 0;
04319 }
04320
04321
04322 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
04323 {
04324 struct sip_request resp;
04325 int seqno = 0;
04326
04327 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
04328 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
04329 return -1;
04330 }
04331 respprep(&resp, p, msg, req);
04332 add_header_contentLength(&resp, 0);
04333
04334
04335 if (msg[0] != '1' && p->owner && p->owner->hangupcause) {
04336 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
04337 }
04338 add_blank_header(&resp);
04339 return send_response(p, &resp, reliable, seqno);
04340 }
04341
04342
04343 static int transmit_response_using_temp(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, struct sip_request *req, char *msg)
04344 {
04345 struct sip_pvt *p = alloca(sizeof(*p));
04346 struct sip_history *hist = NULL;
04347
04348 memset(p, 0, sizeof(*p));
04349
04350 p->method = intended_method;
04351 if (sin) {
04352 p->sa = *sin;
04353 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
04354 p->ourip = __ourip;
04355 } else
04356 p->ourip = __ourip;
04357 p->branch = thread_safe_rand();
04358 make_our_tag(p->tag, sizeof(p->tag));
04359 p->ocseq = 101;
04360
04361 if (useglobal_nat && sin) {
04362 ast_copy_flags(p, &global_flags, SIP_NAT);
04363 memcpy(&p->recv, sin, sizeof(p->recv));
04364 }
04365
04366 ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
04367 build_via(p, p->via, sizeof(p->via));
04368 ast_copy_string(p->callid, callid, sizeof(p->callid));
04369
04370 __transmit_response(p, msg, req, 0);
04371
04372 while ((hist = p->history)) {
04373 p->history = p->history->next;
04374 free(hist);
04375 }
04376
04377 return 0;
04378 }
04379
04380
04381 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
04382 {
04383 return __transmit_response(p, msg, req, 0);
04384 }
04385
04386
04387 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported)
04388 {
04389 struct sip_request resp;
04390 respprep(&resp, p, msg, req);
04391 append_date(&resp);
04392 add_header(&resp, "Unsupported", unsupported);
04393 add_header_contentLength(&resp, 0);
04394 add_blank_header(&resp);
04395 return send_response(p, &resp, 0, 0);
04396 }
04397
04398
04399 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
04400 {
04401 return __transmit_response(p, msg, req, fatal ? 2 : 1);
04402 }
04403
04404
04405 static void append_date(struct sip_request *req)
04406 {
04407 char tmpdat[256];
04408 struct tm tm;
04409 time_t t;
04410
04411 time(&t);
04412 gmtime_r(&t, &tm);
04413 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
04414 add_header(req, "Date", tmpdat);
04415 }
04416
04417
04418 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
04419 {
04420 struct sip_request resp;
04421 respprep(&resp, p, msg, req);
04422 append_date(&resp);
04423 add_header_contentLength(&resp, 0);
04424 add_blank_header(&resp);
04425 return send_response(p, &resp, 0, 0);
04426 }
04427
04428
04429 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
04430 {
04431 struct sip_request resp;
04432 respprep(&resp, p, msg, req);
04433 add_header(&resp, "Accept", "application/sdp");
04434 add_header_contentLength(&resp, 0);
04435 add_blank_header(&resp);
04436 return send_response(p, &resp, reliable, 0);
04437 }
04438
04439
04440 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable, char *header, int stale)
04441 {
04442 struct sip_request resp;
04443 char tmp[512];
04444 int seqno = 0;
04445
04446 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
04447 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
04448 return -1;
04449 }
04450
04451
04452 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
04453 respprep(&resp, p, msg, req);
04454 add_header(&resp, header, tmp);
04455 add_header_contentLength(&resp, 0);
04456 add_blank_header(&resp);
04457 return send_response(p, &resp, reliable, seqno);
04458 }
04459
04460
04461 static int add_text(struct sip_request *req, const char *text)
04462 {
04463
04464 add_header(req, "Content-Type", "text/plain");
04465 add_header_contentLength(req, strlen(text));
04466 add_line(req, text);
04467 return 0;
04468 }
04469
04470
04471
04472 static int add_digit(struct sip_request *req, char digit)
04473 {
04474 char tmp[256];
04475
04476 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
04477 add_header(req, "Content-Type", "application/dtmf-relay");
04478 add_header_contentLength(req, strlen(tmp));
04479 add_line(req, tmp);
04480 return 0;
04481 }
04482
04483
04484
04485 static int add_vidupdate(struct sip_request *req)
04486 {
04487 const char *xml_is_a_huge_waste_of_space =
04488 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
04489 " <media_control>\r\n"
04490 " <vc_primitive>\r\n"
04491 " <to_encoder>\r\n"
04492 " <picture_fast_update>\r\n"
04493 " </picture_fast_update>\r\n"
04494 " </to_encoder>\r\n"
04495 " </vc_primitive>\r\n"
04496 " </media_control>\r\n";
04497 add_header(req, "Content-Type", "application/media_control+xml");
04498 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
04499 add_line(req, xml_is_a_huge_waste_of_space);
04500 return 0;
04501 }
04502
04503 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
04504 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
04505 int debug)
04506 {
04507 int rtp_code;
04508
04509 if (debug)
04510 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
04511 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
04512 return;
04513
04514 ast_build_string(m_buf, m_size, " %d", rtp_code);
04515 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
04516 ast_rtp_lookup_mime_subtype(1, codec),
04517 sample_rate);
04518 if (codec == AST_FORMAT_G729A)
04519
04520 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
04521 else if (codec == AST_FORMAT_G723_1)
04522
04523 ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
04524 }
04525
04526 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
04527 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
04528 int debug)
04529 {
04530 int rtp_code;
04531
04532 if (debug)
04533 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format));
04534 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
04535 return;
04536
04537 ast_build_string(m_buf, m_size, " %d", rtp_code);
04538 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
04539 ast_rtp_lookup_mime_subtype(0, format),
04540 sample_rate);
04541 if (format == AST_RTP_DTMF)
04542
04543 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
04544 }
04545
04546
04547 static int add_sdp(struct sip_request *resp, struct sip_pvt *p)
04548 {
04549 int len = 0;
04550 int pref_codec;
04551 int alreadysent = 0;
04552 struct sockaddr_in sin;
04553 struct sockaddr_in vsin;
04554 char v[256];
04555 char s[256];
04556 char o[256];
04557 char c[256];
04558 char t[256];
04559 char m_audio[256];
04560 char m_video[256];
04561 char a_audio[1024];
04562 char a_video[1024];
04563 char *m_audio_next = m_audio;
04564 char *m_video_next = m_video;
04565 size_t m_audio_left = sizeof(m_audio);
04566 size_t m_video_left = sizeof(m_video);
04567 char *a_audio_next = a_audio;
04568 char *a_video_next = a_video;
04569 size_t a_audio_left = sizeof(a_audio);
04570 size_t a_video_left = sizeof(a_video);
04571 char iabuf[INET_ADDRSTRLEN];
04572 int x;
04573 int capability;
04574 struct sockaddr_in dest;
04575 struct sockaddr_in vdest = { 0, };
04576 int debug;
04577
04578 debug = sip_debug_test_pvt(p);
04579
04580 len = 0;
04581 if (!p->rtp) {
04582 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
04583 return -1;
04584 }
04585 capability = p->jointcapability;
04586
04587 if (!p->sessionid) {
04588 p->sessionid = getpid();
04589 p->sessionversion = p->sessionid;
04590 } else
04591 p->sessionversion++;
04592 ast_rtp_get_us(p->rtp, &sin);
04593 if (p->vrtp)
04594 ast_rtp_get_us(p->vrtp, &vsin);
04595
04596 if (p->redirip.sin_addr.s_addr) {
04597 dest.sin_port = p->redirip.sin_port;
04598 dest.sin_addr = p->redirip.sin_addr;
04599 if (p->redircodecs)
04600 capability = p->redircodecs;
04601 } else {
04602 dest.sin_addr = p->ourip;
04603 dest.sin_port = sin.sin_port;
04604 }
04605
04606
04607 if (p->vrtp) {
04608 if (p->vredirip.sin_addr.s_addr) {
04609 vdest.sin_port = p->vredirip.sin_port;
04610 vdest.sin_addr = p->vredirip.sin_addr;
04611 } else {
04612 vdest.sin_addr = p->ourip;
04613 vdest.sin_port = vsin.sin_port;
04614 }
04615 }
04616 if (debug){
04617 ast_verbose("We're at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(sin.sin_port));
04618 if (p->vrtp)
04619 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(vsin.sin_port));
04620 }
04621
04622
04623
04624
04625 snprintf(v, sizeof(v), "v=0\r\n");
04626 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
04627 snprintf(s, sizeof(s), "s=session\r\n");
04628 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
04629 snprintf(t, sizeof(t), "t=0 0\r\n");
04630
04631 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
04632 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
04633
04634
04635 if (capability & p->prefcodec) {
04636 if (p->prefcodec <= AST_FORMAT_MAX_AUDIO)
04637 add_codec_to_sdp(p, p->prefcodec, 8000,
04638 &m_audio_next, &m_audio_left,
04639 &a_audio_next, &a_audio_left,
04640 debug);
04641 else
04642 add_codec_to_sdp(p, p->prefcodec, 90000,
04643 &m_video_next, &m_video_left,
04644 &a_video_next, &a_video_left,
04645 debug);
04646 alreadysent |= p->prefcodec;
04647 }
04648
04649
04650 for (x = 0; x < 32; x++) {
04651 if (!(pref_codec = ast_codec_pref_index(&p->prefs, x)))
04652 break;
04653
04654 if (!(capability & pref_codec))
04655 continue;
04656
04657 if (alreadysent & pref_codec)
04658 continue;
04659
04660 if (pref_codec <= AST_FORMAT_MAX_AUDIO)
04661 add_codec_to_sdp(p, pref_codec, 8000,
04662 &m_audio_next, &m_audio_left,
04663 &a_audio_next, &a_audio_left,
04664 debug);
04665 else
04666 add_codec_to_sdp(p, pref_codec, 90000,
04667 &m_video_next, &m_video_left,
04668 &a_video_next, &a_video_left,
04669 debug);
04670 alreadysent |= pref_codec;
04671 }
04672
04673
04674 for (x = 1; x <= ((videosupport && p->vrtp) ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
04675 if (!(capability & x))
04676 continue;
04677
04678 if (alreadysent & x)
04679 continue;
04680
04681 if (x <= AST_FORMAT_MAX_AUDIO)
04682 add_codec_to_sdp(p, x, 8000,
04683 &m_audio_next, &m_audio_left,
04684 &a_audio_next, &a_audio_left,
04685 debug);
04686 else
04687 add_codec_to_sdp(p, x, 90000,
04688 &m_video_next, &m_video_left,
04689 &a_video_next, &a_video_left,
04690 debug);
04691 }
04692
04693 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
04694 if (!(p->jointnoncodeccapability & x))
04695 continue;
04696
04697 add_noncodec_to_sdp(p, x, 8000,
04698 &m_audio_next, &m_audio_left,
04699 &a_audio_next, &a_audio_left,
04700 debug);
04701 }
04702
04703 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
04704
04705 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
04706 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
04707
04708 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
04709 ast_build_string(&m_video_next, &m_video_left, "\r\n");
04710
04711 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_audio) + strlen(a_audio);
04712 if ((p->vrtp) && (!ast_test_flag(p, SIP_NOVIDEO)) && (capability & VIDEO_CODEC_MASK))
04713 len += strlen(m_video) + strlen(a_video);
04714
04715 add_header(resp, "Content-Type", "application/sdp");
04716 add_header_contentLength(resp, len);
04717 add_line(resp, v);
04718 add_line(resp, o);
04719 add_line(resp, s);
04720 add_line(resp, c);
04721 add_line(resp, t);
04722 add_line(resp, m_audio);
04723 add_line(resp, a_audio);
04724 if ((p->vrtp) && (!ast_test_flag(p, SIP_NOVIDEO)) && (capability & VIDEO_CODEC_MASK)) {
04725 add_line(resp, m_video);
04726 add_line(resp, a_video);
04727 }
04728
04729
04730 time(&p->lastrtprx);
04731 time(&p->lastrtptx);
04732
04733 return 0;
04734 }
04735
04736
04737 static void copy_request(struct sip_request *dst, struct sip_request *src)
04738 {
04739 long offset;
04740 int x;
04741 offset = ((void *)dst) - ((void *)src);
04742
04743 memcpy(dst, src, sizeof(*dst));
04744
04745 for (x=0; x < src->headers; x++)
04746 dst->header[x] += offset;
04747 for (x=0; x < src->lines; x++)
04748 dst->line[x] += offset;
04749 dst->rlPart1 += offset;
04750 dst->rlPart2 += offset;
04751 }
04752
04753
04754 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
04755 {
04756 struct sip_request resp;
04757 int seqno;
04758 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
04759 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
04760 return -1;
04761 }
04762 respprep(&resp, p, msg, req);
04763 if (p->rtp) {
04764 ast_rtp_offered_from_local(p->rtp, 0);
04765 try_suggested_sip_codec(p);
04766 add_sdp(&resp, p);
04767 } else {
04768 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
04769 }
04770 return send_response(p, &resp, retrans, seqno);
04771 }
04772
04773
04774 static int determine_firstline_parts( struct sip_request *req )
04775 {
04776 char *e, *cmd;
04777 int len;
04778
04779 cmd = ast_skip_blanks(req->header[0]);
04780 if (!*cmd)
04781 return -1;
04782 req->rlPart1 = cmd;
04783 e = ast_skip_nonblanks(cmd);
04784
04785 if (*e)
04786 *e++ = '\0';
04787 e = ast_skip_blanks(e);
04788 if ( !*e )
04789 return -1;
04790
04791 if ( !strcasecmp(cmd, "SIP/2.0") ) {
04792
04793 req->rlPart2 = e;
04794 len = strlen( req->rlPart2 );
04795 if ( len < 2 ) {
04796 return -1;
04797 }
04798 ast_trim_blanks(e);
04799 } else {
04800
04801 if ( *e == '<' ) {
04802 e++;
04803 if ( !*e ) {
04804 return -1;
04805 }
04806 }
04807 req->rlPart2 = e;
04808 if ( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
04809 return -1;
04810 }
04811
04812 while( isspace( *(--e) ) ) {}
04813 if ( *e == '>' ) {
04814 *e = '\0';
04815 } else {
04816 *(++e)= '\0';
04817 }
04818 }
04819 return 1;
04820 }
04821
04822
04823
04824
04825
04826
04827
04828 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
04829 {
04830 struct sip_request req;
04831 if (ast_test_flag(p, SIP_REINVITE_UPDATE))
04832 reqprep(&req, p, SIP_UPDATE, 0, 1);
04833 else
04834 reqprep(&req, p, SIP_INVITE, 0, 1);
04835
04836 add_header(&req, "Allow", ALLOWED_METHODS);
04837 if (sipdebug)
04838 add_header(&req, "X-asterisk-info", "SIP re-invite (RTP bridge)");
04839 ast_rtp_offered_from_local(p->rtp, 1);
04840 add_sdp(&req, p);
04841
04842 copy_request(&p->initreq, &req);
04843 parse_request(&p->initreq);
04844 if (sip_debug_test_pvt(p))
04845 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
04846 p->lastinvite = p->ocseq;
04847 ast_set_flag(p, SIP_OUTGOING);
04848 return send_request(p, &req, 1, p->ocseq);
04849 }
04850
04851
04852 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
04853 {
04854 char stripped[256];
04855 char *c, *n;
04856 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
04857 c = get_in_brackets(stripped);
04858 n = strchr(c, ';');
04859 if (n)
04860 *n = '\0';
04861 if (!ast_strlen_zero(c))
04862 ast_copy_string(p->uri, c, sizeof(p->uri));
04863 }
04864
04865
04866 static void build_contact(struct sip_pvt *p)
04867 {
04868 char iabuf[INET_ADDRSTRLEN];
04869
04870
04871 if (ourport != 5060)
04872 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport);
04873 else
04874 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip));
04875 }
04876
04877
04878 static void build_rpid(struct sip_pvt *p)
04879 {
04880 int send_pres_tags = 1;
04881 const char *privacy = NULL;
04882 const char *screen = NULL;
04883 char buf[256];
04884 const char *clid = default_callerid;
04885 const char *clin = NULL;
04886 char iabuf[INET_ADDRSTRLEN];
04887 const char *fromdomain;
04888
04889 if (p->rpid || p->rpid_from)
04890 return;
04891
04892 if (p->owner && p->owner->cid.cid_num)
04893 clid = p->owner->cid.cid_num;
04894 if (p->owner && p->owner->cid.cid_name)
04895 clin = p->owner->cid.cid_name;
04896 if (ast_strlen_zero(clin))
04897 clin = clid;
04898
04899 switch (p->callingpres) {
04900 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
04901 privacy = "off";
04902 screen = "no";
04903 break;
04904 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
04905 privacy = "off";
04906 screen = "yes";
04907 break;
04908 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
04909 privacy = "off";
04910 screen = "no";
04911 break;
04912 case AST_PRES_ALLOWED_NETWORK_NUMBER:
04913 privacy = "off";
04914 screen = "yes";
04915 break;
04916 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
04917 privacy = "full";
04918 screen = "no";
04919 break;
04920 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
04921 privacy = "full";
04922 screen = "yes";
04923 break;
04924 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
04925 privacy = "full";
04926 screen = "no";
04927 break;
04928 case AST_PRES_PROHIB_NETWORK_NUMBER:
04929 privacy = "full";
04930 screen = "yes";
04931 break;
04932 case AST_PRES_NUMBER_NOT_AVAILABLE:
04933 send_pres_tags = 0;
04934 break;
04935 default:
04936 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
04937 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
04938 privacy = "full";
04939 else
04940 privacy = "off";
04941 screen = "no";
04942 break;
04943 }
04944
04945 fromdomain = ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain;
04946
04947 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
04948 if (send_pres_tags)
04949 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
04950 p->rpid = strdup(buf);
04951
04952 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>;tag=%s", clin,
04953 ast_strlen_zero(p->fromuser) ? clid : p->fromuser,
04954 fromdomain, p->tag);
04955 p->rpid_from = strdup(buf);
04956 }
04957
04958
04959 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
04960 {
04961 char invite_buf[256] = "";
04962 char *invite = invite_buf;
04963 size_t invite_max = sizeof(invite_buf);
04964 char from[256];
04965 char to[256];
04966 char tmp[BUFSIZ/2];
04967 char tmp2[BUFSIZ/2];
04968 char iabuf[INET_ADDRSTRLEN];
04969 char *l = NULL, *n = NULL;
04970 int x;
04971 char urioptions[256]="";
04972
04973 if (ast_test_flag(p, SIP_USEREQPHONE)) {
04974 char onlydigits = 1;
04975 x=0;
04976
04977
04978
04979
04980
04981
04982 if (p->username && p->username[0] == '+')
04983 x=1;
04984
04985 for (; x < strlen(p->username); x++) {
04986 if (!strchr(AST_DIGIT_ANYNUM, p->username[x])) {
04987 onlydigits = 0;
04988 break;
04989 }
04990 }
04991
04992
04993 if (onlydigits)
04994 strcpy(urioptions, ";user=phone");
04995 }
04996
04997
04998 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
04999
05000 if (p->owner) {
05001 l = p->owner->cid.cid_num;
05002 n = p->owner->cid.cid_name;
05003 }
05004
05005 if (!ast_test_flag(p, SIP_SENDRPID) && ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
05006 l = CALLERID_UNKNOWN;
05007 n = l;
05008 }
05009 if (ast_strlen_zero(l))
05010 l = default_callerid;
05011 if (ast_strlen_zero(n))
05012 n = l;
05013
05014 if (!ast_strlen_zero(p->fromuser))
05015 l = p->fromuser;
05016 else
05017 ast_copy_string(p->fromuser, l, sizeof(p->fromuser));
05018
05019
05020 if (!ast_strlen_zero(p->fromname))
05021 n = p->fromname;
05022 else
05023 ast_copy_string(p->fromname, n, sizeof(p->fromname));
05024
05025 if (pedanticsipchecking) {
05026 ast_uri_encode(n, tmp, sizeof(tmp), 0);
05027 n = tmp;
05028 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
05029 l = tmp2;
05030 }
05031
05032 if ((ourport != 5060) && ast_strlen_zero(p->fromdomain))
05033 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, ourport, p->tag);
05034 else
05035 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, p->tag);
05036
05037
05038 if (!ast_strlen_zero(p->fullcontact)) {
05039
05040 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
05041 } else {
05042
05043 ast_build_string(&invite, &invite_max, "sip:");
05044 if (!ast_strlen_zero(p->username)) {
05045 n = p->username;
05046 if (pedanticsipchecking) {
05047 ast_uri_encode(n, tmp, sizeof(tmp), 0);
05048 n = tmp;
05049 }
05050 ast_build_string(&invite, &invite_max, "%s@", n);
05051 }
05052 ast_build_string(&invite, &invite_max, "%s", p->tohost);
05053 if (ntohs(p->sa.sin_port) != 5060)
05054 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
05055 ast_build_string(&invite, &invite_max, "%s", urioptions);
05056 }
05057
05058
05059 if (p->options && p->options->uri_options)
05060 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
05061
05062 ast_copy_string(p->uri, invite_buf, sizeof(p->uri));
05063
05064 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
05065
05066 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", p->uri, p->theirtag);
05067 } else if (p->options && p->options->vxml_url) {
05068
05069 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
05070 } else {
05071 snprintf(to, sizeof(to), "<%s>", p->uri);
05072 }
05073
05074 memset(req, 0, sizeof(struct sip_request));
05075 init_req(req, sipmethod, p->uri);
05076 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
05077
05078 add_header(req, "Via", p->via);
05079
05080
05081
05082 if (ast_test_flag(p, SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
05083 build_rpid(p);
05084 add_header(req, "From", p->rpid_from);
05085 } else {
05086 add_header(req, "From", from);
05087 }
05088 add_header(req, "To", to);
05089 ast_copy_string(p->exten, l, sizeof(p->exten));
05090 build_contact(p);
05091 add_header(req, "Contact", p->our_contact);
05092 add_header(req, "Call-ID", p->callid);
05093 add_header(req, "CSeq", tmp);
05094 if (!ast_strlen_zero(default_useragent))
05095 add_header(req, "User-Agent", default_useragent);
05096 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
05097 if (p->rpid)
05098 add_header(req, "Remote-Party-ID", p->rpid);
05099 }
05100
05101
05102 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
05103 {
05104 struct sip_request req;
05105
05106 req.method = sipmethod;
05107 if (init) {
05108
05109 p->branch ^= thread_safe_rand();
05110 build_via(p, p->via, sizeof(p->via));
05111 if (init > 1)
05112 initreqprep(&req, p, sipmethod);
05113 else
05114 reqprep(&req, p, sipmethod, 0, 1);
05115 } else
05116 reqprep(&req, p, sipmethod, 0, 1);
05117
05118 if (p->options && p->options->auth)
05119 add_header(&req, p->options->authheader, p->options->auth);
05120 append_date(&req);
05121 if (sipmethod == SIP_REFER) {
05122 if (!ast_strlen_zero(p->refer_to))
05123 add_header(&req, "Refer-To", p->refer_to);
05124 if (!ast_strlen_zero(p->referred_by))
05125 add_header(&req, "Referred-By", p->referred_by);
05126 }
05127 #ifdef OSP_SUPPORT
05128 if ((req.method != SIP_OPTIONS) && p->options && !ast_strlen_zero(p->options->osptoken)) {
05129 ast_log(LOG_DEBUG,"Adding OSP Token: %s\n", p->options->osptoken);
05130 add_header(&req, "P-OSP-Auth-Token", p->options->osptoken);
05131 }
05132 #endif
05133 if (p->options && !ast_strlen_zero(p->options->distinctive_ring))
05134 {
05135 add_header(&req, "Alert-Info", p->options->distinctive_ring);
05136 }
05137 add_header(&req, "Allow", ALLOWED_METHODS);
05138 if (p->options && p->options->addsipheaders ) {
05139 struct ast_channel *ast;
05140 char *header = (char *) NULL;
05141 char *content = (char *) NULL;
05142 char *end = (char *) NULL;
05143 struct varshead *headp = (struct varshead *) NULL;
05144 struct ast_var_t *current;
05145
05146 ast = p->owner;
05147 if (ast) {
05148 char *headdup;
05149 headp = &ast->varshead;
05150 if (!headp)
05151 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
05152 else {
05153 AST_LIST_TRAVERSE(headp, current, entries) {
05154
05155 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05156 header = ast_var_value(current);
05157 headdup = ast_strdupa(header);
05158
05159 if (*headdup == '"')
05160 headdup++;
05161 if ((content = strchr(headdup, ':'))) {
05162 *content = '\0';
05163 content++;
05164
05165 while (*content == ' ')
05166 content++;
05167
05168 end = content + strlen(content) -1;
05169 if (*end == '"')
05170 *end = '\0';
05171
05172 add_header(&req, headdup, content);
05173 if (sipdebug)
05174 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
05175 }
05176 }
05177 }
05178 }
05179 }
05180 }
05181 if (sdp && p->rtp) {
05182 ast_rtp_offered_from_local(p->rtp, 1);
05183 add_sdp(&req, p);
05184 } else {
05185 add_header_contentLength(&req, 0);
05186 add_blank_header(&req);
05187 }
05188
05189 if (!p->initreq.headers) {
05190
05191 copy_request(&p->initreq, &req);
05192 parse_request(&p->initreq);
05193 if (sip_debug_test_pvt(p))
05194 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
05195 }
05196 p->lastinvite = p->ocseq;
05197 return send_request(p, &req, init ? 2 : 1, p->ocseq);
05198 }
05199
05200
05201 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate, int timeout)
05202 {
05203 char tmp[4000], from[256], to[256];
05204 char *t = tmp, *c, *a, *mfrom, *mto;
05205 size_t maxbytes = sizeof(tmp);
05206 struct sip_request req;
05207 char hint[AST_MAX_EXTENSION];
05208 char *statestring = "terminated";
05209 const struct cfsubscription_types *subscriptiontype;
05210 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
05211 char *pidfstate = "--";
05212 char *pidfnote= "Ready";
05213
05214 memset(from, 0, sizeof(from));
05215 memset(to, 0, sizeof(to));
05216 memset(tmp, 0, sizeof(tmp));
05217
05218 switch (state) {
05219 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
05220 if (global_notifyringing)
05221 statestring = "early";
05222 else
05223 statestring = "confirmed";
05224 local_state = NOTIFY_INUSE;
05225 pidfstate = "busy";
05226 pidfnote = "Ringing";
05227 break;
05228 case AST_EXTENSION_RINGING:
05229 statestring = "early";
05230 local_state = NOTIFY_INUSE;
05231 pidfstate = "busy";
05232 pidfnote = "Ringing";
05233 break;
05234 case AST_EXTENSION_INUSE:
05235 statestring = "confirmed";
05236 local_state = NOTIFY_INUSE;
05237 pidfstate = "busy";
05238 pidfnote = "On the phone";
05239 break;
05240 case AST_EXTENSION_BUSY:
05241 statestring = "confirmed";
05242 local_state = NOTIFY_CLOSED;
05243 pidfstate = "busy";
05244 pidfnote = "On the phone";
05245 break;
05246 case AST_EXTENSION_UNAVAILABLE:
05247 statestring = "confirmed";
05248 local_state = NOTIFY_CLOSED;
05249 pidfstate = "away";
05250 pidfnote = "Unavailable";
05251 break;
05252 case AST_EXTENSION_NOT_INUSE:
05253 default:
05254
05255 break;
05256 }
05257
05258 subscriptiontype = find_subscription_type(p->subscribed);
05259
05260
05261 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
05262 char *hint2 = hint, *individual_hint = NULL;
05263 while ((individual_hint = strsep(&hint2, "&"))) {
05264
05265 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE) {
05266 local_state = NOTIFY_CLOSED;
05267 pidfstate = "away";
05268 pidfnote = "Not online";
05269 }
05270 }
05271 }
05272
05273 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
05274 c = get_in_brackets(from);
05275 if (strncasecmp(c, "sip:", 4)) {
05276 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
05277 return -1;
05278 }
05279 if ((a = strchr(c, ';')))
05280 *a = '\0';
05281 mfrom = c;
05282
05283 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
05284 c = get_in_brackets(to);
05285 if (strncasecmp(c, "sip:", 4)) {
05286 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
05287 return -1;
05288 }
05289 if ((a = strchr(c, ';')))
05290 *a = '\0';
05291 mto = c;
05292
05293 reqprep(&req, p, SIP_NOTIFY, 0, 1);
05294
05295
05296 add_header(&req, "Event", subscriptiontype->event);
05297 add_header(&req, "Content-Type", subscriptiontype->mediatype);
05298 switch(state) {
05299 case AST_EXTENSION_DEACTIVATED:
05300 if (timeout)
05301 add_header(&req, "Subscription-State", "terminated;reason=timeout");
05302 else {
05303 add_header(&req, "Subscription-State", "terminated;reason=probation");
05304 add_header(&req, "Retry-After", "60");
05305 }
05306 break;
05307 case AST_EXTENSION_REMOVED:
05308 add_header(&req, "Subscription-State", "terminated;reason=noresource");
05309 break;
05310 break;
05311 default:
05312 if (p->expiry)
05313 add_header(&req, "Subscription-State", "active");
05314 else
05315 add_header(&req, "Subscription-State", "terminated;reason=timeout");
05316 }
05317 switch (p->subscribed) {
05318 case XPIDF_XML:
05319 case CPIM_PIDF_XML:
05320 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
05321 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
05322 ast_build_string(&t, &maxbytes, "<presence>\n");
05323 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
05324 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
05325 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
05326 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
05327 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
05328 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
05329 break;
05330 case PIDF_XML:
05331 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
05332 ast_build_string(&t, &maxbytes, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
05333 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
05334 if (pidfstate[0] != '-')
05335 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
05336 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
05337 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote);
05338 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten);
05339 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
05340 if (pidfstate[0] == 'b')
05341 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
05342 else
05343 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
05344 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
05345 break;
05346 case DIALOG_INFO_XML:
05347 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
05348 ast_build_string(&t, &maxbytes, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
05349 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
05350 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
05351 else
05352 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
05353 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
05354 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
05355 break;
05356 case NONE:
05357 default:
05358 break;
05359 }
05360
05361 if (t > tmp + sizeof(tmp))
05362 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
05363
05364 add_header_contentLength(&req, strlen(tmp));
05365 add_line(&req, tmp);
05366
05367 return send_request(p, &req, 1, p->ocseq);
05368 }
05369
05370
05371
05372
05373
05374
05375
05376 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
05377 {
05378 struct sip_request req;
05379 char tmp[500];
05380 char *t = tmp;
05381 size_t maxbytes = sizeof(tmp);
05382 char iabuf[INET_ADDRSTRLEN];
05383
05384 initreqprep(&req, p, SIP_NOTIFY);
05385 add_header(&req, "Event", "message-summary");
05386 add_header(&req, "Content-Type", default_notifymime);
05387
05388 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
05389 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n", !ast_strlen_zero(vmexten) ? vmexten : global_vmexten, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain);
05390 ast_build_string(&t, &maxbytes, "Voice-Message: %d/%d (0/0)\r\n", newmsgs, oldmsgs);
05391
05392 if (t > tmp + sizeof(tmp))
05393 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
05394
05395 add_header_contentLength(&req, strlen(tmp));
05396 add_line(&req, tmp);
05397
05398 if (!p->initreq.headers) {
05399 copy_request(&p->initreq, &req);
05400 parse_request(&p->initreq);
05401 if (sip_debug_test_pvt(p))
05402 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
05403 determine_firstline_parts(&p->initreq);
05404 }
05405
05406 return send_request(p, &req, 1, p->ocseq);
05407 }
05408
05409
05410 static int transmit_sip_request(struct sip_pvt *p,struct sip_request *req)
05411 {
05412 if (!p->initreq.headers) {
05413
05414 copy_request(&p->initreq, req);
05415 parse_request(&p->initreq);
05416 if (sip_debug_test_pvt(p))
05417 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
05418 determine_firstline_parts(&p->initreq);
05419 }
05420
05421 return send_request(p, req, 0, p->ocseq);
05422 }
05423
05424
05425
05426
05427
05428
05429 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq)
05430 {
05431 struct sip_request req;
05432 char tmp[20];
05433 reqprep(&req, p, SIP_NOTIFY, 0, 1);
05434 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
05435 add_header(&req, "Event", tmp);
05436 add_header(&req, "Subscription-state", "terminated;reason=noresource");
05437 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
05438
05439 strcpy(tmp, "SIP/2.0 200 OK\r\n");
05440 add_header_contentLength(&req, strlen(tmp));
05441 add_line(&req, tmp);
05442
05443 if (!p->initreq.headers) {
05444
05445 copy_request(&p->initreq, &req);
05446 parse_request(&p->initreq);
05447 if (sip_debug_test_pvt(p))
05448 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
05449 determine_firstline_parts(&p->initreq);
05450 }
05451
05452 return send_request(p, &req, 1, p->ocseq);
05453 }
05454
05455 static char *regstate2str(int regstate)
05456 {
05457 switch(regstate) {
05458 case REG_STATE_FAILED:
05459 return "Failed";
05460 case REG_STATE_UNREGISTERED:
05461 return "Unregistered";
05462 case REG_STATE_REGSENT:
05463 return "Request Sent";
05464 case REG_STATE_AUTHSENT:
05465 return "Auth. Sent";
05466 case REG_STATE_REGISTERED:
05467 return "Registered";
05468 case REG_STATE_REJECTED:
05469 return "Rejected";
05470 case REG_STATE_TIMEOUT:
05471 return "Timeout";
05472 case REG_STATE_NOAUTH:
05473 return "No Authentication";
05474 default:
05475 return "Unknown";
05476 }
05477 }
05478
05479 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
05480
05481
05482 static int sip_reregister(void *data)
05483 {
05484
05485 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
05486
05487
05488 if (!r)
05489 return 0;
05490
05491 if (r->call && recordhistory) {
05492 char tmp[80];
05493 snprintf(tmp, sizeof(tmp), "Account: %s@%s", r->username, r->hostname);
05494 append_history(r->call, "RegistryRenew", tmp);
05495 }
05496
05497
05498 if (sipdebug)
05499 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
05500
05501 r->expire = -1;
05502 __sip_do_register(r);
05503 ASTOBJ_UNREF(r, sip_registry_destroy);
05504 return 0;
05505 }
05506
05507
05508 static int __sip_do_register(struct sip_registry *r)
05509 {
05510 int res;
05511
05512 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
05513 return res;
05514 }
05515
05516
05517 static int sip_reg_timeout(void *data)
05518 {
05519
05520
05521 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
05522 struct sip_pvt *p;
05523 int res;
05524
05525
05526 if (!r)
05527 return 0;
05528
05529 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
05530 if (r->call) {
05531
05532
05533 p = r->call;
05534 if (p->registry)
05535 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
05536 r->call = NULL;
05537 ast_set_flag(p, SIP_NEEDDESTROY);
05538
05539 __sip_pretend_ack(p);
05540 }
05541
05542 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
05543
05544
05545
05546 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
05547 r->regstate=REG_STATE_FAILED;
05548 } else {
05549 r->regstate=REG_STATE_UNREGISTERED;
05550 r->timeout = -1;
05551 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
05552 }
05553 manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
05554 ASTOBJ_UNREF(r,sip_registry_destroy);
05555 return 0;
05556 }
05557
05558
05559 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader)
05560 {
05561 struct sip_request req;
05562 char from[256];
05563 char to[256];
05564 char tmp[80];
05565 char via[80];
05566 char addr[80];
05567 struct sip_pvt *p;
05568
05569
05570 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
05571 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
05572 return 0;
05573 }
05574
05575 if (r->call) {
05576 if (!auth) {
05577 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
05578 return 0;
05579 } else {
05580 p = r->call;
05581 make_our_tag(p->tag, sizeof(p->tag));
05582 p->theirtag[0]='\0';
05583 }
05584 } else {
05585
05586 if (!r->callid_valid) {
05587 build_callid(r->callid, sizeof(r->callid), __ourip, default_fromdomain);
05588 r->callid_valid = 1;
05589 }
05590
05591 p=sip_alloc( r->callid, NULL, 0, SIP_REGISTER);
05592 if (!p) {
05593 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
05594 return 0;
05595 }
05596 if (recordhistory) {
05597 char tmp[80];
05598 snprintf(tmp, sizeof(tmp), "Account: %s@%s", r->username, r->hostname);
05599 append_history(p, "RegistryInit", tmp);
05600 }
05601
05602 if (create_addr(p, r->hostname)) {
05603
05604
05605 sip_destroy(p);
05606 if (r->timeout > -1) {
05607 ast_sched_del(sched, r->timeout);
05608 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
05609 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
05610 } else {
05611 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
05612 ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
05613 }
05614 r->regattempts++;
05615 return 0;
05616 }
05617
05618 ast_copy_string(r->callid, p->callid, sizeof(r->callid));
05619 if (r->portno)
05620 p->sa.sin_port = htons(r->portno);
05621 else
05622 r->portno = ntohs(p->sa.sin_port);
05623 ast_set_flag(p, SIP_OUTGOING);
05624 r->call=p;
05625 p->registry=ASTOBJ_REF(r);
05626 if (!ast_strlen_zero(r->secret))
05627 ast_copy_string(p->peersecret, r->secret, sizeof(p->peersecret));
05628 if (!ast_strlen_zero(r->md5secret))
05629 ast_copy_string(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret));
05630
05631
05632 if (!ast_strlen_zero(r->authuser)) {
05633 ast_copy_string(p->peername, r->authuser, sizeof(p->peername));
05634 ast_copy_string(p->authname, r->authuser, sizeof(p->authname));
05635 } else {
05636 if (!ast_strlen_zero(r->username)) {
05637 ast_copy_string(p->peername, r->username, sizeof(p->peername));
05638 ast_copy_string(p->authname, r->username, sizeof(p->authname));
05639 ast_copy_string(p->fromuser, r->username, sizeof(p->fromuser));
05640 }
05641 }
05642 if (!ast_strlen_zero(r->username))
05643 ast_copy_string(p->username, r->username, sizeof(p->username));
05644
05645 ast_copy_string(p->exten, r->contact, sizeof(p->exten));
05646
05647
05648
05649
05650
05651
05652 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
05653 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
05654 build_contact(p);
05655 }
05656
05657
05658 if (auth == NULL) {
05659 if (r->timeout > -1) {
05660 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
05661 ast_sched_del(sched, r->timeout);
05662 }
05663 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
05664 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
05665 }
05666
05667 if (strchr(r->username, '@')) {
05668 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
05669 if (!ast_strlen_zero(p->theirtag))
05670 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
05671 else
05672 snprintf(to, sizeof(to), "<sip:%s>", r->username);
05673 } else {
05674 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
05675 if (!ast_strlen_zero(p->theirtag))
05676 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
05677 else
05678 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
05679 }
05680
05681
05682
05683 if (!ast_strlen_zero(p->fromdomain)) {
05684 if (r->portno && r->portno != DEFAULT_SIP_PORT)
05685 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
05686 else
05687 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
05688 } else {
05689 if (r->portno && r->portno != DEFAULT_SIP_PORT)
05690 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
05691 else
05692 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
05693 }
05694 ast_copy_string(p->uri, addr, sizeof(p->uri));
05695
05696 p->branch ^= thread_safe_rand();
05697
05698 memset(&req, 0, sizeof(req));
05699 init_req(&req, sipmethod, addr);
05700
05701
05702 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
05703 p->ocseq = r->ocseq;
05704
05705 build_via(p, via, sizeof(via));
05706 add_header(&req, "Via", via);
05707 add_header(&req, "From", from);
05708 add_header(&req, "To", to);
05709 add_header(&req, "Call-ID", p->callid);
05710 add_header(&req, "CSeq", tmp);
05711 if (!ast_strlen_zero(default_useragent))
05712 add_header(&req, "User-Agent", default_useragent);
05713 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
05714
05715
05716 if (auth)
05717 add_header(&req, authheader, auth);
05718 else if (!ast_strlen_zero(r->nonce)) {
05719 char digest[1024];
05720
05721
05722 if (sipdebug)
05723 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
05724 ast_copy_string(p->realm, r->realm, sizeof(p->realm));
05725 ast_copy_string(p->nonce, r->nonce, sizeof(p->nonce));
05726 ast_copy_string(p->domain, r->domain, sizeof(p->domain));
05727 ast_copy_string(p->opaque, r->opaque, sizeof(p->opaque));
05728 ast_copy_string(p->qop, r->qop, sizeof(p->qop));
05729 r->noncecount++;
05730 p->noncecount = r->noncecount;
05731
05732 memset(digest,0,sizeof(digest));
05733 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
05734 add_header(&req, "Authorization", digest);
05735 else
05736 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
05737
05738 }
05739
05740 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
05741 add_header(&req, "Expires", tmp);
05742 add_header(&req, "Contact", p->our_contact);
05743 add_header(&req, "Event", "registration");
05744 add_header_contentLength(&req, 0);
05745 add_blank_header(&req);
05746 copy_request(&p->initreq, &req);
05747 parse_request(&p->initreq);
05748 if (sip_debug_test_pvt(p)) {
05749 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
05750 }
05751 determine_firstline_parts(&p->initreq);
05752 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
05753 r->regattempts++;
05754 if (option_debug > 3)
05755 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
05756 return send_request(p, &req, 2, p->ocseq);
05757 }
05758
05759
05760 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
05761 {
05762 struct sip_request req;
05763 reqprep(&req, p, SIP_MESSAGE, 0, 1);
05764 add_text(&req, text);
05765 return send_request(p, &req, 1, p->ocseq);
05766 }
05767
05768
05769 static int transmit_refer(struct sip_pvt *p, const char *dest)
05770 {
05771 struct sip_request req;
05772 char from[256];
05773 char *of, *c;
05774 char referto[256];
05775
05776 if (ast_test_flag(p, SIP_OUTGOING))
05777 of = get_header(&p->initreq, "To");
05778 else
05779 of = get_header(&p->initreq, "From");
05780 ast_copy_string(from, of, sizeof(from));
05781 of = get_in_brackets(from);
05782 ast_copy_string(p->from,of,sizeof(p->from));
05783 if (strncasecmp(of, "sip:", 4)) {
05784 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
05785 } else
05786 of += 4;
05787
05788 if ((c = strchr(dest, '@'))) {
05789 c = NULL;
05790 } else if ((c = strchr(of, '@'))) {
05791 *c = '\0';
05792 c++;
05793 }
05794 if (c) {
05795 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
05796 } else {
05797 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
05798 }
05799
05800
05801 ast_copy_string(p->refer_to, referto, sizeof(p->refer_to));
05802 ast_copy_string(p->referred_by, p->our_contact, sizeof(p->referred_by));
05803
05804 reqprep(&req, p, SIP_REFER, 0, 1);
05805 add_header(&req, "Refer-To", referto);
05806 if (!ast_strlen_zero(p->our_contact))
05807 add_header(&req, "Referred-By", p->our_contact);
05808 add_blank_header(&req);
05809 return send_request(p, &req, 1, p->ocseq);
05810 }
05811
05812
05813
05814 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
05815 {
05816 struct sip_request req;
05817 reqprep(&req, p, SIP_INFO, 0, 1);
05818 add_digit(&req, digit);
05819 return send_request(p, &req, 1, p->ocseq);
05820 }
05821
05822
05823 static int transmit_info_with_vidupdate(struct sip_pvt *p)
05824 {
05825 struct sip_request req;
05826 reqprep(&req, p, SIP_INFO, 0, 1);
05827 add_vidupdate(&req);
05828 return send_request(p, &req, 1, p->ocseq);
05829 }
05830
05831
05832 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, int reliable, int newbranch)
05833 {
05834 struct sip_request resp;
05835 reqprep(&resp, p, sipmethod, seqno, newbranch);
05836 add_header_contentLength(&resp, 0);
05837 add_blank_header(&resp);
05838 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
05839 }
05840
05841
05842 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, int reliable, int newbranch)
05843 {
05844 struct sip_request resp;
05845
05846 reqprep(&resp, p, sipmethod, seqno, newbranch);
05847 if (*p->realm) {
05848 char digest[1024];
05849
05850 memset(digest, 0, sizeof(digest));
05851 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
05852 if (p->options && p->options->auth_type == PROXY_AUTH)
05853 add_header(&resp, "Proxy-Authorization", digest);
05854 else if (p->options && p->options->auth_type == WWW_AUTH)
05855 add_header(&resp, "Authorization", digest);
05856 else
05857 add_header(&resp, "Proxy-Authorization", digest);
05858 } else
05859 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
05860 }
05861
05862
05863 if (sipmethod == SIP_BYE) {
05864 if (p->owner && p->owner->hangupcause) {
05865 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
05866 }
05867 }
05868
05869 add_header_contentLength(&resp, 0);
05870 add_blank_header(&resp);
05871 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
05872 }
05873
05874 static void destroy_association(struct sip_peer *peer)
05875 {
05876 if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_IGNOREREGEXPIRE)) {
05877 if (ast_test_flag(&(peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT)) {
05878 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", NULL);
05879 } else {
05880 ast_db_del("SIP/Registry", peer->name);
05881 }
05882 }
05883 }
05884
05885
05886 static int expire_register(void *data)
05887 {
05888 struct sip_peer *peer = data;
05889
05890 if (!peer)
05891 return 0;
05892
05893 memset(&peer->addr, 0, sizeof(peer->addr));
05894
05895 destroy_association(peer);
05896
05897 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
05898 register_peer_exten(peer, 0);
05899 peer->expire = -1;
05900 ast_device_state_changed("SIP/%s", peer->name);
05901
05902
05903
05904
05905 if (ast_test_flag(peer, SIP_SELFDESTRUCT) || ast_test_flag((&peer->flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
05906 peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
05907 ASTOBJ_UNREF(peer, sip_destroy_peer);
05908 }
05909
05910 return 0;
05911 }
05912
05913 static int sip_poke_peer(struct sip_peer *peer);
05914
05915 static int sip_poke_peer_s(void *data)
05916 {
05917 struct sip_peer *peer = data;
05918 peer->pokeexpire = -1;
05919 sip_poke_peer(peer);
05920 return 0;
05921 }
05922
05923
05924 static void reg_source_db(struct sip_peer *peer)
05925 {
05926 char data[256];
05927 char iabuf[INET_ADDRSTRLEN];
05928 struct in_addr in;
05929 int expiry;
05930 int port;
05931 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
05932
05933 if (ast_test_flag(&(peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT))
05934 return;
05935 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
05936 return;
05937
05938 scan = data;
05939 addr = strsep(&scan, ":");
05940 port_str = strsep(&scan, ":");
05941 expiry_str = strsep(&scan, ":");
05942 username = strsep(&scan, ":");
05943 contact = scan;
05944
05945 if (!inet_aton(addr, &in))
05946 return;
05947
05948 if (port_str)
05949 port = atoi(port_str);
05950 else
05951 return;
05952
05953 if (expiry_str)
05954 expiry = atoi(expiry_str);
05955 else
05956 return;
05957
05958 if (username)
05959 ast_copy_string(peer->username, username, sizeof(peer->username));
05960 if (contact)
05961 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
05962
05963 if (option_verbose > 2)
05964 ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
05965 peer->name, peer->username, ast_inet_ntoa(iabuf, sizeof(iabuf), in), port, expiry);
05966
05967 memset(&peer->addr, 0, sizeof(peer->addr));
05968 peer->addr.sin_family = AF_INET;
05969 peer->addr.sin_addr = in;
05970 peer->addr.sin_port = htons(port);
05971 if (sipsock < 0) {
05972
05973 if (peer->pokeexpire > -1)
05974 ast_sched_del(sched, peer->pokeexpire);
05975 peer->pokeexpire = ast_sched_add(sched, thread_safe_rand() % 5000 + 1, sip_poke_peer_s, peer);
05976 } else
05977 sip_poke_peer(peer);
05978 if (peer->expire > -1)
05979 ast_sched_del(sched, peer->expire);
05980 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
05981 register_peer_exten(peer, 1);
05982 }
05983
05984
05985 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
05986 {
05987 char contact[SIP_LEN_CONTACT];
05988 char *c, *n, *pt;
05989 int port;
05990 struct hostent *hp;
05991 struct ast_hostent ahp;
05992 struct sockaddr_in oldsin;
05993
05994
05995 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
05996 c = get_in_brackets(contact);
05997
05998
05999 ast_copy_string(pvt->fullcontact, c, sizeof(pvt->fullcontact));
06000
06001
06002 ast_copy_string(pvt->okcontacturi, c, sizeof(pvt->okcontacturi));
06003
06004
06005 if (strncasecmp(c, "sip:", 4)) {
06006 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
06007 } else
06008 c += 4;
06009
06010
06011 n = strchr(c, ';');
06012 if (n)
06013 *n = '\0';
06014
06015
06016 n = strchr(c, '@');
06017 if (!n) {
06018 n = c;
06019 c = NULL;
06020 } else {
06021 *n = '\0';
06022 n++;
06023 }
06024 pt = strchr(n, ':');
06025 if (pt) {
06026 *pt = '\0';
06027 pt++;
06028 port = atoi(pt);
06029 } else
06030 port = DEFAULT_SIP_PORT;
06031
06032 memcpy(&oldsin, &pvt->sa, sizeof(oldsin));
06033
06034 if (!(ast_test_flag(pvt, SIP_NAT) & SIP_NAT_ROUTE)) {
06035
06036
06037 hp = ast_gethostbyname(n, &ahp);
06038 if (!hp) {
06039 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
06040 return -1;
06041 }
06042 pvt->sa.sin_family = AF_INET;
06043 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
06044 pvt->sa.sin_port = htons(port);
06045 } else {
06046
06047
06048 memcpy(&pvt->sa, &pvt->recv, sizeof(pvt->sa));
06049 }
06050 return 0;
06051 }
06052
06053
06054 enum parse_register_result {
06055 PARSE_REGISTER_FAILED,
06056 PARSE_REGISTER_UPDATE,
06057 PARSE_REGISTER_QUERY,
06058 };
06059
06060
06061 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
06062 {
06063 char contact[BUFSIZ];
06064 char data[BUFSIZ];
06065 char iabuf[INET_ADDRSTRLEN];
06066 char *expires = get_header(req, "Expires");
06067 int expiry = atoi(expires);
06068 char *c, *n, *pt;
06069 int port;
06070 char *useragent;
06071 struct hostent *hp;
06072 struct ast_hostent ahp;
06073 struct sockaddr_in oldsin;
06074
06075 if (ast_strlen_zero(expires)) {
06076 expires = strcasestr(get_header(req, "Contact"), ";expires=");
06077 if (expires) {
06078 char *ptr;
06079 if ((ptr = strchr(expires, ';')))
06080 *ptr = '\0';
06081 if (sscanf(expires + 9, "%30d", &expiry) != 1)
06082 expiry = default_expiry;
06083 } else {
06084
06085 expiry = default_expiry;
06086 }
06087 }
06088
06089 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
06090 if (strchr(contact, '<') == NULL) {
06091 char *ptr = strchr(contact, ';');
06092 if (ptr)
06093 *ptr = '\0';
06094 }
06095 c = get_in_brackets(contact);
06096
06097
06098
06099
06100
06101 if (ast_strlen_zero(c) && ast_strlen_zero(expires)) {
06102
06103 if ((p->expire > -1) && !ast_strlen_zero(p->fullcontact)) {
06104 pvt->expiry = ast_sched_when(sched, p->expire);
06105 }
06106 return PARSE_REGISTER_QUERY;
06107 } else if (!strcasecmp(c, "*") || !expiry) {
06108
06109 memset(&p->addr, 0, sizeof(p->addr));
06110 if (p->expire > -1)
06111 ast_sched_del(sched, p->expire);
06112 p->expire = -1;
06113
06114 destroy_association(p);
06115
06116 register_peer_exten(p, 0);
06117 p->fullcontact[0] = '\0';
06118 p->useragent[0] = '\0';
06119 p->sipoptions = 0;
06120 p->lastms = 0;
06121
06122 if (option_verbose > 2)
06123 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->name);
06124 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", p->name);
06125 return PARSE_REGISTER_UPDATE;
06126 }
06127 ast_copy_string(p->fullcontact, c, sizeof(p->fullcontact));
06128
06129 snprintf(pvt->our_contact, sizeof(pvt->our_contact) - 1, "<%s>", c);
06130
06131 if (strncasecmp(c, "sip:", 4)) {
06132 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
06133 } else
06134 c += 4;
06135
06136 n = strchr(c, ';');
06137 if (n) {
06138 *n = '\0';
06139 }
06140
06141 n = strchr(c, '@');
06142 if (!n) {
06143 n = c;
06144 c = NULL;
06145 } else {
06146 *n = '\0';
06147 n++;
06148 }
06149 pt = strchr(n, ':');
06150 if (pt) {
06151 *pt = '\0';
06152 pt++;
06153 port = atoi(pt);
06154 } else
06155 port = DEFAULT_SIP_PORT;
06156 memcpy(&oldsin, &p->addr, sizeof(oldsin));
06157 if (!(ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)) {
06158
06159 hp = ast_gethostbyname(n, &ahp);
06160 if (!hp) {
06161 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
06162 return PARSE_REGISTER_FAILED;
06163 }
06164 p->addr.sin_family = AF_INET;
06165 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
06166 p->addr.sin_port = htons(port);
06167 } else {
06168
06169
06170 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
06171 }
06172
06173 if (c && ast_strlen_zero(p->username))
06174 ast_copy_string(p->username, c, sizeof(p->username));
06175
06176 if (p->expire > -1) {
06177 ast_sched_del(sched, p->expire);
06178 p->expire = -1;
06179 }
06180 if ((expiry < 1) || (expiry > max_expiry))
06181 expiry = max_expiry;
06182 if (!ast_test_flag(p, SIP_REALTIME))
06183 p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
06184 else
06185 p->expire = -1;
06186 pvt->expiry = expiry;
06187 snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry, p->username, p->fullcontact);
06188 if (!ast_test_flag((&p->flags_page2), SIP_PAGE2_RT_FROMCONTACT))
06189 ast_db_put("SIP/Registry", p->name, data);
06190 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", p->name);
06191 if (inaddrcmp(&p->addr, &oldsin)) {
06192 sip_poke_peer(p);
06193 if (option_verbose > 2)
06194 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->name, ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry);
06195 register_peer_exten(p, 1);
06196 }
06197
06198
06199 p->sipoptions = pvt->sipoptions;
06200
06201
06202 useragent = get_header(req, "User-Agent");
06203 if (useragent && strcasecmp(useragent, p->useragent)) {
06204 ast_copy_string(p->useragent, useragent, sizeof(p->useragent));
06205 if (option_verbose > 3) {
06206 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n",p->useragent,p->name);
06207 }
06208 }
06209 return PARSE_REGISTER_UPDATE;
06210 }
06211
06212
06213 static void free_old_route(struct sip_route *route)
06214 {
06215 struct sip_route *next;
06216 while (route) {
06217 next = route->next;
06218 free(route);
06219 route = next;
06220 }
06221 }
06222
06223
06224 static void list_route(struct sip_route *route)
06225 {
06226 if (!route) {
06227 ast_verbose("list_route: no route\n");
06228 return;
06229 }
06230 while (route) {
06231 ast_verbose("list_route: hop: <%s>\n", route->hop);
06232 route = route->next;
06233 }
06234 }
06235
06236
06237 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
06238 {
06239 struct sip_route *thishop, *head, *tail;
06240 int start = 0;
06241 int len;
06242 char *rr, *contact, *c;
06243
06244
06245 if (p->route && p->route_persistant) {
06246 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
06247 return;
06248 }
06249
06250 if (p->route) {
06251 free_old_route(p->route);
06252 p->route = NULL;
06253 }
06254
06255 p->route_persistant = backwards;
06256
06257
06258 head = NULL; tail = head;
06259
06260 for (;;) {
06261
06262 rr = __get_header(req, "Record-Route", &start);
06263 if (*rr == '\0') break;
06264 for (;;) {
06265
06266
06267 rr = strchr(rr, '<');
06268 if (!rr) break;
06269 ++rr;
06270 len = strcspn(rr, ">") + 1;
06271
06272 thishop = malloc(sizeof(*thishop) + len);
06273 if (thishop) {
06274 ast_copy_string(thishop->hop, rr, len);
06275 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
06276
06277 if (backwards) {
06278
06279 thishop->next = head;