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
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094 #include "asterisk.h"
00095
00096 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 119926 $")
00097
00098 #include <stdio.h>
00099 #include <ctype.h>
00100 #include <string.h>
00101 #include <unistd.h>
00102 #include <sys/socket.h>
00103 #include <sys/ioctl.h>
00104 #include <net/if.h>
00105 #include <errno.h>
00106 #include <stdlib.h>
00107 #include <fcntl.h>
00108 #include <netdb.h>
00109 #include <signal.h>
00110 #include <sys/signal.h>
00111 #include <netinet/in.h>
00112 #include <netinet/in_systm.h>
00113 #include <arpa/inet.h>
00114 #include <netinet/ip.h>
00115 #include <regex.h>
00116
00117 #include "asterisk/lock.h"
00118 #include "asterisk/channel.h"
00119 #include "asterisk/config.h"
00120 #include "asterisk/logger.h"
00121 #include "asterisk/module.h"
00122 #include "asterisk/pbx.h"
00123 #include "asterisk/options.h"
00124 #include "asterisk/sched.h"
00125 #include "asterisk/io.h"
00126 #include "asterisk/rtp.h"
00127 #include "asterisk/udptl.h"
00128 #include "asterisk/acl.h"
00129 #include "asterisk/manager.h"
00130 #include "asterisk/callerid.h"
00131 #include "asterisk/cli.h"
00132 #include "asterisk/app.h"
00133 #include "asterisk/musiconhold.h"
00134 #include "asterisk/dsp.h"
00135 #include "asterisk/features.h"
00136 #include "asterisk/srv.h"
00137 #include "asterisk/astdb.h"
00138 #include "asterisk/causes.h"
00139 #include "asterisk/utils.h"
00140 #include "asterisk/file.h"
00141 #include "asterisk/astobj.h"
00142 #include "asterisk/devicestate.h"
00143 #include "asterisk/linkedlists.h"
00144 #include "asterisk/stringfields.h"
00145 #include "asterisk/monitor.h"
00146 #include "asterisk/localtime.h"
00147 #include "asterisk/abstract_jb.h"
00148 #include "asterisk/compiler.h"
00149 #include "asterisk/threadstorage.h"
00150 #include "asterisk/translate.h"
00151
00152 #ifndef FALSE
00153 #define FALSE 0
00154 #endif
00155
00156 #ifndef TRUE
00157 #define TRUE 1
00158 #endif
00159
00160 #define SIPBUFSIZE 512
00161
00162 #define XMIT_ERROR -2
00163
00164 #define VIDEO_CODEC_MASK 0x1fc0000
00165 #ifndef IPTOS_MINCOST
00166 #define IPTOS_MINCOST 0x02
00167 #endif
00168
00169
00170
00171 #define DEFAULT_DEFAULT_EXPIRY 120
00172 #define DEFAULT_MIN_EXPIRY 60
00173 #define DEFAULT_MAX_EXPIRY 3600
00174 #define DEFAULT_REGISTRATION_TIMEOUT 20
00175 #define DEFAULT_MAX_FORWARDS "70"
00176
00177
00178
00179 #define EXPIRY_GUARD_SECS 15
00180 #define EXPIRY_GUARD_LIMIT 30
00181
00182 #define EXPIRY_GUARD_MIN 500
00183
00184
00185
00186 #define EXPIRY_GUARD_PCT 0.20
00187
00188 #define DEFAULT_EXPIRY 900
00189
00190 static int min_expiry = DEFAULT_MIN_EXPIRY;
00191 static int max_expiry = DEFAULT_MAX_EXPIRY;
00192 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00193 static int expiry = DEFAULT_EXPIRY;
00194
00195 #ifndef MAX
00196 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00197 #endif
00198
00199 #define CALLERID_UNKNOWN "Unknown"
00200
00201 #define DEFAULT_MAXMS 2000
00202 #define DEFAULT_FREQ_OK 60 * 1000
00203 #define DEFAULT_FREQ_NOTOK 10 * 1000
00204
00205 #define DEFAULT_RETRANS 1000
00206 #define MAX_RETRANS 6
00207 #define SIP_TRANS_TIMEOUT 32000
00208
00209
00210 #define DEFAULT_TRANS_TIMEOUT -1
00211 #define MAX_AUTHTRIES 3
00212
00213 #define SIP_MAX_HEADERS 64
00214 #define SIP_MAX_LINES 64
00215 #define SIP_MAX_PACKET 4096
00216
00217 #define SDP_MAX_RTPMAP_CODECS 32
00218
00219 #define INITIAL_CSEQ 101
00220
00221
00222 static struct ast_jb_conf default_jbconf =
00223 {
00224 .flags = 0,
00225 .max_size = -1,
00226 .resync_threshold = -1,
00227 .impl = ""
00228 };
00229 static struct ast_jb_conf global_jbconf;
00230
00231 static const char config[] = "sip.conf";
00232 static const char notify_config[] = "sip_notify.conf";
00233
00234 #define RTP 1
00235 #define NO_RTP 0
00236
00237
00238
00239
00240 enum transfermodes {
00241 TRANSFER_OPENFORALL,
00242 TRANSFER_CLOSED,
00243 };
00244
00245
00246 enum sip_result {
00247 AST_SUCCESS = 0,
00248 AST_FAILURE = -1,
00249 };
00250
00251
00252
00253
00254 enum invitestates {
00255 INV_NONE = 0,
00256 INV_CALLING = 1,
00257 INV_PROCEEDING = 2,
00258 INV_EARLY_MEDIA = 3,
00259 INV_COMPLETED = 4,
00260 INV_CONFIRMED = 5,
00261 INV_TERMINATED = 6,
00262
00263 INV_CANCELLED = 7,
00264 };
00265
00266
00267
00268
00269
00270
00271
00272
00273
00274 enum xmittype {
00275 XMIT_CRITICAL = 2,
00276
00277 XMIT_RELIABLE = 1,
00278 XMIT_UNRELIABLE = 0,
00279 };
00280
00281 enum parse_register_result {
00282 PARSE_REGISTER_FAILED,
00283 PARSE_REGISTER_UPDATE,
00284 PARSE_REGISTER_QUERY,
00285 };
00286
00287 enum subscriptiontype {
00288 NONE = 0,
00289 XPIDF_XML,
00290 DIALOG_INFO_XML,
00291 CPIM_PIDF_XML,
00292 PIDF_XML,
00293 MWI_NOTIFICATION
00294 };
00295
00296 static const struct cfsubscription_types {
00297 enum subscriptiontype type;
00298 const char * const event;
00299 const char * const mediatype;
00300 const char * const text;
00301 } subscription_types[] = {
00302 { NONE, "-", "unknown", "unknown" },
00303
00304 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00305 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00306 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00307 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00308 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00309 };
00310
00311
00312 enum sipmethod {
00313 SIP_UNKNOWN,
00314 SIP_RESPONSE,
00315 SIP_REGISTER,
00316 SIP_OPTIONS,
00317 SIP_NOTIFY,
00318 SIP_INVITE,
00319 SIP_ACK,
00320 SIP_PRACK,
00321 SIP_BYE,
00322 SIP_REFER,
00323 SIP_SUBSCRIBE,
00324 SIP_MESSAGE,
00325 SIP_UPDATE,
00326 SIP_INFO,
00327 SIP_CANCEL,
00328 SIP_PUBLISH,
00329 SIP_PING,
00330 };
00331
00332
00333
00334
00335
00336
00337 enum sip_auth_type {
00338 PROXY_AUTH,
00339 WWW_AUTH,
00340 };
00341
00342
00343 enum check_auth_result {
00344 AUTH_SUCCESSFUL = 0,
00345 AUTH_CHALLENGE_SENT = 1,
00346 AUTH_SECRET_FAILED = -1,
00347 AUTH_USERNAME_MISMATCH = -2,
00348 AUTH_NOT_FOUND = -3,
00349 AUTH_FAKE_AUTH = -4,
00350 AUTH_UNKNOWN_DOMAIN = -5,
00351 AUTH_PEER_NOT_DYNAMIC = -6,
00352 AUTH_ACL_FAILED = -7,
00353 };
00354
00355
00356 enum sipregistrystate {
00357 REG_STATE_UNREGISTERED = 0,
00358 REG_STATE_REGSENT,
00359 REG_STATE_AUTHSENT,
00360 REG_STATE_REGISTERED,
00361 REG_STATE_REJECTED,
00362 REG_STATE_TIMEOUT,
00363 REG_STATE_NOAUTH,
00364 REG_STATE_FAILED,
00365 };
00366
00367 #define CAN_NOT_CREATE_DIALOG 0
00368 #define CAN_CREATE_DIALOG 1
00369 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
00370
00371
00372 static const struct cfsip_methods {
00373 enum sipmethod id;
00374 int need_rtp;
00375 char * const text;
00376 int can_create;
00377 } sip_methods[] = {
00378 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
00379 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00380 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00381 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00382 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00383 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00384 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00385 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00386 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00387 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00388 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
00389 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00390 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00391 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00392 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00393 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00394 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00395 };
00396
00397
00398
00399
00400
00401
00402
00403
00404
00405
00406
00407 #define SUPPORTED 1
00408 #define NOT_SUPPORTED 0
00409
00410 #define SIP_OPT_REPLACES (1 << 0)
00411 #define SIP_OPT_100REL (1 << 1)
00412 #define SIP_OPT_TIMER (1 << 2)
00413 #define SIP_OPT_EARLY_SESSION (1 << 3)
00414 #define SIP_OPT_JOIN (1 << 4)
00415 #define SIP_OPT_PATH (1 << 5)
00416 #define SIP_OPT_PREF (1 << 6)
00417 #define SIP_OPT_PRECONDITION (1 << 7)
00418 #define SIP_OPT_PRIVACY (1 << 8)
00419 #define SIP_OPT_SDP_ANAT (1 << 9)
00420 #define SIP_OPT_SEC_AGREE (1 << 10)
00421 #define SIP_OPT_EVENTLIST (1 << 11)
00422 #define SIP_OPT_GRUU (1 << 12)
00423 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00424 #define SIP_OPT_NOREFERSUB (1 << 14)
00425 #define SIP_OPT_HISTINFO (1 << 15)
00426 #define SIP_OPT_RESPRIORITY (1 << 16)
00427
00428
00429
00430 static const struct cfsip_options {
00431 int id;
00432 int supported;
00433 char * const text;
00434 } sip_options[] = {
00435
00436 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
00437
00438 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
00439
00440 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
00441
00442 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
00443
00444 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
00445
00446 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
00447
00448 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
00449
00450 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
00451
00452 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00453
00454 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
00455
00456 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
00457
00458 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00459
00460 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00461
00462 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
00463
00464 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00465
00466 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
00467
00468 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
00469
00470 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
00471 };
00472
00473
00474
00475 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
00476
00477
00478 #define SUPPORTED_EXTENSIONS "replaces"
00479
00480
00481 #define STANDARD_SIP_PORT 5060
00482
00483
00484
00485
00486
00487
00488
00489
00490
00491
00492
00493
00494 #define DEFAULT_CONTEXT "default"
00495 #define DEFAULT_MOHINTERPRET "default"
00496 #define DEFAULT_MOHSUGGEST ""
00497 #define DEFAULT_VMEXTEN "asterisk"
00498 #define DEFAULT_CALLERID "asterisk"
00499 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
00500 #define DEFAULT_MWITIME 10
00501 #define DEFAULT_ALLOWGUEST TRUE
00502 #define DEFAULT_SRVLOOKUP TRUE
00503 #define DEFAULT_COMPACTHEADERS FALSE
00504 #define DEFAULT_TOS_SIP 0
00505 #define DEFAULT_TOS_AUDIO 0
00506 #define DEFAULT_TOS_VIDEO 0
00507 #define DEFAULT_ALLOW_EXT_DOM TRUE
00508 #define DEFAULT_REALM "asterisk"
00509 #define DEFAULT_NOTIFYRINGING TRUE
00510 #define DEFAULT_PEDANTIC FALSE
00511 #define DEFAULT_AUTOCREATEPEER FALSE
00512 #define DEFAULT_QUALIFY FALSE
00513 #define DEFAULT_T1MIN 100
00514 #define DEFAULT_MAX_CALL_BITRATE (384)
00515 #ifndef DEFAULT_USERAGENT
00516 #define DEFAULT_USERAGENT "Asterisk PBX"
00517 #endif
00518
00519
00520
00521
00522 static char default_context[AST_MAX_CONTEXT];
00523 static char default_subscribecontext[AST_MAX_CONTEXT];
00524 static char default_language[MAX_LANGUAGE];
00525 static char default_callerid[AST_MAX_EXTENSION];
00526 static char default_fromdomain[AST_MAX_EXTENSION];
00527 static char default_notifymime[AST_MAX_EXTENSION];
00528 static int default_qualify;
00529 static char default_vmexten[AST_MAX_EXTENSION];
00530 static char default_mohinterpret[MAX_MUSICCLASS];
00531 static char default_mohsuggest[MAX_MUSICCLASS];
00532
00533 static int default_maxcallbitrate;
00534 static struct ast_codec_pref default_prefs;
00535
00536
00537 static int global_directrtpsetup;
00538 static int global_limitonpeers;
00539 static int global_rtautoclear;
00540 static int global_notifyringing;
00541 static int global_notifyhold;
00542 static int global_alwaysauthreject;
00543 static int srvlookup;
00544 static int pedanticsipchecking;
00545 static int autocreatepeer;
00546 static int global_relaxdtmf;
00547 static int global_rtptimeout;
00548 static int global_rtpholdtimeout;
00549 static int global_rtpkeepalive;
00550 static int global_reg_timeout;
00551 static int global_regattempts_max;
00552 static int global_allowguest;
00553 static int global_allowsubscribe;
00554
00555 static int global_mwitime;
00556 static unsigned int global_tos_sip;
00557 static unsigned int global_tos_audio;
00558 static unsigned int global_tos_video;
00559 static int compactheaders;
00560 static int recordhistory;
00561 static int dumphistory;
00562 static char global_realm[MAXHOSTNAMELEN];
00563 static char global_regcontext[AST_MAX_CONTEXT];
00564 static char global_useragent[AST_MAX_EXTENSION];
00565 static int allow_external_domains;
00566 static int global_callevents;
00567 static int global_t1min;
00568 static int global_autoframing;
00569 static enum transfermodes global_allowtransfer;
00570
00571 static int global_matchexterniplocally;
00572
00573
00574 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00575
00576
00577 static int suserobjs = 0;
00578 static int ruserobjs = 0;
00579 static int speerobjs = 0;
00580 static int rpeerobjs = 0;
00581 static int apeerobjs = 0;
00582 static int regobjs = 0;
00583
00584 static struct ast_flags global_flags[2] = {{0}};
00585
00586
00587 AST_MUTEX_DEFINE_STATIC(iflock);
00588
00589
00590
00591 AST_MUTEX_DEFINE_STATIC(netlock);
00592
00593 AST_MUTEX_DEFINE_STATIC(monlock);
00594
00595 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00596
00597
00598
00599 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00600
00601 static int sip_reloading = FALSE;
00602 static enum channelreloadreason sip_reloadreason;
00603
00604 static struct sched_context *sched;
00605 static struct io_context *io;
00606 static int *sipsock_read_id;
00607 static int *siptcpsock_read_id;
00608
00609 #define DEC_CALL_LIMIT 0
00610 #define INC_CALL_LIMIT 1
00611 #define DEC_CALL_RINGING 2
00612 #define INC_CALL_RINGING 3
00613
00614
00615 struct sip_request {
00616 char *rlPart1;
00617 char *rlPart2;
00618 int len;
00619 int headers;
00620 int method;
00621 int lines;
00622 unsigned int flags;
00623 char *header[SIP_MAX_HEADERS];
00624 char *line[SIP_MAX_LINES];
00625 char data[SIP_MAX_PACKET];
00626 unsigned int sdp_start;
00627 unsigned int sdp_end;
00628 };
00629
00630
00631
00632
00633
00634
00635
00636
00637
00638
00639
00640
00641
00642
00643
00644
00645
00646
00647
00648
00649
00650 struct sip_dual {
00651 struct ast_channel *chan1;
00652 struct ast_channel *chan2;
00653 struct sip_request req;
00654 int seqno;
00655 };
00656
00657 struct sip_pkt;
00658
00659
00660 struct sip_invite_param {
00661 const char *distinctive_ring;
00662 int addsipheaders;
00663 const char *uri_options;
00664 const char *vxml_url;
00665 char *auth;
00666 char *authheader;
00667 enum sip_auth_type auth_type;
00668 const char *replaces;
00669 int transfer;
00670 };
00671
00672
00673 struct sip_route {
00674 struct sip_route *next;
00675 char hop[0];
00676 };
00677
00678
00679 enum domain_mode {
00680 SIP_DOMAIN_AUTO,
00681 SIP_DOMAIN_CONFIG,
00682 };
00683
00684
00685
00686
00687
00688 struct domain {
00689 char domain[MAXHOSTNAMELEN];
00690 char context[AST_MAX_EXTENSION];
00691 enum domain_mode mode;
00692 AST_LIST_ENTRY(domain) list;
00693 };
00694
00695 static AST_LIST_HEAD_STATIC(domain_list, domain);
00696
00697
00698
00699 struct sip_history {
00700 AST_LIST_ENTRY(sip_history) list;
00701 char event[0];
00702 };
00703
00704 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00705
00706
00707 struct sip_auth {
00708 char realm[AST_MAX_EXTENSION];
00709 char username[256];
00710 char secret[256];
00711 char md5secret[256];
00712 struct sip_auth *next;
00713 };
00714
00715
00716 #define SIP_ALREADYGONE (1 << 0)
00717 #define SIP_NEEDDESTROY (1 << 1)
00718 #define SIP_NOVIDEO (1 << 2)
00719 #define SIP_RINGING (1 << 3)
00720 #define SIP_PROGRESS_SENT (1 << 4)
00721 #define SIP_NEEDREINVITE (1 << 5)
00722 #define SIP_PENDINGBYE (1 << 6)
00723 #define SIP_GOTREFER (1 << 7)
00724 #define SIP_PROMISCREDIR (1 << 8)
00725 #define SIP_TRUSTRPID (1 << 9)
00726 #define SIP_USEREQPHONE (1 << 10)
00727 #define SIP_REALTIME (1 << 11)
00728 #define SIP_USECLIENTCODE (1 << 12)
00729 #define SIP_OUTGOING (1 << 13)
00730 #define SIP_FREE_BIT (1 << 14)
00731 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15)
00732 #define SIP_DTMF (3 << 16)
00733 #define SIP_DTMF_RFC2833 (0 << 16)
00734 #define SIP_DTMF_INBAND (1 << 16)
00735 #define SIP_DTMF_INFO (2 << 16)
00736 #define SIP_DTMF_AUTO (3 << 16)
00737
00738 #define SIP_NAT (3 << 18)
00739 #define SIP_NAT_NEVER (0 << 18)
00740 #define SIP_NAT_RFC3581 (1 << 18)
00741 #define SIP_NAT_ROUTE (2 << 18)
00742 #define SIP_NAT_ALWAYS (3 << 18)
00743
00744 #define SIP_REINVITE (7 << 20)
00745 #define SIP_CAN_REINVITE (1 << 20)
00746 #define SIP_CAN_REINVITE_NAT (2 << 20)
00747 #define SIP_REINVITE_UPDATE (4 << 20)
00748
00749 #define SIP_INSECURE_PORT (1 << 23)
00750 #define SIP_INSECURE_INVITE (1 << 24)
00751
00752 #define SIP_PROG_INBAND (3 << 25)
00753 #define SIP_PROG_INBAND_NEVER (0 << 25)
00754 #define SIP_PROG_INBAND_NO (1 << 25)
00755 #define SIP_PROG_INBAND_YES (2 << 25)
00756 #define SIP_NO_HISTORY (1 << 27)
00757 #define SIP_CALL_LIMIT (1 << 28)
00758 #define SIP_SENDRPID (1 << 29)
00759 #define SIP_INC_COUNT (1 << 30)
00760 #define SIP_G726_NONSTANDARD (1 << 31)
00761
00762 #define SIP_FLAGS_TO_COPY \
00763 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
00764 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
00765 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
00766
00767
00768
00769 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
00770 #define SIP_PAGE2_RTUPDATE (1 << 1)
00771 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
00772 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
00773 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
00774
00775 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9)
00776 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
00777 #define SIP_PAGE2_DEBUG (3 << 11)
00778 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
00779 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
00780 #define SIP_PAGE2_DYNAMIC (1 << 13)
00781 #define SIP_PAGE2_SELFDESTRUCT (1 << 14)
00782 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
00783 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)
00784 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17)
00785 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18)
00786 #define SIP_PAGE2_INC_RINGING (1 << 19)
00787 #define SIP_PAGE2_T38SUPPORT (7 << 20)
00788 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20)
00789 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20)
00790 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20)
00791 #define SIP_PAGE2_CALL_ONHOLD (3 << 23)
00792 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23)
00793 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23)
00794 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)
00795 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
00796 #define SIP_PAGE2_BUGGY_MWI (1 << 26)
00797 #define SIP_PAGE2_OUTGOING_CALL (1 << 27)
00798 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 28)
00799 #define SIP_PAGE2_TCP (1 << 29)
00800 #define SIP_PAGE2_TCP_CONNECTED (1 << 30)
00801
00802 #define SIP_PAGE2_FLAGS_TO_COPY \
00803 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
00804 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_UDPTL_DESTINATION)
00805
00806
00807 #define SIP_PKT_DEBUG (1 << 0)
00808 #define SIP_PKT_WITH_TOTAG (1 << 1)
00809 #define SIP_PKT_IGNORE (1 << 2)
00810 #define SIP_PKT_IGNORE_RESP (1 << 3)
00811 #define SIP_PKT_IGNORE_REQ (1 << 4)
00812
00813
00814 #define T38FAX_FILL_BIT_REMOVAL (1 << 0)
00815 #define T38FAX_TRANSCODING_MMR (1 << 1)
00816 #define T38FAX_TRANSCODING_JBIG (1 << 2)
00817
00818 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
00819 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3)
00820
00821 #define T38FAX_UDP_EC_NONE (0 << 4)
00822 #define T38FAX_UDP_EC_FEC (1 << 4)
00823 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4)
00824
00825 #define T38FAX_VERSION (3 << 6)
00826 #define T38FAX_VERSION_0 (0 << 6)
00827 #define T38FAX_VERSION_1 (1 << 6)
00828
00829 #define T38FAX_RATE_2400 (1 << 8)
00830 #define T38FAX_RATE_4800 (1 << 9)
00831 #define T38FAX_RATE_7200 (1 << 10)
00832 #define T38FAX_RATE_9600 (1 << 11)
00833 #define T38FAX_RATE_12000 (1 << 12)
00834 #define T38FAX_RATE_14400 (1 << 13)
00835
00836
00837 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
00838
00839 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
00840 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
00841 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
00842
00843
00844 enum t38state {
00845 T38_DISABLED = 0,
00846 T38_LOCAL_DIRECT,
00847 T38_LOCAL_REINVITE,
00848 T38_PEER_DIRECT,
00849 T38_PEER_REINVITE,
00850 T38_ENABLED
00851 };
00852
00853
00854 struct t38properties {
00855 struct ast_flags t38support;
00856 int capability;
00857 int peercapability;
00858 int jointcapability;
00859 enum t38state state;
00860 };
00861
00862
00863 enum referstatus {
00864 REFER_IDLE,
00865 REFER_SENT,
00866 REFER_RECEIVED,
00867 REFER_CONFIRMED,
00868 REFER_ACCEPTED,
00869 REFER_RINGING,
00870 REFER_200OK,
00871 REFER_FAILED,
00872 REFER_NOAUTH
00873 };
00874
00875 static const struct c_referstatusstring {
00876 enum referstatus status;
00877 char *text;
00878 } referstatusstrings[] = {
00879 { REFER_IDLE, "<none>" },
00880 { REFER_SENT, "Request sent" },
00881 { REFER_RECEIVED, "Request received" },
00882 { REFER_ACCEPTED, "Accepted" },
00883 { REFER_RINGING, "Target ringing" },
00884 { REFER_200OK, "Done" },
00885 { REFER_FAILED, "Failed" },
00886 { REFER_NOAUTH, "Failed - auth failure" }
00887 } ;
00888
00889
00890
00891 struct sip_refer {
00892 char refer_to[AST_MAX_EXTENSION];
00893 char refer_to_domain[AST_MAX_EXTENSION];
00894 char refer_to_urioption[AST_MAX_EXTENSION];
00895 char refer_to_context[AST_MAX_EXTENSION];
00896 char referred_by[AST_MAX_EXTENSION];
00897 char referred_by_name[AST_MAX_EXTENSION];
00898 char refer_contact[AST_MAX_EXTENSION];
00899 char replaces_callid[SIPBUFSIZE];
00900 char replaces_callid_totag[SIPBUFSIZE/2];
00901 char replaces_callid_fromtag[SIPBUFSIZE/2];
00902 struct sip_pvt *refer_call;
00903 int attendedtransfer;
00904 int localtransfer;
00905 enum referstatus status;
00906 };
00907
00908
00909 static struct sip_pvt {
00910 ast_mutex_t lock;
00911 int method;
00912 enum invitestates invitestate;
00913 AST_DECLARE_STRING_FIELDS(
00914 AST_STRING_FIELD(callid);
00915 AST_STRING_FIELD(randdata);
00916 AST_STRING_FIELD(accountcode);
00917 AST_STRING_FIELD(realm);
00918 AST_STRING_FIELD(nonce);
00919 AST_STRING_FIELD(opaque);
00920 AST_STRING_FIELD(qop);
00921 AST_STRING_FIELD(domain);
00922 AST_STRING_FIELD(from);
00923 AST_STRING_FIELD(useragent);
00924 AST_STRING_FIELD(exten);
00925 AST_STRING_FIELD(context);
00926 AST_STRING_FIELD(subscribecontext);
00927 AST_STRING_FIELD(subscribeuri);
00928 AST_STRING_FIELD(fromdomain);
00929 AST_STRING_FIELD(fromuser);
00930 AST_STRING_FIELD(fromname);
00931 AST_STRING_FIELD(tohost);
00932 AST_STRING_FIELD(language);
00933 AST_STRING_FIELD(mohinterpret);
00934 AST_STRING_FIELD(mohsuggest);
00935 AST_STRING_FIELD(rdnis);
00936 AST_STRING_FIELD(theirtag);
00937 AST_STRING_FIELD(username);
00938 AST_STRING_FIELD(peername);
00939 AST_STRING_FIELD(authname);
00940 AST_STRING_FIELD(uri);
00941 AST_STRING_FIELD(okcontacturi);
00942 AST_STRING_FIELD(peersecret);
00943 AST_STRING_FIELD(peermd5secret);
00944 AST_STRING_FIELD(cid_num);
00945 AST_STRING_FIELD(cid_name);
00946 AST_STRING_FIELD(via);
00947 AST_STRING_FIELD(fullcontact);
00948 AST_STRING_FIELD(our_contact);
00949 AST_STRING_FIELD(rpid);
00950 AST_STRING_FIELD(rpid_from);
00951 );
00952 unsigned int ocseq;
00953 unsigned int icseq;
00954 ast_group_t callgroup;
00955 ast_group_t pickupgroup;
00956 int lastinvite;
00957 int lastnoninvite;
00958 struct ast_flags flags[2];
00959 int timer_t1;
00960 unsigned int sipoptions;
00961 struct ast_codec_pref prefs;
00962 int capability;
00963 int jointcapability;
00964 int peercapability;
00965 int prefcodec;
00966 int noncodeccapability;
00967 int jointnoncodeccapability;
00968 int redircodecs;
00969 int maxcallbitrate;
00970 struct t38properties t38;
00971 struct sockaddr_in udptlredirip;
00972 struct ast_udptl *udptl;
00973 int callingpres;
00974 int authtries;
00975 int expiry;
00976 long branch;
00977 char tag[11];
00978 int sessionid;
00979 int sessionversion;
00980 struct sockaddr_in sa;
00981 struct sockaddr_in redirip;
00982 struct sockaddr_in vredirip;
00983 time_t lastrtprx;
00984 time_t lastrtptx;
00985 int rtptimeout;
00986 struct sockaddr_in recv;
00987 struct in_addr ourip;
00988 struct ast_channel *owner;
00989 struct sip_route *route;
00990 int route_persistant;
00991 struct sip_auth *peerauth;
00992 int noncecount;
00993 char lastmsg[256];
00994 int amaflags;
00995 int pendinginvite;
00996 struct sip_request initreq;
00997
00998
00999 int maxtime;
01000 int initid;
01001 int waitid;
01002 int autokillid;
01003 enum transfermodes allowtransfer;
01004 struct sip_refer *refer;
01005 enum subscriptiontype subscribed;
01006 int stateid;
01007 int laststate;
01008 int dialogver;
01009
01010 struct ast_dsp *vad;
01011
01012 struct sip_peer *relatedpeer;
01013
01014 struct sip_registry *registry;
01015 struct ast_rtp *rtp;
01016 struct ast_rtp *vrtp;
01017 struct sip_pkt *packets;
01018 struct sip_history_head *history;
01019 size_t history_entries;
01020 struct ast_variable *chanvars;
01021 struct sip_pvt *next;
01022 struct sip_invite_param *options;
01023 int autoframing;
01024 int sockfd;
01025 } *iflist = NULL;
01026
01027
01028 #define MAX_HISTORY_ENTRIES 50
01029
01030 #define FLAG_RESPONSE (1 << 0)
01031 #define FLAG_FATAL (1 << 1)
01032
01033
01034 struct sip_pkt {
01035 struct sip_pkt *next;
01036 int retrans;
01037 int method;
01038 int seqno;
01039 unsigned int flags;
01040 struct sip_pvt *owner;
01041 int retransid;
01042 int timer_a;
01043 int timer_t1;
01044 int packetlen;
01045 char data[0];
01046 };
01047
01048
01049 struct sip_user {
01050
01051 ASTOBJ_COMPONENTS(struct sip_user);
01052 char secret[80];
01053 char md5secret[80];
01054 char context[AST_MAX_CONTEXT];
01055 char subscribecontext[AST_MAX_CONTEXT];
01056 char cid_num[80];
01057 char cid_name[80];
01058 char accountcode[AST_MAX_ACCOUNT_CODE];
01059 char language[MAX_LANGUAGE];
01060 char mohinterpret[MAX_MUSICCLASS];
01061 char mohsuggest[MAX_MUSICCLASS];
01062 char useragent[256];
01063 struct ast_codec_pref prefs;
01064 ast_group_t callgroup;
01065 ast_group_t pickupgroup;
01066 unsigned int sipoptions;
01067 struct ast_flags flags[2];
01068 int amaflags;
01069 int callingpres;
01070 int capability;
01071 int inUse;
01072 int call_limit;
01073 enum transfermodes allowtransfer;
01074 struct ast_ha *ha;
01075 struct ast_variable *chanvars;
01076 int maxcallbitrate;
01077 int autoframing;
01078 };
01079
01080
01081
01082 struct sip_peer {
01083 ASTOBJ_COMPONENTS(struct sip_peer);
01084
01085 char secret[80];
01086 char md5secret[80];
01087 struct sip_auth *auth;
01088 char context[AST_MAX_CONTEXT];
01089 char subscribecontext[AST_MAX_CONTEXT];
01090 char username[80];
01091 char accountcode[AST_MAX_ACCOUNT_CODE];
01092 int amaflags;
01093 char tohost[MAXHOSTNAMELEN];
01094 char regexten[AST_MAX_EXTENSION];
01095 char fromuser[80];
01096 char fromdomain[MAXHOSTNAMELEN];
01097 char fullcontact[256];
01098 char cid_num[80];
01099 char cid_name[80];
01100 int callingpres;
01101 int inUse;
01102 int inRinging;
01103 int onHold;
01104 int call_limit;
01105 enum transfermodes allowtransfer;
01106 char vmexten[AST_MAX_EXTENSION];
01107 char mailbox[AST_MAX_EXTENSION];
01108 char language[MAX_LANGUAGE];
01109 char mohinterpret[MAX_MUSICCLASS];
01110 char mohsuggest[MAX_MUSICCLASS];
01111 char useragent[256];
01112 struct ast_codec_pref prefs;
01113 int lastmsgssent;
01114 time_t lastmsgcheck;
01115 unsigned int sipoptions;
01116 struct ast_flags flags[2];
01117 int expire;
01118 int capability;
01119 int rtptimeout;
01120 int rtpholdtimeout;
01121 int rtpkeepalive;
01122 ast_group_t callgroup;
01123 ast_group_t pickupgroup;
01124 struct sockaddr_in addr;
01125 int maxcallbitrate;
01126
01127
01128 struct sip_pvt *call;
01129 int pokeexpire;
01130 int lastms;
01131 int maxms;
01132 struct timeval ps;
01133
01134 struct sockaddr_in defaddr;
01135 struct ast_ha *ha;
01136 struct ast_variable *chanvars;
01137 struct sip_pvt *mwipvt;
01138 int lastmsg;
01139 int autoframing;
01140 int sockfd;
01141 };
01142
01143
01144
01145
01146 struct sip_registry {
01147 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01148 AST_DECLARE_STRING_FIELDS(
01149 AST_STRING_FIELD(callid);
01150 AST_STRING_FIELD(realm);
01151 AST_STRING_FIELD(nonce);
01152 AST_STRING_FIELD(opaque);
01153 AST_STRING_FIELD(qop);
01154 AST_STRING_FIELD(domain);
01155 AST_STRING_FIELD(username);
01156 AST_STRING_FIELD(authuser);
01157 AST_STRING_FIELD(hostname);
01158 AST_STRING_FIELD(secret);
01159 AST_STRING_FIELD(md5secret);
01160 AST_STRING_FIELD(contact);
01161 AST_STRING_FIELD(random);
01162 );
01163 int portno;
01164 int expire;
01165 int regattempts;
01166 int timeout;
01167 int refresh;
01168 struct sip_pvt *call;
01169 enum sipregistrystate regstate;
01170 time_t regtime;
01171 int callid_valid;
01172 unsigned int ocseq;
01173 struct sockaddr_in us;
01174 int noncecount;
01175 char lastmsg[256];
01176 };
01177
01178
01179
01180
01181 static struct ast_user_list {
01182 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
01183 } userl;
01184
01185
01186 static struct ast_peer_list {
01187 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
01188 } peerl;
01189
01190
01191 static struct ast_register_list {
01192 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01193 int recheck;
01194 } regl;
01195
01196 static void temp_pvt_cleanup(void *);
01197
01198
01199 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01200
01201
01202 static struct sip_auth *authl = NULL;
01203
01204
01205
01206 static int sipsock = -1;
01207 static int siptcpsock = -1;
01208 static struct sockaddr_in bindaddr = { 0, };
01209 static struct sockaddr_in externip;
01210 static char externhost[MAXHOSTNAMELEN];
01211 static time_t externexpire = 0;
01212 static int externrefresh = 10;
01213 static struct ast_ha *localaddr;
01214 static struct in_addr __ourip;
01215 static struct sockaddr_in outboundproxyip;
01216 static int ourport;
01217 static struct sockaddr_in debugaddr;
01218
01219 static struct ast_config *notify_types;
01220
01221
01222
01223
01224
01225
01226 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
01227 static int sip_devicestate(void *data);
01228 static int sip_sendtext(struct ast_channel *ast, const char *text);
01229 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01230 static int sip_hangup(struct ast_channel *ast);
01231 static int sip_answer(struct ast_channel *ast);
01232 static struct ast_frame *sip_read(struct ast_channel *ast);
01233 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01234 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01235 static int sip_transfer(struct ast_channel *ast, const char *dest);
01236 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01237 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01238 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01239
01240
01241 static int sipsock_read(int *id, int fd, short events, void *ignore);
01242 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
01243 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
01244 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01245 static int retrans_pkt(const void *data);
01246 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
01247 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
01248 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01249 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01250 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01251 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01252 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01253 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
01254 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01255 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
01256 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01257 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01258 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
01259 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
01260 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01261 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01262 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01263 static int transmit_refer(struct sip_pvt *p, const char *dest);
01264 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
01265 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01266 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01267 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01268 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01269 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01270 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01271 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
01272 static int sip_send_mwi_to_peer(struct sip_peer *peer);
01273 static int does_peer_need_mwi(struct sip_peer *peer);
01274
01275
01276 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
01277 int useglobal_nat, const int intended_method);
01278 static int __sip_autodestruct(const void *data);
01279 static void sip_scheddestroy(struct sip_pvt *p, int ms);
01280 static int sip_cancel_destroy(struct sip_pvt *p);
01281 static void sip_destroy(struct sip_pvt *p);
01282 static int __sip_destroy(struct sip_pvt *p, int lockowner);
01283 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01284 static void __sip_pretend_ack(struct sip_pvt *p);
01285 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01286 static int auto_congest(const void *nothing);
01287 static int update_call_counter(struct sip_pvt *fup, int event);
01288 static int hangup_sip2cause(int cause);
01289 static const char *hangup_cause2sip(int cause);
01290 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
01291 static void free_old_route(struct sip_route *route);
01292 static void list_route(struct sip_route *route);
01293 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01294 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
01295 struct sip_request *req, char *uri);
01296 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01297 static void check_pendings(struct sip_pvt *p);
01298 static void *sip_park_thread(void *stuff);
01299 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
01300 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01301
01302
01303 static void try_suggested_sip_codec(struct sip_pvt *p);
01304 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01305 static const char *get_sdp(struct sip_request *req, const char *name);
01306 static int find_sdp(struct sip_request *req);
01307 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
01308 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
01309 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
01310 int debug, int *min_packet_size);
01311 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
01312 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
01313 int debug);
01314 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
01315 static void stop_media_flows(struct sip_pvt *p);
01316
01317
01318 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01319 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01320 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01321 const char *secret, const char *md5secret, int sipmethod,
01322 char *uri, enum xmittype reliable, int ignore);
01323 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01324 int sipmethod, char *uri, enum xmittype reliable,
01325 struct sockaddr_in *sin, struct sip_peer **authpeer);
01326 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
01327
01328
01329 static int check_sip_domain(const char *domain, char *context, size_t len);
01330 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01331 static void clear_sip_domains(void);
01332
01333
01334 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
01335 static int clear_realm_authentication(struct sip_auth *authlist);
01336 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
01337
01338
01339 static int sip_do_reload(enum channelreloadreason reason);
01340 static int reload_config(enum channelreloadreason reason);
01341 static int expire_register(const void *data);
01342 static void *do_monitor(void *data);
01343 static int restart_monitor(void);
01344 static int sip_send_mwi_to_peer(struct sip_peer *peer);
01345 static int sip_addrcmp(char *name, struct sockaddr_in *sin);
01346 static int sip_refer_allocate(struct sip_pvt *p);
01347 static void ast_quiet_chan(struct ast_channel *chan);
01348 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01349
01350
01351 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01352 static int sip_devicestate(void *data);
01353 static int sip_poke_noanswer(const void *data);
01354 static int sip_poke_peer(struct sip_peer *peer);
01355 static void sip_poke_all_peers(void);
01356 static void sip_peer_hold(struct sip_pvt *p, int hold);
01357
01358
01359 static const char *sip_nat_mode(const struct sip_pvt *p);
01360 static int sip_show_inuse(int fd, int argc, char *argv[]);
01361 static char *transfermode2str(enum transfermodes mode) attribute_const;
01362 static char *nat2str(int nat) attribute_const;
01363 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01364 static int sip_show_users(int fd, int argc, char *argv[]);
01365 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01366 static int sip_show_peers(int fd, int argc, char *argv[]);
01367 static int sip_show_objects(int fd, int argc, char *argv[]);
01368 static void print_group(int fd, ast_group_t group, int crlf);
01369 static const char *dtmfmode2str(int mode) attribute_const;
01370 static const char *insecure2str(int port, int invite) attribute_const;
01371 static void cleanup_stale_contexts(char *new, char *old);
01372 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01373 static const char *domain_mode_to_text(const enum domain_mode mode);
01374 static int sip_show_domains(int fd, int argc, char *argv[]);
01375 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01376 static int sip_show_peer(int fd, int argc, char *argv[]);
01377 static int sip_show_user(int fd, int argc, char *argv[]);
01378 static int sip_show_registry(int fd, int argc, char *argv[]);
01379 static int sip_show_settings(int fd, int argc, char *argv[]);
01380 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01381 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01382 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
01383 static int sip_show_channels(int fd, int argc, char *argv[]);
01384 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
01385 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
01386 static char *complete_sipch(const char *line, const char *word, int pos, int state);
01387 static char *complete_sip_peer(const char *word, int state, int flags2);
01388 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01389 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
01390 static char *complete_sip_user(const char *word, int state, int flags2);
01391 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
01392 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01393 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
01394 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
01395 static int sip_show_channel(int fd, int argc, char *argv[]);
01396 static int sip_show_history(int fd, int argc, char *argv[]);
01397 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
01398 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
01399 static int sip_do_debug(int fd, int argc, char *argv[]);
01400 static int sip_no_debug(int fd, int argc, char *argv[]);
01401 static int sip_notify(int fd, int argc, char *argv[]);
01402 static int sip_do_history(int fd, int argc, char *argv[]);
01403 static int sip_no_history(int fd, int argc, char *argv[]);
01404 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
01405 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01406 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01407 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01408 static int sip_dtmfmode(struct ast_channel *chan, void *data);
01409 static int sip_addheader(struct ast_channel *chan, void *data);
01410 static int sip_do_reload(enum channelreloadreason reason);
01411 static int sip_reload(int fd, int argc, char *argv[]);
01412 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen);
01413
01414
01415
01416
01417
01418 static void sip_dump_history(struct sip_pvt *dialog);
01419 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
01420 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01421 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01422 static void sip_dump_history(struct sip_pvt *dialog);
01423
01424
01425 static struct sip_peer *temp_peer(const char *name);
01426 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
01427 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
01428 static int update_call_counter(struct sip_pvt *fup, int event);
01429 static void sip_destroy_peer(struct sip_peer *peer);
01430 static void sip_destroy_user(struct sip_user *user);
01431 static int sip_poke_peer(struct sip_peer *peer);
01432 static int sip_poke_peer_s(const void *data);
01433 static void set_peer_defaults(struct sip_peer *peer);
01434 static struct sip_peer *temp_peer(const char *name);
01435 static void register_peer_exten(struct sip_peer *peer, int onoff);
01436 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
01437 static struct sip_user *find_user(const char *name, int realtime);
01438 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01439 static int expire_register(const void *data);
01440 static void reg_source_db(struct sip_peer *peer);
01441 static void destroy_association(struct sip_peer *peer);
01442 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01443
01444
01445 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
01446 static struct sip_user *realtime_user(const char *username);
01447 static void update_peer(struct sip_peer *p, int expiry);
01448 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
01449 static int sip_prune_realtime(int fd, int argc, char *argv[]);
01450
01451
01452 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
01453 static void sip_registry_destroy(struct sip_registry *reg);
01454 static int sip_register(char *value, int lineno);
01455 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
01456 static int sip_reregister(const void *data);
01457 static int __sip_do_register(struct sip_registry *r);
01458 static int sip_reg_timeout(const void *data);
01459 static void sip_send_all_registers(void);
01460
01461
01462 static void append_date(struct sip_request *req);
01463 static int determine_firstline_parts(struct sip_request *req);
01464 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01465 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01466 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01467 static int find_sip_method(const char *msg);
01468 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
01469 static int parse_request(struct sip_request *req);
01470 static const char *get_header(const struct sip_request *req, const char *name);
01471 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
01472 static int method_match(enum sipmethod id, const char *name);
01473 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01474 static char *get_in_brackets(char *tmp);
01475 static const char *find_alias(const char *name, const char *_default);
01476 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01477 static int lws2sws(char *msgbuf, int len);
01478 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01479 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01480 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01481 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01482 static int set_address_from_contact(struct sip_pvt *pvt);
01483 static void check_via(struct sip_pvt *p, const struct sip_request *req);
01484 static char *get_calleridname(const char *input, char *output, size_t outputsize);
01485 static int get_rpid_num(const char *input, char *output, int maxlen);
01486 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
01487 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
01488 static int get_msg_text(char *buf, int len, struct sip_request *req);
01489 static void free_old_route(struct sip_route *route);
01490 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01491
01492
01493 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01494 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01495 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
01496 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
01497 static int init_resp(struct sip_request *resp, const char *msg);
01498 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01499 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
01500 static void build_via(struct sip_pvt *p);
01501 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01502 static int create_addr(struct sip_pvt *dialog, const char *opeer);
01503 static char *generate_random_string(char *buf, size_t size);
01504 static void build_callid_pvt(struct sip_pvt *pvt);
01505 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
01506 static void make_our_tag(char *tagbuf, size_t len);
01507 static int add_header(struct sip_request *req, const char *var, const char *value);
01508 static int add_header_contentLength(struct sip_request *req, int len);
01509 static int add_line(struct sip_request *req, const char *line);
01510 static int add_text(struct sip_request *req, const char *text);
01511 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
01512 static int add_vidupdate(struct sip_request *req);
01513 static void add_route(struct sip_request *req, struct sip_route *route);
01514 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01515 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01516 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01517 static void set_destination(struct sip_pvt *p, char *uri);
01518 static void append_date(struct sip_request *req);
01519 static void build_contact(struct sip_pvt *p);
01520 static void build_rpid(struct sip_pvt *p);
01521
01522
01523 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
01524 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
01525 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
01526 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01527 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
01528 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01529 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01530 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
01531 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01532 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
01533 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
01534 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
01535 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
01536
01537
01538 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
01539 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
01540 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
01541 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
01542
01543
01544 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
01545 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
01546 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
01547 static int sip_get_codec(struct ast_channel *chan);
01548 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
01549
01550
01551 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
01552 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01553 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
01554 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01555 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01556
01557
01558 static const struct ast_channel_tech sip_tech = {
01559 .type = "SIP",
01560 .description = "Session Initiation Protocol (SIP)",
01561 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
01562 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01563 .requester = sip_request_call,
01564 .devicestate = sip_devicestate,
01565 .call = sip_call,
01566 .hangup = sip_hangup,
01567 .answer = sip_answer,
01568 .read = sip_read,
01569 .write = sip_write,
01570 .write_video = sip_write,
01571 .indicate = sip_indicate,
01572 .transfer = sip_transfer,
01573 .fixup = sip_fixup,
01574 .send_digit_begin = sip_senddigit_begin,
01575 .send_digit_end = sip_senddigit_end,
01576 .bridge = ast_rtp_bridge,
01577 .send_text = sip_sendtext,
01578 .func_channel_read = acf_channel_read,
01579 };
01580
01581
01582
01583
01584 static const struct ast_channel_tech sip_tech_info = {
01585 .type = "SIP",
01586 .description = "Session Initiation Protocol (SIP)",
01587 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
01588 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01589 .requester = sip_request_call,
01590 .devicestate = sip_devicestate,
01591 .call = sip_call,
01592 .hangup = sip_hangup,
01593 .answer = sip_answer,
01594 .read = sip_read,
01595 .write = sip_write,
01596 .write_video = sip_write,
01597 .indicate = sip_indicate,
01598 .transfer = sip_transfer,
01599 .fixup = sip_fixup,
01600 .send_digit_end = sip_senddigit_end,
01601 .bridge = ast_rtp_bridge,
01602 .send_text = sip_sendtext,
01603 .func_channel_read = acf_channel_read,
01604 };
01605
01606
01607
01608 #define UNLINK(element, head, prev) do { \
01609 if (prev) \
01610 (prev)->next = (element)->next; \
01611 else \
01612 (head) = (element)->next; \
01613 } while (0)
01614
01615
01616 static struct ast_rtp_protocol sip_rtp = {
01617 type: "SIP",
01618 get_rtp_info: sip_get_rtp_peer,
01619 get_vrtp_info: sip_get_vrtp_peer,
01620 set_rtp_peer: sip_set_rtp_peer,
01621 get_codec: sip_get_codec,
01622 };
01623
01624
01625 static struct ast_udptl_protocol sip_udptl = {
01626 type: "SIP",
01627 get_udptl_info: sip_get_udptl_peer,
01628 set_udptl_peer: sip_set_udptl_peer,
01629 };
01630
01631
01632 static char *referstatus2str(enum referstatus rstatus)
01633 {
01634 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
01635 int x;
01636
01637 for (x = 0; x < i; x++) {
01638 if (referstatusstrings[x].status == rstatus)
01639 return (char *) referstatusstrings[x].text;
01640 }
01641 return "";
01642 }
01643
01644
01645
01646
01647 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
01648 {
01649 if (p->initreq.headers && option_debug) {
01650 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
01651 }
01652
01653 copy_request(&p->initreq, req);
01654 parse_request(&p->initreq);
01655 if (ast_test_flag(req, SIP_PKT_DEBUG))
01656 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
01657 }
01658
01659 static void sip_alreadygone(struct sip_pvt *dialog)
01660 {
01661 if (option_debug > 2)
01662 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
01663 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
01664 }
01665
01666
01667
01668
01669
01670
01671
01672
01673 static int method_match(enum sipmethod id, const char *name)
01674 {
01675 int len = strlen(sip_methods[id].text);
01676 int l_name = name ? strlen(name) : 0;
01677
01678 return (l_name >= len && name[len] < 33 &&
01679 !strncasecmp(sip_methods[id].text, name, len));
01680 }
01681
01682
01683 static int find_sip_method(const char *msg)
01684 {
01685 int i, res = 0;
01686
01687 if (ast_strlen_zero(msg))
01688 return 0;
01689 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
01690 if (method_match(i, msg))
01691 res = sip_methods[i].id;
01692 }
01693 return res;
01694 }
01695
01696
01697 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
01698 {
01699 char *next, *sep;
01700 char *temp;
01701 unsigned int profile = 0;
01702 int i, found;
01703
01704 if (ast_strlen_zero(supported) )
01705 return 0;
01706 temp = ast_strdupa(supported);
01707
01708 if (option_debug > 2 && sipdebug)
01709 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
01710
01711 for (next = temp; next; next = sep) {
01712 found = FALSE;
01713 if ( (sep = strchr(next, ',')) != NULL)
01714 *sep++ = '\0';
01715 next = ast_skip_blanks(next);
01716 if (option_debug > 2 && sipdebug)
01717 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
01718 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
01719 if (!strcasecmp(next, sip_options[i].text)) {
01720 profile |= sip_options[i].id;
01721 found = TRUE;
01722 if (option_debug > 2 && sipdebug)
01723 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
01724 break;
01725 }
01726 }
01727 if (!found && option_debug > 2 && sipdebug) {
01728 if (!strncasecmp(next, "x-", 2))
01729 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
01730 else
01731 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
01732 }
01733 }
01734
01735 if (pvt)
01736 pvt->sipoptions = profile;
01737 return profile;
01738 }
01739
01740
01741 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
01742 {
01743 if (!sipdebug)
01744 return 0;
01745 if (debugaddr.sin_addr.s_addr) {
01746 if (((ntohs(debugaddr.sin_port) != 0)
01747 && (debugaddr.sin_port != addr->sin_port))
01748 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
01749 return 0;
01750 }
01751 return 1;
01752 }
01753
01754
01755 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
01756 {
01757 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
01758 }
01759
01760
01761 static const char *sip_nat_mode(const struct sip_pvt *p)
01762 {
01763 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
01764 }
01765
01766
01767 static inline int sip_debug_test_pvt(struct sip_pvt *p)
01768 {
01769 if (!sipdebug)
01770 return 0;
01771 return sip_debug_test_addr(sip_real_dst(p));
01772 }
01773
01774
01775 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
01776 {
01777 int res;
01778 const struct sockaddr_in *dst = sip_real_dst(p);
01779
01780 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TCP)) {
01781 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_TCP_CONNECTED)) {
01782 if (connect(p->sockfd, (const struct sockaddr *)dst, sizeof(struct sockaddr_in)) == 0) {
01783 ast_set_flag(&p->flags[1], SIP_PAGE2_TCP_CONNECTED);
01784 } else if (errno == EISCONN) {
01785 ast_set_flag(&p->flags[1], SIP_PAGE2_TCP_CONNECTED);
01786 } else {
01787 ast_log(LOG_ERROR, "Connect Failed Sock: %i %s:%d %s\n",p->sockfd,ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), strerror(errno));
01788 }
01789 }
01790 res = write(p->sockfd, data, len);
01791 } else
01792 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
01793
01794 if (res == -1) {
01795 switch (errno) {
01796 case EBADF:
01797 case EHOSTUNREACH:
01798 case ENETDOWN:
01799 case ENETUNREACH:
01800 case ECONNREFUSED:
01801 res = XMIT_ERROR;
01802 }
01803 }
01804 if (res != len)
01805 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
01806 return res;
01807 }
01808
01809
01810
01811 static void build_via(struct sip_pvt *p)
01812 {
01813
01814 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
01815
01816
01817 ast_string_field_build(p, via, "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
01818 ast_test_flag(&p->flags[1], SIP_PAGE2_TCP) ? "TCP" : "UDP", ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
01819 }
01820
01821
01822
01823
01824
01825
01826
01827 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
01828 {
01829 struct sockaddr_in theirs, ours;
01830
01831
01832 ast_ouraddrfor(them, us);
01833 theirs.sin_addr = *them;
01834 ours.sin_addr = *us;
01835
01836 if (localaddr && externip.sin_addr.s_addr &&
01837 (ast_apply_ha(localaddr, &theirs)) &&
01838 (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
01839 if (externexpire && time(NULL) >= externexpire) {
01840 struct ast_hostent ahp;
01841 struct hostent *hp;
01842
01843 externexpire = time(NULL) + externrefresh;
01844 if ((hp = ast_gethostbyname(externhost, &ahp))) {
01845 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
01846 } else
01847 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
01848 }
01849 *us = externip.sin_addr;
01850 if (option_debug) {
01851 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
01852 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
01853 }
01854 } else if (bindaddr.sin_addr.s_addr)
01855 *us = bindaddr.sin_addr;
01856 return AST_SUCCESS;
01857 }
01858
01859
01860
01861 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
01862
01863 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
01864 __attribute__ ((format (printf, 2, 3)));
01865
01866
01867 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
01868 {
01869 char buf[80], *c = buf;
01870 struct sip_history *hist;
01871 int l;
01872
01873 vsnprintf(buf, sizeof(buf), fmt, ap);
01874 strsep(&c, "\r\n");
01875 l = strlen(buf) + 1;
01876 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
01877 return;
01878 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
01879 free(hist);
01880 return;
01881 }
01882 memcpy(hist->event, buf, l);
01883 if (p->history_entries == MAX_HISTORY_ENTRIES) {
01884 struct sip_history *oldest;
01885 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
01886 p->history_entries--;
01887 free(oldest);
01888 }
01889 AST_LIST_INSERT_TAIL(p->history, hist, list);
01890 p->history_entries++;
01891 }
01892
01893
01894 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
01895 {
01896 va_list ap;
01897
01898 if (!p)
01899 return;
01900
01901 if (ast_test_flag(&p->flags[0], SIP_NO_HISTORY)
01902 && !recordhistory && !dumphistory) {
01903 return;
01904 }
01905
01906 va_start(ap, fmt);
01907 append_history_va(p, fmt, ap);
01908 va_end(ap);
01909
01910 return;
01911 }
01912
01913
01914 static int retrans_pkt(const void *data)
01915 {
01916 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
01917 int reschedule = DEFAULT_RETRANS;
01918 int xmitres = 0;
01919
01920
01921 ast_mutex_lock(&pkt->owner->lock);
01922
01923 if (pkt->retrans < MAX_RETRANS) {
01924 pkt->retrans++;
01925 if (!pkt->timer_t1) {
01926 if (sipdebug && option_debug > 3)
01927 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);
01928 } else {
01929 int siptimer_a;
01930
01931 if (sipdebug && option_debug > 3)
01932 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
01933 if (!pkt->timer_a)
01934 pkt->timer_a = 2 ;
01935 else
01936 pkt->timer_a = 2 * pkt->timer_a;
01937
01938
01939 siptimer_a = pkt->timer_t1 * pkt->timer_a;
01940 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
01941 siptimer_a = 4000;
01942
01943
01944 reschedule = siptimer_a;
01945 if (option_debug > 3)
01946 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);
01947 }
01948
01949 if (sip_debug_test_pvt(pkt->owner)) {
01950 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
01951 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
01952 pkt->retrans, sip_nat_mode(pkt->owner),
01953 ast_inet_ntoa(dst->sin_addr),
01954 ntohs(dst->sin_port), pkt->data);
01955 }
01956
01957 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
01958 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
01959 ast_mutex_unlock(&pkt->owner->lock);
01960 if (xmitres == XMIT_ERROR)
01961 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
01962 else
01963 return reschedule;
01964 }
01965
01966 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
01967 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug)
01968 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s from %s for packet seqno %d (%s %s %s)\n", pkt->owner->callid, pkt->owner->from, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response: " : "Request: ", sip_methods[pkt->method].text);
01969 } else if ((pkt->method == SIP_OPTIONS) && sipdebug) {
01970 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
01971 }
01972 if (xmitres == XMIT_ERROR) {
01973 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission of transaction in call id %s \n", pkt->owner->callid);
01974 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
01975 } else
01976 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
01977
01978 pkt->retransid = -1;
01979
01980 if (ast_test_flag(pkt, FLAG_FATAL)) {
01981 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
01982 DEADLOCK_AVOIDANCE(&pkt->owner->lock);
01983 }
01984
01985 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
01986 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
01987
01988 if (pkt->owner->owner) {
01989 sip_alreadygone(pkt->owner);
01990 ast_log(LOG_WARNING, "Hanging up call %s from channel %s . No reply to our critical packet after %d retries.\n", pkt->owner->callid, pkt->owner->owner->name, pkt->retrans);
01991 ast_queue_hangup(pkt->owner->owner);
01992 ast_channel_unlock(pkt->owner->owner);
01993 } else {
01994
01995
01996
01997 if (pkt->method != SIP_OPTIONS) {
01998 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
01999 sip_alreadygone(pkt->owner);
02000 if (option_debug)
02001 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
02002 }
02003 }
02004 }
02005
02006 if (pkt->method == SIP_BYE) {
02007
02008 if (pkt->owner->owner)
02009 ast_channel_unlock(pkt->owner->owner);
02010 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
02011 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
02012 }
02013
02014
02015 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
02016 if (cur == pkt)
02017 break;
02018 }
02019 if (cur) {
02020 if (prev)
02021 prev->next = cur->next;
02022 else
02023 pkt->owner->packets = cur->next;
02024 ast_mutex_unlock(&pkt->owner->lock);
02025 free(cur);
02026 pkt = NULL;
02027 } else
02028 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
02029 if (pkt)
02030 ast_mutex_unlock(&pkt->owner->lock);
02031 return 0;
02032 }
02033
02034
02035
02036
02037 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
02038 {
02039 struct sip_pkt *pkt;
02040 int siptimer_a = DEFAULT_RETRANS;
02041 int xmitres = 0;
02042
02043 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
02044 return AST_FAILURE;
02045 memcpy(pkt->data, data, len);
02046 pkt->method = sipmethod;
02047 pkt->packetlen = len;
02048 pkt->next = p->packets;
02049 pkt->owner = p;
02050 pkt->seqno = seqno;
02051 if (resp)
02052 ast_set_flag(pkt, FLAG_RESPONSE);
02053 pkt->data[len] = '\0';
02054 pkt->timer_t1 = p->timer_t1;
02055 pkt->retransid = -1;
02056 if (fatal)
02057 ast_set_flag(pkt, FLAG_FATAL);
02058 if (pkt->timer_t1)
02059 siptimer_a = pkt->timer_t1 * 2;
02060
02061 if (option_debug > 3 && sipdebug)
02062 ast_log(LOG_DEBUG, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
02063 pkt->retransid = -1;
02064 pkt->next = p->packets;
02065 p->packets = pkt;
02066 if (sipmethod == SIP_INVITE) {
02067
02068 p->pendinginvite = seqno;
02069 }
02070
02071 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
02072
02073 if (xmitres == XMIT_ERROR) {
02074 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
02075 return AST_FAILURE;
02076 } else {
02077
02078 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
02079 return AST_SUCCESS;
02080 }
02081 }
02082
02083
02084 static int __sip_autodestruct(const void *data)
02085 {
02086 struct sip_pvt *p = (struct sip_pvt *)data;
02087
02088
02089 if (p->subscribed) {
02090 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
02091 p->subscribed = NONE;
02092 append_history(p, "Subscribestatus", "timeout");
02093 if (option_debug > 2)
02094 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
02095 return 10000;
02096 }
02097
02098
02099 if (p->packets) {
02100 if (option_debug > 2)
02101 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
02102 append_history(p, "ReliableXmit", "timeout");
02103 return 10000;
02104 }
02105
02106
02107 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
02108 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
02109
02110
02111 p->autokillid = -1;
02112
02113 if (option_debug)
02114 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
02115 append_history(p, "AutoDestroy", "%s", p->callid);
02116 if (p->owner) {
02117 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
02118 ast_queue_hangup(p->owner);
02119 } else if (p->refer) {
02120 if (option_debug > 2)
02121 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
02122 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
02123 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
02124 } else
02125 sip_destroy(p);
02126 return 0;
02127 }
02128
02129
02130 static void sip_scheddestroy(struct sip_pvt *p, int ms)
02131 {
02132 if (ms < 0) {
02133 if (p->timer_t1 == 0)
02134 p->timer_t1 = 500;
02135 ms = p->timer_t1 * 64;
02136 }
02137 if (sip_debug_test_pvt(p))
02138 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
02139 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
02140 append_history(p, "SchedDestroy", "%d ms", ms);
02141
02142 AST_SCHED_DEL(sched, p->autokillid);
02143 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
02144 }
02145
02146
02147 static int sip_cancel_destroy(struct sip_pvt *p)
02148 {
02149 int res = 0;
02150 if (p->autokillid > -1) {
02151 if (!(res = ast_sched_del(sched, p->autokillid))) {
02152 append_history(p, "CancelDestroy", "");
02153 p->autokillid = -1;
02154 }
02155 }
02156 return res;
02157 }
02158
02159
02160
02161 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
02162 {
02163 struct sip_pkt *cur, *prev = NULL;
02164
02165
02166 char *msg;
02167 int res = FALSE;
02168
02169 msg = sip_methods[sipmethod].text;
02170
02171 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
02172 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
02173 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
02174 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
02175 if (!resp && (seqno == p->pendinginvite)) {
02176 if (option_debug)
02177 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
02178 p->pendinginvite = 0;
02179 }
02180
02181 res = TRUE;
02182 UNLINK(cur, p->packets, prev);
02183 if (cur->retransid > -1) {
02184 if (sipdebug && option_debug > 3)
02185 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
02186 }
02187
02188
02189
02190
02191
02192
02193
02194
02195
02196
02197
02198
02199
02200
02201
02202
02203 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
02204 DEADLOCK_AVOIDANCE(&p->lock);
02205 }
02206 free(cur);
02207 break;
02208 }
02209 }
02210 if (option_debug)
02211 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res == FALSE ? "Not Found" : "Found");
02212 }
02213
02214
02215
02216 static void __sip_pretend_ack(struct sip_pvt *p)
02217 {
02218 struct sip_pkt *cur = NULL;
02219
02220 while (p->packets) {
02221 int method;
02222 if (cur == p->packets) {
02223 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
02224 return;
02225 }
02226 cur = p->packets;
02227 method = (cur->method) ? cur->method : find_sip_method(cur->data);
02228 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
02229 }
02230 }
02231
02232
02233 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
02234 {
02235 struct sip_pkt *cur;
02236 int res = -1;
02237
02238 for (cur = p->packets; cur; cur = cur->next) {
02239 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
02240 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
02241
02242 if (cur->retransid > -1) {
02243 if (option_debug > 3 && sipdebug)
02244 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
02245 }
02246 AST_SCHED_DEL(sched, cur->retransid);
02247 res = 0;
02248 break;
02249 }
02250 }
02251 if (option_debug)
02252 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
02253 return res;
02254 }
02255
02256
02257
02258 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
02259 {
02260 memset(dst, 0, sizeof(*dst));
02261 memcpy(dst->data, src->data, sizeof(dst->data));
02262 dst->len = src->len;
02263 parse_request(dst);
02264 }
02265
02266
02267 static void add_blank(struct sip_request *req)
02268 {
02269 if (!req->lines) {
02270
02271 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
02272 req->len += strlen(req->data + req->len);
02273 }
02274 }
02275
02276
02277 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
02278 {
02279 int res;
02280
02281 add_blank(req);
02282 if (sip_debug_test_pvt(p)) {
02283 const struct sockaddr_in *dst = sip_real_dst(p);
02284
02285 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
02286 reliable ? "Reliably " : "", sip_nat_mode(p),
02287 ast_inet_ntoa(dst->sin_addr),
02288 ntohs(dst->sin_port), req->data);
02289 }
02290 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
02291 struct sip_request tmp;
02292 parse_copy(&tmp, req);
02293 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
02294 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
02295 }
02296 res = (reliable) ?
02297 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
02298 __sip_xmit(p, req->data, req->len);
02299 if (res > 0)
02300 return 0;
02301 return res;
02302 }
02303
02304
02305 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
02306 {
02307 int res;
02308
02309 add_blank(req);
02310 if (sip_debug_test_pvt(p)) {
02311 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
02312 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
02313 else
02314 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
02315 }
02316 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
02317 struct sip_request tmp;
02318 parse_copy(&tmp, req);
02319 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
02320 }
02321 res = (reliable) ?
02322 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
02323 __sip_xmit(p, req->data, req->len);
02324 return res;
02325 }
02326
02327
02328
02329
02330
02331 static const char *find_closing_quote(const char *start, const char *lim)
02332 {
02333 char last_char = '\0';
02334 const char *s;
02335 for (s = start; *s && s != lim; last_char = *s++) {
02336 if (*s == '"' && last_char != '\\')
02337 break;
02338 }
02339 return s;
02340 }
02341
02342
02343
02344
02345
02346
02347
02348
02349
02350
02351
02352
02353 static char *get_in_brackets(char *tmp)
02354 {
02355 const char *parse = tmp;
02356 char *first_bracket;
02357
02358
02359
02360
02361
02362 while ( (first_bracket = strchr(parse, '<')) ) {
02363 char *first_quote = strchr(parse, '"');
02364
02365 if (!first_quote || first_quote > first_bracket)
02366 break;
02367
02368 parse = find_closing_quote(first_quote + 1, NULL);
02369 if (!*parse) {
02370
02371 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
02372 break;
02373 }
02374 parse++;
02375 }
02376 if (first_bracket) {
02377 char *second_bracket = strchr(first_bracket + 1, '>');
02378 if (second_bracket) {
02379 *second_bracket = '\0';
02380 tmp = first_bracket + 1;
02381 } else {
02382 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
02383 }
02384 }
02385 return tmp;
02386 }
02387
02388
02389
02390 static int sip_sendtext(struct ast_channel *ast, const char *text)
02391 {
02392 struct sip_pvt *p = ast->tech_pvt;
02393 int debug = sip_debug_test_pvt(p);
02394
02395 if (debug)
02396 ast_verbose("Sending text %s on %s\n", text, ast->name);
02397 if (!p)
02398 return -1;
02399 if (ast_strlen_zero(text))
02400 return 0;
02401 if (debug)
02402 ast_verbose("Really sending text %s on %s\n", text, ast->name);
02403 transmit_message_with_text(p, text);
02404 return 0;
02405 }
02406
02407
02408
02409
02410
02411
02412 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
02413 {
02414 char port[10];
02415 char ipaddr[INET_ADDRSTRLEN];
02416 char regseconds[20];
02417
02418 char *sysname = ast_config_AST_SYSTEM_NAME;
02419 char *syslabel = NULL;
02420
02421 time_t nowtime = time(NULL) + expirey;
02422 const char *fc = fullcontact ? "fullcontact" : NULL;
02423
02424 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
02425 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
02426 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
02427
02428 if (ast_strlen_zero(sysname))
02429 sysname = NULL;
02430 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
02431 syslabel = "regserver";
02432
02433 if (fc)
02434 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
02435 "port", port, "regseconds", regseconds,
02436 "username", username, fc, fullcontact, syslabel, sysname, NULL);
02437 else
02438 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
02439 "port", port, "regseconds", regseconds,
02440 "username", username, syslabel, sysname, NULL);
02441 }
02442
02443
02444 static void register_peer_exten(struct sip_peer *peer, int onoff)
02445 {
02446 char multi[256];
02447 char *stringp, *ext, *context;
02448
02449
02450
02451
02452
02453 if (ast_strlen_zero(global_regcontext))
02454 return;
02455
02456 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
02457 stringp = multi;
02458 while ((ext = strsep(&stringp, "&"))) {
02459 if ((context = strchr(ext, '@'))) {
02460 *context++ = '\0';
02461 if (!ast_context_find(context)) {
02462 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
02463 continue;
02464 }
02465 } else {
02466 context = global_regcontext;
02467 }
02468 if (onoff)
02469 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
02470 ast_strdup(peer->name), ast_free, "SIP");
02471 else
02472 ast_context_remove_extension(context, ext, 1, NULL);
02473 }
02474 }
02475
02476
02477 static void sip_destroy_peer(struct sip_peer *peer)
02478 {
02479 if (option_debug > 2)
02480 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
02481
02482
02483 if (peer->call)
02484 sip_destroy(peer->call);
02485
02486 if (peer->mwipvt)
02487 sip_destroy(peer->mwipvt);
02488
02489 if (peer->chanvars) {
02490 ast_variables_destroy(peer->chanvars);
02491 peer->chanvars = NULL;
02492 }
02493
02494 register_peer_exten(peer, FALSE);
02495 ast_free_ha(peer->ha);
02496 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
02497 apeerobjs--;
02498 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
02499 rpeerobjs--;
02500 else
02501 speerobjs--;
02502 clear_realm_authentication(peer->auth);
02503 peer->auth = NULL;
02504 free(peer);
02505 }
02506
02507
02508 static void update_peer(struct sip_peer *p, int expiry)
02509 {
02510 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
02511 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
02512 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
02513 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
02514 }
02515 }
02516
02517
02518
02519
02520
02521
02522
02523 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
02524 {
02525 struct sip_peer *peer=NULL;
02526 struct ast_variable *var = NULL;
02527 struct ast_config *peerlist = NULL;
02528 struct ast_variable *tmp;
02529 struct ast_flags flags = {0};
02530 const char *iabuf = NULL;
02531 char portstring[6];
02532 const char *insecure;
02533 char *cat = NULL;
02534 unsigned short portnum;
02535
02536
02537 if (newpeername) {
02538 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
02539 if (!var && sin)
02540 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
02541 if (!var) {
02542 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
02543
02544
02545
02546
02547
02548
02549 if (var && sin) {
02550 for (tmp = var; tmp; tmp = tmp->next) {
02551 if (!strcasecmp(tmp->name, "host")) {
02552 struct hostent *hp;
02553 struct ast_hostent ahp;
02554 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
02555
02556 ast_variables_destroy(var);
02557 var = NULL;
02558 }
02559 break;
02560 }
02561 }
02562 }
02563 }
02564 }
02565
02566 if (!var && sin) {
02567 iabuf = ast_inet_ntoa(sin->sin_addr);
02568 portnum = ntohs(sin->sin_port);
02569 sprintf(portstring, "%d", portnum);
02570 var = ast_load_realtime("sippeers", "host", iabuf, "port", portstring, NULL);
02571 if (!var)
02572 var = ast_load_realtime("sippeers", "ipaddr", iabuf, "port", portstring, NULL);
02573 if (!var) {
02574 peerlist = ast_load_realtime_multientry("sippeers", "host", iabuf, NULL);
02575 if(peerlist){
02576 while((cat = ast_category_browse(peerlist, cat)))
02577 {
02578 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
02579 set_insecure_flags(&flags, insecure, -1);
02580 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
02581 var = ast_category_root(peerlist, cat);
02582 break;
02583 }
02584 }
02585 }
02586 if(!var) {
02587 ast_config_destroy(peerlist);
02588 peerlist = NULL;
02589 cat = NULL;
02590 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", iabuf, NULL);
02591 if(peerlist) {
02592 while((cat = ast_category_browse(peerlist, cat)))
02593 {
02594 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
02595 set_insecure_flags(&flags, insecure, -1);
02596 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
02597 var = ast_category_root(peerlist, cat);
02598 break;
02599 }
02600 }
02601 }
02602 }
02603 }
02604 }
02605
02606 if (!var) {
02607 if(peerlist)
02608 ast_config_destroy(peerlist);
02609 return NULL;
02610 }
02611
02612 for (tmp = var; tmp; tmp = tmp->next) {
02613
02614 if (!strcasecmp(tmp->name, "type") &&
02615 !strcasecmp(tmp->value, "user")) {
02616 ast_variables_destroy(var);
02617 return NULL;
02618 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
02619 newpeername = tmp->value;
02620 }
02621 }
02622
02623 if (!newpeername) {
02624 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
02625 if(peerlist)
02626 ast_config_destroy(peerlist);
02627 else
02628 ast_variables_destroy(var);
02629 return NULL;
02630 }
02631
02632
02633 peer = build_peer(newpeername, var, NULL, 1);
02634 if (!peer) {
02635 if(peerlist)
02636 ast_config_destroy(peerlist);
02637 else
02638 ast_variables_destroy(var);
02639 return NULL;
02640 }
02641
02642 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
02643
02644 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
02645 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
02646 if (!AST_SCHED_DEL(sched, peer->expire)) {
02647 struct sip_peer *peer_ptr = peer;
02648 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
02649 }
02650 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, ASTOBJ_REF(peer));
02651 if (peer->expire == -1) {
02652 struct sip_peer *peer_ptr = peer;
02653 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
02654 }
02655 }
02656 ASTOBJ_CONTAINER_LINK(&peerl,peer);
02657 } else {
02658 ast_set_flag(&peer->flags[0], SIP_REALTIME);
02659 }
02660 if(peerlist)
02661 ast_config_destroy(peerlist);
02662 else
02663 ast_variables_destroy(var);
02664 return peer;
02665 }
02666
02667
02668 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
02669 {
02670
02671 struct sip_peer *p = (struct sip_peer *) name;
02672 return !(!inaddrcmp(&p->addr, sin) ||
02673 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
02674 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
02675 }
02676
02677
02678
02679
02680 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
02681 {
02682 struct sip_peer *p = NULL;
02683
02684 if (peer)
02685 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
02686 else
02687 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
02688
02689 if (!p && realtime)
02690 p = realtime_peer(peer, sin);
02691
02692 return p;
02693 }
02694
02695
02696 static void sip_destroy_user(struct sip_user *user)
02697 {
02698 if (option_debug > 2)
02699 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
02700 ast_free_ha(user->ha);
02701 if (user->chanvars) {
02702 ast_variables_destroy(user->chanvars);
02703 user->chanvars = NULL;
02704 }
02705 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
02706 ruserobjs--;
02707 else
02708 suserobjs--;
02709 free(user);
02710 }
02711
02712
02713
02714
02715 static struct sip_user *realtime_user(const char *username)
02716 {
02717 struct ast_variable *var;
02718 struct ast_variable *tmp;
02719 struct sip_user *user = NULL;
02720
02721 var = ast_load_realtime("sipusers", "name", username, NULL);
02722
02723 if (!var)
02724 return NULL;
02725
02726 for (tmp = var; tmp; tmp = tmp->next) {
02727 if (!strcasecmp(tmp->name, "type") &&
02728 !strcasecmp(tmp->value, "peer")) {
02729 ast_variables_destroy(var);
02730 return NULL;
02731 }
02732 }
02733
02734 user = build_user(username, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
02735
02736 if (!user) {
02737 ast_variables_destroy(var);
02738 return NULL;
02739 }
02740
02741 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
02742 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
02743 suserobjs++;
02744 ASTOBJ_CONTAINER_LINK(&userl,user);
02745 } else {
02746
02747 suserobjs--;
02748 ruserobjs++;
02749 ast_set_flag(&user->flags[0], SIP_REALTIME);
02750 }
02751 ast_variables_destroy(var);
02752 return user;
02753 }
02754
02755
02756
02757
02758
02759 static struct sip_user *find_user(const char *name, int realtime)
02760 {
02761 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
02762 if (!u && realtime)
02763 u = realtime_user(name);
02764 return u;
02765 }
02766
02767
02768 static void do_setnat(struct sip_pvt *p, int natflags)
02769 {
02770 const char *mode = natflags ? "On" : "Off";
02771
02772 if (p->rtp) {
02773 if (option_debug)
02774 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
02775 ast_rtp_setnat(p->rtp, natflags);
02776 }
02777 if (p->vrtp) {
02778 if (option_debug)
02779 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
02780 ast_rtp_setnat(p->vrtp, natflags);
02781 }
02782 if (p->udptl) {
02783 if (option_debug)
02784 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
02785 ast_udptl_setnat(p->udptl, natflags);
02786 }
02787 }
02788
02789
02790
02791
02792 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
02793 {
02794 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
02795 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
02796 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
02797 dialog->recv = dialog->sa;
02798 } else
02799 return -1;
02800
02801 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
02802 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
02803 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_TCP | SIP_PAGE2_TCP_CONNECTED);
02804 dialog->sockfd = peer->sockfd;
02805 dialog->capability = peer->capability;
02806 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
02807 ast_rtp_destroy(dialog->vrtp);
02808 dialog->vrtp = NULL;
02809 }
02810 dialog->prefs = peer->prefs;
02811 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
02812 dialog->t38.capability = global_t38_capability;
02813 if (dialog->udptl) {
02814 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
02815 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
02816 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
02817 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
02818 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
02819 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
02820 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
02821 if (option_debug > 1)
02822 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
02823 }
02824 dialog->t38.jointcapability = dialog->t38.capability;
02825 } else if (dialog->udptl) {
02826 ast_udptl_destroy(dialog->udptl);
02827 dialog->udptl = NULL;
02828 }
02829 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
02830
02831 if (dialog->rtp) {
02832 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
02833 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
02834 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
02835 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
02836 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
02837
02838 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
02839 dialog->autoframing = peer->autoframing;
02840 }
02841 if (dialog->vrtp) {
02842 ast_rtp_setdtmf(dialog->vrtp, 0);
02843 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
02844 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
02845 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
02846 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
02847 }
02848
02849 ast_string_field_set(dialog, peername, peer->name);
02850 ast_string_field_set(dialog, authname, peer->username);
02851 ast_string_field_set(dialog, username, peer->username);
02852 ast_string_field_set(dialog, peersecret, peer->secret);
02853 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
02854 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
02855 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
02856 ast_string_field_set(dialog, tohost, peer->tohost);
02857 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
02858 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
02859 char *tmpcall;
02860 char *c;
02861 tmpcall = ast_strdupa(dialog->callid);
02862 c = strchr(tmpcall, '@');
02863 if (c) {
02864 *c = '\0';
02865 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
02866 }
02867 }
02868 if (ast_strlen_zero(dialog->tohost))
02869 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
02870 if (!ast_strlen_zero(peer->fromdomain))
02871 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
02872 if (!ast_strlen_zero(peer->fromuser))
02873 ast_string_field_set(dialog, fromuser, peer->fromuser);
02874 if (!ast_strlen_zero(peer->language))
02875 ast_string_field_set(dialog, language, peer->language);
02876 dialog->maxtime = peer->maxms;
02877 dialog->callgroup = peer->callgroup;
02878 dialog->pickupgroup = peer->pickupgroup;
02879 dialog->allowtransfer = peer->allowtransfer;
02880
02881
02882 if (peer->maxms && peer->lastms)
02883 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
02884 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
02885 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
02886 dialog->noncodeccapability |= AST_RTP_DTMF;
02887 else
02888 dialog->noncodeccapability &= ~AST_RTP_DTMF;
02889 dialog->jointnoncodeccapability = dialog->noncodeccapability;
02890 ast_string_field_set(dialog, context, peer->context);
02891 dialog->rtptimeout = peer->rtptimeout;
02892 if (peer->call_limit)
02893 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
02894 dialog->maxcallbitrate = peer->maxcallbitrate;
02895
02896 return 0;
02897 }
02898
02899
02900
02901
02902 static int create_addr(struct sip_pvt *dialog, const char *opeer)
02903 {
02904 struct hostent *hp;
02905 struct ast_hostent ahp;
02906 struct sip_peer *p;
02907 char *port;
02908 int portno;
02909 char host[MAXHOSTNAMELEN], *hostn;
02910 char peer[256];
02911
02912 ast_copy_string(peer, opeer, sizeof(peer));
02913 port = strchr(peer, ':');
02914 if (port)
02915 *port++ = '\0';
02916 dialog->sa.sin_family = AF_INET;
02917 dialog->timer_t1 = 500;
02918 p = find_peer(peer, NULL, 1);
02919
02920 if (p) {
02921 int res = create_addr_from_peer(dialog, p);
02922 ASTOBJ_UNREF(p, sip_destroy_peer);
02923 return res;
02924 }
02925 hostn = peer;
02926 portno = port ? atoi(port) : STANDARD_SIP_PORT;
02927 if (srvlookup) {
02928 char service[MAXHOSTNAMELEN];
02929 int tportno;
02930 int ret;
02931
02932 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
02933 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
02934 if (ret > 0) {
02935 hostn = host;
02936 portno = tportno;
02937 }
02938 }
02939 hp = ast_gethostbyname(hostn, &ahp);
02940 if (!hp) {
02941 ast_log(LOG_WARNING, "No such host: %s\n", peer);
02942 return -1;
02943 }
02944 ast_string_field_set(dialog, tohost, peer);
02945 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
02946 dialog->sa.sin_port = htons(portno);
02947 dialog->recv = dialog->sa;
02948 return 0;
02949 }
02950
02951
02952 static int auto_congest(const void *nothing)
02953 {
02954 struct sip_pvt *p = (struct sip_pvt *)nothing;
02955
02956 ast_mutex_lock(&p->lock);
02957 p->initid = -1;
02958 if (p->owner) {
02959
02960 if (!ast_channel_trylock(p->owner)) {
02961 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
02962 append_history(p, "Cong", "Auto-congesting (timer)");
02963 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
02964 ast_channel_unlock(p->owner);
02965 }
02966 }
02967 ast_mutex_unlock(&p->lock);
02968 return 0;
02969 }
02970
02971
02972
02973
02974 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
02975 {
02976 int res, xmitres = 0;
02977 struct sip_pvt *p;
02978 struct varshead *headp;
02979 struct ast_var_t *current;
02980 const char *referer = NULL;
02981
02982 p = ast->tech_pvt;
02983 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
02984 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
02985 return -1;
02986 }
02987
02988
02989 headp=&ast->varshead;
02990 AST_LIST_TRAVERSE(headp,current,entries) {
02991
02992 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
02993 p->options->vxml_url = ast_var_value(current);
02994 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
02995 p->options->uri_options = ast_var_value(current);
02996 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
02997
02998 p->options->distinctive_ring = ast_var_value(current);
02999 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
03000
03001 p->options->addsipheaders = 1;
03002 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
03003
03004 p->options->transfer = 1;
03005 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
03006
03007 referer = ast_var_value(current);
03008 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
03009
03010 p->options->replaces = ast_var_value(current);
03011 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
03012 p->t38.state = T38_LOCAL_DIRECT;
03013 if (option_debug)
03014 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
03015 }
03016
03017 }
03018
03019 res = 0;
03020 ast_set_flag(&p->flags[0], SIP_OUTGOING);
03021
03022 if (p->options->transfer) {
03023 char buf[SIPBUFSIZE/2];
03024
03025 if (referer) {
03026 if (sipdebug && option_debug > 2)
03027 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
03028 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
03029 } else
03030 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
03031 ast_string_field_set(p, cid_name, buf);
03032 }
03033 if (option_debug)
03034 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
03035
03036 res = update_call_counter(p, INC_CALL_RINGING);
03037 if ( res != -1 ) {
03038 p->callingpres = ast->cid.cid_pres;
03039 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
03040 p->jointnoncodeccapability = p->noncodeccapability;
03041
03042
03043 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
03044 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
03045 res = -1;
03046 } else {
03047 p->t38.jointcapability = p->t38.capability;
03048 if (option_debug > 1)
03049 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
03050 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
03051 if (xmitres == XMIT_ERROR)
03052 return -1;
03053
03054 p->invitestate = INV_CALLING;
03055
03056
03057 AST_SCHED_DEL(sched, p->initid);
03058 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
03059 }
03060 }
03061 return res;
03062 }
03063
03064
03065
03066 static void sip_registry_destroy(struct sip_registry *reg)
03067 {
03068
03069 if (option_debug > 2)
03070 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
03071
03072 if (reg->call) {
03073
03074
03075 reg->call->registry = NULL;
03076 if (option_debug > 2)
03077 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
03078 sip_destroy(reg->call);
03079 }
03080 AST_SCHED_DEL(sched, reg->expire);
03081 AST_SCHED_DEL(sched, reg->timeout);
03082 ast_string_field_free_memory(reg);
03083 regobjs--;
03084 free(reg);
03085
03086 }
03087
03088
03089 static int __sip_destroy(struct sip_pvt *p, int lockowner)
03090 {
03091 struct sip_pvt *cur, *prev = NULL;
03092 struct sip_pkt *cp;
03093
03094
03095 if (p->rtp && ast_rtp_get_bridged(p->rtp)) {
03096 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
03097 return -1;
03098 }
03099
03100 if (p->vrtp && ast_rtp_get_bridged(p->vrtp)) {
03101 ast_verbose("Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
03102 return -1;
03103 }
03104
03105 if (sip_debug_test_pvt(p) || option_debug > 2)
03106 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
03107
03108 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
03109 update_call_counter(p, DEC_CALL_LIMIT);
03110 if (option_debug > 1)
03111 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
03112 }
03113
03114
03115 if (p->owner) {
03116 if (lockowner)
03117 ast_channel_lock(p->owner);
03118 if (option_debug)
03119 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
03120 p->owner->tech_pvt = NULL;
03121
03122 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
03123 if (lockowner)
03124 ast_channel_unlock(p->owner);
03125
03126 usleep(1);
03127 }
03128
03129
03130 if (p->relatedpeer) {
03131 p->relatedpeer->mwipvt = NULL;
03132 ASTOBJ_UNREF(p->relatedpeer, sip_destroy_peer);
03133 }
03134
03135 if (dumphistory)
03136 sip_dump_history(p);
03137
03138 if (p->options)
03139 free(p->options);
03140
03141 if (p->stateid > -1)
03142 ast_extension_state_del(p->stateid, NULL);
03143 AST_SCHED_DEL(sched, p->initid);
03144 AST_SCHED_DEL(sched, p->waitid);
03145 AST_SCHED_DEL(sched, p->autokillid);
03146
03147 if (p->rtp) {
03148 ast_rtp_destroy(p->rtp);
03149 }
03150 if (p->vrtp) {
03151 ast_rtp_destroy(p->vrtp);
03152 }
03153 if (p->udptl)
03154 ast_udptl_destroy(p->udptl);
03155 if (p->refer)
03156 free(p->refer);
03157 if (p->route) {
03158 free_old_route(p->route);
03159 p->route = NULL;
03160 }
03161 if (p->registry) {
03162 if (p->registry->call == p)
03163 p->registry->call = NULL;
03164 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
03165 }
03166
03167
03168 if (p->history) {
03169 struct sip_history *hist;
03170 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
03171 free(hist);
03172 p->history_entries--;
03173 }
03174 free(p->history);
03175 p->history = NULL;
03176 }
03177
03178 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
03179 if (cur == p) {
03180 UNLINK(cur, iflist, prev);
03181 break;
03182 }
03183 }
03184 if (!cur) {
03185 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
03186 return 0;
03187 }
03188
03189
03190 while((cp = p->packets)) {
03191 p->packets = p->packets->next;
03192 AST_SCHED_DEL(sched, cp->retransid);
03193 free(cp);
03194 }
03195 if (p->chanvars) {
03196 ast_variables_destroy(p->chanvars);
03197 p->chanvars = NULL;
03198 }
03199 ast_mutex_destroy(&p->lock);
03200
03201 ast_string_field_free_memory(p);
03202
03203 free(p);
03204 return 0;
03205 }
03206
03207
03208
03209
03210
03211
03212
03213
03214
03215
03216
03217
03218
03219
03220
03221 static int update_call_counter(struct sip_pvt *fup, int event)
03222 {
03223 char name[256];
03224 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
03225 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
03226 struct sip_user *u = NULL;
03227 struct sip_peer *p = NULL;
03228
03229 if (option_debug > 2)
03230 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
03231
03232
03233
03234 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
03235 return 0;
03236
03237 ast_copy_string(name, fup->username, sizeof(name));
03238
03239
03240 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
03241 inuse = &u->inUse;
03242 call_limit = &u->call_limit;
03243 inringing = NULL;
03244 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) {
03245 inuse = &p->inUse;
03246 call_limit = &p->call_limit;
03247 inringing = &p->inRinging;
03248 ast_copy_string(name, fup->peername, sizeof(name));
03249 }
03250 if (!p && !u) {
03251 if (option_debug > 1)
03252 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
03253 return 0;
03254 }
03255
03256 switch(event) {
03257
03258 case DEC_CALL_LIMIT:
03259 if ( *inuse > 0 ) {
03260 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
03261 (*inuse)--;
03262 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
03263 }
03264 } else {
03265 *inuse = 0;
03266 }
03267 if (inringing) {
03268 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03269 if (*inringing > 0)
03270 (*inringing)--;
03271 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
03272 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
03273 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03274 }
03275 }
03276 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
03277 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
03278 sip_peer_hold(fup, 0);
03279 }
03280 if (option_debug > 1 || sipdebug) {
03281 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
03282 }
03283 break;
03284
03285 case INC_CALL_RINGING:
03286 case INC_CALL_LIMIT:
03287 if (*call_limit > 0 ) {
03288
03289 if (outgoing && (*inuse >= *call_limit)) {
03290 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
03291 if (u)
03292 ASTOBJ_UNREF(u, sip_destroy_user);
03293 else
03294 ASTOBJ_UNREF(p, sip_destroy_peer);
03295 return -1;
03296 }
03297 }
03298 if (inringing && (event == INC_CALL_RINGING)) {
03299 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03300 (*inringing)++;
03301 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03302 }
03303 }
03304
03305 (*inuse)++;
03306 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
03307 if (option_debug > 1 || sipdebug) {
03308 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
03309 }
03310 break;
03311
03312 case DEC_CALL_RINGING:
03313 if (inringing) {
03314 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03315 if (*inringing > 0)
03316 (*inringing)--;
03317 else if (!ast_test_flag(&p->flags[0], SIP_REALTIME) || ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
03318 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
03319 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03320 }
03321 }
03322 break;
03323
03324 default:
03325 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
03326 }
03327 if (p) {
03328 ast_device_state_changed("SIP/%s", p->name);
03329 ASTOBJ_UNREF(p, sip_destroy_peer);
03330 } else
03331 ASTOBJ_UNREF(u, sip_destroy_user);
03332 return 0;
03333 }
03334
03335
03336 static void sip_destroy(struct sip_pvt *p)
03337 {
03338 ast_mutex_lock(&iflock);
03339 if (option_debug > 2)
03340 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
03341 __sip_destroy(p, 1);
03342 ast_mutex_unlock(&iflock);
03343 }
03344
03345
03346 static int hangup_sip2cause(int cause)
03347 {
03348
03349
03350 switch(cause) {
03351 case 401:
03352 return AST_CAUSE_CALL_REJECTED;
03353 case 403:
03354 return AST_CAUSE_CALL_REJECTED;
03355 case 404:
03356 return AST_CAUSE_UNALLOCATED;
03357 case 405:
03358 return AST_CAUSE_INTERWORKING;
03359 case 407:
03360 return AST_CAUSE_CALL_REJECTED;
03361 case 408:
03362 return AST_CAUSE_NO_USER_RESPONSE;
03363 case 409:
03364 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
03365 case 410:
03366 return AST_CAUSE_UNALLOCATED;
03367 case 411:
03368 return AST_CAUSE_INTERWORKING;
03369 case 413:
03370 return AST_CAUSE_INTERWORKING;
03371 case 414:
03372 return AST_CAUSE_INTERWORKING;
03373 case 415:
03374 return AST_CAUSE_INTERWORKING;
03375 case 420:
03376 return AST_CAUSE_NO_ROUTE_DESTINATION;
03377 case 480:
03378 return AST_CAUSE_NO_ANSWER;
03379 case 481:
03380 return AST_CAUSE_INTERWORKING;
03381 case 482:
03382 return AST_CAUSE_INTERWORKING;
03383 case 483:
03384 return AST_CAUSE_NO_ANSWER;
03385 case 484:
03386 return AST_CAUSE_INVALID_NUMBER_FORMAT;
03387 case 485:
03388 return AST_CAUSE_UNALLOCATED;
03389 case 486:
03390 return AST_CAUSE_BUSY;
03391 case 487:
03392 return AST_CAUSE_INTERWORKING;
03393 case 488:
03394 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
03395 case 491:
03396 return AST_CAUSE_INTERWORKING;
03397 case 493:
03398 return AST_CAUSE_INTERWORKING;
03399 case 500:
03400 return AST_CAUSE_FAILURE;
03401 case 501:
03402 return AST_CAUSE_FACILITY_REJECTED;
03403 case 502:
03404 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03405 case 503:
03406 return AST_CAUSE_CONGESTION;
03407 case 504:
03408 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
03409 case 505:
03410 return AST_CAUSE_INTERWORKING;
03411 case 600:
03412 return AST_CAUSE_USER_BUSY;
03413 case 603:
03414 return AST_CAUSE_CALL_REJECTED;
03415 case 604:
03416 return AST_CAUSE_UNALLOCATED;
03417 case 606:
03418 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
03419 default:
03420 return AST_CAUSE_NORMAL;
03421 }
03422
03423 return 0;
03424 }
03425
03426
03427
03428
03429
03430
03431
03432
03433
03434
03435
03436
03437
03438
03439
03440
03441
03442
03443
03444
03445
03446
03447
03448
03449
03450
03451
03452
03453
03454
03455
03456
03457
03458 static const char *hangup_cause2sip(int cause)
03459 {
03460 switch (cause) {
03461 case AST_CAUSE_UNALLOCATED:
03462 case AST_CAUSE_NO_ROUTE_DESTINATION:
03463 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
03464 return "404 Not Found";
03465 case AST_CAUSE_CONGESTION:
03466 case AST_CAUSE_SWITCH_CONGESTION:
03467 return "503 Service Unavailable";
03468 case AST_CAUSE_NO_USER_RESPONSE:
03469 return "408 Request Timeout";
03470 case AST_CAUSE_NO_ANSWER:
03471 return "480 Temporarily unavailable";
03472 case AST_CAUSE_CALL_REJECTED:
03473 return "403 Forbidden";
03474 case AST_CAUSE_NUMBER_CHANGED:
03475 return "410 Gone";
03476 case AST_CAUSE_NORMAL_UNSPECIFIED:
03477 return "480 Temporarily unavailable";
03478 case AST_CAUSE_INVALID_NUMBER_FORMAT:
03479 return "484 Address incomplete";
03480 case AST_CAUSE_USER_BUSY:
03481 return "486 Busy here";
03482 case AST_CAUSE_FAILURE:
03483 return "500 Server internal failure";
03484 case AST_CAUSE_FACILITY_REJECTED:
03485 return "501 Not Implemented";
03486 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
03487 return "503 Service Unavailable";
03488
03489 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
03490 return "502 Bad Gateway";
03491 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
03492 return "488 Not Acceptable Here";
03493
03494 case AST_CAUSE_NOTDEFINED:
03495 default:
03496 if (option_debug)
03497 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
03498 return NULL;
03499 }
03500
03501
03502 return 0;
03503 }
03504
03505
03506
03507
03508 static int sip_hangup(struct ast_channel *ast)
03509 {
03510 struct sip_pvt *p = ast->tech_pvt;
03511 int needcancel = FALSE;
03512 int needdestroy = 0;
03513 struct ast_channel *oldowner = ast;
03514
03515 if (!p) {
03516 if (option_debug)
03517 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
03518 return 0;
03519 }
03520
03521 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
03522 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
03523 if (option_debug && sipdebug)
03524 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
03525 update_call_counter(p, DEC_CALL_LIMIT);
03526 }
03527 if (option_debug >3)
03528 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
03529 if (p->autokillid > -1 && sip_cancel_destroy(p))
03530 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
03531 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03532 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
03533 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
03534 p->owner->tech_pvt = NULL;
03535 p->owner = NULL;
03536 return 0;
03537 }
03538 if (option_debug) {
03539 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
03540 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
03541 else {
03542 if (option_debug)
03543 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
03544 }
03545 }
03546 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
03547 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
03548
03549 ast_mutex_lock(&p->lock);
03550 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
03551 if (option_debug && sipdebug)
03552 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
03553 update_call_counter(p, DEC_CALL_LIMIT);
03554 }
03555
03556
03557 if (p->owner != ast) {
03558 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
03559 ast_mutex_unlock(&p->lock);
03560 return 0;
03561 }
03562
03563 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
03564 needcancel = TRUE;
03565 if (option_debug > 3)
03566 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
03567 }
03568
03569 stop_media_flows(p);
03570
03571 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
03572
03573
03574 if (p->vad)
03575 ast_dsp_free(p->vad);
03576
03577 p->owner = NULL;
03578 ast->tech_pvt = NULL;
03579
03580 ast_module_unref(ast_module_info->self);
03581
03582
03583
03584
03585
03586
03587
03588 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
03589 needdestroy = 1;
03590 else if (p->invitestate != INV_CALLING)
03591 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03592
03593
03594 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
03595 if (needcancel) {
03596 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03597
03598 __sip_pretend_ack(p);
03599 p->invitestate = INV_CANCELLED;
03600
03601
03602 if (p->invitestate == INV_CALLING) {
03603
03604 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
03605
03606 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03607 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
03608 } else {
03609
03610 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
03611
03612
03613 needdestroy = 0;
03614 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03615 }
03616 if ( p->initid != -1 ) {
03617
03618
03619 update_call_counter(p, INC_CALL_LIMIT);
03620 }
03621 } else {
03622 const char *res;
03623 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
03624 transmit_response_reliable(p, res, &p->initreq);
03625 else
03626 transmit_response_reliable(p, "603 Declined", &p->initreq);
03627 p->invitestate = INV_TERMINATED;
03628 }
03629 } else {
03630 if (!p->pendinginvite) {
03631 char *audioqos = "";
03632 char *videoqos = "";
03633 if (p->rtp)
03634 audioqos = ast_rtp_get_quality(p->rtp, NULL);
03635 if (p->vrtp)
03636 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
03637
03638 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03639
03640
03641 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
03642 if (p->rtp)
03643 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
03644 if (p->vrtp)
03645 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
03646 }
03647 if (p->rtp && oldowner)
03648 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
03649 if (p->vrtp && oldowner)
03650 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
03651 } else {
03652
03653
03654 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
03655 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
03656 AST_SCHED_DEL(sched, p->waitid);
03657 if (sip_cancel_destroy(p))
03658 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
03659 }
03660 }
03661 }
03662 if (needdestroy)
03663 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
03664 ast_mutex_unlock(&p->lock);
03665 return 0;
03666 }
03667
03668
03669 static void try_suggested_sip_codec(struct sip_pvt *p)
03670 {
03671 int fmt;
03672 const char *codec;
03673
03674 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
03675 if (!codec)
03676 return;
03677
03678 fmt = ast_getformatbyname(codec);
03679 if (fmt) {
03680 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
03681 if (p->jointcapability & fmt) {
03682 p->jointcapability &= fmt;
03683 p->capability &= fmt;
03684 } else
03685 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
03686 } else
03687 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
03688 return;
03689 }
03690
03691
03692
03693 static int sip_answer(struct ast_channel *ast)
03694 {
03695 int res = 0;
03696 struct sip_pvt *p = ast->tech_pvt;
03697
03698 ast_mutex_lock(&p->lock);
03699 if (ast->_state != AST_STATE_UP) {
03700 try_suggested_sip_codec(p);
03701
03702 ast_setstate(ast, AST_STATE_UP);
03703 if (option_debug)
03704 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
03705 if (p->t38.state == T38_PEER_DIRECT) {
03706 p->t38.state = T38_ENABLED;
03707 if (option_debug > 1)
03708 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
03709 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
03710 } else {
03711 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
03712 }
03713 }
03714 ast_mutex_unlock(&p->lock);
03715 return res;
03716 }
03717
03718
03719 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
03720 {
03721 struct sip_pvt *p = ast->tech_pvt;
03722 int res = 0;
03723
03724 switch (frame->frametype) {
03725 case AST_FRAME_VOICE:
03726 if (!(frame->subclass & ast->nativeformats)) {
03727 char s1[512], s2[512], s3[512];
03728 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
03729 frame->subclass,
03730 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
03731 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
03732 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
03733 ast->readformat,
03734 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
03735 ast->writeformat);
03736 return 0;
03737 }
03738 if (p) {
03739 ast_mutex_lock(&p->lock);
03740 if (p->rtp) {
03741
03742 if ((ast->_state != AST_STATE_UP) &&
03743 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03744 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03745 ast_rtp_new_source(p->rtp);
03746 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03747 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03748 }
03749 p->lastrtptx = time(NULL);
03750 res = ast_rtp_write(p->rtp, frame);
03751 }
03752 ast_mutex_unlock(&p->lock);
03753 }
03754 break;
03755 case AST_FRAME_VIDEO:
03756 if (p) {
03757 ast_mutex_lock(&p->lock);
03758 if (p->vrtp) {
03759
03760 if ((ast->_state != AST_STATE_UP) &&
03761 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03762 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03763 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03764 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03765 }
03766 p->lastrtptx = time(NULL);
03767 res = ast_rtp_write(p->vrtp, frame);
03768 }
03769 ast_mutex_unlock(&p->lock);
03770 }
03771 break;
03772 case AST_FRAME_IMAGE:
03773 return 0;
03774 break;
03775 case AST_FRAME_MODEM:
03776 if (p) {
03777 ast_mutex_lock(&p->lock);
03778
03779
03780
03781
03782 if (p->udptl && ast->_state == AST_STATE_UP)
03783 res = ast_udptl_write(p->udptl, frame);
03784 ast_mutex_unlock(&p->lock);
03785 }
03786 break;
03787 default:
03788 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
03789 return 0;
03790 }
03791
03792 return res;
03793 }
03794
03795
03796
03797 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
03798 {
03799 int ret = -1;
03800 struct sip_pvt *p;
03801
03802 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
03803 ast_log(LOG_DEBUG, "New channel is zombie\n");
03804 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
03805 ast_log(LOG_DEBUG, "Old channel is zombie\n");
03806
03807 if (!newchan || !newchan->tech_pvt) {
03808 if (!newchan)
03809 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
03810 else
03811 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
03812 return -1;
03813 }
03814 p = newchan->tech_pvt;
03815
03816 if (!p) {
03817 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
03818 return -1;
03819 }
03820
03821 ast_mutex_lock(&p->lock);
03822 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
03823 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
03824 if (p->owner != oldchan)
03825 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
03826 else {
03827 p->owner = newchan;
03828
03829
03830
03831
03832
03833
03834 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0);
03835 ret = 0;
03836 }
03837 if (option_debug > 2)
03838 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
03839
03840 ast_mutex_unlock(&p->lock);
03841 return ret;
03842 }
03843
03844 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
03845 {
03846 struct sip_pvt *p = ast->tech_pvt;
03847 int res = 0;
03848
03849 ast_mutex_lock(&p->lock);
03850 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
03851 case SIP_DTMF_INBAND:
03852 res = -1;
03853 break;
03854 case SIP_DTMF_RFC2833:
03855 if (p->rtp)
03856 ast_rtp_senddigit_begin(p->rtp, digit);
03857 break;
03858 default:
03859 break;
03860 }
03861 ast_mutex_unlock(&p->lock);
03862
03863 return res;
03864 }
03865
03866
03867
03868 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
03869 {
03870 struct sip_pvt *p = ast->tech_pvt;
03871 int res = 0;
03872
03873 ast_mutex_lock(&p->lock);
03874 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
03875 case SIP_DTMF_INFO:
03876 transmit_info_with_digit(p, digit, duration);
03877 break;
03878 case SIP_DTMF_RFC2833:
03879 if (p->rtp)
03880 ast_rtp_senddigit_end(p->rtp, digit);
03881 break;
03882 case SIP_DTMF_INBAND:
03883 res = -1;
03884 break;
03885 }
03886 ast_mutex_unlock(&p->lock);
03887
03888 return res;
03889 }
03890
03891
03892 static int sip_transfer(struct ast_channel *ast, const char *dest)
03893 {
03894 struct sip_pvt *p = ast->tech_pvt;
03895 int res;
03896
03897 if (dest == NULL)
03898 dest = "";
03899 ast_mutex_lock(&p->lock);
03900 if (ast->_state == AST_STATE_RING)
03901 res = sip_sipredirect(p, dest);
03902 else
03903 res = transmit_refer(p, dest);
03904 ast_mutex_unlock(&p->lock);
03905 return res;
03906 }
03907
03908
03909
03910
03911
03912
03913 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
03914 {
03915 struct sip_pvt *p = ast->tech_pvt;
03916 int res = 0;
03917
03918 ast_mutex_lock(&p->lock);
03919 switch(condition) {
03920 case AST_CONTROL_RINGING:
03921 if (ast->_state == AST_STATE_RING) {
03922 p->invitestate = INV_EARLY_MEDIA;
03923 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
03924 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
03925
03926 transmit_response(p, "180 Ringing", &p->initreq);
03927 ast_set_flag(&p->flags[0], SIP_RINGING);
03928 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
03929 break;
03930 } else {
03931
03932 }
03933 }
03934 res = -1;
03935 break;
03936 case AST_CONTROL_BUSY:
03937 if (ast->_state != AST_STATE_UP) {
03938 transmit_response(p, "486 Busy Here", &p->initreq);
03939 p->invitestate = INV_COMPLETED;
03940 sip_alreadygone(p);
03941 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
03942 break;
03943 }
03944 res = -1;
03945 break;
03946 case AST_CONTROL_CONGESTION:
03947 if (ast->_state != AST_STATE_UP) {
03948 transmit_response(p, "503 Service Unavailable", &p->initreq);
03949 p->invitestate = INV_COMPLETED;
03950 sip_alreadygone(p);
03951 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
03952 break;
03953 }
03954 res = -1;
03955 break;
03956 case AST_CONTROL_PROCEEDING:
03957 if ((ast->_state != AST_STATE_UP) &&
03958 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03959 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03960 transmit_response(p, "100 Trying", &p->initreq);
03961 p->invitestate = INV_PROCEEDING;
03962 break;
03963 }
03964 res = -1;
03965 break;
03966 case AST_CONTROL_PROGRESS:
03967 if ((ast->_state != AST_STATE_UP) &&
03968 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03969 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03970 p->invitestate = INV_EARLY_MEDIA;
03971 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03972 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03973 break;
03974 }
03975 res = -1;
03976 break;
03977 case AST_CONTROL_HOLD:
03978 ast_rtp_new_source(p->rtp);
03979 ast_moh_start(ast, data, p->mohinterpret);
03980 break;
03981 case AST_CONTROL_UNHOLD:
03982 ast_rtp_new_source(p->rtp);
03983 ast_moh_stop(ast);
03984 break;
03985 case AST_CONTROL_VIDUPDATE:
03986 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
03987 transmit_info_with_vidupdate(p);
03988
03989 } else
03990 res = -1;
03991 break;
03992 case AST_CONTROL_SRCUPDATE:
03993 ast_rtp_new_source(p->rtp);
03994 break;
03995 case -1:
03996 res = -1;
03997 break;
03998 default:
03999 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
04000 res = -1;
04001 break;
04002 }
04003 ast_mutex_unlock(&p->lock);
04004 return res;
04005 }
04006
04007
04008
04009
04010
04011
04012
04013 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
04014 {
04015 struct ast_channel *tmp;
04016 struct ast_variable *v = NULL;
04017 int fmt;
04018 int what;
04019 int needvideo = 0, video = 0;
04020 char *decoded_exten;
04021
04022 if (option_debug != 0) {
04023 ast_verbose(VERBOSE_PREFIX_3 "NEW SIP CHANNEL, title: <%s>\n", title?title:"Null");
04024 ast_verbose(VERBOSE_PREFIX_3 "from: %s\n", i->from);
04025 ast_verbose(VERBOSE_PREFIX_3 "username: <%s>\n", i->username);
04026 ast_verbose(VERBOSE_PREFIX_3 "peername: <%s>\n", i->peername);
04027 ast_verbose(VERBOSE_PREFIX_3 "fromdomain: %s\n", i->fromdomain);
04028 ast_verbose(VERBOSE_PREFIX_3 "fromuser: %s\n", i->fromuser);
04029 ast_verbose(VERBOSE_PREFIX_3 "fromname: %s\n", i->fromname);
04030 ast_verbose(VERBOSE_PREFIX_3 "fullcontact: %s\n", i->fullcontact);
04031 }
04032
04033 {
04034 char my_name[128];
04035 const char *f, *fromdomain = NULL;
04036
04037 if (!ast_strlen_zero(i->fromdomain) && strchr(i->fromdomain,':'))
04038 fromdomain = strchr(i->fromdomain,':') + 1;
04039 else
04040 fromdomain = i->fromdomain;
04041
04042 if (!ast_strlen_zero(i->username)) {
04043 if (!ast_strlen_zero(title) && strcmp(i->username, title)) {
04044
04045 snprintf(my_name, sizeof(my_name), "%s@%s", i->username, title);
04046 } else {
04047
04048 snprintf(my_name, sizeof(my_name), "%s", i->username);
04049 }
04050 } else {
04051 if (!ast_strlen_zero(i->peername)) {
04052
04053 snprintf(my_name, sizeof(my_name), "%s", i->peername);
04054 } else {
04055 if (!ast_strlen_zero(title)) {
04056 snprintf(my_name, sizeof(my_name), "%s", title);
04057 } else if (!ast_strlen_zero(i->from)) {
04058 f = i->from;
04059 if (!strncmp(f, "sip:", 4))
04060 f += 4;
04061 snprintf(my_name, sizeof(my_name), "%s", f);
04062 } else {
04063 snprintf(my_name, sizeof(my_name), "%s", fromdomain);
04064 }
04065 }
04066 }
04067 ast_mutex_unlock(&i->lock);
04068
04069 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "SIP/%s-%08x", my_name, (int)(long) i);
04070
04071 }
04072 if (!tmp) {
04073 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
04074 ast_mutex_lock(&i->lock);
04075 return NULL;
04076 }
04077 ast_mutex_lock(&i->lock);
04078
04079 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
04080 tmp->tech = &sip_tech_info;
04081 else
04082 tmp->tech = &sip_tech;
04083
04084
04085
04086 if (i->jointcapability) {
04087 what = i->jointcapability;
04088 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
04089 } else if (i->capability) {
04090 what = i->capability;
04091 video = i->capability & AST_FORMAT_VIDEO_MASK;
04092 } else {
04093 what = global_capability;
04094 video = global_capability & AST_FORMAT_VIDEO_MASK;
04095 }
04096
04097
04098 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video;
04099 if (option_debug > 2) {
04100 char buf[SIPBUFSIZE];
04101 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
04102 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
04103 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
04104 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
04105 if (i->prefcodec)
04106 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
04107 }
04108
04109
04110 fmt = ast_best_codec(tmp->nativeformats);
04111
04112
04113
04114
04115
04116 if (i->vrtp) {
04117 if (i->prefcodec)
04118 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
04119 else
04120 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
04121 }
04122
04123 if (option_debug > 2) {
04124 if (needvideo)
04125 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
04126 else
04127 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
04128 }
04129
04130
04131
04132 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
04133 i->vad = ast_dsp_new();
04134 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
04135 if (global_relaxdtmf)
04136 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04137 }
04138 if (i->rtp) {
04139 tmp->fds[0] = ast_rtp_fd(i->rtp);
04140 tmp->fds[1] = ast_rtcp_fd(i->rtp);
04141 }
04142 if (needvideo && i->vrtp) {
04143 tmp->fds[2] = ast_rtp_fd(i->vrtp);
04144 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
04145 }
04146 if (i->udptl) {
04147 tmp->fds[5] = ast_udptl_fd(i->udptl);
04148 }
04149 if (state == AST_STATE_RING)
04150 tmp->rings = 1;
04151 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
04152 tmp->writeformat = fmt;
04153 tmp->rawwriteformat = fmt;
04154 tmp->readformat = fmt;
04155 tmp->rawreadformat = fmt;
04156 tmp->tech_pvt = i;
04157
04158 tmp->callgroup = i->callgroup;
04159 tmp->pickupgroup = i->pickupgroup;
04160 tmp->cid.cid_pres = i->callingpres;
04161 if (!ast_strlen_zero(i->accountcode))
04162 ast_string_field_set(tmp, accountcode, i->accountcode);
04163 if (i->amaflags)
04164 tmp->amaflags = i->amaflags;
04165 if (!ast_strlen_zero(i->language))
04166 ast_string_field_set(tmp, language, i->language);
04167 i->owner = tmp;
04168 ast_module_ref(ast_module_info->self);
04169 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
04170
04171
04172
04173
04174 decoded_exten = ast_strdupa(i->exten);
04175 ast_uri_decode(decoded_exten);
04176 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
04177
04178
04179
04180 tmp->cid.cid_ani = ast_strdup(i->cid_num);
04181 if (!ast_strlen_zero(i->rdnis))
04182 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
04183
04184 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
04185 tmp->cid.cid_dnid = ast_strdup(i->exten);
04186
04187 tmp->priority = 1;
04188 if (!ast_strlen_zero(i->uri))
04189 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
04190 if (!ast_strlen_zero(i->domain))
04191 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
04192 if (!ast_strlen_zero(i->useragent))
04193 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
04194 if (!ast_strlen_zero(i->callid))
04195 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
04196 if (i->rtp)
04197 ast_jb_configure(tmp, &global_jbconf);
04198
04199
04200 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
04201 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
04202
04203
04204 for (v = i->chanvars ; v ; v = v->next)
04205 pbx_builtin_setvar_helper(tmp, v->name, v->value);
04206
04207 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
04208 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
04209 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
04210 ast_hangup(tmp);
04211 tmp = NULL;
04212 }
04213
04214 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
04215 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
04216
04217 return tmp;
04218 }
04219
04220
04221 static char *get_body_by_line(const char *line, const char *name, int nameLen)
04222 {
04223 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
04224 return ast_skip_blanks(line + nameLen + 1);
04225
04226 return "";
04227 }
04228
04229
04230
04231
04232
04233 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
04234 {
04235 int len = strlen(name);
04236
04237 while (*start < req->sdp_end) {
04238 const char *r = get_body_by_line(req->line[(*start)++], name, len);
04239 if (r[0] != '\0')
04240 return r;
04241 }
04242
04243 return "";
04244 }
04245
04246
04247 static const char *get_sdp(struct sip_request *req, const char *name)
04248 {
04249 int dummy = 0;
04250
04251 return get_sdp_iterate(&dummy, req, name);
04252 }
04253
04254
04255 static char *get_body(struct sip_request *req, char *name)
04256 {
04257 int x;
04258 int len = strlen(name);
04259 char *r;
04260
04261 for (x = 0; x < req->lines; x++) {
04262 r = get_body_by_line(req->line[x], name, len);
04263 if (r[0] != '\0')
04264 return r;
04265 }
04266
04267 return "";
04268 }
04269
04270
04271 static const char *find_alias(const char *name, const char *_default)
04272 {
04273
04274 static const struct cfalias {
04275 char * const fullname;
04276 char * const shortname;
04277 } aliases[] = {
04278 { "Content-Type", "c" },
04279 { "Content-Encoding", "e" },
04280 { "From", "f" },
04281 { "Call-ID", "i" },
04282 { "Contact", "m" },
04283 { "Content-Length", "l" },
04284 { "Subject", "s" },
04285 { "To", "t" },
04286 { "Supported", "k" },
04287 { "Refer-To", "r" },
04288 { "Referred-By", "b" },
04289 { "Allow-Events", "u" },
04290 { "Event", "o" },
04291 { "Via", "v" },
04292 { "Accept-Contact", "a" },
04293 { "Reject-Contact", "j" },
04294 { "Request-Disposition", "d" },
04295 { "Session-Expires", "x" },
04296 { "Identity", "y" },
04297 { "Identity-Info", "n" },
04298 };
04299 int x;
04300
04301 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
04302 if (!strcasecmp(aliases[x].fullname, name))
04303 return aliases[x].shortname;
04304
04305 return _default;
04306 }
04307
04308 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
04309 {
04310 int pass;
04311
04312
04313
04314
04315
04316
04317
04318
04319
04320
04321 for (pass = 0; name && pass < 2;pass++) {
04322 int x, len = strlen(name);
04323 for (x=*start; x<req->headers; x++) {
04324 if (!strncasecmp(req->header[x], name, len)) {
04325 char *r = req->header[x] + len;
04326 if (pedanticsipchecking)
04327 r = ast_skip_blanks(r);
04328
04329 if (*r == ':') {
04330 *start = x+1;
04331 return ast_skip_blanks(r+1);
04332 }
04333 }
04334 }
04335 if (pass == 0)
04336 name = find_alias(name, NULL);
04337 }
04338
04339
04340 return "";
04341 }
04342
04343
04344 static const char *get_header(const struct sip_request *req, const char *name)
04345 {
04346 int start = 0;
04347 return __get_header(req, name, &start);
04348 }
04349
04350
04351 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
04352 {
04353
04354 struct ast_frame *f;
04355
04356 if (!p->rtp) {
04357
04358 return &ast_null_frame;
04359 }
04360
04361 switch(ast->fdno) {
04362 case 0:
04363 f = ast_rtp_read(p->rtp);
04364 break;
04365 case 1:
04366 f = ast_rtcp_read(p->rtp);
04367 break;
04368 case 2:
04369 f = ast_rtp_read(p->vrtp);
04370 break;
04371 case 3:
04372 f = ast_rtcp_read(p->vrtp);
04373 break;
04374 case 5:
04375 f = ast_udptl_read(p->udptl);
04376 break;
04377 default:
04378 f = &ast_null_frame;
04379 }
04380
04381 if (f && (f->frametype == AST_FRAME_DTMF) &&
04382 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
04383 return &ast_null_frame;
04384
04385
04386 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
04387 return f;
04388
04389 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
04390 if (!(f->subclass & p->jointcapability)) {
04391 if (option_debug) {
04392 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
04393 ast_getformatname(f->subclass), p->owner->name);
04394 }
04395 return &ast_null_frame;
04396 }
04397 if (option_debug)
04398 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
04399 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
04400 ast_set_read_format(p->owner, p->owner->readformat);
04401 ast_set_write_format(p->owner, p->owner->writeformat);
04402 }
04403
04404 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
04405 f = ast_dsp_process(p->owner, p->vad, f);
04406 if (f && f->frametype == AST_FRAME_DTMF) {
04407 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
04408 if (option_debug)
04409 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
04410 *faxdetect = 1;
04411 } else if (option_debug) {
04412 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
04413 }
04414 }
04415 }
04416
04417 return f;
04418 }
04419
04420
04421 static struct ast_frame *sip_read(struct ast_channel *ast)
04422 {
04423 struct ast_frame *fr;
04424 struct sip_pvt *p = ast->tech_pvt;
04425 int faxdetected = FALSE;
04426
04427 ast_mutex_lock(&p->lock);
04428 fr = sip_rtp_read(ast, p, &faxdetected);
04429 p->lastrtprx = time(NULL);
04430
04431
04432
04433 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
04434 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
04435 if (!p->pendinginvite) {
04436 if (option_debug > 2)
04437 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
04438 p->t38.state = T38_LOCAL_REINVITE;
04439 transmit_reinvite_with_t38_sdp(p);
04440 if (option_debug > 1)
04441 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
04442 }
04443 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04444 if (option_debug > 2)
04445 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
04446 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04447 }
04448 }
04449
04450
04451 if (fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
04452 fr = &ast_null_frame;
04453 }
04454
04455 ast_mutex_unlock(&p->lock);
04456 return fr;
04457 }
04458
04459
04460
04461 static char *generate_random_string(char *buf, size_t size)
04462 {
04463 long val[4];
04464 int x;
04465
04466 for (x=0; x<4; x++)
04467 val[x] = ast_random();
04468 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
04469
04470 return buf;
04471 }
04472
04473
04474 static void build_callid_pvt(struct sip_pvt *pvt)
04475 {
04476 char buf[33];
04477
04478 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
04479
04480 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
04481
04482 }
04483
04484
04485 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
04486 {
04487 char buf[33];
04488
04489 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
04490
04491 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
04492 }
04493
04494
04495 static void make_our_tag(char *tagbuf, size_t len)
04496 {
04497 snprintf(tagbuf, len, "as%08lx", ast_random());
04498 }
04499
04500
04501 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
04502 int useglobal_nat, const int intended_method)
04503 {
04504 struct sip_pvt *p;
04505
04506 if (!(p = ast_calloc(1, sizeof(*p))))
04507 return NULL;
04508
04509 if (ast_string_field_init(p, 512)) {
04510 free(p);
04511 return NULL;
04512 }
04513
04514 ast_mutex_init(&p->lock);
04515
04516 p->method = intended_method;
04517 p->initid = -1;
04518 p->waitid = -1;
04519 p->autokillid = -1;
04520 p->subscribed = NONE;
04521 p->stateid = -1;
04522 p->sockfd=-1;
04523 p->prefs = default_prefs;
04524
04525 if (intended_method != SIP_OPTIONS)
04526 p->timer_t1 = 500;
04527
04528 if (sin) {
04529 p->sa = *sin;
04530 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
04531 p->ourip = __ourip;
04532 } else
04533 p->ourip = __ourip;
04534
04535
04536 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
04537 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04538
04539 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
04540
04541 p->branch = ast_random();
04542 make_our_tag(p->tag, sizeof(p->tag));
04543 p->ocseq = INITIAL_CSEQ;
04544
04545 if (sip_methods[intended_method].need_rtp) {
04546 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
04547
04548 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
04549 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
04550 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
04551 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
04552 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
04553 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
04554 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
04555 ast_mutex_destroy(&p->lock);
04556 if (p->chanvars) {
04557 ast_variables_destroy(p->chanvars);
04558 p->chanvars = NULL;
04559 }
04560 free(p);
04561 return NULL;
04562 }
04563 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04564 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04565 ast_rtp_settos(p->rtp, global_tos_audio);
04566 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
04567 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
04568 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
04569 if (p->vrtp) {
04570 ast_rtp_settos(p->vrtp, global_tos_video);
04571 ast_rtp_setdtmf(p->vrtp, 0);
04572 ast_rtp_setdtmfcompensate(p->vrtp, 0);
04573 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
04574 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
04575 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
04576 }
04577 if (p->udptl)
04578 ast_udptl_settos(p->udptl, global_tos_audio);
04579 p->maxcallbitrate = default_maxcallbitrate;
04580 p->autoframing = global_autoframing;
04581 ast_rtp_codec_setpref(p->rtp, &p->prefs);
04582 }
04583
04584 if (useglobal_nat && sin) {
04585
04586 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
04587 p->recv = *sin;
04588 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04589 }
04590
04591 if (p->method != SIP_REGISTER)
04592 ast_string_field_set(p, fromdomain, default_fromdomain);
04593 build_via(p);
04594 if (!callid)
04595 build_callid_pvt(p);
04596 else
04597 ast_string_field_set(p, callid, callid);
04598
04599 ast_string_field_set(p, mohinterpret, default_mohinterpret);
04600 ast_string_field_set(p, mohsuggest, default_mohsuggest);
04601 p->capability = global_capability;
04602 p->allowtransfer = global_allowtransfer;
04603 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
04604 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
04605 p->noncodeccapability |= AST_RTP_DTMF;
04606 if (p->udptl) {
04607 p->t38.capability = global_t38_capability;
04608 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
04609 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
04610 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
04611 p->t38.capability |= T38FAX_UDP_EC_FEC;
04612 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
04613 p->t38.capability |= T38FAX_UDP_EC_NONE;
04614 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
04615 p->t38.jointcapability = p->t38.capability;
04616 }
04617 ast_string_field_set(p, context, default_context);
04618
04619
04620 ast_mutex_lock(&iflock);
04621 p->next = iflist;
04622 iflist = p;
04623 ast_mutex_unlock(&iflock);
04624 if (option_debug)
04625 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");
04626 return p;
04627 }
04628
04629
04630
04631 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
04632 {
04633 struct sip_pvt *p = NULL;
04634 char *tag = "";
04635 char totag[128];
04636 char fromtag[128];
04637 const char *callid = get_header(req, "Call-ID");
04638 const char *from = get_header(req, "From");
04639 const char *to = get_header(req, "To");
04640 const char *cseq = get_header(req, "Cseq");
04641
04642
04643
04644 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
04645 ast_strlen_zero(from) || ast_strlen_zero(cseq))
04646 return NULL;
04647
04648 if (pedanticsipchecking) {
04649
04650
04651
04652
04653
04654
04655 if (gettag(req, "To", totag, sizeof(totag)))
04656 ast_set_flag(req, SIP_PKT_WITH_TOTAG);
04657 gettag(req, "From", fromtag, sizeof(fromtag));
04658
04659 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
04660
04661 if (option_debug > 4 )
04662 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);
04663 }
04664
04665 ast_mutex_lock(&iflock);
04666 for (p = iflist; p; p = p->next) {
04667
04668 int found = FALSE;
04669 if (ast_strlen_zero(p->callid))
04670 continue;
04671 if (req->method == SIP_REGISTER)
04672 found = (!strcmp(p->callid, callid));
04673 else
04674 found = (!strcmp(p->callid, callid) &&
04675 (!pedanticsipchecking || ast_strlen_zero(tag) || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
04676
04677 if (option_debug > 4)
04678 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);
04679
04680
04681 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) {
04682 if (p->tag[0] == '\0' && totag[0]) {
04683
04684 found = FALSE;
04685 } else if (totag[0]) {
04686 if (strcmp(totag, p->tag)) {
04687 found = FALSE;
04688 }
04689 }
04690 if (!found && option_debug > 4)
04691 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);
04692 }
04693
04694
04695 if (found) {
04696
04697 ast_mutex_lock(&p->lock);
04698 ast_mutex_unlock(&iflock);
04699 return p;
04700 }
04701 }
04702 ast_mutex_unlock(&iflock);
04703
04704
04705 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
04706 if (intended_method == SIP_REFER) {
04707
04708 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
04709 } else if (intended_method == SIP_NOTIFY) {
04710
04711
04712 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
04713 } else {
04714
04715 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
04716
04717 ast_mutex_lock(&p->lock);
04718 } else {
04719
04720
04721
04722
04723
04724
04725
04726
04727 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
04728 if (option_debug > 3)
04729 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
04730 }
04731 }
04732 return p;
04733 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
04734
04735 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
04736 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
04737
04738
04739
04740 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
04741 }
04742
04743
04744
04745 return p;
04746 }
04747
04748
04749 static int sip_register(char *value, int lineno)
04750 {
04751 struct sip_registry *reg;
04752 int portnum = 0;
04753 char username[256] = "";
04754 char *hostname=NULL, *secret=NULL, *authuser=NULL;
04755 char *porta=NULL;
04756 char *contact=NULL;
04757
04758 if (!value)
04759 return -1;
04760 ast_copy_string(username, value, sizeof(username));
04761
04762 hostname = strrchr(username, '@');
04763 if (hostname)
04764 *hostname++ = '\0';
04765 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
04766 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
04767 return -1;
04768 }
04769
04770 secret = strchr(username, ':');
04771 if (secret) {
04772 *secret++ = '\0';
04773 authuser = strchr(secret, ':');
04774 if (authuser)
04775 *authuser++ = '\0';
04776 }
04777
04778 contact = strchr(hostname, '/');
04779 if (contact)
04780 *contact++ = '\0';
04781 if (ast_strlen_zero(contact))
04782 contact = "s";
04783 porta = strchr(hostname, ':');
04784 if (porta) {
04785 *porta++ = '\0';
04786 portnum = atoi(porta);
04787 if (portnum == 0) {
04788 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
04789 return -1;
04790 }
04791 }
04792 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
04793 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
04794 return -1;
04795 }
04796
04797 if (ast_string_field_init(reg, 256)) {
04798 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
04799 free(reg);
04800 return -1;
04801 }
04802
04803 regobjs++;
04804 ASTOBJ_INIT(reg);
04805 ast_string_field_set(reg, contact, contact);
04806 if (!ast_strlen_zero(username))
04807 ast_string_field_set(reg, username, username);
04808 if (hostname)
04809 ast_string_field_set(reg, hostname, hostname);
04810 if (authuser)
04811 ast_string_field_set(reg, authuser, authuser);
04812 if (secret)
04813 ast_string_field_set(reg, secret, secret);
04814 reg->expire = -1;
04815 reg->timeout = -1;
04816 reg->refresh = default_expiry;
04817 reg->portno = portnum;
04818 reg->callid_valid = FALSE;
04819 reg->ocseq = INITIAL_CSEQ;
04820 ASTOBJ_CONTAINER_LINK(®l, reg);
04821 ASTOBJ_UNREF(reg,sip_registry_destroy);
04822 return 0;
04823 }
04824
04825
04826
04827 static int lws2sws(char *msgbuf, int len)
04828 {
04829 int h = 0, t = 0;
04830 int lws = 0;
04831
04832 for (; h < len;) {
04833
04834 if (msgbuf[h] == '\r') {
04835 h++;
04836 continue;
04837 }
04838
04839 if (msgbuf[h] == '\n') {
04840
04841 if (h + 1 == len)
04842 break;
04843
04844 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
04845
04846 h++;
04847 continue;
04848 }
04849
04850 msgbuf[t++] = msgbuf[h++];
04851 lws = 0;
04852 continue;
04853 }
04854 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
04855 if (lws) {
04856 h++;
04857 continue;
04858 }
04859 msgbuf[t++] = msgbuf[h++];
04860 lws = 1;
04861 continue;
04862 }
04863 msgbuf[t++] = msgbuf[h++];
04864 if (lws)
04865 lws = 0;
04866 }
04867 msgbuf[t] = '\0';
04868 return t;
04869 }
04870
04871
04872
04873
04874 static int parse_request(struct sip_request *req)
04875 {
04876
04877 char *c;
04878 int f = 0;
04879
04880 c = req->data;
04881
04882
04883 req->header[f] = c;
04884 while(*c) {
04885 if (*c == '\n') {
04886
04887 *c = 0;
04888
04889 if (sipdebug && option_debug > 3)
04890 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
04891 if (ast_strlen_zero(req->header[f])) {
04892
04893 c++;
04894 break;
04895 }
04896 if (f >= SIP_MAX_HEADERS - 1) {
04897 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
04898 } else
04899 f++;
04900 req->header[f] = c + 1;
04901 } else if (*c == '\r') {
04902
04903 *c = 0;
04904 }
04905 c++;
04906 }
04907
04908 if (!ast_strlen_zero(req->header[f])) {
04909 if (sipdebug && option_debug > 3)
04910 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
04911 f++;
04912 }
04913 req->headers = f;
04914
04915 f = 0;
04916 req->line[f] = c;
04917 while(*c) {
04918 if (*c == '\n') {
04919
04920 *c = 0;
04921 if (sipdebug && option_debug > 3)
04922 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
04923 if (f >= SIP_MAX_LINES - 1) {
04924 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
04925 } else
04926 f++;
04927 req->line[f] = c + 1;
04928 } else if (*c == '\r') {
04929
04930 *c = 0;
04931 }
04932 c++;
04933 }
04934
04935 if (!ast_strlen_zero(req->line[f]))
04936 f++;
04937 req->lines = f;
04938 if (*c)
04939 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
04940
04941 return determine_firstline_parts(req);
04942 }
04943
04944
04945
04946
04947
04948
04949
04950
04951
04952 static int find_sdp(struct sip_request *req)
04953 {
04954 const char *content_type;
04955 const char *content_length;
04956 const char *search;
04957 char *boundary;
04958 unsigned int x;
04959 int boundaryisquoted = FALSE;
04960 int found_application_sdp = FALSE;
04961 int found_end_of_headers = FALSE;
04962
04963 content_length = get_header(req, "Content-Length");
04964
04965 if (!ast_strlen_zero(content_length)) {
04966 if (sscanf(content_length, "%ud", &x) != 1) {
04967 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
04968 return 0;
04969 }
04970
04971
04972
04973 if (x == 0)
04974 return 0;
04975 }
04976
04977 content_type = get_header(req, "Content-Type");
04978
04979
04980 if (!strcasecmp(content_type, "application/sdp")) {
04981 req->sdp_start = 0;
04982 req->sdp_end = req->lines;
04983 return req->lines ? 1 : 0;
04984 }
04985
04986
04987 if (strncasecmp(content_type, "multipart/mixed", 15))
04988 return 0;
04989
04990
04991 if ((search = strcasestr(content_type, ";boundary=")))
04992 search += 10;
04993 else if ((search = strcasestr(content_type, "; boundary=")))
04994 search += 11;
04995 else
04996 return 0;
04997
04998 if (ast_strlen_zero(search))
04999 return 0;
05000
05001
05002 if (*search == '\"') {
05003 search++;
05004 boundaryisquoted = TRUE;
05005 }
05006
05007
05008
05009 boundary = ast_strdupa(search - 2);
05010 boundary[0] = boundary[1] = '-';
05011
05012 if (boundaryisquoted)
05013 boundary[strlen(boundary) - 1] = '\0';
05014
05015
05016
05017
05018 for (x = 0; x < (req->lines ); x++) {
05019 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
05020 if(found_application_sdp && found_end_of_headers){
05021 req->sdp_end = x-1;
05022 return 1;
05023 }
05024 found_application_sdp = FALSE;
05025 }
05026 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
05027 found_application_sdp = TRUE;
05028
05029 if(strlen(req->line[x]) == 0 ){
05030 if(found_application_sdp && !found_end_of_headers){
05031 req->sdp_start = x;
05032 found_end_of_headers = TRUE;
05033 }
05034 }
05035 }
05036 if(found_application_sdp && found_end_of_headers) {
05037 req->sdp_end = x;
05038 return TRUE;
05039 }
05040 return FALSE;
05041 }
05042
05043
05044 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
05045 {
05046 if (global_notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
05047 sip_peer_hold(dialog, holdstate);
05048 if (global_callevents)
05049 manager_event(EVENT_FLAG_CALL, holdstate ? "Hold" : "Unhold",
05050 "Channel: %s\r\n"
05051 "Uniqueid: %s\r\n",
05052 dialog->owner->name,
05053 dialog->owner->uniqueid);
05054 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data);
05055 if (!holdstate) {
05056 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
05057 return;
05058 }
05059
05060
05061 if (sendonly == 1)
05062 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
05063 else if (sendonly == 2)
05064 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
05065 else
05066 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
05067 return;
05068 }
05069
05070
05071
05072
05073
05074
05075 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
05076 {
05077 const char *m;
05078 const char *c;
05079 const char *a;
05080 char host[258];
05081 int len = -1;
05082 int portno = -1;
05083 int vportno = -1;
05084 int udptlportno = -1;
05085 int peert38capability = 0;
05086 char s[256];
05087 int old = 0;
05088
05089
05090 int peercapability = 0, peernoncodeccapability = 0;
05091 int vpeercapability = 0, vpeernoncodeccapability = 0;
05092 struct sockaddr_in sin;
05093 struct sockaddr_in vsin;
05094
05095 const char *codecs;
05096 struct hostent *hp;
05097 struct hostent *vhp = NULL;
05098 struct ast_hostent audiohp;
05099 struct ast_hostent videohp;
05100 int codec;
05101 int destiterator = 0;
05102 int iterator;
05103 int sendonly = -1;
05104 int numberofports;
05105 struct ast_rtp *newaudiortp, *newvideortp;
05106 int newjointcapability;
05107 int newpeercapability;
05108 int newnoncodeccapability;
05109 int numberofmediastreams = 0;
05110 int debug = sip_debug_test_pvt(p);
05111
05112 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
05113 int last_rtpmap_codec=0;
05114
05115 if (!p->rtp) {
05116 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
05117 return -1;
05118 }
05119
05120
05121 newaudiortp = alloca(ast_rtp_alloc_size());
05122 memset(newaudiortp, 0, ast_rtp_alloc_size());
05123 ast_rtp_new_init(newaudiortp);
05124 ast_rtp_pt_clear(newaudiortp);
05125
05126 newvideortp = alloca(ast_rtp_alloc_size());
05127 memset(newvideortp, 0, ast_rtp_alloc_size());
05128 ast_rtp_new_init(newvideortp);
05129 ast_rtp_pt_clear(newvideortp);
05130
05131
05132 p->lastrtprx = p->lastrtptx = time(NULL);
05133
05134
05135
05136 m = get_sdp(req, "m");
05137 destiterator = req->sdp_start;
05138 c = get_sdp_iterate(&destiterator, req, "c");
05139 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
05140 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
05141 return -1;
05142 }
05143
05144
05145 if (sscanf(c, "IN IP4 %256s", host) != 1) {
05146 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
05147 return -1;
05148 }
05149
05150
05151 hp = ast_gethostbyname(host, &audiohp);
05152 if (!hp) {
05153 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
05154 return -1;
05155 }
05156 vhp = hp;
05157
05158 iterator = req->sdp_start;
05159 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
05160
05161
05162
05163 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
05164 int x;
05165 int audio = FALSE;
05166
05167 numberofports = 1;
05168 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
05169 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
05170 audio = TRUE;
05171 numberofmediastreams++;
05172
05173 portno = x;
05174
05175 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
05176 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
05177 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
05178 return -1;
05179 }
05180 if (debug)
05181 ast_verbose("Found RTP audio format %d\n", codec);
05182 ast_rtp_set_m_type(newaudiortp, codec);
05183 }
05184 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
05185 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
05186
05187 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
05188 numberofmediastreams++;
05189 vportno = x;
05190
05191 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
05192 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
05193 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
05194 return -1;
05195 }
05196 if (debug)
05197 ast_verbose("Found RTP video format %d\n", codec);
05198 ast_rtp_set_m_type(newvideortp, codec);
05199 }
05200 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
05201 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
05202 if (debug)
05203 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
05204 udptlportno = x;
05205 numberofmediastreams++;
05206
05207 if (p->owner && p->lastinvite) {
05208 p->t38.state = T38_PEER_REINVITE;
05209 if (option_debug > 1)
05210 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
05211 } else {
05212 p->t38.state = T38_PEER_DIRECT;
05213 if (option_debug > 1)
05214 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
05215 }
05216 } else
05217 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
05218 if (numberofports > 1)
05219 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
05220
05221
05222
05223 c = get_sdp_iterate(&destiterator, req, "c");
05224 if (!ast_strlen_zero(c)) {
05225 if (sscanf(c, "IN IP4 %256s", host) != 1) {
05226 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
05227 } else {
05228
05229 if (audio) {
05230 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
05231 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
05232 return -2;
05233 }
05234 } else if (!(vhp = ast_gethostbyname(host, &videohp))) {
05235 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
05236 return -2;
05237 }
05238 }
05239
05240 }
05241 }
05242 if (portno == -1 && vportno == -1 && udptlportno == -1)
05243
05244
05245 return -2;
05246
05247 if (numberofmediastreams > 2)
05248
05249 return -3;
05250
05251
05252 sin.sin_family = AF_INET;
05253 vsin.sin_family = AF_INET;
05254 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
05255 if (vhp)
05256 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
05257
05258
05259 if (p->udptl) {
05260 if (udptlportno > 0) {
05261 sin.sin_port = htons(udptlportno);
05262 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
05263 struct sockaddr_in peer;
05264 ast_rtp_get_peer(p->rtp, &peer);
05265 if (peer.sin_addr.s_addr) {
05266 memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(&sin.sin_addr));
05267 if (debug) {
05268 ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(sin.sin_addr));
05269 }
05270 }
05271 }
05272 ast_udptl_set_peer(p->udptl, &sin);
05273 if (debug)
05274 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
05275 } else {
05276 ast_udptl_stop(p->udptl);
05277 if (debug)
05278 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
05279 }
05280 }
05281
05282
05283 if (p->rtp) {
05284 if (portno > 0) {
05285 sin.sin_port = htons(portno);
05286 ast_rtp_set_peer(p->rtp, &sin);
05287 if (debug)
05288 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
05289 } else {
05290 if (udptlportno > 0) {
05291 if (debug)
05292 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
05293 } else {
05294 ast_rtp_stop(p->rtp);
05295 if (debug)
05296 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
05297 }
05298 }
05299 }
05300
05301 if (vportno != -1)
05302 vsin.sin_port = htons(vportno);
05303
05304
05305
05306
05307
05308 iterator = req->sdp_start;
05309 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
05310 char* mimeSubtype = ast_strdupa(a);
05311 if (option_debug > 1) {
05312 int breakout = FALSE;
05313
05314
05315 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
05316 if (debug)
05317 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
05318 breakout = TRUE;
05319 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
05320
05321
05322
05323
05324 if (debug)
05325 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
05326 breakout = TRUE;
05327 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
05328
05329 if (debug)
05330 ast_verbose("Got unsupported a:framerate in SDP offer \n");
05331 breakout = TRUE;
05332 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
05333
05334 if (debug)
05335 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
05336 breakout = TRUE;
05337 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
05338
05339 if (debug)
05340 ast_verbose("Got unsupported a:crypto in SDP offer \n");
05341 breakout = TRUE;
05342 }
05343 if (breakout)
05344 continue;
05345 }
05346 if (!strcasecmp(a, "sendonly")) {
05347 if (sendonly == -1)
05348 sendonly = 1;
05349 continue;
05350 } else if (!strcasecmp(a, "inactive")) {
05351 if (sendonly == -1)
05352 sendonly = 2;
05353 continue;
05354 } else if (!strcasecmp(a, "sendrecv")) {
05355 if (sendonly == -1)
05356 sendonly = 0;
05357 continue;
05358 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
05359 char *tmp = strrchr(a, ':');
05360 long int framing = 0;
05361 if (tmp) {
05362 tmp++;
05363 framing = strtol(tmp, NULL, 10);
05364 if (framing == LONG_MIN || framing == LONG_MAX) {
05365 framing = 0;
05366 if (option_debug)
05367 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
05368 }
05369 }
05370 if (framing && p->autoframing) {
05371 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
05372 int codec_n;
05373 int format = 0;
05374 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
05375 format = ast_rtp_codec_getformat(codec_n);
05376 if (!format)
05377 continue;
05378 if (option_debug)
05379 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
05380 ast_codec_pref_setsize(pref, format, framing);
05381 }
05382 ast_rtp_codec_setpref(p->rtp, pref);
05383 }
05384 continue;
05385 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
05386
05387 int found = FALSE;
05388
05389
05390
05391 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
05392
05393 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
05394 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
05395 if (debug)
05396 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
05397 found_rtpmap_codecs[last_rtpmap_codec] = codec;
05398 last_rtpmap_codec++;
05399 found = TRUE;
05400
05401 } else if (p->vrtp) {
05402 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
05403 if (debug)
05404 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
05405 found_rtpmap_codecs[last_rtpmap_codec] = codec;
05406 last_rtpmap_codec++;
05407 found = TRUE;
05408 }
05409 }
05410 } else {
05411 if (debug)
05412 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
05413 }
05414
05415 if (!found) {
05416
05417
05418
05419 ast_rtp_unset_m_type(newaudiortp, codec);
05420 ast_rtp_unset_m_type(newvideortp, codec);
05421 if (debug)
05422 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
05423 }
05424 }
05425 }
05426
05427 if (udptlportno != -1) {
05428 int found = 0, x;
05429
05430 old = 0;
05431
05432
05433 iterator = req->sdp_start;
05434 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
05435 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
05436 found = 1;
05437 if (option_debug > 2)
05438 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
05439 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
05440 found = 1;
05441 if (option_debug > 2)
05442 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
05443 switch (x) {
05444 case 14400:
05445 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05446 break;
05447 case 12000:
05448 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05449 break;
05450 case 9600:
05451 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05452 break;
05453 case 7200:
05454 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05455 break;
05456 case 4800:
05457 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
05458 break;
05459 case 2400:
05460 peert38capability |= T38FAX_RATE_2400;
05461 break;
05462 }
05463 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
05464 found = 1;
05465 if (option_debug > 2)
05466 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
05467 if (x == 0)
05468 peert38capability |= T38FAX_VERSION_0;
05469 else if (x == 1)
05470 peert38capability |= T38FAX_VERSION_1;
05471 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
05472 found = 1;
05473 if (option_debug > 2)
05474 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
05475 ast_udptl_set_far_max_datagram(p->udptl, x);
05476 ast_udptl_set_local_max_datagram(p->udptl, x);
05477 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
05478 found = 1;
05479 if (option_debug > 2)
05480 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
05481 if (x == 1)
05482 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
05483 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
05484 found = 1;
05485 if (option_debug > 2)
05486 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
05487 if (x == 1)
05488 peert38capability |= T38FAX_TRANSCODING_MMR;
05489 }
05490 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
05491 found = 1;
05492 if (option_debug > 2)
05493 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
05494 if (x == 1)
05495 peert38capability |= T38FAX_TRANSCODING_JBIG;
05496 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
05497 found = 1;
05498 if (option_debug > 2)
05499 ast_log(LOG_DEBUG, "RateManagement: %s\n", s);
05500 if (!strcasecmp(s, "localTCF"))
05501 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
05502 else if (!strcasecmp(s, "transferredTCF"))
05503 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
05504 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
05505 found = 1;
05506 if (option_debug > 2)
05507 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
05508 if (!strcasecmp(s, "t38UDPRedundancy")) {
05509 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
05510 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05511 } else if (!strcasecmp(s, "t38UDPFEC")) {
05512 peert38capability |= T38FAX_UDP_EC_FEC;
05513 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05514 } else {
05515 peert38capability |= T38FAX_UDP_EC_NONE;
05516 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05517 }
05518 }
05519 }
05520 if (found) {
05521 p->t38.peercapability = peert38capability;
05522 p->t38.jointcapability = (peert38capability & 255);
05523 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
05524 p->t38.jointcapability |= (peert38capability & p->t38.capability);
05525 }
05526 if (debug)
05527 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
05528 p->t38.capability,
05529 p->t38.peercapability,
05530 p->t38.jointcapability);
05531 } else {
05532 p->t38.state = T38_DISABLED;
05533 if (option_debug > 2)
05534 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
05535 }
05536
05537
05538 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
05539 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
05540
05541 newjointcapability = p->capability & (peercapability | vpeercapability);
05542 newpeercapability = (peercapability | vpeercapability);
05543 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
05544
05545
05546 if (debug) {
05547
05548 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE];
05549
05550 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
05551 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
05552 ast_getformatname_multiple(s2, SIPBUFSIZE, newpeercapability),
05553 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
05554 ast_getformatname_multiple(s4, SIPBUFSIZE, newjointcapability));
05555
05556 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
05557 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
05558 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
05559 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
05560 }
05561 if (!newjointcapability) {
05562
05563 if (!p->t38.jointcapability || !udptlportno) {
05564 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
05565
05566 return -1;
05567 } else {
05568 if (option_debug > 2)
05569 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
05570 return 0;
05571 }
05572 }
05573
05574
05575
05576 p->jointcapability = newjointcapability;
05577 p->peercapability = newpeercapability;
05578 p->jointnoncodeccapability = newnoncodeccapability;
05579
05580 ast_rtp_pt_copy(p->rtp, newaudiortp);
05581 if (p->vrtp)
05582 ast_rtp_pt_copy(p->vrtp, newvideortp);
05583
05584 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
05585 ast_clear_flag(&p->flags[0], SIP_DTMF);
05586 if (newnoncodeccapability & AST_RTP_DTMF) {
05587
05588 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
05589
05590 ast_rtp_setdtmf(p->rtp, 1);
05591 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05592 } else {
05593 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
05594 }
05595 }
05596
05597
05598 if (p->rtp && sin.sin_port) {
05599 ast_rtp_set_peer(p->rtp, &sin);
05600 if (debug)
05601 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
05602 }
05603
05604
05605 if (p->vrtp && vsin.sin_port) {
05606 ast_rtp_set_peer(p->vrtp, &vsin);
05607 if (debug)
05608 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
05609 }
05610
05611
05612 if (option_debug > 1) {
05613 char buf[SIPBUFSIZE];
05614 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
05615 }
05616
05617 if (!p->owner)
05618 return 0;
05619
05620 if (option_debug > 3)
05621 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
05622
05623 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05624 if (debug) {
05625 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
05626 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
05627 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
05628 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
05629 }
05630 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
05631 ast_set_read_format(p->owner, p->owner->readformat);
05632 ast_set_write_format(p->owner, p->owner->writeformat);
05633 }
05634
05635 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
05636 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
05637
05638 ast_queue_frame(p->owner, &ast_null_frame);
05639 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
05640 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
05641 S_OR(p->mohsuggest, NULL),
05642 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
05643 if (sendonly)
05644 ast_rtp_stop(p->rtp);
05645
05646
05647 ast_queue_frame(p->owner, &ast_null_frame);
05648 }
05649
05650
05651 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1))
05652 change_hold_state(p, req, FALSE, sendonly);
05653 else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1))
05654 change_hold_state(p, req, TRUE, sendonly);
05655 return 0;
05656 }
05657
05658
05659
05660 static int add_header(struct sip_request *req, const char *var, const char *value)
05661 {
05662 int maxlen = sizeof(req->data) - 4 - req->len;
05663
05664 if (req->headers == SIP_MAX_HEADERS) {
05665 ast_log(LOG_WARNING, "Out of SIP header space\n");
05666 return -1;
05667 }
05668
05669 if (req->lines) {
05670 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
05671 return -1;
05672 }
05673
05674 if (maxlen <= 0) {
05675 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
05676 return -1;
05677 }
05678
05679 req->header[req->headers] = req->data + req->len;
05680
05681 if (compactheaders)
05682 var = find_alias(var, var);
05683
05684 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
05685 req->len += strlen(req->header[req->headers]);
05686 req->headers++;
05687
05688 return 0;
05689 }
05690
05691
05692 static int add_header_contentLength(struct sip_request *req, int len)
05693 {
05694 char clen[10];
05695
05696 snprintf(clen, sizeof(clen), "%d", len);
05697 return add_header(req, "Content-Length", clen);
05698 }
05699
05700
05701 static int add_line(struct sip_request *req, const char *line)
05702 {
05703 if (req->lines == SIP_MAX_LINES) {
05704 ast_log(LOG_WARNING, "Out of SIP line space\n");
05705 return -1;
05706 }
05707 if (!req->lines) {
05708
05709 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
05710 req->len += strlen(req->data + req->len);
05711 }
05712 if (req->len >= sizeof(req->data) - 4) {
05713 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
05714 return -1;
05715 }
05716 req->line[req->lines] = req->data + req->len;
05717 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
05718 req->len += strlen(req->line[req->lines]);
05719 req->lines++;
05720 return 0;
05721 }
05722
05723
05724 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
05725 {
05726 const char *tmp = get_header(orig, field);
05727
05728 if (!ast_strlen_zero(tmp))
05729 return add_header(req, field, tmp);
05730 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
05731 return -1;
05732 }
05733
05734
05735 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
05736 {
05737 int start = 0;
05738 int copied = 0;
05739 for (;;) {
05740 const char *tmp = __get_header(orig, field, &start);
05741
05742 if (ast_strlen_zero(tmp))
05743 break;
05744
05745 add_header(req, field, tmp);
05746 copied++;
05747 }
05748 return copied ? 0 : -1;
05749 }
05750
05751
05752
05753
05754
05755
05756
05757 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
05758 {
05759 int copied = 0;
05760 int start = 0;
05761
05762 for (;;) {
05763 char new[512];
05764 const char *oh = __get_header(orig, field, &start);
05765
05766 if (ast_strlen_zero(oh))
05767 break;
05768
05769 if (!copied) {
05770 char leftmost[512], *others, *rport;
05771
05772
05773 ast_copy_string(leftmost, oh, sizeof(leftmost));
05774 others = strchr(leftmost, ',');
05775 if (others)
05776 *others++ = '\0';
05777
05778
05779 rport = strstr(leftmost, ";rport");
05780 if (rport && *(rport+6) == '=')
05781 rport = NULL;
05782
05783
05784 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
05785
05786 char *end;
05787
05788 rport = strstr(leftmost, ";rport");
05789
05790 if (rport) {
05791 end = strchr(rport + 1, ';');
05792 if (end)
05793 memmove(rport, end, strlen(end) + 1);
05794 else
05795 *rport = '\0';
05796 }
05797
05798
05799 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
05800 leftmost, ast_inet_ntoa(p->recv.sin_addr),
05801 ntohs(p->recv.sin_port),
05802 others ? "," : "", others ? others : "");
05803 } else {
05804
05805 snprintf(new, sizeof(new), "%s;received=%s%s%s",
05806 leftmost, ast_inet_ntoa(p->recv.sin_addr),
05807 others ? "," : "", others ? others : "");
05808 }
05809 oh = new;
05810 }
05811 add_header(req, field, oh);
05812 copied++;
05813 }
05814 if (!copied) {
05815 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
05816 return -1;
05817 }
05818 return 0;
05819 }
05820
05821
05822 static void add_route(struct sip_request *req, struct sip_route *route)
05823 {
05824 char r[SIPBUFSIZE*2], *p;
05825 int n, rem = sizeof(r);
05826
05827 if (!route)
05828 return;
05829
05830 p = r;
05831 for (;route ; route = route->next) {
05832 n = strlen(route->hop);
05833 if (rem < n+3)
05834 break;
05835 if (p != r) {
05836 *p++ = ',';
05837 --rem;
05838 }
05839 *p++ = '<';
05840 ast_copy_string(p, route->hop, rem);
05841 p += n;
05842 *p++ = '>';
05843 rem -= (n+2);
05844 }
05845 *p = '\0';
05846 add_header(req, "Route", r);
05847 }
05848
05849
05850 static void set_destination(struct sip_pvt *p, char *uri)
05851 {
05852 char *h, *maddr, hostname[256];
05853 int port, hn;
05854 struct hostent *hp;
05855 struct ast_hostent ahp;
05856 int debug=sip_debug_test_pvt(p);
05857
05858
05859
05860
05861 if (debug)
05862 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
05863
05864
05865 h = strchr(uri, '@');
05866 if (h)
05867 ++h;
05868 else {
05869 h = uri;
05870 if (strncasecmp(h, "sip:", 4) == 0)
05871 h += 4;
05872 else if (strncasecmp(h, "sips:", 5) == 0)
05873 h += 5;
05874 }
05875 hn = strcspn(h, ":;>") + 1;
05876 if (hn > sizeof(hostname))
05877 hn = sizeof(hostname);
05878 ast_copy_string(hostname, h, hn);
05879
05880 h += hn - 1;
05881
05882
05883 if (*h == ':') {
05884
05885 ++h;
05886 port = strtol(h, &h, 10);
05887 }
05888 else
05889 port = STANDARD_SIP_PORT;
05890
05891
05892 maddr = strstr(h, "maddr=");
05893 if (maddr) {
05894 maddr += 6;
05895 hn = strspn(maddr, "0123456789.") + 1;
05896 if (hn > sizeof(hostname))
05897 hn = sizeof(hostname);
05898 ast_copy_string(hostname, maddr, hn);
05899 }
05900
05901 hp = ast_gethostbyname(hostname, &ahp);
05902 if (hp == NULL) {
05903 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
05904 return;
05905 }
05906 p->sa.sin_family = AF_INET;
05907 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
05908 p->sa.sin_port = htons(port);
05909 if (debug)
05910 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
05911 }
05912
05913
05914 static int init_resp(struct sip_request *resp, const char *msg)
05915 {
05916
05917 memset(resp, 0, sizeof(*resp));
05918 resp->method = SIP_RESPONSE;
05919 resp->header[0] = resp->data;
05920 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
05921 resp->len = strlen(resp->header[0]);
05922 resp->headers++;
05923 return 0;
05924 }
05925
05926
05927 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
05928 {
05929
05930 memset(req, 0, sizeof(*req));
05931 req->method = sipmethod;
05932 req->header[0] = req->data;
05933 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
05934 req->len = strlen(req->header[0]);
05935 req->headers++;
05936 return 0;
05937 }
05938
05939
05940
05941 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
05942 {
05943 char newto[256];
05944 const char *ot;
05945
05946 init_resp(resp, msg);
05947 copy_via_headers(p, resp, req, "Via");
05948 if (msg[0] == '1' || msg[0] == '2')
05949 copy_all_header(resp, req, "Record-Route");
05950 copy_header(resp, req, "From");
05951 ot = get_header(req, "To");
05952 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
05953
05954
05955 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
05956 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
05957 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
05958 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
05959 else
05960 ast_copy_string(newto, ot, sizeof(newto));
05961 ot = newto;
05962 }
05963 add_header(resp, "To", ot);
05964 copy_header(resp, req, "Call-ID");
05965 copy_header(resp, req, "CSeq");
05966 if (!ast_strlen_zero(global_useragent))
05967 add_header(resp, "User-Agent", global_useragent);
05968 add_header(resp, "Allow", ALLOWED_METHODS);
05969 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
05970 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
05971
05972
05973 char tmp[256];
05974
05975 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
05976 add_header(resp, "Expires", tmp);
05977 if (p->expiry) {
05978 char contact[SIPBUFSIZE];
05979 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
05980 add_header(resp, "Contact", contact);
05981 }
05982 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
05983 add_header(resp, "Contact", p->our_contact);
05984 }
05985 return 0;
05986 }
05987
05988
05989 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
05990 {
05991 struct sip_request *orig = &p->initreq;
05992 char stripped[80];
05993 char tmp[80];
05994 char newto[256];
05995 const char *c;
05996 const char *ot, *of;
05997 int is_strict = FALSE;
05998
05999 memset(req, 0, sizeof(struct sip_request));
06000
06001 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
06002
06003 if (!seqno) {
06004 p->ocseq++;
06005 seqno = p->ocseq;
06006 }
06007
06008 if (newbranch) {
06009 p->branch ^= ast_random();
06010 build_via(p);
06011 }
06012
06013
06014 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
06015 is_strict = TRUE;
06016 if (sipdebug)
06017 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
06018 }
06019
06020 if (sipmethod == SIP_CANCEL)
06021 c = p->initreq.rlPart2;
06022 else if (sipmethod == SIP_ACK) {
06023
06024
06025 if (!ast_strlen_zero(p->okcontacturi))
06026 c = is_strict ? p->route->hop : p->okcontacturi;
06027 else
06028 c = p->initreq.rlPart2;
06029 } else if (!ast_strlen_zero(p->okcontacturi))
06030 c = is_strict ? p->route->hop : p->okcontacturi;
06031 else if (!ast_strlen_zero(p->uri))
06032 c = p->uri;
06033 else {
06034 char *n;
06035
06036 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
06037 sizeof(stripped));
06038 n = get_in_brackets(stripped);
06039 c = strsep(&n, ";");
06040 }
06041 init_req(req, sipmethod, c);
06042
06043 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
06044
06045 add_header(req, "Via", p->via);
06046 if (p->route) {
06047 set_destination(p, p->route->hop);
06048 add_route(req, is_strict ? p->route->next : p->route);
06049 }
06050
06051 ot = get_header(orig, "To");
06052 of = get_header(orig, "From");
06053
06054
06055
06056 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
06057
06058
06059 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
06060 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
06061 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
06062 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
06063 else
06064 snprintf(newto, sizeof(newto), "%s", ot);
06065 ot = newto;
06066 }
06067
06068 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06069 add_header(req, "From", of);
06070 add_header(req, "To", ot);
06071 } else {
06072 add_header(req, "From", ot);
06073 add_header(req, "To", of);
06074 }
06075
06076 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
06077 add_header(req, "Contact", p->our_contact);
06078
06079 copy_header(req, orig, "Call-ID");
06080 add_header(req, "CSeq", tmp);
06081
06082 if (!ast_strlen_zero(global_useragent))
06083 add_header(req, "User-Agent", global_useragent);
06084 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
06085
06086 if (!ast_strlen_zero(p->rpid))
06087 add_header(req, "Remote-Party-ID", p->rpid);
06088
06089 return 0;
06090 }
06091
06092
06093 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
06094 {
06095 struct sip_request resp;
06096 int seqno = 0;
06097
06098 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
06099 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
06100 return -1;
06101 }
06102 respprep(&resp, p, msg, req);
06103 add_header_contentLength(&resp, 0);
06104
06105
06106 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
06107 char buf[10];
06108
06109 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
06110 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
06111 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
06112 }
06113 return send_response(p, &resp, reliable, seqno);
06114 }
06115
06116 static void temp_pvt_cleanup(void *data)
06117 {
06118 struct sip_pvt *p = data;
06119
06120 ast_string_field_free_memory(p);
06121
06122 free(data);
06123 }
06124
06125
06126 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
06127 {
06128 struct sip_pvt *p = NULL;
06129
06130 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
06131 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
06132 return -1;
06133 }
06134
06135
06136 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
06137 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
06138 if (ast_string_field_init(p, 512))
06139 return -1;
06140 }
06141
06142
06143 p->method = intended_method;
06144
06145 if (sin) {
06146 p->sa = *sin;
06147 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
06148 p->ourip = __ourip;
06149 } else
06150 p->ourip = __ourip;
06151
06152 p->branch = ast_random();
06153 make_our_tag(p->tag, sizeof(p->tag));
06154 p->ocseq = INITIAL_CSEQ;
06155
06156 if (useglobal_nat && sin) {
06157 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
06158 p->recv = *sin;
06159 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
06160 }
06161 check_via(p, req);
06162
06163 ast_string_field_set(p, fromdomain, default_fromdomain);
06164 build_via(p);
06165 ast_string_field_set(p, callid, callid);
06166
06167
06168 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
06169
06170
06171 ast_string_field_reset_all(p);
06172
06173 return 0;
06174 }
06175
06176
06177 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
06178 {
06179 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
06180 }
06181
06182
06183 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
06184 {
06185 struct sip_request resp;
06186 respprep(&resp, p, msg, req);
06187 append_date(&resp);
06188 add_header(&resp, "Unsupported", unsupported);
06189 add_header_contentLength(&resp, 0);
06190 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
06191 }
06192
06193
06194
06195
06196 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
06197 {
06198 return __transmit_response(p, msg, req, XMIT_CRITICAL);
06199 }
06200
06201
06202 static void append_date(struct sip_request *req)
06203 {
06204 char tmpdat[256];
06205 struct tm tm;
06206 time_t t = time(NULL);
06207
06208 gmtime_r(&t, &tm);
06209 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
06210 add_header(req, "Date", tmpdat);
06211 }
06212
06213
06214 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
06215 {
06216 struct sip_request resp;
06217 respprep(&resp, p, msg, req);
06218 append_date(&resp);
06219 add_header_contentLength(&resp, 0);
06220 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
06221 }
06222
06223
06224 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
06225 {
06226 struct sip_request resp;
06227 respprep(&resp, p, msg, req);
06228 add_header(&resp, "Accept", "application/sdp");
06229 add_header_contentLength(&resp, 0);
06230 return send_response(p, &resp, reliable, 0);
06231 }
06232
06233
06234 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
06235 {
06236 struct sip_request resp;
06237 char tmp[512];
06238 int seqno = 0;
06239
06240 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
06241 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
06242 return -1;
06243 }
06244
06245
06246 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
06247 respprep(&resp, p, msg, req);
06248 add_header(&resp, header, tmp);
06249 add_header_contentLength(&resp, 0);
06250 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
06251 return send_response(p, &resp, reliable, seqno);
06252 }
06253
06254
06255 static int add_text(struct sip_request *req, const char *text)
06256 {
06257
06258 add_header(req, "Content-Type", "text/plain");
06259 add_header_contentLength(req, strlen(text));
06260 add_line(req, text);
06261 return 0;
06262 }
06263
06264
06265
06266 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
06267 {
06268 char tmp[256];
06269
06270 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
06271 add_header(req, "Content-Type", "application/dtmf-relay");
06272 add_header_contentLength(req, strlen(tmp));
06273 add_line(req, tmp);
06274 return 0;
06275 }
06276
06277
06278
06279 static int add_vidupdate(struct sip_request *req)
06280 {
06281 const char *xml_is_a_huge_waste_of_space =
06282 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
06283 " <media_control>\r\n"
06284 " <vc_primitive>\r\n"
06285 " <to_encoder>\r\n"
06286 " <picture_fast_update>\r\n"
06287 " </picture_fast_update>\r\n"
06288 " </to_encoder>\r\n"
06289 " </vc_primitive>\r\n"
06290 " </media_control>\r\n";
06291 add_header(req, "Content-Type", "application/media_control+xml");
06292 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
06293 add_line(req, xml_is_a_huge_waste_of_space);
06294 return 0;
06295 }
06296
06297
06298 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
06299 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
06300 int debug, int *min_packet_size)
06301 {
06302 int rtp_code;
06303 struct ast_format_list fmt;
06304
06305
06306 if (debug)
06307 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
06308 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
06309 return;
06310
06311 if (p->rtp) {
06312 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
06313 fmt = ast_codec_pref_getsize(pref, codec);
06314 } else
06315 return;
06316 ast_build_string(m_buf, m_size, " %d", rtp_code);
06317 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
06318 ast_rtp_lookup_mime_subtype(1, codec,
06319 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
06320 sample_rate);
06321 if (codec == AST_FORMAT_G729A) {
06322
06323 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
06324 } else if (codec == AST_FORMAT_G723_1) {
06325
06326 ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
06327 } else if (codec == AST_FORMAT_ILBC) {
06328
06329 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
06330 }
06331
06332 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
06333 *min_packet_size = fmt.cur_ms;
06334
06335
06336 if ((*min_packet_size) == 0 && fmt.cur_ms)
06337 *min_packet_size = fmt.cur_ms;
06338 }
06339
06340
06341 static int t38_get_rate(int t38cap)
06342 {
06343 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
06344
06345 if (maxrate & T38FAX_RATE_14400) {
06346 if (option_debug > 1)
06347 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
06348 return 14400;
06349 } else if (maxrate & T38FAX_RATE_12000) {
06350 if (option_debug > 1)
06351 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
06352 return 12000;
06353 } else if (maxrate & T38FAX_RATE_9600) {
06354 if (option_debug > 1)
06355 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
06356 return 9600;
06357 } else if (maxrate & T38FAX_RATE_7200) {
06358 if (option_debug > 1)
06359 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
06360 return 7200;
06361 } else if (maxrate & T38FAX_RATE_4800) {
06362 if (option_debug > 1)
06363 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
06364 return 4800;
06365 } else if (maxrate & T38FAX_RATE_2400) {
06366 if (option_debug > 1)
06367 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
06368 return 2400;
06369 } else {
06370 if (option_debug > 1)
06371 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
06372 return 0;
06373 }
06374 }
06375
06376
06377 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
06378 {
06379 int len = 0;
06380 int x = 0;
06381 struct sockaddr_in udptlsin;
06382 char v[256] = "";
06383 char s[256] = "";
06384 char o[256] = "";
06385 char c[256] = "";
06386 char t[256] = "";
06387 char m_modem[256];
06388 char a_modem[1024];
06389 char *m_modem_next = m_modem;
06390 size_t m_modem_left = sizeof(m_modem);
06391 char *a_modem_next = a_modem;
06392 size_t a_modem_left = sizeof(a_modem);
06393 struct sockaddr_in udptldest = { 0, };
06394 int debug;
06395
06396 debug = sip_debug_test_pvt(p);
06397 len = 0;
06398 if (!p->udptl) {
06399 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
06400 return -1;
06401 }
06402
06403 if (!p->sessionid) {
06404 p->sessionid = getpid();
06405 p->sessionversion = p->sessionid;
06406 } else
06407 p->sessionversion++;
06408
06409
06410 ast_udptl_get_us(p->udptl, &udptlsin);
06411
06412
06413 if (p->udptlredirip.sin_addr.s_addr) {
06414 udptldest.sin_port = p->udptlredirip.sin_port;
06415 udptldest.sin_addr = p->udptlredirip.sin_addr;
06416 } else {
06417 udptldest.sin_addr = p->ourip;
06418 udptldest.sin_port = udptlsin.sin_port;
06419 }
06420
06421 if (debug)
06422 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
06423
06424
06425
06426
06427 if (debug) {
06428 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
06429 p->t38.capability,
06430 p->t38.peercapability,
06431 p->t38.jointcapability);
06432 }
06433 snprintf(v, sizeof(v), "v=0\r\n");
06434 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
06435 snprintf(s, sizeof(s), "s=session\r\n");
06436 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
06437 snprintf(t, sizeof(t), "t=0 0\r\n");
06438 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
06439
06440 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
06441 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
06442 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
06443 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
06444 if ((x = t38_get_rate(p->t38.jointcapability)))
06445 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
06446 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
06447 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
06448 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
06449 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
06450 x = ast_udptl_get_local_max_datagram(p->udptl);
06451 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
06452 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
06453 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
06454 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
06455 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
06456 add_header(resp, "Content-Type", "application/sdp");
06457 add_header_contentLength(resp, len);
06458 add_line(resp, v);
06459 add_line(resp, o);
06460 add_line(resp, s);
06461 add_line(resp, c);
06462 add_line(resp, t);
06463 add_line(resp, m_modem);
06464 add_line(resp, a_modem);
06465
06466
06467 p->lastrtprx = p->lastrtptx = time(NULL);
06468
06469 return 0;
06470 }
06471
06472
06473
06474 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
06475 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
06476 int debug)
06477 {
06478 int rtp_code;
06479
06480 if (debug)
06481 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
06482 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
06483 return;
06484
06485 ast_build_string(m_buf, m_size, " %d", rtp_code);
06486 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
06487 ast_rtp_lookup_mime_subtype(0, format, 0),
06488 sample_rate);
06489 if (format == AST_RTP_DTMF)
06490
06491 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
06492 }
06493
06494
06495
06496
06497
06498
06499 #define SDP_SAMPLE_RATE(x) 8000
06500
06501
06502 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
06503 {
06504 int len = 0;
06505 int alreadysent = 0;
06506
06507 struct sockaddr_in sin;
06508 struct sockaddr_in vsin;
06509 struct sockaddr_in dest;
06510 struct sockaddr_in vdest = { 0, };
06511
06512
06513 char *version = "v=0\r\n";
06514 char *subject = "s=session\r\n";
06515 char owner[256];
06516 char connection[256];
06517 char *stime = "t=0 0\r\n";
06518 char bandwidth[256] = "";
06519 char *hold;
06520 char m_audio[256];
06521 char m_video[256];
06522 char a_audio[1024];
06523 char a_video[1024];
06524 char *m_audio_next = m_audio;
06525 char *m_video_next = m_video;
06526 size_t m_audio_left = sizeof(m_audio);
06527 size_t m_video_left = sizeof(m_video);
06528 char *a_audio_next = a_audio;
06529 char *a_video_next = a_video;
06530 size_t a_audio_left = sizeof(a_audio);
06531 size_t a_video_left = sizeof(a_video);
06532
06533 int x;
06534 int capability;
06535 int needvideo = FALSE;
06536 int debug = sip_debug_test_pvt(p);
06537 int min_audio_packet_size = 0;
06538 int min_video_packet_size = 0;
06539
06540 m_video[0] = '\0';
06541
06542 if (!p->rtp) {
06543 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
06544 return AST_FAILURE;
06545 }
06546
06547
06548 if (!p->sessionid) {
06549 p->sessionid = getpid();
06550 p->sessionversion = p->sessionid;
06551 } else
06552 p->sessionversion++;
06553
06554
06555 ast_rtp_get_us(p->rtp, &sin);
06556 if (p->vrtp)
06557 ast_rtp_get_us(p->vrtp, &vsin);
06558
06559
06560 if (p->redirip.sin_addr.s_addr) {
06561 dest.sin_port = p->redirip.sin_port;
06562 dest.sin_addr = p->redirip.sin_addr;
06563 } else {
06564 dest.sin_addr = p->ourip;
06565 dest.sin_port = sin.sin_port;
06566 }
06567
06568 capability = p->jointcapability;
06569
06570
06571 if (option_debug > 1) {
06572 char codecbuf[SIPBUFSIZE];
06573 ast_log(LOG_DEBUG, "** Our capability: %s Video flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), ast_test_flag(&p->flags[0], SIP_NOVIDEO) ? "True" : "False");
06574 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
06575 }
06576
06577 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
06578 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
06579 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
06580 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
06581 }
06582 #endif
06583
06584
06585 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
06586 if (p->vrtp) {
06587 needvideo = TRUE;
06588 if (option_debug > 1)
06589 ast_log(LOG_DEBUG, "This call needs video offers!\n");
06590 } else if (option_debug > 1)
06591 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
06592 }
06593
06594
06595
06596
06597 if (needvideo) {
06598
06599 if (p->vredirip.sin_addr.s_addr) {
06600 vdest.sin_addr = p->vredirip.sin_addr;
06601 vdest.sin_port = p->vredirip.sin_port;
06602 } else {
06603 vdest.sin_addr = p->ourip;
06604 vdest.sin_port = vsin.sin_port;
06605 }
06606 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
06607
06608
06609 if (p->maxcallbitrate)
06610 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
06611 if (debug)
06612 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
06613 }
06614
06615 if (debug)
06616 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
06617
06618
06619
06620
06621
06622
06623 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
06624 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
06625 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
06626
06627 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
06628 hold = "a=recvonly\r\n";
06629 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
06630 hold = "a=inactive\r\n";
06631 else
06632 hold = "a=sendrecv\r\n";
06633
06634
06635
06636
06637
06638
06639
06640
06641
06642
06643 if (capability & p->prefcodec) {
06644 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
06645
06646 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
06647 &m_audio_next, &m_audio_left,
06648 &a_audio_next, &a_audio_left,
06649 debug, &min_audio_packet_size);
06650 alreadysent |= codec;
06651 }
06652
06653
06654 for (x = 0; x < 32; x++) {
06655 int codec;
06656
06657 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
06658 break;
06659
06660 if (!(capability & codec))
06661 continue;
06662
06663 if (alreadysent & codec)
06664 continue;
06665
06666 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
06667 &m_audio_next, &m_audio_left,
06668 &a_audio_next, &a_audio_left,
06669 debug, &min_audio_packet_size);
06670 alreadysent |= codec;
06671 }
06672
06673
06674 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
06675 if (!(capability & x))
06676 continue;
06677
06678 if (alreadysent & x)
06679 continue;
06680
06681 if (x <= AST_FORMAT_MAX_AUDIO)
06682 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
06683 &m_audio_next, &m_audio_left,
06684 &a_audio_next, &a_audio_left,
06685 debug, &min_audio_packet_size);
06686 else
06687 add_codec_to_sdp(p, x, 90000,
06688 &m_video_next, &m_video_left,
06689 &a_video_next, &a_video_left,
06690 debug, &min_video_packet_size);
06691 }
06692
06693
06694 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
06695 if (!(p->jointnoncodeccapability & x))
06696 continue;
06697
06698 add_noncodec_to_sdp(p, x, 8000,
06699 &m_audio_next, &m_audio_left,
06700 &a_audio_next, &a_audio_left,
06701 debug);
06702 }
06703
06704 if (option_debug > 2)
06705 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
06706
06707 if (!p->owner || !ast_internal_timing_enabled(p->owner))
06708 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
06709
06710 if (min_audio_packet_size)
06711 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
06712
06713 if (min_video_packet_size)
06714 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
06715
06716 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
06717 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
06718
06719 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
06720 if (needvideo)
06721 ast_build_string(&m_video_next, &m_video_left, "\r\n");
06722
06723 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
06724 if (needvideo)
06725 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
06726
06727 add_header(resp, "Content-Type", "application/sdp");
06728 add_header_contentLength(resp, len);
06729 add_line(resp, version);
06730 add_line(resp, owner);
06731 add_line(resp, subject);
06732 add_line(resp, connection);
06733 if (needvideo)
06734 add_line(resp, bandwidth);
06735 add_line(resp, stime);
06736 add_line(resp, m_audio);
06737 add_line(resp, a_audio);
06738 add_line(resp, hold);
06739 if (needvideo) {
06740 add_line(resp, m_video);
06741 add_line(resp, a_video);
06742 add_line(resp, hold);
06743 }
06744
06745
06746 p->lastrtprx = p->lastrtptx = time(NULL);
06747
06748 if (option_debug > 2) {
06749 char buf[SIPBUFSIZE];
06750 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
06751 }
06752
06753 return AST_SUCCESS;
06754 }
06755
06756
06757 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
06758 {
06759 struct sip_request resp;
06760 int seqno;
06761
06762 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
06763 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
06764 return -1;
06765 }
06766 respprep(&resp, p, msg, req);
06767 if (p->udptl) {
06768 ast_udptl_offered_from_local(p->udptl, 0);
06769 add_t38_sdp(&resp, p);
06770 } else
06771 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
06772 if (retrans && !p->pendinginvite)
06773 p->pendinginvite = seqno;
06774 return send_response(p, &resp, retrans, seqno);
06775 }
06776
06777
06778 static void copy_request(struct sip_request *dst, const struct sip_request *src)
06779 {
06780 long offset;
06781 int x;
06782 offset = ((void *)dst) - ((void *)src);
06783
06784 memcpy(dst, src, sizeof(*dst));
06785
06786 for (x=0; x < src->headers; x++)
06787 dst->header[x] += offset;
06788 for (x=0; x < src->lines; x++)
06789 dst->line[x] += offset;
06790 dst->rlPart1 += offset;
06791 dst->rlPart2 += offset;
06792 }
06793
06794
06795
06796
06797 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
06798 {
06799 struct sip_request resp;
06800 int seqno;
06801 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
06802 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
06803 return -1;
06804 }
06805 respprep(&resp, p, msg, req);
06806 if (p->rtp) {
06807 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06808 if (option_debug)
06809 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
06810 ast_rtp_codec_setpref(p->rtp, &p->prefs);
06811 }
06812 try_suggested_sip_codec(p);
06813 add_sdp(&resp, p);
06814 } else
06815 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
06816 if (reliable && !p->pendinginvite)
06817 p->pendinginvite = seqno;
06818 return send_response(p, &resp, reliable, seqno);
06819 }
06820
06821
06822 static int determine_firstline_parts(struct sip_request *req)
06823 {
06824 char *e = ast_skip_blanks(req->header[0]);
06825
06826 if (!*e)
06827 return -1;
06828 req->rlPart1 = e;
06829 e = ast_skip_nonblanks(e);
06830 if (*e)
06831 *e++ = '\0';
06832
06833 e = ast_skip_blanks(e);
06834 if ( !*e )
06835 return -1;
06836 ast_trim_blanks(e);
06837
06838 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) {
06839 if (strlen(e) < 3)
06840 return -1;
06841 req->rlPart2 = e;
06842 } else {
06843 if ( *e == '<' ) {
06844 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
06845 e++;
06846 if (!*e)
06847 return -1;
06848 }
06849 req->rlPart2 = e;
06850 e = ast_skip_nonblanks(e);
06851 if (*e)
06852 *e++ = '\0';
06853 e = ast_skip_blanks(e);
06854 if (strcasecmp(e, "SIP/2.0") ) {
06855 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
06856 return -1;
06857 }
06858 }
06859 return 1;
06860 }
06861
06862
06863
06864
06865
06866
06867
06868 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
06869 {
06870 struct sip_request req;
06871
06872 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
06873
06874 add_header(&req, "Allow", ALLOWED_METHODS);
06875 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
06876 if (sipdebug)
06877 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
06878 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
06879 append_history(p, "ReInv", "Re-invite sent");
06880 add_sdp(&req, p);
06881
06882 initialize_initreq(p, &req);
06883 p->lastinvite = p->ocseq;
06884 ast_set_flag(&p->flags[0], SIP_OUTGOING);
06885 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
06886 }
06887
06888
06889
06890
06891
06892 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
06893 {
06894 struct sip_request req;
06895
06896 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
06897
06898 add_header(&req, "Allow", ALLOWED_METHODS);
06899 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
06900 if (sipdebug)
06901 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
06902 ast_udptl_offered_from_local(p->udptl, 1);
06903 add_t38_sdp(&req, p);
06904
06905 initialize_initreq(p, &req);
06906 ast_set_flag(&p->flags[0], SIP_OUTGOING);
06907 p->lastinvite = p->ocseq;
06908 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
06909 }
06910
06911
06912 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
06913 {
06914 char stripped[SIPBUFSIZE];
06915 char *c;
06916
06917 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
06918 c = get_in_brackets(stripped);
06919 c = strsep(&c, ";");
06920 if (!ast_strlen_zero(c))
06921 ast_string_field_set(p, uri, c);
06922 }
06923
06924
06925 static void build_contact(struct sip_pvt *p)
06926 {
06927
06928 if (ourport != STANDARD_SIP_PORT)
06929 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip), ourport);
06930 else
06931 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
06932 }
06933
06934
06935 static void build_rpid(struct sip_pvt *p)
06936 {
06937 int send_pres_tags = TRUE;
06938 const char *privacy=NULL;
06939 const char *screen=NULL;
06940 char buf[256];
06941 const char *clid = default_callerid;
06942 const char *clin = NULL;
06943 const char *fromdomain;
06944
06945 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
06946 return;
06947
06948 if (p->owner && p->owner->cid.cid_num)
06949 clid = p->owner->cid.cid_num;
06950 if (p->owner && p->owner->cid.cid_name)
06951 clin = p->owner->cid.cid_name;
06952 if (ast_strlen_zero(clin))
06953 clin = clid;
06954
06955 switch (p->callingpres) {
06956 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
06957 privacy = "off";
06958 screen = "no";
06959 break;
06960 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
06961 privacy = "off";
06962 screen = "yes";
06963 break;
06964 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
06965 privacy = "off";
06966 screen = "no";
06967 break;
06968 case AST_PRES_ALLOWED_NETWORK_NUMBER:
06969 privacy = "off";
06970 screen = "yes";
06971 break;
06972 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
06973 privacy = "full";
06974 screen = "no";
06975 break;
06976 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
06977 privacy = "full";
06978 screen = "yes";
06979 break;
06980 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
06981 privacy = "full";
06982 screen = "no";
06983 break;
06984 case AST_PRES_PROHIB_NETWORK_NUMBER:
06985 privacy = "full";
06986 screen = "yes";
06987 break;
06988 case AST_PRES_NUMBER_NOT_AVAILABLE:
06989 send_pres_tags = FALSE;
06990 break;
06991 default:
06992 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
06993 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
06994 privacy = "full";
06995 else
06996 privacy = "off";
06997 screen = "no";
06998 break;
06999 }
07000
07001 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
07002
07003 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
07004 if (send_pres_tags)
07005 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
07006 ast_string_field_set(p, rpid, buf);
07007
07008 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
07009 S_OR(p->fromuser, clid),
07010 fromdomain, p->tag);
07011 }
07012
07013
07014 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
07015 {
07016 char invite_buf[256] = "";
07017 char *invite = invite_buf;
07018 size_t invite_max = sizeof(invite_buf);
07019 char from[256];
07020 char to[256];
07021 char tmp[SIPBUFSIZE/2];
07022 char tmp2[SIPBUFSIZE/2];
07023 const char *l = NULL, *n = NULL;
07024 const char *urioptions = "";
07025
07026 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
07027 const char *s = p->username;
07028
07029
07030
07031
07032
07033
07034 if (*s == '+')
07035 s++;
07036 for (; *s; s++) {
07037 if (!strchr(AST_DIGIT_ANYNUM, *s) )
07038 break;
07039 }
07040
07041 if (*s)
07042 urioptions = ";user=phone";
07043 }
07044
07045
07046 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
07047
07048 if (p->owner) {
07049 l = p->owner->cid.cid_num;
07050 n = p->owner->cid.cid_name;
07051 }
07052
07053 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
07054 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
07055 l = CALLERID_UNKNOWN;
07056 n = l;
07057 }
07058 if (ast_strlen_zero(l))
07059 l = default_callerid;
07060 if (ast_strlen_zero(n))
07061 n = l;
07062
07063 if (!ast_strlen_zero(p->fromuser))
07064 l = p->fromuser;
07065 else
07066 ast_string_field_set(p, fromuser, l);
07067
07068
07069 if (!ast_strlen_zero(p->fromname))
07070 n = p->fromname;
07071 else
07072 ast_string_field_set(p, fromname, n);
07073
07074 if (pedanticsipchecking) {
07075 ast_uri_encode(n, tmp, sizeof(tmp), 0);
07076 n = tmp;
07077 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
07078 l = tmp2;
07079 }
07080
07081 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
07082 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), ourport, p->tag);
07083 else
07084 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
07085
07086
07087 if (!ast_strlen_zero(p->fullcontact)) {
07088
07089 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
07090 } else {
07091
07092 ast_build_string(&invite, &invite_max, "sip:");
07093 if (!ast_strlen_zero(p->username)) {
07094 n = p->username;
07095 if (pedanticsipchecking) {
07096 ast_uri_encode(n, tmp, sizeof(tmp), 0);
07097 n = tmp;
07098 }
07099 ast_build_string(&invite, &invite_max, "%s@", n);
07100 }
07101 ast_build_string(&invite, &invite_max, "%s", p->tohost);
07102 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
07103 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
07104 ast_build_string(&invite, &invite_max, "%s", urioptions);
07105 }
07106
07107
07108 if (p->options && !ast_strlen_zero(p->options->uri_options))
07109 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
07110
07111 ast_string_field_set(p, uri, invite_buf);
07112
07113 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
07114
07115 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
07116 } else if (p->options && p->options->vxml_url) {
07117
07118 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
07119 } else
07120 snprintf(to, sizeof(to), "<%s>", p->uri);
07121
07122 init_req(req, sipmethod, p->uri);
07123 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
07124
07125 add_header(req, "Via", p->via);
07126
07127
07128
07129 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
07130 build_rpid(p);
07131 add_header(req, "From", p->rpid_from);
07132 } else
07133 add_header(req, "From", from);
07134 add_header(req, "To", to);
07135 ast_string_field_set(p, exten, l);
07136 build_contact(p);
07137 add_header(req, "Contact", p->our_contact);
07138 add_header(req, "Call-ID", p->callid);
07139 add_header(req, "CSeq", tmp);
07140 if (!ast_strlen_zero(global_useragent))
07141 add_header(req, "User-Agent", global_useragent);
07142 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
07143 if (!ast_strlen_zero(p->rpid))
07144 add_header(req, "Remote-Party-ID", p->rpid);
07145 }
07146
07147
07148 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
07149 {
07150 struct sip_request req;
07151
07152 req.method = sipmethod;
07153 if (init) {
07154
07155 p->branch ^= ast_random();
07156 build_via(p);
07157 if (init > 1)
07158 initreqprep(&req, p, sipmethod);
07159 else
07160 reqprep(&req, p, sipmethod, 0, 1);
07161 } else
07162 reqprep(&req, p, sipmethod, 0, 1);
07163
07164 if (p->options && p->options->auth)
07165 add_header(&req, p->options->authheader, p->options->auth);
07166 append_date(&req);
07167 if (sipmethod == SIP_REFER) {
07168 if (p->refer) {
07169 char buf[SIPBUFSIZE];
07170 if (!ast_strlen_zero(p->refer->refer_to))
07171 add_header(&req, "Refer-To", p->refer->refer_to);
07172 if (!ast_strlen_zero(p->refer->referred_by)) {
07173 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
07174 add_header(&req, "Referred-By", buf);
07175 }
07176 }
07177 }
07178
07179
07180 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
07181 add_header(&req, "Replaces", p->options->replaces);
07182 add_header(&req, "Require", "replaces");
07183 }
07184
07185 add_header(&req, "Allow", ALLOWED_METHODS);
07186 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
07187 if (p->options && p->options->addsipheaders && p->owner) {
07188 struct ast_channel *chan = p->owner;
07189 struct varshead *headp;
07190
07191 ast_channel_lock(chan);
07192
07193 headp = &chan->varshead;
07194
07195 if (!headp)
07196 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
07197 else {
07198 const struct ast_var_t *current;
07199 AST_LIST_TRAVERSE(headp, current, entries) {
07200
07201 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
07202 char *content, *end;
07203 const char *header = ast_var_value(current);
07204 char *headdup = ast_strdupa(header);
07205
07206
07207 if (*headdup == '"')
07208 headdup++;
07209 if ((content = strchr(headdup, ':'))) {
07210 *content++ = '\0';
07211 content = ast_skip_blanks(content);
07212
07213 end = content + strlen(content) -1;
07214 if (*end == '"')
07215 *end = '\0';
07216
07217 add_header(&req, headdup, content);
07218 if (sipdebug)
07219 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
07220 }
07221 }
07222 }
07223 }
07224
07225 ast_channel_unlock(chan);
07226 }
07227 if (sdp) {
07228 if (p->udptl && (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)) {
07229 ast_udptl_offered_from_local(p->udptl, 1);
07230 if (option_debug)
07231 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
07232 add_t38_sdp(&req, p);
07233 } else if (p->rtp)
07234 add_sdp(&req, p);
07235 } else {
07236 add_header_contentLength(&req, 0);
07237 }
07238
07239 if (!p->initreq.headers)
07240 initialize_initreq(p, &req);
07241 p->lastinvite = p->ocseq;
07242 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
07243 }
07244
07245
07246 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
07247 {
07248 char tmp[4000], from[256], to[256];
07249 char *t = tmp, *c, *mfrom, *mto;
07250 size_t maxbytes = sizeof(tmp);
07251 struct sip_request req;
07252 char hint[AST_MAX_EXTENSION];
07253 char *statestring = "terminated";
07254 const struct cfsubscription_types *subscriptiontype;
07255 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
07256 char *pidfstate = "--";
07257 char *pidfnote= "Ready";
07258
07259 memset(from, 0, sizeof(from));
07260 memset(to, 0, sizeof(to));
07261 memset(tmp, 0, sizeof(tmp));
07262
07263 switch (state) {
07264 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
07265 statestring = (global_notifyringing) ? "early" : "confirmed";
07266 local_state = NOTIFY_INUSE;
07267 pidfstate = "busy";
07268 pidfnote = "Ringing";
07269 break;
07270 case AST_EXTENSION_RINGING:
07271 statestring = "early";
07272 local_state = NOTIFY_INUSE;
07273 pidfstate = "busy";
07274 pidfnote = "Ringing";
07275 break;
07276 case AST_EXTENSION_INUSE:
07277 statestring = "confirmed";
07278 local_state = NOTIFY_INUSE;
07279 pidfstate = "busy";
07280 pidfnote = "On the phone";
07281 break;
07282 case AST_EXTENSION_BUSY:
07283 statestring = "confirmed";
07284 local_state = NOTIFY_CLOSED;
07285 pidfstate = "busy";
07286 pidfnote = "On the phone";
07287 break;
07288 case AST_EXTENSION_UNAVAILABLE:
07289 statestring = "terminated";
07290 local_state = NOTIFY_CLOSED;
07291 pidfstate = "away";
07292 pidfnote = "Unavailable";
07293 break;
07294 case AST_EXTENSION_ONHOLD:
07295 statestring = "confirmed";
07296 local_state = NOTIFY_CLOSED;
07297 pidfstate = "busy";
07298 pidfnote = "On Hold";
07299 break;
07300 case AST_EXTENSION_NOT_INUSE:
07301 default:
07302
07303 break;
07304 }
07305
07306 subscriptiontype = find_subscription_type(p->subscribed);
07307
07308
07309 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
07310 char *hint2 = hint, *individual_hint = NULL;
07311 int hint_count = 0, unavailable_count = 0;
07312
07313 while ((individual_hint = strsep(&hint2, "&"))) {
07314 hint_count++;
07315
07316 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
07317 unavailable_count++;
07318 }
07319
07320
07321
07322
07323 if (hint_count > 0 && hint_count == unavailable_count) {
07324 local_state = NOTIFY_CLOSED;
07325 pidfstate = "away";
07326 pidfnote = "Not online";
07327 }
07328 }
07329
07330 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
07331 c = get_in_brackets(from);
07332 if (strncasecmp(c, "sip:", 4)) {
07333 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
07334 return -1;
07335 }
07336 mfrom = strsep(&c, ";");
07337
07338 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
07339 c = get_in_brackets(to);
07340 if (strncasecmp(c, "sip:", 4)) {
07341 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
07342 return -1;
07343 }
07344 mto = strsep(&c, ";");
07345
07346 reqprep(&req, p, SIP_NOTIFY, 0, 1);
07347
07348
07349 add_header(&req, "Event", subscriptiontype->event);
07350 add_header(&req, "Content-Type", subscriptiontype->mediatype);
07351 switch(state) {
07352 case AST_EXTENSION_DEACTIVATED:
07353 if (timeout)
07354 add_header(&req, "Subscription-State", "terminated;reason=timeout");
07355 else {
07356 add_header(&req, "Subscription-State", "terminated;reason=probation");
07357 add_header(&req, "Retry-After", "60");
07358 }
07359 break;
07360 case AST_EXTENSION_REMOVED:
07361 add_header(&req, "Subscription-State", "terminated;reason=noresource");
07362 break;
07363 default:
07364 if (p->expiry)
07365 add_header(&req, "Subscription-State", "active");
07366 else
07367 add_header(&req, "Subscription-State", "terminated;reason=timeout");
07368 }
07369 switch (p->subscribed) {
07370 case XPIDF_XML:
07371 case CPIM_PIDF_XML:
07372 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
07373 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
07374 ast_build_string(&t, &maxbytes, "<presence>\n");
07375 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
07376 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
07377 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
07378 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
07379 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
07380 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
07381 break;
07382 case PIDF_XML:
07383 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
07384 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);
07385 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
07386 if (pidfstate[0] != '-')
07387 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
07388 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
07389 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote);
07390 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten);
07391 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
07392 if (pidfstate[0] == 'b')
07393 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
07394 else
07395 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
07396 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
07397 break;
07398 case DIALOG_INFO_XML:
07399 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
07400 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);
07401 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
07402 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
07403 else
07404 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
07405 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
07406 if (state == AST_EXTENSION_ONHOLD) {
07407 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
07408 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
07409 "</target>\n</local>\n", mto);
07410 }
07411 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
07412 break;
07413 case NONE:
07414 default:
07415 break;
07416 }
07417
07418 if (t > tmp + sizeof(tmp))
07419 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
07420
07421 add_header_contentLength(&req, strlen(tmp));
07422 add_line(&req, tmp);
07423 p->pendinginvite = p->ocseq;
07424
07425 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07426 }
07427
07428
07429
07430
07431
07432
07433
07434 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
07435 {
07436 struct sip_request req;
07437 char tmp[500];
07438 char *t = tmp;
07439 size_t maxbytes = sizeof(tmp);
07440
07441 initreqprep(&req, p, SIP_NOTIFY);
07442 add_header(&req, "Event", "message-summary");
07443 add_header(&req, "Content-Type", default_notifymime);
07444
07445 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
07446 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
07447 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
07448
07449
07450
07451 ast_build_string(&t, &maxbytes, "Voice-Message: %d/%d%s\r\n", newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
07452
07453 if (p->subscribed) {
07454 if (p->expiry)
07455 add_header(&req, "Subscription-State", "active");
07456 else
07457 add_header(&req, "Subscription-State", "terminated;reason=timeout");
07458 }
07459
07460 if (t > tmp + sizeof(tmp))
07461 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
07462
07463 add_header_contentLength(&req, strlen(tmp));
07464 add_line(&req, tmp);
07465
07466 if (!p->initreq.headers)
07467 initialize_initreq(p, &req);
07468 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07469 }
07470
07471
07472 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
07473 {
07474 if (!p->initreq.headers)
07475 initialize_initreq(p, req);
07476 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
07477 }
07478
07479
07480 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
07481 {
07482 struct sip_request req;
07483 char tmp[SIPBUFSIZE/2];
07484
07485 reqprep(&req, p, SIP_NOTIFY, 0, 1);
07486 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
07487 add_header(&req, "Event", tmp);
07488 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
07489 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
07490 add_header(&req, "Allow", ALLOWED_METHODS);
07491 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
07492
07493 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
07494 add_header_contentLength(&req, strlen(tmp));
07495 add_line(&req, tmp);
07496
07497 if (!p->initreq.headers)
07498 initialize_initreq(p, &req);
07499
07500 p->lastnoninvite = p->ocseq;
07501
07502 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07503 }
07504
07505
07506 static char *regstate2str(enum sipregistrystate regstate)
07507 {
07508 switch(regstate) {
07509 case REG_STATE_FAILED:
07510 return "Failed";
07511 case REG_STATE_UNREGISTERED:
07512 return "Unregistered";
07513 case REG_STATE_REGSENT:
07514 return "Request Sent";
07515 case REG_STATE_AUTHSENT:
07516 return "Auth. Sent";
07517 case REG_STATE_REGISTERED:
07518 return "Registered";
07519 case REG_STATE_REJECTED:
07520 return "Rejected";
07521 case REG_STATE_TIMEOUT:
07522 return "Timeout";
07523 case REG_STATE_NOAUTH:
07524 return "No Authentication";
07525 default:
07526 return "Unknown";
07527 }
07528 }
07529
07530
07531 static int sip_reregister(const void *data)
07532 {
07533
07534 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
07535
07536
07537 if (!r)
07538 return 0;
07539
07540 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
07541 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
07542
07543
07544 if (sipdebug)
07545 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
07546
07547 r->expire = -1;
07548 __sip_do_register(r);
07549 ASTOBJ_UNREF(r, sip_registry_destroy);
07550 return 0;
07551 }
07552
07553
07554 static int __sip_do_register(struct sip_registry *r)
07555 {
07556 int res;
07557
07558 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
07559 return res;
07560 }
07561
07562
07563 static int sip_reg_timeout(const void *data)
07564 {
07565
07566
07567 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
07568 struct sip_pvt *p;
07569 int res;
07570
07571
07572 if (!r)
07573 return 0;
07574
07575 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
07576 if (r->call) {
07577
07578
07579 p = r->call;
07580 ast_mutex_lock(&p->lock);
07581 if (p->registry)
07582 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
07583 r->call = NULL;
07584 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
07585
07586 __sip_pretend_ack(p);
07587 ast_mutex_unlock(&p->lock);
07588 }
07589
07590 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
07591
07592
07593
07594 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
07595 r->regstate = REG_STATE_FAILED;
07596 } else {
07597 r->regstate = REG_STATE_UNREGISTERED;
07598 r->timeout = -1;
07599 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
07600 }
07601 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
07602 ASTOBJ_UNREF(r, sip_registry_destroy);
07603 return 0;
07604 }
07605
07606
07607 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
07608 {
07609 struct sip_request req;
07610 char from[256];
07611 char to[256];
07612 char tmp[80];
07613 char addr[80];
07614 struct sip_pvt *p;
07615
07616
07617 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
07618 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
07619 return 0;
07620 }
07621
07622 if (r->call) {
07623 if (!auth) {
07624 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
07625 return 0;
07626 } else {
07627 p = r->call;
07628 make_our_tag(p->tag, sizeof(p->tag));
07629 ast_string_field_free(p, theirtag);
07630 }
07631 } else {
07632
07633 if (!r->callid_valid) {
07634 build_callid_registry(r, __ourip, default_fromdomain);
07635 r->callid_valid = TRUE;
07636 }
07637
07638 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
07639 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
07640 return 0;
07641 }
07642 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
07643 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
07644
07645 if (create_addr(p, r->hostname)) {
07646
07647
07648 sip_destroy(p);
07649
07650 if (r->timeout > -1)
07651 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
07652 else
07653 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);
07654
07655 AST_SCHED_DEL(sched, r->timeout);
07656 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
07657 r->regattempts++;
07658 return 0;
07659 }
07660
07661 ast_string_field_set(r, callid, p->callid);
07662 if (r->portno) {
07663 p->sa.sin_port = htons(r->portno);
07664 p->recv.sin_port = htons(r->portno);
07665 } else
07666 r->portno = ntohs(p->sa.sin_port);
07667 ast_set_flag(&p->flags[0], SIP_OUTGOING);
07668 r->call=p;
07669 p->registry = ASTOBJ_REF(r);
07670 if (!ast_strlen_zero(r->secret))
07671 ast_string_field_set(p, peersecret, r->secret);
07672 if (!ast_strlen_zero(r->md5secret))
07673 ast_string_field_set(p, peermd5secret, r->md5secret);
07674
07675
07676 if (!ast_strlen_zero(r->authuser)) {
07677 ast_string_field_set(p, peername, r->authuser);
07678 ast_string_field_set(p, authname, r->authuser);
07679 } else if (!ast_strlen_zero(r->username)) {
07680 ast_string_field_set(p, peername, r->username);
07681 ast_string_field_set(p, authname, r->username);
07682 ast_string_field_set(p, fromuser, r->username);
07683 }
07684 if (!ast_strlen_zero(r->username))
07685 ast_string_field_set(p, username, r->username);
07686
07687 ast_string_field_set(p, exten, r->contact);
07688
07689
07690
07691
07692
07693
07694 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
07695 p->ourip = bindaddr.sin_addr;
07696 build_contact(p);
07697 }
07698
07699
07700 if (auth == NULL) {
07701 if (r->timeout > -1)
07702 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
07703 AST_SCHED_DEL(sched, r->timeout);
07704 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
07705 if (option_debug)
07706 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
07707 }
07708
07709 if (strchr(r->username, '@')) {
07710 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
07711 if (!ast_strlen_zero(p->theirtag))
07712 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
07713 else
07714 snprintf(to, sizeof(to), "<sip:%s>", r->username);
07715 } else {
07716 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
07717 if (!ast_strlen_zero(p->theirtag))
07718 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
07719 else
07720 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
07721 }
07722
07723
07724
07725 if (!ast_strlen_zero(p->fromdomain)) {
07726 if (r->portno && r->portno != STANDARD_SIP_PORT)
07727 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
07728 else
07729 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
07730 } else {
07731 if (r->portno && r->portno != STANDARD_SIP_PORT)
07732 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
07733 else
07734 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
07735 }
07736 ast_string_field_set(p, uri, addr);
07737
07738 p->branch ^= ast_random();
07739
07740 init_req(&req, sipmethod, addr);
07741
07742
07743 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
07744 p->ocseq = r->ocseq;
07745
07746 build_via(p);
07747 add_header(&req, "Via", p->via);
07748 add_header(&req, "From", from);
07749 add_header(&req, "To", to);
07750 add_header(&req, "Call-ID", p->callid);
07751 add_header(&req, "CSeq", tmp);
07752 if (!ast_strlen_zero(global_useragent))
07753 add_header(&req, "User-Agent", global_useragent);
07754 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
07755
07756
07757 if (auth)
07758 add_header(&req, authheader, auth);
07759 else if (!ast_strlen_zero(r->nonce)) {
07760 char digest[1024];
07761
07762
07763 if (sipdebug)
07764 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
07765 ast_string_field_set(p, realm, r->realm);
07766 ast_string_field_set(p, nonce, r->nonce);
07767 ast_string_field_set(p, domain, r->domain);
07768 ast_string_field_set(p, opaque, r->opaque);
07769 ast_string_field_set(p, qop, r->qop);
07770 r->noncecount++;
07771 p->noncecount = r->noncecount;
07772
07773 memset(digest,0,sizeof(digest));
07774 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
07775 add_header(&req, "Authorization", digest);
07776 else
07777 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
07778
07779 }
07780
07781 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
07782 add_header(&req, "Expires", tmp);
07783 add_header(&req, "Contact", p->our_contact);
07784 add_header(&req, "Event", "registration");
07785 add_header_contentLength(&req, 0);
07786
07787 initialize_initreq(p, &req);
07788 if (sip_debug_test_pvt(p))
07789 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
07790 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
07791 r->regattempts++;
07792 if (option_debug > 3)
07793 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
07794 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
07795 }
07796
07797
07798 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
07799 {
07800 struct sip_request req;
07801
07802 reqprep(&req, p, SIP_MESSAGE, 0, 1);
07803 add_text(&req, text);
07804 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07805 }
07806
07807
07808 static int sip_refer_allocate(struct sip_pvt *p)
07809 {
07810 p->refer = ast_calloc(1, sizeof(struct sip_refer));
07811 return p->refer ? 1 : 0;
07812 }
07813
07814
07815
07816
07817
07818
07819 static int transmit_refer(struct sip_pvt *p, const char *dest)
07820 {
07821 struct sip_request req = {
07822 .headers = 0,
07823 };
07824 char from[256];
07825 const char *of;
07826 char *c;
07827 char referto[256];
07828 char *ttag, *ftag;
07829 char *theirtag = ast_strdupa(p->theirtag);
07830
07831 if (option_debug || sipdebug)
07832 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
07833
07834
07835 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07836 of = get_header(&p->initreq, "To");
07837 ttag = theirtag;
07838 ftag = p->tag;
07839 } else {
07840 of = get_header(&p->initreq, "From");
07841 ftag = theirtag;
07842 ttag = p->tag;
07843 }
07844
07845 ast_copy_string(from, of, sizeof(from));
07846 of = get_in_brackets(from);
07847 ast_string_field_set(p, from, of);
07848 if (strncasecmp(of, "sip:", 4))
07849 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
07850 else
07851 of += 4;
07852
07853 if ((c = strchr(dest, '@')))
07854 c = NULL;
07855 else if ((c = strchr(of, '@')))
07856 *c++ = '\0';
07857 if (c)
07858 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
07859 else
07860 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
07861
07862
07863 sip_refer_allocate(p);
07864 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
07865 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
07866 p->refer->status = REFER_SENT;
07867
07868 reqprep(&req, p, SIP_REFER, 0, 1);
07869
07870 add_header(&req, "Refer-To", referto);
07871 add_header(&req, "Allow", ALLOWED_METHODS);
07872 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
07873 if (!ast_strlen_zero(p->our_contact))
07874 add_header(&req, "Referred-By", p->our_contact);
07875
07876 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07877
07878
07879
07880
07881
07882
07883
07884
07885 }
07886
07887
07888
07889 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
07890 {
07891 struct sip_request req;
07892
07893 reqprep(&req, p, SIP_INFO, 0, 1);
07894 add_digit(&req, digit, duration);
07895 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07896 }
07897
07898
07899 static int transmit_info_with_vidupdate(struct sip_pvt *p)
07900 {
07901 struct sip_request req;
07902
07903 reqprep(&req, p, SIP_INFO, 0, 1);
07904 add_vidupdate(&req);
07905 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07906 }
07907
07908
07909
07910
07911 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
07912 {
07913 struct sip_request resp;
07914
07915 if (sipmethod == SIP_ACK)
07916 p->invitestate = INV_CONFIRMED;
07917
07918 reqprep(&resp, p, sipmethod, seqno, newbranch);
07919 add_header_contentLength(&resp, 0);
07920 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
07921 }
07922
07923
07924 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
07925 {
07926 struct sip_request resp;
07927
07928 reqprep(&resp, p, sipmethod, seqno, newbranch);
07929 if (!ast_strlen_zero(p->realm)) {
07930 char digest[1024];
07931
07932 memset(digest, 0, sizeof(digest));
07933 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
07934 if (p->options && p->options->auth_type == PROXY_AUTH)
07935 add_header(&resp, "Proxy-Authorization", digest);
07936 else if (p->options && p->options->auth_type == WWW_AUTH)
07937 add_header(&resp, "Authorization", digest);
07938 else
07939 add_header(&resp, "Proxy-Authorization", digest);
07940 } else
07941 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
07942 }
07943
07944
07945 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
07946 char buf[10];
07947
07948 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
07949 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
07950 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
07951 }
07952
07953 add_header_contentLength(&resp, 0);
07954 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
07955 }
07956
07957
07958 static void destroy_association(struct sip_peer *peer)
07959 {
07960 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
07961 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
07962 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
07963 else
07964 ast_db_del("SIP/Registry", peer->name);
07965 }
07966 }
07967
07968
07969 static int expire_register(const void *data)
07970 {
07971 struct sip_peer *peer = (struct sip_peer *)data;
07972
07973 if (!peer)
07974 return 0;
07975
07976 memset(&peer->addr, 0, sizeof(peer->addr));
07977 if (peer->sockfd > 0) {
07978 close(peer->sockfd);
07979 ast_clear_flag(&peer->flags[1], SIP_PAGE2_TCP_CONNECTED);
07980 }
07981
07982 destroy_association(peer);
07983
07984 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
07985 register_peer_exten(peer, FALSE);
07986 peer->expire = -1;
07987 ast_device_state_changed("SIP/%s", peer->name);
07988
07989
07990
07991
07992 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
07993 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
07994 struct sip_peer *peer_ptr = peer_ptr;
07995 peer_ptr = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
07996 if (peer_ptr) {
07997 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
07998 }
07999 }
08000
08001 ASTOBJ_UNREF(peer, sip_destroy_peer);
08002
08003 return 0;
08004 }
08005
08006
08007 static int sip_poke_peer_s(const void *data)
08008 {
08009 struct sip_peer *peer = (struct sip_peer *) data;
08010
08011 peer->pokeexpire = -1;
08012
08013 sip_poke_peer(peer);
08014
08015 ASTOBJ_UNREF(peer, sip_destroy_peer);
08016
08017 return 0;
08018 }
08019
08020
08021 static void reg_source_db(struct sip_peer *peer)
08022 {
08023 char data[256];
08024 struct in_addr in;
08025 int expiry;
08026 int port;
08027 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
08028
08029 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
08030 return;
08031 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
08032 return;
08033
08034 scan = data;
08035 addr = strsep(&scan, ":");
08036 port_str = strsep(&scan, ":");
08037 expiry_str = strsep(&scan, ":");
08038 username = strsep(&scan, ":");
08039 contact = scan;
08040
08041 if (!inet_aton(addr, &in))
08042 return;
08043
08044 if (port_str)
08045 port = atoi(port_str);
08046 else
08047 return;
08048
08049 if (expiry_str)
08050 expiry = atoi(expiry_str);
08051 else
08052 return;
08053
08054 if (username)
08055 ast_copy_string(peer->username, username, sizeof(peer->username));
08056 if (contact)
08057 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
08058
08059 if (option_debug > 1)
08060 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
08061 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
08062
08063 memset(&peer->addr, 0, sizeof(peer->addr));
08064 peer->addr.sin_family = AF_INET;
08065 peer->addr.sin_addr = in;
08066 peer->addr.sin_port = htons(port);
08067 if ((sipsock < 0) || (siptcpsock < 0)){
08068
08069 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
08070 struct sip_peer *peer_ptr = peer;
08071 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
08072 }
08073 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, ASTOBJ_REF(peer));
08074 if (peer->pokeexpire == -1) {
08075 struct sip_peer *peer_ptr = peer;
08076 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
08077 }
08078 } else
08079 sip_poke_peer(peer);
08080 if (!AST_SCHED_DEL(sched, peer->expire)) {
08081 struct sip_peer *peer_ptr = peer;
08082 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
08083 }
08084 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
08085 if (peer->expire == -1) {
08086 struct sip_peer *peer_ptr = peer;
08087 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
08088 }
08089 register_peer_exten(peer, TRUE);
08090 }
08091
08092
08093 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
08094 {
08095 char contact[SIPBUFSIZE];
08096 char *c;
08097
08098
08099 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
08100 c = get_in_brackets(contact);
08101
08102
08103 ast_string_field_set(pvt, fullcontact, c);
08104
08105
08106 ast_string_field_set(pvt, okcontacturi, c);
08107
08108
08109
08110 return TRUE;
08111 }
08112
08113
08114 static int set_address_from_contact(struct sip_pvt *pvt)
08115 {
08116 struct hostent *hp;
08117 struct ast_hostent ahp;
08118 int port;
08119 char *c, *host, *pt;
08120 char contact_buf[256];
08121 char *contact;
08122
08123 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
08124
08125
08126 pvt->sa = pvt->recv;
08127 return 0;
08128 }
08129
08130
08131 ast_copy_string(contact_buf, pvt->fullcontact, sizeof(contact_buf));
08132 contact = contact_buf;
08133
08134
08135 if (strncasecmp(contact, "sip:", 4)) {
08136 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
08137 } else
08138 contact += 4;
08139
08140
08141
08142
08143
08144 host = strchr(contact, '@');
08145 if (!host) {
08146 host = contact;
08147 c = NULL;
08148 } else {
08149 *host++ = '\0';
08150 }
08151 pt = strchr(host, ':');
08152 if (pt) {
08153 *pt++ = '\0';
08154 port = atoi(pt);
08155 } else
08156 port = STANDARD_SIP_PORT;
08157
08158 contact = strsep(&contact, ";");
08159 host = strsep(&host, ";");
08160
08161
08162
08163 hp = ast_gethostbyname(host, &ahp);
08164 if (!hp) {
08165 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
08166 return -1;
08167 }
08168 pvt->sa.sin_family = AF_INET;
08169 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
08170 pvt->sa.sin_port = htons(port);
08171
08172 return 0;
08173 }
08174
08175
08176
08177 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
08178 {
08179 char contact[SIPBUFSIZE];
08180 char data[SIPBUFSIZE];
08181 const char *expires = get_header(req, "Expires");
08182 int expiry = atoi(expires);
08183 char *curi, *n, *pt;
08184 int port;
08185 const char *useragent;
08186 struct hostent *hp;
08187 struct ast_hostent ahp;
08188 struct sockaddr_in oldsin;
08189
08190 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
08191
08192 if (ast_strlen_zero(expires)) {
08193 expires = strcasestr(contact, ";expires=");
08194 if (expires) {
08195
08196 expires = strsep((char **) &expires, ";");
08197 if (sscanf(expires + 9, "%d", &expiry) != 1)
08198 expiry = default_expiry;
08199 } else {
08200
08201 expiry = default_expiry;
08202 }
08203 }
08204
08205
08206 curi = contact;
08207 if (strchr(contact, '<') == NULL)
08208 strsep(&curi, ";");
08209 curi = get_in_brackets(contact);
08210
08211
08212
08213
08214
08215 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
08216
08217 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
08218 pvt->expiry = ast_sched_when(sched, peer->expire);
08219 return PARSE_REGISTER_QUERY;
08220 } else if (!strcasecmp(curi, "*") || !expiry) {
08221
08222 memset(&peer->addr, 0, sizeof(peer->addr));
08223 if (!AST_SCHED_DEL(sched, peer->expire)) {
08224 struct sip_peer *peer_ptr = peer;
08225 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
08226 }
08227
08228 destroy_association(peer);
08229
08230 register_peer_exten(peer, 0);
08231 peer->fullcontact[0] = '\0';
08232 peer->useragent[0] = '\0';
08233 peer->sipoptions = 0;
08234 peer->lastms = 0;
08235
08236 if (option_verbose > 2)
08237 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
08238 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
08239 return PARSE_REGISTER_UPDATE;
08240 }
08241
08242
08243 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
08244
08245
08246 ast_string_field_build(pvt, our_contact, "<%s>", curi);
08247
08248
08249 if (strncasecmp(curi, "sip:", 4)) {
08250 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
08251 } else
08252 curi += 4;
08253
08254 curi = strsep(&curi, ";");
08255
08256 n = strchr(curi, '@');
08257 if (!n) {
08258 n = curi;
08259 curi = NULL;
08260 } else
08261 *n++ = '\0';
08262 pt = strchr(n, ':');
08263 if (pt) {
08264 *pt++ = '\0';
08265 port = atoi(pt);
08266 } else
08267 port = STANDARD_SIP_PORT;
08268 oldsin = peer->addr;
08269 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
08270
08271 hp = ast_gethostbyname(n, &ahp);
08272 if (!hp) {
08273 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
08274 return PARSE_REGISTER_FAILED;
08275 }
08276 peer->addr.sin_family = AF_INET;
08277 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
08278 peer->addr.sin_port = htons(port);
08279 } else {
08280
08281
08282 peer->addr = pvt->recv;
08283 }
08284
08285
08286 peer->sipoptions = pvt->sipoptions;
08287
08288 if (curi && ast_strlen_zero(peer->username))
08289 ast_copy_string(peer->username, curi, sizeof(peer->username));
08290
08291 if (!AST_SCHED_DEL(sched, peer->expire)) {
08292 struct sip_peer *peer_ptr = peer;
08293 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
08294 }
08295 if (expiry > max_expiry)
08296 expiry = max_expiry;
08297 if (expiry < min_expiry)
08298 expiry = min_expiry;
08299 if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) {
08300 peer->expire = -1;
08301 } else {
08302 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, ASTOBJ_REF(peer));
08303 if (peer->expire == -1) {
08304 struct sip_peer *peer_ptr = peer;
08305 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
08306 }
08307 }
08308 pvt->expiry = expiry;
08309 snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expiry, peer->username, peer->fullcontact);
08310 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
08311 ast_db_put("SIP/Registry", peer->name, data);
08312 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
08313
08314
08315 if (inaddrcmp(&peer->addr, &oldsin)) {
08316 sip_poke_peer(peer);
08317 if (option_verbose > 2)
08318 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expiry);
08319 register_peer_exten(peer, 1);
08320 }
08321
08322
08323 useragent = get_header(req, "User-Agent");
08324 if (strcasecmp(useragent, peer->useragent)) {
08325 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
08326 if (option_verbose > 3)
08327 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
08328 }
08329
08330
08331 if (((!ast_test_flag(&peer->flags[1], SIP_PAGE2_TCP)) || (peer->sockfd != pvt->sockfd)) && (ast_test_flag(&pvt->flags[1], SIP_PAGE2_TCP))) {
08332 ast_set_flag(&peer->flags[1], SIP_PAGE2_TCP);
08333 peer->sockfd=pvt->sockfd;
08334 ast_set_flag(&peer->flags[1], SIP_PAGE2_TCP_CONNECTED);
08335 }
08336 return PARSE_REGISTER_UPDATE;
08337 }
08338
08339
08340 static void free_old_route(struct sip_route *route)
08341 {
08342 struct sip_route *next;
08343
08344 while (route) {
08345 next = route->next;
08346 free(route);
08347 route = next;
08348 }
08349 }
08350
08351
08352 static void list_route(struct sip_route *route)
08353 {
08354 if (!route)
08355 ast_verbose("list_route: no route\n");
08356 else {
08357 for (;route; route = route->next)
08358 ast_verbose("list_route: hop: <%s>\n", route->hop);
08359 }
08360 }
08361
08362
08363 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
08364 {
08365 struct sip_route *thishop, *head, *tail;
08366 int start = 0;
08367 int len;
08368 const char *rr, *contact, *c;
08369
08370
08371 if (p->route && p->route_persistant) {
08372 if (option_debug)
08373 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
08374 return;
08375 }
08376
08377 if (p->route) {
08378 free_old_route(p->route);
08379 p->route = NULL;
08380 }
08381
08382
08383 p->route_persistant = 1;
08384
08385
08386
08387
08388
08389
08390 head = NULL;
08391 tail = head;
08392
08393 for (;;) {
08394
08395 rr = __get_header(req, "Record-Route", &start);
08396 if (*rr == '\0')
08397 break;
08398 for (; (rr = strchr(rr, '<')) ; rr += len) {
08399 ++rr;
08400 len = strcspn(rr, ">") + 1;
08401
08402 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
08403
08404 ast_copy_string(thishop->hop, rr, len);
08405 if (option_debug > 1)
08406 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
08407
08408 if (backwards) {
08409
08410 thishop->next = head;
08411 head = thishop;
08412
08413 if (!tail)
08414 tail = thishop;
08415 } else {
08416 thishop->next = NULL;
08417
08418 if (tail)
08419 tail->next = thishop;
08420 else
08421 head = thishop;
08422 tail = thishop;
08423 }
08424 }
08425 }
08426 }
08427
08428
08429 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
08430
08431
08432 contact = get_header(req, "Contact");
08433 if (!ast_strlen_zero(contact)) {
08434 if (option_debug > 1)
08435 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
08436
08437 c = strchr(contact, '<');
08438 if (c) {
08439
08440 ++c;
08441 len = strcspn(c, ">") + 1;
08442 } else {
08443
08444 c = contact;
08445 len = strlen(contact) + 1;
08446 }
08447 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
08448
08449 ast_copy_string(thishop->hop, c, len);
08450 thishop->next = NULL;
08451
08452 if (tail)
08453 tail->next = thishop;
08454 else
08455 head = thishop;
08456 }
08457 }
08458 }
08459
08460
08461 p->route = head;
08462
08463
08464 if (sip_debug_test_pvt(p))
08465 list_route(p->route);
08466 }
08467
08468 AST_THREADSTORAGE(check_auth_buf, check_auth_buf_init);
08469 #define CHECK_AUTH_BUF_INITLEN 256
08470
08471
08472
08473
08474
08475
08476 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
08477 const char *secret, const char *md5secret, int sipmethod,
08478 char *uri, enum xmittype reliable, int ignore)
08479 {
08480 const char *response = "407 Proxy Authentication Required";
08481 const char *reqheader = "Proxy-Authorization";
08482 const char *respheader = "Proxy-Authenticate";
08483 const char *authtoken;
08484 char a1_hash[256];
08485 char resp_hash[256]="";
08486 char *c;
08487 int wrongnonce = FALSE;
08488 int good_response;
08489 const char *usednonce = p->randdata;
08490 struct ast_dynamic_str *buf;
08491 int res;
08492
08493
08494 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
08495 struct x {
08496 const char *key;
08497 const char *s;
08498 } *i, keys[] = {
08499 [K_RESP] = { "response=", "" },
08500 [K_URI] = { "uri=", "" },
08501 [K_USER] = { "username=", "" },
08502 [K_NONCE] = { "nonce=", "" },
08503 [K_LAST] = { NULL, NULL}
08504 };
08505
08506
08507 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
08508 return AUTH_SUCCESSFUL;
08509 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
08510
08511
08512
08513 response = "401 Unauthorized";
08514 reqheader = "Authorization";
08515 respheader = "WWW-Authenticate";
08516 }
08517 authtoken = get_header(req, reqheader);
08518 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
08519
08520
08521 if (!reliable) {
08522
08523
08524 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
08525
08526 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08527 }
08528 return AUTH_CHALLENGE_SENT;
08529 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
08530
08531 ast_string_field_build(p, randdata, "%08lx", ast_random());
08532 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
08533
08534 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08535 return AUTH_CHALLENGE_SENT;
08536 }
08537
08538
08539
08540
08541
08542
08543 if (!(buf = ast_dynamic_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
08544 return AUTH_SECRET_FAILED;
08545
08546
08547 res = ast_dynamic_str_thread_set(&buf, 0, &check_auth_buf, "%s", authtoken);
08548
08549 if (res == AST_DYNSTR_BUILD_FAILED)
08550 return AUTH_SECRET_FAILED;
08551
08552 c = buf->str;
08553
08554 while(c && *(c = ast_skip_blanks(c)) ) {
08555 for (i = keys; i->key != NULL; i++) {
08556 const char *separator = ",";
08557
08558 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
08559 continue;
08560
08561 c += strlen(i->key);
08562 if (*c == '"') {
08563 c++;
08564 separator = "\"";
08565 }
08566 i->s = c;
08567 strsep(&c, separator);
08568 break;
08569 }
08570 if (i->key == NULL)
08571 strsep(&c, " ,");
08572 }
08573
08574
08575 if (strcmp(username, keys[K_USER].s)) {
08576 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
08577 username, keys[K_USER].s);
08578
08579 return AUTH_USERNAME_MISMATCH;
08580 }
08581
08582
08583 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
08584 wrongnonce = TRUE;
08585 usednonce = keys[K_NONCE].s;
08586 }
08587
08588 if (!ast_strlen_zero(md5secret))
08589 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
08590 else {
08591 char a1[256];
08592 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
08593 ast_md5_hash(a1_hash, a1);
08594 }
08595
08596
08597 {
08598 char a2[256];
08599 char a2_hash[256];
08600 char resp[256];
08601
08602 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
08603 S_OR(keys[K_URI].s, uri));
08604 ast_md5_hash(a2_hash, a2);
08605 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
08606 ast_md5_hash(resp_hash, resp);
08607 }
08608
08609 good_response = keys[K_RESP].s &&
08610 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
08611 if (wrongnonce) {
08612 if (good_response) {
08613 if (sipdebug)
08614 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
08615
08616 ast_string_field_build(p, randdata, "%08lx", ast_random());
08617 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
08618 } else {
08619
08620 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
08621 if (sipdebug)
08622 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
08623 ast_string_field_build(p, randdata, "%08lx", ast_random());
08624 } else {
08625 if (sipdebug)
08626 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
08627 }
08628 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
08629 }
08630
08631
08632 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08633 return AUTH_CHALLENGE_SENT;
08634 }
08635 if (good_response) {
08636 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
08637 return AUTH_SUCCESSFUL;
08638 }
08639
08640
08641
08642
08643
08644
08645 return AUTH_SECRET_FAILED;
08646 }
08647
08648
08649 static void sip_peer_hold(struct sip_pvt *p, int hold)
08650 {
08651 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
08652
08653 if (!peer)
08654 return;
08655
08656
08657 if (hold)
08658 peer->onHold++;
08659 else
08660 peer->onHold--;
08661
08662
08663 ast_device_state_changed("SIP/%s", peer->name);
08664
08665 return;
08666 }
08667
08668
08669
08670
08671 static int cb_extensionstate(char *context, char* exten, int state, void *data)
08672 {
08673 struct sip_pvt *p = data;
08674
08675 ast_mutex_lock(&p->lock);
08676
08677 switch(state) {
08678 case AST_EXTENSION_DEACTIVATED:
08679 case AST_EXTENSION_REMOVED:
08680 if (p->autokillid > -1 && sip_cancel_destroy(p))
08681 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
08682 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08683 ast_verbose(VERBOSE_PREFIX_2 "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
08684 p->stateid = -1;
08685 p->subscribed = NONE;
08686 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
08687 break;
08688 default:
08689 p->laststate = state;
08690 break;
08691 }
08692 if (p->subscribed != NONE) {
08693 if (!p->pendinginvite) {
08694 transmit_state_notify(p, state, 1, FALSE);
08695 } else {
08696
08697
08698 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
08699 }
08700 }
08701 if (option_verbose > 1)
08702 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
08703 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
08704
08705
08706 ast_mutex_unlock(&p->lock);
08707
08708 return 0;
08709 }
08710
08711
08712
08713
08714 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
08715 {
08716 ast_string_field_build(p, randdata, "%08lx", ast_random());
08717 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
08718 }
08719
08720
08721
08722
08723
08724
08725 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
08726 struct sip_request *req, char *uri)
08727 {
08728 enum check_auth_result res = AUTH_NOT_FOUND;
08729 struct sip_peer *peer;
08730 char tmp[256];
08731 char *name, *c;
08732 char *t;
08733 char *domain;
08734
08735
08736 t = uri;
08737 while(*t && (*t > 32) && (*t != ';'))
08738 t++;
08739 *t = '\0';
08740
08741 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
08742 if (pedanticsipchecking)
08743 ast_uri_decode(tmp);
08744
08745 c = get_in_brackets(tmp);
08746 c = strsep(&c, ";");
08747
08748 if (!strncasecmp(c, "sip:", 4)) {
08749 name = c + 4;
08750 } else {
08751 name = c;
08752 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
08753 }
08754
08755
08756 if ((c = strchr(name, '@'))) {
08757 *c++ = '\0';
08758 domain = c;
08759 if ((c = strchr(domain, ':')))
08760 *c = '\0';
08761 if (!AST_LIST_EMPTY(&domain_list)) {
08762 if (!check_sip_domain(domain, NULL, 0)) {
08763 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
08764 return AUTH_UNKNOWN_DOMAIN;
08765 }
08766 }
08767 }
08768
08769 ast_string_field_set(p, exten, name);
08770 build_contact(p);
08771 peer = find_peer(name, NULL, 1);
08772 if (!(peer && ast_apply_ha(peer->ha, sin))) {
08773
08774 if (peer) {
08775 ASTOBJ_UNREF(peer, sip_destroy_peer);
08776 res = AUTH_ACL_FAILED;
08777 } else
08778 res = AUTH_NOT_FOUND;
08779 }
08780 if (peer) {
08781
08782 if (p->rtp) {
08783 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
08784 p->autoframing = peer->autoframing;
08785 }
08786 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
08787 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
08788 res = AUTH_PEER_NOT_DYNAMIC;
08789 } else {
08790 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
08791 transmit_response(p, "100 Trying", req);
08792 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
08793 if (sip_cancel_destroy(p))
08794 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
08795
08796
08797
08798 switch (parse_register_contact(p, peer, req)) {
08799 case PARSE_REGISTER_FAILED:
08800 ast_log(LOG_WARNING, "Failed to parse contact info\n");
08801 transmit_response_with_date(p, "400 Bad Request", req);
08802 peer->lastmsgssent = -1;
08803 res = 0;
08804 break;
08805 case PARSE_REGISTER_QUERY:
08806 transmit_response_with_date(p, "200 OK", req);
08807 peer->lastmsgssent = -1;
08808 res = 0;
08809 break;
08810 case PARSE_REGISTER_UPDATE:
08811 update_peer(peer, p->expiry);
08812
08813 transmit_response_with_date(p, "200 OK", req);
08814 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
08815 peer->lastmsgssent = -1;
08816 res = 0;
08817 break;
08818 }
08819 }
08820 }
08821 }
08822 if (!peer && autocreatepeer) {
08823
08824 peer = temp_peer(name);
08825 if (peer) {
08826 ASTOBJ_CONTAINER_LINK(&peerl, peer);
08827 if (sip_cancel_destroy(p))
08828 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
08829 switch (parse_register_contact(p, peer, req)) {
08830 case PARSE_REGISTER_FAILED:
08831 ast_log(LOG_WARNING, "Failed to parse contact info\n");
08832 transmit_response_with_date(p, "400 Bad Request", req);
08833 peer->lastmsgssent = -1;
08834 res = 0;
08835 break;
08836 case PARSE_REGISTER_QUERY:
08837 transmit_response_with_date(p, "200 OK", req);
08838 peer->lastmsgssent = -1;
08839 res = 0;
08840 break;
08841 case PARSE_REGISTER_UPDATE:
08842
08843 transmit_response_with_date(p, "200 OK", req);
08844 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
08845 peer->lastmsgssent = -1;
08846 res = 0;
08847 break;
08848 }
08849 }
08850 }
08851 if (!res) {
08852 ast_device_state_changed("SIP/%s", peer->name);
08853 }
08854 if (res < 0) {
08855 switch (res) {
08856 case AUTH_SECRET_FAILED:
08857
08858 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
08859 break;
08860 case AUTH_USERNAME_MISMATCH:
08861
08862
08863
08864
08865 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
08866 break;
08867 case AUTH_NOT_FOUND:
08868 case AUTH_PEER_NOT_DYNAMIC:
08869 case AUTH_ACL_FAILED:
08870 if (global_alwaysauthreject) {
08871 transmit_fake_auth_response(p, &p->initreq, 1);
08872 } else {
08873
08874 if (res == AUTH_PEER_NOT_DYNAMIC)
08875 transmit_response(p, "403 Forbidden", &p->initreq);
08876 else
08877 transmit_response(p, "404 Not found", &p->initreq);
08878 }
08879 break;
08880 default:
08881 break;
08882 }
08883 }
08884 if (peer)
08885 ASTOBJ_UNREF(peer, sip_destroy_peer);
08886
08887 return res;
08888 }
08889
08890
08891 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
08892 {
08893 char tmp[256], *c, *a;
08894 struct sip_request *req;
08895
08896 req = oreq;
08897 if (!req)
08898 req = &p->initreq;
08899 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
08900 if (ast_strlen_zero(tmp))
08901 return 0;
08902 c = get_in_brackets(tmp);
08903 if (strncasecmp(c, "sip:", 4)) {
08904 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
08905 return -1;
08906 }
08907 c += 4;
08908 a = c;
08909 strsep(&a, "@;");
08910 if (sip_debug_test_pvt(p))
08911 ast_verbose("RDNIS is %s\n", c);
08912 ast_string_field_set(p, rdnis, c);
08913
08914 return 0;
08915 }
08916
08917
08918
08919
08920 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
08921 {
08922 char tmp[256] = "", *uri, *a;
08923 char tmpf[256] = "", *from;
08924 struct sip_request *req;
08925 char *colon;
08926
08927 req = oreq;
08928 if (!req)
08929 req = &p->initreq;
08930
08931
08932 if (req->rlPart2)
08933 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
08934
08935 if (pedanticsipchecking)
08936 ast_uri_decode(tmp);
08937
08938 uri = get_in_brackets(tmp);
08939
08940 if (strncasecmp(uri, "sip:", 4)) {
08941 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
08942 return -1;
08943 }
08944 uri += 4;
08945
08946
08947 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
08948 if (!ast_strlen_zero(tmpf)) {
08949 if (pedanticsipchecking)
08950 ast_uri_decode(tmpf);
08951 from = get_in_brackets(tmpf);
08952 } else {
08953 from = NULL;
08954 }
08955
08956 if (!ast_strlen_zero(from)) {
08957 if (strncasecmp(from, "sip:", 4)) {
08958 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
08959 return -1;
08960 }
08961 from += 4;
08962 if ((a = strchr(from, '@')))
08963 *a++ = '\0';
08964 else
08965 a = from;
08966 from = strsep(&from, ";");
08967 a = strsep(&a, ";");
08968 ast_string_field_set(p, fromdomain, a);
08969 }
08970
08971
08972
08973
08974 if ((a = strchr(uri, '@'))) {
08975 *a++ = '\0';
08976 } else {
08977 a = uri;
08978 uri = "s";
08979 }
08980 colon = strchr(a, ':');
08981 if (colon)
08982 *colon = '\0';
08983
08984 uri = strsep(&uri, ";");
08985 a = strsep(&a, ";");
08986
08987 ast_string_field_set(p, domain, a);
08988
08989 if (!AST_LIST_EMPTY(&domain_list)) {
08990 char domain_context[AST_MAX_EXTENSION];
08991
08992 domain_context[0] = '\0';
08993 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
08994 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
08995 if (option_debug)
08996 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
08997 return -2;
08998 }
08999 }
09000
09001 if (!ast_strlen_zero(domain_context))
09002 ast_string_field_set(p, context, domain_context);
09003 }
09004
09005
09006 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
09007 ast_string_field_set(p, context, p->subscribecontext);
09008
09009 if (sip_debug_test_pvt(p))
09010 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
09011
09012
09013 if (req->method == SIP_SUBSCRIBE) {
09014 char hint[AST_MAX_EXTENSION];
09015 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
09016 } else {
09017
09018
09019
09020
09021
09022 char *decoded_uri = ast_strdupa(uri);
09023 ast_uri_decode(decoded_uri);
09024 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
09025 !strcmp(uri, ast_pickup_ext())) {
09026 if (!oreq)
09027 ast_string_field_set(p, exten, uri);
09028 return 0;
09029 }
09030 }
09031
09032
09033 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
09034 ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) ||
09035 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
09036 return 1;
09037 }
09038
09039 return -1;
09040 }
09041
09042
09043
09044
09045
09046
09047 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
09048 {
09049 struct sip_pvt *sip_pvt_ptr;
09050
09051 ast_mutex_lock(&iflock);
09052
09053 if (option_debug > 3 && totag)
09054 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
09055
09056
09057 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
09058 if (!strcmp(sip_pvt_ptr->callid, callid)) {
09059 int match = 1;
09060 char *ourtag = sip_pvt_ptr->tag;
09061
09062
09063 ast_mutex_lock(&sip_pvt_ptr->lock);
09064
09065
09066
09067
09068
09069 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || (!ast_strlen_zero(totag) && strcmp(totag, ourtag))))
09070 match = 0;
09071
09072 if (!match) {
09073 ast_mutex_unlock(&sip_pvt_ptr->lock);
09074 continue;
09075 }
09076
09077 if (option_debug > 3 && totag)
09078 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
09079 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
09080 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
09081
09082
09083 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
09084 DEADLOCK_AVOIDANCE(&sip_pvt_ptr->lock);
09085 }
09086 break;
09087 }
09088 }
09089 ast_mutex_unlock(&iflock);
09090 if (option_debug > 3 && !sip_pvt_ptr)
09091 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
09092 return sip_pvt_ptr;
09093 }
09094
09095
09096
09097 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
09098 {
09099
09100 const char *p_referred_by = NULL;
09101 char *h_refer_to = NULL;
09102 char *h_referred_by = NULL;
09103 char *refer_to;
09104 const char *p_refer_to;
09105 char *referred_by_uri = NULL;
09106 char *ptr;
09107 struct sip_request *req = NULL;
09108 const char *transfer_context = NULL;
09109 struct sip_refer *referdata;
09110
09111
09112 req = outgoing_req;
09113 referdata = transferer->refer;
09114
09115 if (!req)
09116 req = &transferer->initreq;
09117
09118 p_refer_to = get_header(req, "Refer-To");
09119 if (ast_strlen_zero(p_refer_to)) {
09120 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
09121 return -2;
09122 }
09123 h_refer_to = ast_strdupa(p_refer_to);
09124 refer_to = get_in_brackets(h_refer_to);
09125 if (pedanticsipchecking)
09126 ast_uri_decode(refer_to);
09127
09128 if (strncasecmp(refer_to, "sip:", 4)) {
09129 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
09130 return -3;
09131 }
09132 refer_to += 4;
09133
09134
09135 p_referred_by = get_header(req, "Referred-By");
09136 if (!ast_strlen_zero(p_referred_by)) {
09137 char *lessthan;
09138 h_referred_by = ast_strdupa(p_referred_by);
09139 if (pedanticsipchecking)
09140 ast_uri_decode(h_referred_by);
09141
09142
09143 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
09144 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
09145 *(lessthan - 1) = '\0';
09146 }
09147
09148 referred_by_uri = get_in_brackets(h_referred_by);
09149 if(strncasecmp(referred_by_uri, "sip:", 4)) {
09150 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
09151 referred_by_uri = (char *) NULL;
09152 } else {
09153 referred_by_uri += 4;
09154 }
09155 }
09156
09157
09158 if ((ptr = strchr(refer_to, '?'))) {
09159 *ptr++ = '\0';
09160 if (!strncasecmp(ptr, "REPLACES=", 9)) {
09161 char *to = NULL, *from = NULL;
09162
09163
09164 referdata->attendedtransfer = 1;
09165 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
09166 ast_uri_decode(referdata->replaces_callid);
09167 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
09168 *ptr++ = '\0';
09169 }
09170
09171 if (ptr) {
09172
09173 to = strcasestr(ptr, "to-tag=");
09174 from = strcasestr(ptr, "from-tag=");
09175 }
09176
09177
09178 if (to) {
09179 ptr = to + 7;
09180 if ((to = strchr(ptr, '&')))
09181 *to = '\0';
09182 if ((to = strchr(ptr, ';')))
09183 *to = '\0';
09184 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
09185 }
09186
09187 if (from) {
09188 ptr = from + 9;
09189 if ((to = strchr(ptr, '&')))
09190 *to = '\0';
09191 if ((to = strchr(ptr, ';')))
09192 *to = '\0';
09193 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
09194 }
09195
09196 if (option_debug > 1) {
09197 if (!pedanticsipchecking)
09198 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
09199 else
09200 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
09201 }
09202 }
09203 }
09204
09205 if ((ptr = strchr(refer_to, '@'))) {
09206 char *urioption = NULL, *domain;
09207 *ptr++ = '\0';
09208
09209 if ((urioption = strchr(ptr, ';')))
09210 *urioption++ = '\0';
09211
09212 domain = ptr;
09213 if ((ptr = strchr(domain, ':')))
09214 *ptr = '\0';
09215
09216
09217 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
09218 if (urioption)
09219 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
09220 }
09221
09222 if ((ptr = strchr(refer_to, ';')))
09223 *ptr = '\0';
09224 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
09225
09226 if (referred_by_uri) {
09227 if ((ptr = strchr(referred_by_uri, ';')))
09228 *ptr = '\0';
09229 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
09230 } else {
09231 referdata->referred_by[0] = '\0';
09232 }
09233
09234
09235 if (transferer->owner)
09236 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
09237
09238
09239 if (ast_strlen_zero(transfer_context)) {
09240 transfer_context = S_OR(transferer->owner->macrocontext,
09241 S_OR(transferer->context, default_context));
09242 }
09243
09244 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
09245
09246
09247 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
09248 if (sip_debug_test_pvt(transferer)) {
09249 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
09250 }
09251
09252 return 0;
09253 }
09254 if (sip_debug_test_pvt(transferer))
09255 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
09256
09257
09258 return -1;
09259 }
09260
09261
09262
09263 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
09264 {
09265 char tmp[256] = "", *c, *a;
09266 struct sip_request *req = oreq ? oreq : &p->initreq;
09267 struct sip_refer *referdata = NULL;
09268 const char *transfer_context = NULL;
09269
09270 if (!p->refer && !sip_refer_allocate(p))
09271 return -1;
09272
09273 referdata = p->refer;
09274
09275 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
09276 c = get_in_brackets(tmp);
09277
09278 if (pedanticsipchecking)
09279 ast_uri_decode(c);
09280
09281 if (strncasecmp(c, "sip:", 4)) {
09282 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
09283 return -1;
09284 }
09285 c += 4;
09286 if ((a = strchr(c, ';')))
09287 *a = '\0';
09288
09289 if ((a = strchr(c, '@'))) {
09290 *a++ = '\0';
09291 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
09292 }
09293
09294 if (sip_debug_test_pvt(p))
09295 ast_verbose("Looking for %s in %s\n", c, p->context);
09296
09297 if (p->owner)
09298 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
09299
09300
09301 if (ast_strlen_zero(transfer_context)) {
09302 transfer_context = S_OR(p->owner->macrocontext,
09303 S_OR(p->context, default_context));
09304 }
09305 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
09306
09307 if (option_debug)
09308 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
09309 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
09310 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
09311 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
09312 referdata->refer_call = NULL;
09313
09314 ast_string_field_set(p, context, transfer_context);
09315 return 0;
09316 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
09317 return 1;
09318 }
09319
09320 return -1;
09321 }
09322
09323 static void check_via(struct sip_pvt *p, const struct sip_request *req)
09324 {
09325 char via[512];
09326 char *c, *pt;
09327 struct hostent *hp;
09328 struct ast_hostent ahp;
09329
09330 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
09331
09332
09333 c = strchr(via, ',');
09334 if (c)
09335 *c = '\0';
09336
09337
09338 c = strstr(via, ";rport");
09339 if (c && (c[6] != '='))
09340 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
09341
09342 c = strchr(via, ';');
09343 if (c)
09344 *c = '\0';
09345
09346 c = strchr(via, ' ');
09347 if (c) {
09348 *c = '\0';
09349 c = ast_skip_blanks(c+1);
09350 if ((strcasecmp(via, "SIP/2.0/UDP")) && (strcasecmp(via, "SIP/2.0/TCP"))) {
09351 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
09352 return;
09353 }
09354 pt = strchr(c, ':');
09355 if (pt)
09356 *pt++ = '\0';
09357 hp = ast_gethostbyname(c, &ahp);
09358 if (!hp) {
09359 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
09360 return;
09361 }
09362 memset(&p->sa, 0, sizeof(p->sa));
09363 p->sa.sin_family = AF_INET;
09364 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09365 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
09366
09367 if (sip_debug_test_pvt(p)) {
09368 const struct sockaddr_in *dst = sip_real_dst(p);
09369 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
09370 }
09371 }
09372 }
09373
09374
09375 static char *get_calleridname(const char *input, char *output, size_t outputsize)
09376 {
09377 const char *end = strchr(input,'<');
09378 const char *tmp = strchr(input,'"');
09379 int bytes = 0;
09380 int maxbytes = outputsize - 1;
09381
09382 if (!end || end == input)
09383 return NULL;
09384
09385 end--;
09386
09387 if (tmp && tmp <= end) {
09388
09389
09390
09391 end = strchr(tmp+1, '"');
09392 if (!end)
09393 return NULL;
09394 bytes = (int) (end - tmp);
09395
09396 if (bytes > maxbytes)
09397 bytes = maxbytes;
09398 ast_copy_string(output, tmp + 1, bytes);
09399 } else {
09400
09401
09402 input = ast_skip_blanks(input);
09403
09404 while(*end && *end < 33 && end > input)
09405 end--;
09406 if (end >= input) {
09407 bytes = (int) (end - input) + 2;
09408
09409 if (bytes > maxbytes)
09410 bytes = maxbytes;
09411 ast_copy_string(output, input, bytes);
09412 } else
09413 return NULL;
09414 }
09415 return output;
09416 }
09417
09418
09419
09420
09421
09422 static int get_rpid_num(const char *input, char *output, int maxlen)
09423 {
09424 char *start;
09425 char *end;
09426
09427 start = strchr(input,':');
09428 if (!start) {
09429 output[0] = '\0';
09430 return 0;
09431 }
09432 start++;
09433
09434
09435 ast_copy_string(output,start,maxlen);
09436 output[maxlen-1] = '\0';
09437
09438 end = strchr(output,'@');
09439 if (end)
09440 *end = '\0';
09441 else
09442 output[0] = '\0';
09443 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
09444 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
09445
09446 return 0;
09447 }
09448
09449
09450
09451
09452
09453
09454
09455 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
09456 int sipmethod, char *uri, enum xmittype reliable,
09457 struct sockaddr_in *sin, struct sip_peer **authpeer)
09458 {
09459 struct sip_user *user = NULL;
09460 struct sip_peer *peer;
09461 char from[256], *c;
09462 char *of;
09463 char rpid_num[50];
09464 const char *rpid;
09465 enum check_auth_result res = AUTH_SUCCESSFUL;
09466 char *t;
09467 char calleridname[50];
09468 int debug=sip_debug_test_addr(sin);
09469 struct ast_variable *tmpvar = NULL, *v = NULL;
09470 char *uri2 = ast_strdupa(uri);
09471
09472
09473 t = uri2;
09474 while (*t && *t > 32 && *t != ';')
09475 t++;
09476 *t = '\0';
09477 ast_copy_string(from, get_header(req, "From"), sizeof(from));
09478 if (pedanticsipchecking)
09479 ast_uri_decode(from);
09480
09481 memset(calleridname, 0, sizeof(calleridname));
09482 get_calleridname(from, calleridname, sizeof(calleridname));
09483 if (calleridname[0])
09484 ast_string_field_set(p, cid_name, calleridname);
09485
09486 rpid = get_header(req, "Remote-Party-ID");
09487 memset(rpid_num, 0, sizeof(rpid_num));
09488 if (!ast_strlen_zero(rpid))
09489 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
09490
09491 of = get_in_brackets(from);
09492 if (ast_strlen_zero(p->exten)) {
09493 t = uri2;
09494 if (!strncasecmp(t, "sip:", 4))
09495 t+= 4;
09496 ast_string_field_set(p, exten, t);
09497 t = strchr(p->exten, '@');
09498 if (t)
09499 *t = '\0';
09500 if (ast_strlen_zero(p->our_contact))
09501 build_contact(p);
09502 }
09503
09504 ast_string_field_set(p, from, of);
09505 if (strncasecmp(of, "sip:", 4)) {
09506 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
09507 } else
09508 of += 4;
09509
09510 if ((c = strchr(of, '@'))) {
09511 char *tmp;
09512 *c = '\0';
09513 if ((c = strchr(of, ':')))
09514 *c = '\0';
09515 tmp = ast_strdupa(of);
09516
09517
09518
09519 tmp = strsep(&tmp, ";");
09520 if (ast_is_shrinkable_phonenumber(tmp))
09521 ast_shrink_phone_number(tmp);
09522 ast_string_field_set(p, cid_num, tmp);
09523 }
09524
09525 if (!authpeer)
09526 user = find_user(of, 1);
09527
09528
09529 if (user && ast_apply_ha(user->ha, sin)) {
09530 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
09531 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09532
09533 for (v = user->chanvars ; v ; v = v->next) {
09534 if ((tmpvar = ast_variable_new(v->name, v->value))) {
09535 tmpvar->next = p->chanvars;
09536 p->chanvars = tmpvar;
09537 }
09538 }
09539 p->prefs = user->prefs;
09540
09541 if (p->rtp) {
09542 ast_rtp_codec_setpref(p->rtp, &p->prefs);
09543 p->autoframing = user->autoframing;
09544 }
09545
09546 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
09547 char *tmp;
09548 if (*calleridname)
09549 ast_string_field_set(p, cid_name, calleridname);
09550 tmp = ast_strdupa(rpid_num);
09551 if (ast_is_shrinkable_phonenumber(tmp))
09552 ast_shrink_phone_number(tmp);
09553 ast_string_field_set(p, cid_num, tmp);
09554 }
09555
09556 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
09557
09558 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
09559 if (sip_cancel_destroy(p))
09560 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
09561 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
09562 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09563
09564 if (p->sipoptions)
09565 user->sipoptions = p->sipoptions;
09566
09567
09568 if (user->call_limit)
09569 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
09570 if (!ast_strlen_zero(user->context))
09571 ast_string_field_set(p, context, user->context);
09572 if (!ast_strlen_zero(user->cid_num)) {
09573 char *tmp = ast_strdupa(user->cid_num);
09574 if (ast_is_shrinkable_phonenumber(tmp))
09575 ast_shrink_phone_number(tmp);
09576 ast_string_field_set(p, cid_num, tmp);
09577 }
09578 if (!ast_strlen_zero(user->cid_name))
09579 ast_string_field_set(p, cid_name, user->cid_name);
09580 ast_string_field_set(p, username, user->name);
09581 ast_string_field_set(p, peername, user->name);
09582 ast_string_field_set(p, peersecret, user->secret);
09583 ast_string_field_set(p, peermd5secret, user->md5secret);
09584 ast_string_field_set(p, subscribecontext, user->subscribecontext);
09585 ast_string_field_set(p, accountcode, user->accountcode);
09586 ast_string_field_set(p, language, user->language);
09587 ast_string_field_set(p, mohsuggest, user->mohsuggest);
09588 ast_string_field_set(p, mohinterpret, user->mohinterpret);
09589 p->allowtransfer = user->allowtransfer;
09590 p->amaflags = user->amaflags;
09591 p->callgroup = user->callgroup;
09592 p->pickupgroup = user->pickupgroup;
09593 if (user->callingpres)
09594 p->callingpres = user->callingpres;
09595
09596
09597 p->capability = user->capability;
09598 p->jointcapability = user->capability;
09599 if (p->peercapability)
09600 p->jointcapability &= p->peercapability;
09601 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
09602 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
09603 p->noncodeccapability |= AST_RTP_DTMF;
09604 else
09605 p->noncodeccapability &= ~AST_RTP_DTMF;
09606 p->jointnoncodeccapability = p->noncodeccapability;
09607 if (p->t38.peercapability)
09608 p->t38.jointcapability &= p->t38.peercapability;
09609 p->maxcallbitrate = user->maxcallbitrate;
09610
09611 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
09612 ast_rtp_destroy(p->vrtp);
09613 p->vrtp = NULL;
09614 }
09615 }
09616 if (user && debug)
09617 ast_verbose("Found user '%s'\n", user->name);
09618 } else {
09619 if (user) {
09620 if (!authpeer && debug)
09621 ast_verbose("Found user '%s', but fails host access\n", user->name);
09622 ASTOBJ_UNREF(user,sip_destroy_user);
09623 }
09624 user = NULL;
09625 }
09626
09627 if (!user) {
09628
09629 if (sipmethod == SIP_SUBSCRIBE)
09630
09631 peer = find_peer(of, NULL, 1);
09632 else
09633
09634
09635
09636
09637 peer = find_peer(NULL, &p->recv, 1);
09638
09639 if (peer) {
09640
09641 if (p->rtp) {
09642 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
09643 p->autoframing = peer->autoframing;
09644 }
09645 if (debug)
09646 ast_verbose("Found peer '%s'\n", peer->name);
09647
09648
09649 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
09650 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09651
09652
09653 if (p->sipoptions)
09654 peer->sipoptions = p->sipoptions;
09655
09656
09657 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
09658 char *tmp = ast_strdupa(rpid_num);
09659 if (*calleridname)
09660 ast_string_field_set(p, cid_name, calleridname);
09661 if (ast_is_shrinkable_phonenumber(tmp))
09662 ast_shrink_phone_number(tmp);
09663 ast_string_field_set(p, cid_num, tmp);
09664 }
09665 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
09666
09667 ast_string_field_set(p, peersecret, peer->secret);
09668 ast_string_field_set(p, peermd5secret, peer->md5secret);
09669 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
09670 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
09671 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
09672 if (peer->callingpres)
09673 p->callingpres = peer->callingpres;
09674 if (peer->maxms && peer->lastms)
09675 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
09676 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
09677
09678 ast_string_field_free(p, peersecret);
09679 ast_string_field_free(p, peermd5secret);
09680 }
09681 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
09682 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
09683 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09684
09685 if (peer->call_limit)
09686 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
09687 ast_string_field_set(p, peername, peer->name);
09688 ast_string_field_set(p, authname, peer->name);
09689
09690
09691 for (v = peer->chanvars ; v ; v = v->next) {
09692 if ((tmpvar = ast_variable_new(v->name, v->value))) {
09693 tmpvar->next = p->chanvars;
09694 p->chanvars = tmpvar;
09695 }
09696 }
09697 if (authpeer) {
09698 (*authpeer) = ASTOBJ_REF(peer);
09699 }
09700
09701 if (!ast_strlen_zero(peer->username)) {
09702 ast_string_field_set(p, username, peer->username);
09703
09704
09705 ast_string_field_set(p, authname, peer->username);
09706 }
09707 if (!ast_strlen_zero(peer->cid_num)) {
09708 char *tmp = ast_strdupa(peer->cid_num);
09709 if (ast_is_shrinkable_phonenumber(tmp))
09710 ast_shrink_phone_number(tmp);
09711 ast_string_field_set(p, cid_num, tmp);
09712 }
09713 if (!ast_strlen_zero(peer->cid_name))
09714 ast_string_field_set(p, cid_name, peer->cid_name);
09715 ast_string_field_set(p, fullcontact, peer->fullcontact);
09716 if (!ast_strlen_zero(peer->context))
09717 ast_string_field_set(p, context, peer->context);
09718 ast_string_field_set(p, peersecret, peer->secret);
09719 ast_string_field_set(p, peermd5secret, peer->md5secret);
09720 ast_string_field_set(p, language, peer->language);
09721 ast_string_field_set(p, accountcode, peer->accountcode);
09722 p->amaflags = peer->amaflags;
09723 p->callgroup = peer->callgroup;
09724 p->pickupgroup = peer->pickupgroup;
09725 p->capability = peer->capability;
09726 p->prefs = peer->prefs;
09727 p->jointcapability = peer->capability;
09728 if (p->peercapability)
09729 p->jointcapability &= p->peercapability;
09730 p->maxcallbitrate = peer->maxcallbitrate;
09731 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
09732 ast_rtp_destroy(p->vrtp);
09733 p->vrtp = NULL;
09734 }
09735 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
09736 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
09737 p->noncodeccapability |= AST_RTP_DTMF;
09738 else
09739 p->noncodeccapability &= ~AST_RTP_DTMF;
09740 p->jointnoncodeccapability = p->noncodeccapability;
09741 if (p->t38.peercapability)
09742 p->t38.jointcapability &= p->t38.peercapability;
09743 }
09744 ASTOBJ_UNREF(peer, sip_destroy_peer);
09745 } else {
09746 if (debug)
09747 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
09748
09749
09750 if (!global_allowguest) {
09751 if (global_alwaysauthreject)
09752 res = AUTH_FAKE_AUTH;
09753 else
09754 res = AUTH_SECRET_FAILED;
09755 } else if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
09756 char *tmp = ast_strdupa(rpid_num);
09757 if (*calleridname)
09758 ast_string_field_set(p, cid_name, calleridname);
09759 if (ast_is_shrinkable_phonenumber(tmp))
09760 ast_shrink_phone_number(tmp);
09761 ast_string_field_set(p, cid_num, tmp);
09762 }
09763 }
09764
09765 }
09766
09767 if (user)
09768 ASTOBJ_UNREF(user, sip_destroy_user);
09769 return res;
09770 }
09771
09772
09773
09774
09775 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
09776 {
09777 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
09778 }
09779
09780
09781 static int get_msg_text(char *buf, int len, struct sip_request *req)
09782 {
09783 int x;
09784 int y;
09785
09786 buf[0] = '\0';
09787 y = len - strlen(buf) - 5;
09788 if (y < 0)
09789 y = 0;
09790 for (x=0;x<req->lines;x++) {
09791 strncat(buf, req->line[x], y);
09792 y -= strlen(req->line[x]) + 1;
09793 if (y < 0)
09794 y = 0;
09795 if (y != 0)
09796 strcat(buf, "\n");
09797 }
09798 return 0;
09799 }
09800
09801
09802
09803
09804
09805 static void receive_message(struct sip_pvt *p, struct sip_request *req)
09806 {
09807 char buf[1024];
09808 struct ast_frame f;
09809 const char *content_type = get_header(req, "Content-Type");
09810
09811 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
09812 transmit_response(p, "415 Unsupported Media Type", req);
09813 if (!p->owner)
09814 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09815 return;
09816 }
09817
09818 if (get_msg_text(buf, sizeof(buf), req)) {
09819 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
09820 transmit_response(p, "202 Accepted", req);
09821 if (!p->owner)
09822 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09823 return;
09824 }
09825
09826 if (p->owner) {
09827 if (sip_debug_test_pvt(p))
09828 ast_verbose("Message received: '%s'\n", buf);
09829 memset(&f, 0, sizeof(f));
09830 f.frametype = AST_FRAME_TEXT;
09831 f.subclass = 0;
09832 f.offset = 0;
09833 f.data = buf;
09834 f.datalen = strlen(buf);
09835 ast_queue_frame(p->owner, &f);
09836 transmit_response(p, "202 Accepted", req);
09837 } else {
09838 ast_log(LOG_WARNING,"Received message to %s from %s, dropped it...\n Content-Type:%s\n Message: %s\n", get_header(req,"To"), get_header(req,"From"), content_type, buf);
09839 transmit_response(p, "405 Method Not Allowed", req);
09840 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09841 }
09842 return;
09843 }
09844
09845
09846 static int sip_show_inuse(int fd, int argc, char *argv[])
09847 {
09848 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
09849 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
09850 char ilimits[40];
09851 char iused[40];
09852 int showall = FALSE;
09853
09854 if (argc < 3)
09855 return RESULT_SHOWUSAGE;
09856
09857 if (argc == 4 && !strcmp(argv[3],"all"))
09858 showall = TRUE;
09859
09860 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
09861 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
09862 ASTOBJ_RDLOCK(iterator);
09863 if (iterator->call_limit)
09864 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
09865 else
09866 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
09867 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
09868 if (showall || iterator->call_limit)
09869 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
09870 ASTOBJ_UNLOCK(iterator);
09871 } while (0) );
09872
09873 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
09874
09875 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
09876 ASTOBJ_RDLOCK(iterator);
09877 if (iterator->call_limit)
09878 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
09879 else
09880 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
09881 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
09882 if (showall || iterator->call_limit)
09883 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
09884 ASTOBJ_UNLOCK(iterator);
09885 } while (0) );
09886
09887 return RESULT_SUCCESS;
09888 #undef FORMAT
09889 #undef FORMAT2
09890 }
09891
09892
09893 static char *transfermode2str(enum transfermodes mode)
09894 {
09895 if (mode == TRANSFER_OPENFORALL)
09896 return "open";
09897 else if (mode == TRANSFER_CLOSED)
09898 return "closed";
09899 return "strict";
09900 }
09901
09902
09903 static char *nat2str(int nat)
09904 {
09905 switch(nat) {
09906 case SIP_NAT_NEVER:
09907 return "No";
09908 case SIP_NAT_ROUTE:
09909 return "Route";
09910 case SIP_NAT_ALWAYS:
09911 return "Always";
09912 case SIP_NAT_RFC3581:
09913 return "RFC3581";
09914 default:
09915 return "Unknown";
09916 }
09917 }
09918
09919
09920
09921
09922 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
09923 {
09924 int res = 0;
09925 if (peer->maxms) {
09926 if (peer->lastms < 0) {
09927 ast_copy_string(status, "UNREACHABLE", statuslen);
09928 } else if (peer->lastms > peer->maxms) {
09929 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
09930 res = 1;
09931 } else if (peer->lastms) {
09932 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
09933 res = 1;
09934 } else {
09935 ast_copy_string(status, "UNKNOWN", statuslen);
09936 }
09937 } else {
09938 ast_copy_string(status, "Unmonitored", statuslen);
09939
09940 res = -1;
09941 }
09942 return res;
09943 }
09944
09945
09946 static int sip_show_users(int fd, int argc, char *argv[])
09947 {
09948 regex_t regexbuf;
09949 int havepattern = FALSE;
09950
09951 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
09952
09953 switch (argc) {
09954 case 5:
09955 if (!strcasecmp(argv[3], "like")) {
09956 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
09957 return RESULT_SHOWUSAGE;
09958 havepattern = TRUE;
09959 } else
09960 return RESULT_SHOWUSAGE;
09961 case 3:
09962 break;
09963 default:
09964 return RESULT_SHOWUSAGE;
09965 }
09966
09967 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
09968 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
09969 ASTOBJ_RDLOCK(iterator);
09970
09971 if (havepattern && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
09972 ASTOBJ_UNLOCK(iterator);
09973 continue;
09974 }
09975
09976 ast_cli(fd, FORMAT, iterator->name,
09977 iterator->secret,
09978 iterator->accountcode,
09979 iterator->context,
09980 iterator->ha ? "Yes" : "No",
09981 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
09982 ASTOBJ_UNLOCK(iterator);
09983 } while (0)
09984 );
09985
09986 if (havepattern)
09987 regfree(®exbuf);
09988
09989 return RESULT_SUCCESS;
09990 #undef FORMAT
09991 }
09992
09993 static char mandescr_show_peers[] =
09994 "Description: Lists SIP peers in text format with details on current status.\n"
09995 "Variables: \n"
09996 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
09997
09998
09999
10000 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
10001 {
10002 const char *id = astman_get_header(m,"ActionID");
10003 const char *a[] = {"sip", "show", "peers"};
10004 char idtext[256] = "";
10005 int total = 0;
10006
10007 if (!ast_strlen_zero(id))
10008 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
10009
10010 astman_send_ack(s, m, "Peer status list will follow");
10011
10012 _sip_show_peers(-1, &total, s, m, 3, a);
10013
10014 astman_append(s,
10015 "Event: PeerlistComplete\r\n"
10016 "ListItems: %d\r\n"
10017 "%s"
10018 "\r\n", total, idtext);
10019 return 0;
10020 }
10021
10022
10023 static int sip_show_peers(int fd, int argc, char *argv[])
10024 {
10025 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
10026 }
10027
10028
10029 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
10030 {
10031 regex_t regexbuf;
10032 int havepattern = FALSE;
10033
10034 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
10035 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
10036
10037 char name[256];
10038 int total_peers = 0;
10039 int peers_mon_online = 0;
10040 int peers_mon_offline = 0;
10041 int peers_unmon_offline = 0;
10042 int peers_unmon_online = 0;
10043 const char *id;
10044 char idtext[256] = "";
10045 int realtimepeers;
10046
10047 realtimepeers = ast_check_realtime("sippeers");
10048
10049 if (s) {
10050 id = astman_get_header(m,"ActionID");
10051 if (!ast_strlen_zero(id))
10052 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
10053 }
10054
10055 switch (argc) {
10056 case 5:
10057 if (!strcasecmp(argv[3], "like")) {
10058 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
10059 return RESULT_SHOWUSAGE;
10060 havepattern = TRUE;
10061 } else
10062 return RESULT_SHOWUSAGE;
10063 case 3:
10064 break;
10065 default:
10066 return RESULT_SHOWUSAGE;
10067 }
10068
10069 if (!s)
10070 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
10071
10072 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10073 char status[20] = "";
10074 char srch[2000];
10075 char pstatus;
10076
10077 ASTOBJ_RDLOCK(iterator);
10078
10079 if (havepattern && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
10080 ASTOBJ_UNLOCK(iterator);
10081 continue;
10082 }
10083
10084 if (!ast_strlen_zero(iterator->username) && !s)
10085 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
10086 else
10087 ast_copy_string(name, iterator->name, sizeof(name));
10088
10089 pstatus = peer_status(iterator, status, sizeof(status));
10090 if (pstatus == 1)
10091 peers_mon_online++;
10092 else if (pstatus == 0)
10093 peers_mon_offline++;
10094 else {
10095 if (iterator->addr.sin_port == 0)
10096 peers_unmon_offline++;
10097 else
10098 peers_unmon_online++;
10099 }
10100
10101 snprintf(srch, sizeof(srch), FORMAT, name,
10102 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10103 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ",
10104 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
10105 iterator->ha ? " A " : " ",
10106 ntohs(iterator->addr.sin_port), status,
10107 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10108
10109 if (!s) {
10110 ast_cli(fd, FORMAT, name,
10111 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10112 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ",
10113 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
10114 iterator->ha ? " A " : " ",
10115
10116 ntohs(iterator->addr.sin_port), status,
10117 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10118 } else {
10119
10120 astman_append(s,
10121 "Event: PeerEntry\r\n%s"
10122 "Channeltype: SIP\r\n"
10123 "ObjectName: %s\r\n"
10124 "ChanObjectType: peer\r\n"
10125 "IPaddress: %s\r\n"
10126 "IPport: %d\r\n"
10127 "Dynamic: %s\r\n"
10128 "Natsupport: %s\r\n"
10129 "VideoSupport: %s\r\n"
10130 "ACL: %s\r\n"
10131 "Status: %s\r\n"
10132 "RealtimeDevice: %s\r\n\r\n",
10133 idtext,
10134 iterator->name,
10135 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
10136 ntohs(iterator->addr.sin_port),
10137 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no",
10138 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
10139 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
10140 iterator->ha ? "yes" : "no",
10141 status,
10142 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
10143 }
10144
10145 ASTOBJ_UNLOCK(iterator);
10146
10147 total_peers++;
10148 } while(0) );
10149
10150 if (!s)
10151 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
10152 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
10153
10154 if (havepattern)
10155 regfree(®exbuf);
10156
10157 if (total)
10158 *total = total_peers;
10159
10160
10161 return RESULT_SUCCESS;
10162 #undef FORMAT
10163 #undef FORMAT2
10164 }
10165
10166
10167 static int sip_show_objects(int fd, int argc, char *argv[])
10168 {
10169 char tmp[256];
10170 if (argc != 3)
10171 return RESULT_SHOWUSAGE;
10172 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
10173 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
10174 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
10175 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
10176 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
10177 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), ®l);
10178 return RESULT_SUCCESS;
10179 }
10180
10181 static void print_group(int fd, ast_group_t group, int crlf)
10182 {
10183 char buf[256];
10184 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
10185 }
10186
10187
10188 static const char *dtmfmode2str(int mode)
10189 {
10190 switch (mode) {
10191 case SIP_DTMF_RFC2833:
10192 return "rfc2833";
10193 case SIP_DTMF_INFO:
10194 return "info";
10195 case SIP_DTMF_INBAND:
10196 return "inband";
10197 case SIP_DTMF_AUTO:
10198 return "auto";
10199 }
10200 return "<error>";
10201 }
10202
10203
10204 static const char *insecure2str(int port, int invite)
10205 {
10206 if (port && invite)
10207 return "port,invite";
10208 else if (port)
10209 return "port";
10210 else if (invite)
10211 return "invite";
10212 else
10213 return "no";
10214 }
10215
10216
10217
10218
10219 static void cleanup_stale_contexts(char *new, char *old)
10220 {
10221 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
10222
10223 while ((oldcontext = strsep(&old, "&"))) {
10224 stalecontext = '\0';
10225 ast_copy_string(newlist, new, sizeof(newlist));
10226 stringp = newlist;
10227 while ((newcontext = strsep(&stringp, "&"))) {
10228 if (strcmp(newcontext, oldcontext) == 0) {
10229
10230 stalecontext = '\0';
10231 break;
10232 } else if (strcmp(newcontext, oldcontext)) {
10233 stalecontext = oldcontext;
10234 }
10235
10236 }
10237 if (stalecontext)
10238 ast_context_destroy(ast_context_find(stalecontext), "SIP");
10239 }
10240 }
10241
10242
10243 static int sip_prune_realtime(int fd, int argc, char *argv[])
10244 {
10245 struct sip_peer *peer;
10246 struct sip_user *user;
10247 int pruneuser = FALSE;
10248 int prunepeer = FALSE;
10249 int multi = FALSE;
10250 char *name = NULL;
10251 regex_t regexbuf;
10252
10253 switch (argc) {
10254 case 4:
10255 if (!strcasecmp(argv[3], "user"))
10256 return RESULT_SHOWUSAGE;
10257 if (!strcasecmp(argv[3], "peer"))
10258 return RESULT_SHOWUSAGE;
10259 if (!strcasecmp(argv[3], "like"))
10260 return RESULT_SHOWUSAGE;
10261 if (!strcasecmp(argv[3], "all")) {
10262 multi = TRUE;
10263 pruneuser = prunepeer = TRUE;
10264 } else {
10265 pruneuser = prunepeer = TRUE;
10266 name = argv[3];
10267 }
10268 break;
10269 case 5:
10270 if (!strcasecmp(argv[4], "like"))
10271 return RESULT_SHOWUSAGE;
10272 if (!strcasecmp(argv[3], "all"))
10273 return RESULT_SHOWUSAGE;
10274 if (!strcasecmp(argv[3], "like")) {
10275 multi = TRUE;
10276 name = argv[4];
10277 pruneuser = prunepeer = TRUE;
10278 } else if (!strcasecmp(argv[3], "user")) {
10279 pruneuser = TRUE;
10280 if (!strcasecmp(argv[4], "all"))
10281 multi = TRUE;
10282 else
10283 name = argv[4];
10284 } else if (!strcasecmp(argv[3], "peer")) {
10285 prunepeer = TRUE;
10286 if (!strcasecmp(argv[4], "all"))
10287 multi = TRUE;
10288 else
10289 name = argv[4];
10290 } else
10291 return RESULT_SHOWUSAGE;
10292 break;
10293 case 6:
10294 if (strcasecmp(argv[4], "like"))
10295 return RESULT_SHOWUSAGE;
10296 if (!strcasecmp(argv[3], "user")) {
10297 pruneuser = TRUE;
10298 name = argv[5];
10299 } else if (!strcasecmp(argv[3], "peer")) {
10300 prunepeer = TRUE;
10301 name = argv[5];
10302 } else
10303 return RESULT_SHOWUSAGE;
10304 break;
10305 default:
10306 return RESULT_SHOWUSAGE;
10307 }
10308
10309 if (multi && name) {
10310 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
10311 return RESULT_SHOWUSAGE;
10312 }
10313
10314 if (multi) {
10315 if (prunepeer) {
10316 int pruned = 0;
10317
10318 ASTOBJ_CONTAINER_WRLOCK(&peerl);
10319 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10320 ASTOBJ_RDLOCK(iterator);
10321 if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
10322 ASTOBJ_UNLOCK(iterator);
10323 continue;
10324 };
10325 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10326 ASTOBJ_MARK(iterator);
10327 pruned++;
10328 }
10329 ASTOBJ_UNLOCK(iterator);
10330 } while (0) );
10331 if (pruned) {
10332 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
10333 ast_cli(fd, "%d peers pruned.\n", pruned);
10334 } else
10335 ast_cli(fd, "No peers found to prune.\n");
10336 ASTOBJ_CONTAINER_UNLOCK(&peerl);
10337 }
10338 if (pruneuser) {
10339 int pruned = 0;
10340
10341 ASTOBJ_CONTAINER_WRLOCK(&userl);
10342 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
10343 ASTOBJ_RDLOCK(iterator);
10344 if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
10345 ASTOBJ_UNLOCK(iterator);
10346 continue;
10347 };
10348 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10349 ASTOBJ_MARK(iterator);
10350 pruned++;
10351 }
10352 ASTOBJ_UNLOCK(iterator);
10353 } while (0) );
10354 if (pruned) {
10355 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
10356 ast_cli(fd, "%d users pruned.\n", pruned);
10357 } else
10358 ast_cli(fd, "No users found to prune.\n");
10359 ASTOBJ_CONTAINER_UNLOCK(&userl);
10360 }
10361 } else {
10362 if (prunepeer) {
10363 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
10364 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10365 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
10366 ASTOBJ_CONTAINER_LINK(&peerl, peer);
10367 } else
10368 ast_cli(fd, "Peer '%s' pruned.\n", name);
10369 ASTOBJ_UNREF(peer, sip_destroy_peer);
10370 } else
10371 ast_cli(fd, "Peer '%s' not found.\n", name);
10372 }
10373 if (pruneuser) {
10374 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
10375 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10376 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
10377 ASTOBJ_CONTAINER_LINK(&userl, user);
10378 } else
10379 ast_cli(fd, "User '%s' pruned.\n", name);
10380 ASTOBJ_UNREF(user, sip_destroy_user);
10381 } else
10382 ast_cli(fd, "User '%s' not found.\n", name);
10383 }
10384 }
10385
10386 return RESULT_SUCCESS;
10387 }
10388
10389
10390 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
10391 {
10392 int x, codec;
10393
10394 for(x = 0; x < 32 ; x++) {
10395 codec = ast_codec_pref_index(pref, x);
10396 if (!codec)
10397 break;
10398 ast_cli(fd, "%s", ast_getformatname(codec));
10399 ast_cli(fd, ":%d", pref->framing[x]);
10400 if (x < 31 && ast_codec_pref_index(pref, x + 1))
10401 ast_cli(fd, ",");
10402 }
10403 if (!x)
10404 ast_cli(fd, "none");
10405 }
10406
10407
10408 static const char *domain_mode_to_text(const enum domain_mode mode)
10409 {
10410 switch (mode) {
10411 case SIP_DOMAIN_AUTO:
10412 return "[Automatic]";
10413 case SIP_DOMAIN_CONFIG:
10414 return "[Configured]";
10415 }
10416
10417 return "";
10418 }
10419
10420
10421 static int sip_show_domains(int fd, int argc, char *argv[])
10422 {
10423 struct domain *d;
10424 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
10425
10426 if (AST_LIST_EMPTY(&domain_list)) {
10427 ast_cli(fd, "SIP Domain support not enabled.\n\n");
10428 return RESULT_SUCCESS;
10429 } else {
10430 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
10431 AST_LIST_LOCK(&domain_list);
10432 AST_LIST_TRAVERSE(&domain_list, d, list)
10433 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
10434 domain_mode_to_text(d->mode));
10435 AST_LIST_UNLOCK(&domain_list);
10436 ast_cli(fd, "\n");
10437 return RESULT_SUCCESS;
10438 }
10439 }
10440 #undef FORMAT
10441
10442 static char mandescr_show_peer[] =
10443 "Description: Show one SIP peer with details on current status.\n"
10444 "Variables: \n"
10445 " Peer: <name> The peer name you want to check.\n"
10446 " ActionID: <id> Optional action ID for this AMI transaction.\n";
10447
10448
10449 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
10450 {
10451 const char *a[4];
10452 const char *peer;
10453 int ret;
10454
10455 peer = astman_get_header(m,"Peer");
10456 if (ast_strlen_zero(peer)) {
10457 astman_send_error(s, m, "Peer: <name> missing.\n");
10458 return 0;
10459 }
10460 a[0] = "sip";
10461 a[1] = "show";
10462 a[2] = "peer";
10463 a[3] = peer;
10464
10465 ret = _sip_show_peer(1, -1, s, m, 4, a);
10466 astman_append(s, "\r\n\r\n" );
10467 return ret;
10468 }
10469
10470
10471
10472
10473 static int sip_show_peer(int fd, int argc, char *argv[])
10474 {
10475 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
10476 }
10477
10478
10479 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
10480 {
10481 char status[30] = "";
10482 char cbuf[256];
10483 struct sip_peer *peer;
10484 char codec_buf[512];
10485 struct ast_codec_pref *pref;
10486 struct ast_variable *v;
10487 struct sip_auth *auth;
10488 int x = 0, codec = 0, load_realtime;
10489 int realtimepeers;
10490
10491 realtimepeers = ast_check_realtime("sippeers");
10492
10493 if (argc < 4)
10494 return RESULT_SHOWUSAGE;
10495
10496 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10497 peer = find_peer(argv[3], NULL, load_realtime);
10498 if (s) {
10499 if (peer) {
10500 const char *id = astman_get_header(m,"ActionID");
10501
10502 astman_append(s, "Response: Success\r\n");
10503 if (!ast_strlen_zero(id))
10504 astman_append(s, "ActionID: %s\r\n",id);
10505 } else {
10506 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
10507 astman_send_error(s, m, cbuf);
10508 return 0;
10509 }
10510 }
10511 if (peer && type==0 ) {
10512 ast_cli(fd,"\n\n");
10513 ast_cli(fd, " * Name : %s\n", peer->name);
10514 if (realtimepeers) {
10515 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
10516 }
10517 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
10518 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
10519 for (auth = peer->auth; auth; auth = auth->next) {
10520 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
10521 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
10522 }
10523 ast_cli(fd, " Context : %s\n", peer->context);
10524 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
10525 ast_cli(fd, " Language : %s\n", peer->language);
10526 if (!ast_strlen_zero(peer->accountcode))
10527 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10528 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10529 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10530 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10531 if (!ast_strlen_zero(peer->fromuser))
10532 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10533 if (!ast_strlen_zero(peer->fromdomain))
10534 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10535 ast_cli(fd, " Callgroup : ");
10536 print_group(fd, peer->callgroup, 0);
10537 ast_cli(fd, " Pickupgroup : ");
10538 print_group(fd, peer->pickupgroup, 0);
10539 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10540 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10541 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10542 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10543 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10544 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10545 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10546 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10547 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT), ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)));
10548 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10549 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10550 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10551 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10552 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10553 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10554 #endif
10555 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10556 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10557 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10558 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10559 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10560 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10561 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10562 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10563
10564
10565 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10566 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10567 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10568 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
10569 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10570 ast_cli(fd, " Transport : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_TCP) ? "TCP" : "UDP");
10571 if (!ast_strlen_zero(global_regcontext))
10572 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10573 ast_cli(fd, " Def. Username: %s\n", peer->username);
10574 ast_cli(fd, " SIP Options : ");
10575 if (peer->sipoptions) {
10576 int lastoption = -1;
10577 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10578 if (sip_options[x].id != lastoption) {
10579 if (peer->sipoptions & sip_options[x].id)
10580 ast_cli(fd, "%s ", sip_options[x].text);
10581 lastoption = x;
10582 }
10583 }
10584 } else
10585 ast_cli(fd, "(none)");
10586
10587 ast_cli(fd, "\n");
10588 ast_cli(fd, " Codecs : ");
10589 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10590 ast_cli(fd, "%s\n", codec_buf);
10591 ast_cli(fd, " Codec Order : (");
10592 print_codec_to_cli(fd, &peer->prefs);
10593 ast_cli(fd, ")\n");
10594
10595 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10596 ast_cli(fd, " Status : ");
10597 peer_status(peer, status, sizeof(status));
10598 ast_cli(fd, "%s\n",status);
10599 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10600 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10601 if (peer->chanvars) {
10602 ast_cli(fd, " Variables :\n");
10603 for (v = peer->chanvars ; v ; v = v->next)
10604 ast_cli(fd, " %s = %s\n", v->name, v->value);
10605 }
10606 ast_cli(fd,"\n");
10607 ASTOBJ_UNREF(peer,sip_destroy_peer);
10608 } else if (peer && type == 1) {
10609 char buf[256];
10610 astman_append(s, "Channeltype: SIP\r\n");
10611 astman_append(s, "ObjectName: %s\r\n", peer->name);
10612 astman_append(s, "ChanObjectType: peer\r\n");
10613 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10614 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10615 astman_append(s, "Context: %s\r\n", peer->context);
10616 astman_append(s, "Language: %s\r\n", peer->language);
10617 if (!ast_strlen_zero(peer->accountcode))
10618 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10619 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10620 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10621 if (!ast_strlen_zero(peer->fromuser))
10622 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10623 if (!ast_strlen_zero(peer->fromdomain))
10624 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10625 astman_append(s, "Callgroup: ");
10626 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10627 astman_append(s, "Pickupgroup: ");
10628 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10629 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10630 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10631 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10632 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
10633 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10634 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10635 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10636 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10637 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT), ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)));
10638 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10639 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10640 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10641 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10642 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10643 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10644
10645
10646 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10647 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10648 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10649 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
10650 astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10651 astman_append(s, "Default-Username: %s\r\n", peer->username);
10652 if (!ast_strlen_zero(global_regcontext))
10653 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10654 astman_append(s, "Codecs: ");
10655 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10656 astman_append(s, "%s\r\n", codec_buf);
10657 astman_append(s, "CodecOrder: ");
10658 pref = &peer->prefs;
10659 for(x = 0; x < 32 ; x++) {
10660 codec = ast_codec_pref_index(pref,x);
10661 if (!codec)
10662 break;
10663 astman_append(s, "%s", ast_getformatname(codec));
10664 if (x < 31 && ast_codec_pref_index(pref,x+1))
10665 astman_append(s, ",");
10666 }
10667
10668 astman_append(s, "\r\n");
10669 astman_append(s, "Status: ");
10670 peer_status(peer, status, sizeof(status));
10671 astman_append(s, "%s\r\n", status);
10672 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10673 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10674 if (peer->chanvars) {
10675 for (v = peer->chanvars ; v ; v = v->next) {
10676 astman_append(s, "ChanVariable:\n");
10677 astman_append(s, " %s,%s\r\n", v->name, v->value);
10678 }
10679 }
10680
10681 ASTOBJ_UNREF(peer,sip_destroy_peer);
10682
10683 } else {
10684 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10685 ast_cli(fd,"\n");
10686 }
10687
10688 return RESULT_SUCCESS;
10689 }
10690
10691
10692 static int sip_show_user(int fd, int argc, char *argv[])
10693 {
10694 char cbuf[256];
10695 struct sip_user *user;
10696 struct ast_variable *v;
10697 int load_realtime;
10698
10699 if (argc < 4)
10700 return RESULT_SHOWUSAGE;
10701
10702
10703 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10704
10705 user = find_user(argv[3], load_realtime);
10706 if (user) {
10707 ast_cli(fd,"\n\n");
10708 ast_cli(fd, " * Name : %s\n", user->name);
10709 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10710 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10711 ast_cli(fd, " Context : %s\n", user->context);
10712 ast_cli(fd, " Language : %s\n", user->language);
10713 if (!ast_strlen_zero(user->accountcode))
10714 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10715 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10716 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10717 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10718 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10719 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10720 ast_cli(fd, " Callgroup : ");
10721 print_group(fd, user->callgroup, 0);
10722 ast_cli(fd, " Pickupgroup : ");
10723 print_group(fd, user->pickupgroup, 0);
10724 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10725 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10726 ast_cli(fd, " Codec Order : (");
10727 print_codec_to_cli(fd, &user->prefs);
10728 ast_cli(fd, ")\n");
10729
10730 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10731 if (user->chanvars) {
10732 ast_cli(fd, " Variables :\n");
10733 for (v = user->chanvars ; v ; v = v->next)
10734 ast_cli(fd, " %s = %s\n", v->name, v->value);
10735 }
10736 ast_cli(fd,"\n");
10737 ASTOBJ_UNREF(user,sip_destroy_user);
10738 } else {
10739 ast_cli(fd,"User %s not found.\n", argv[3]);
10740 ast_cli(fd,"\n");
10741 }
10742
10743 return RESULT_SUCCESS;
10744 }
10745
10746
10747 static int sip_show_registry(int fd, int argc, char *argv[])
10748 {
10749 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10750 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10751 char host[80];
10752 char tmpdat[256];
10753 struct tm tm;
10754
10755
10756 if (argc != 3)
10757 return RESULT_SHOWUSAGE;
10758 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10759 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
10760 ASTOBJ_RDLOCK(iterator);
10761 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10762 if (iterator->regtime) {
10763 ast_localtime(&iterator->regtime, &tm, NULL);
10764 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10765 } else {
10766 tmpdat[0] = 0;
10767 }
10768 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10769 ASTOBJ_UNLOCK(iterator);
10770 } while(0));
10771 return RESULT_SUCCESS;
10772 #undef FORMAT
10773 #undef FORMAT2
10774 }
10775
10776
10777 static int sip_show_settings(int fd, int argc, char *argv[])
10778 {
10779 int realtimepeers;
10780 int realtimeusers;
10781 char codec_buf[SIPBUFSIZE];
10782
10783 realtimepeers = ast_check_realtime("sippeers");
10784 realtimeusers = ast_check_realtime("sipusers");
10785
10786 if (argc != 3)
10787 return RESULT_SHOWUSAGE;
10788 ast_cli(fd, "\n\nGlobal Settings:\n");
10789 ast_cli(fd, "----------------\n");
10790 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10791 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10792 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10793 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10794 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10795 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10796 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10797 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10798 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10799 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10800 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10801 ast_cli(fd, " Our auth realm %s\n", global_realm);
10802 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10803 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10804 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10805 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10806 ast_cli(fd, " User Agent: %s\n", global_useragent);
10807 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10808 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10809 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10810 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10811 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10812 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10813 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10814 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10815 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10816 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10817 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10818 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10819 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10820 #endif
10821 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10822 if (!realtimepeers && !realtimeusers)
10823 ast_cli(fd, " SIP realtime: Disabled\n" );
10824 else
10825 ast_cli(fd, " SIP realtime: Enabled\n" );
10826
10827 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10828 ast_cli(fd, "---------------------------\n");
10829 ast_cli(fd, " Codecs: ");
10830 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10831 ast_cli(fd, "%s\n", codec_buf);
10832 ast_cli(fd, " Codec Order: ");
10833 print_codec_to_cli(fd, &default_prefs);
10834 ast_cli(fd, "\n");
10835 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10836 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10837 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10838 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10839 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10840 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10841 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10842 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10843 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10844 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10845 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10846 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10847 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10848 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10849 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10850 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10851 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10852 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10853 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10854 ast_cli(fd, "\nDefault Settings:\n");
10855 ast_cli(fd, "-----------------\n");
10856 ast_cli(fd, " Context: %s\n", default_context);
10857 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10858 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10859 ast_cli(fd, " Qualify: %d\n", default_qualify);
10860 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10861 ast_cli(fd, " Progress inband: %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
10862 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10863 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10864 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10865 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10866
10867
10868 if (realtimepeers || realtimeusers) {
10869 ast_cli(fd, "\nRealtime SIP Settings:\n");
10870 ast_cli(fd, "----------------------\n");
10871 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10872 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10873 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10874 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10875 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10876 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10877 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10878 }
10879 ast_cli(fd, "\n----\n");
10880 return RESULT_SUCCESS;
10881 }
10882
10883
10884 static const char *subscription_type2str(enum subscriptiontype subtype)
10885 {
10886 int i;
10887
10888 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10889 if (subscription_types[i].type == subtype) {
10890 return subscription_types[i].text;
10891 }
10892 }
10893 return subscription_types[0].text;
10894 }
10895
10896
10897 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10898 {
10899 int i;
10900
10901 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10902 if (subscription_types[i].type == subtype) {
10903 return &subscription_types[i];
10904 }
10905 }
10906 return &subscription_types[0];
10907 }
10908
10909
10910 static int sip_show_channels(int fd, int argc, char *argv[])
10911 {
10912 return __sip_show_channels(fd, argc, argv, 0);
10913 }
10914
10915
10916 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10917 {
10918 return __sip_show_channels(fd, argc, argv, 1);
10919 }
10920
10921
10922 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10923 {
10924 #define FORMAT3L "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s %6d\n"
10925 #define FORMAT3H "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s %-6s\n"
10926 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-15.15s %-7.7s %-15.15s\n"
10927 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10928 struct sip_pvt *cur;
10929 int numchans = 0;
10930 char *referstatus = NULL;
10931
10932 if (argc != 3)
10933 return RESULT_SHOWUSAGE;
10934 ast_mutex_lock(&iflock);
10935 cur = iflist;
10936 if (!subscriptions)
10937 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10938 else
10939 ast_cli(fd, FORMAT3H, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
10940 for (; cur; cur = cur->next) {
10941 referstatus = "";
10942 if (cur->refer) {
10943 referstatus = referstatus2str(cur->refer->status);
10944 }
10945 if (cur->subscribed == NONE && !subscriptions) {
10946 char formatbuf[SIPBUFSIZE/2];
10947 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10948 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10949 cur->callid,
10950 cur->ocseq, cur->icseq,
10951 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
10952 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10953 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10954 cur->lastmsg ,
10955 referstatus
10956 );
10957 numchans++;
10958 }
10959 if (cur->subscribed != NONE && subscriptions) {
10960 ast_cli(fd, FORMAT3L, ast_inet_ntoa(cur->sa.sin_addr),
10961 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10962 cur->callid,
10963
10964 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10965 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10966 subscription_type2str(cur->subscribed),
10967 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>",
10968 cur->expiry
10969 );
10970 numchans++;
10971 }
10972 }
10973 ast_mutex_unlock(&iflock);
10974 if (!subscriptions)
10975 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10976 else
10977 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10978 return RESULT_SUCCESS;
10979 #undef FORMAT
10980 #undef FORMAT2
10981 #undef FORMAT3
10982 }
10983
10984
10985 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10986 {
10987 int which=0;
10988 struct sip_pvt *cur;
10989 char *c = NULL;
10990 int wordlen = strlen(word);
10991
10992 if (pos != 3) {
10993 return NULL;
10994 }
10995
10996 ast_mutex_lock(&iflock);
10997 for (cur = iflist; cur; cur = cur->next) {
10998 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10999 c = ast_strdup(cur->callid);
11000 break;
11001 }
11002 }
11003 ast_mutex_unlock(&iflock);
11004 return c;
11005 }
11006
11007
11008 static char *complete_sip_peer(const char *word, int state, int flags2)
11009 {
11010 char *result = NULL;
11011 int wordlen = strlen(word);
11012 int which = 0;
11013
11014 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
11015
11016 if (!strncasecmp(word, iterator->name, wordlen) &&
11017 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
11018 ++which > state)
11019 result = ast_strdup(iterator->name);
11020 } while(0) );
11021 return result;
11022 }
11023
11024
11025 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
11026 {
11027 if (pos == 3)
11028 return complete_sip_peer(word, state, 0);
11029
11030 return NULL;
11031 }
11032
11033
11034 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
11035 {
11036 if (pos == 3)
11037 return complete_sip_peer(word, state, 0);
11038
11039 return NULL;
11040 }
11041
11042
11043 static char *complete_sip_user(const char *word, int state, int flags2)
11044 {
11045 char *result = NULL;
11046 int wordlen = strlen(word);
11047 int which = 0;
11048
11049 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
11050
11051 if (!strncasecmp(word, iterator->name, wordlen)) {
11052 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
11053 continue;
11054 if (++which > state) {
11055 result = ast_strdup(iterator->name);
11056 }
11057 }
11058 } while(0) );
11059 return result;
11060 }
11061
11062
11063 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
11064 {
11065 if (pos == 3)
11066 return complete_sip_user(word, state, 0);
11067
11068 return NULL;
11069 }
11070
11071
11072 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
11073 {
11074 char *c = NULL;
11075
11076 if (pos == 2) {
11077 int which = 0;
11078 char *cat = NULL;
11079 int wordlen = strlen(word);
11080
11081
11082
11083 if (!notify_types)
11084 return NULL;
11085
11086 while ( (cat = ast_category_browse(notify_types, cat)) ) {
11087 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
11088 c = ast_strdup(cat);
11089 break;
11090 }
11091 }
11092 return c;
11093 }
11094
11095 if (pos > 2)
11096 return complete_sip_peer(word, state, 0);
11097
11098 return NULL;
11099 }
11100
11101
11102 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
11103 {
11104 if (pos == 4)
11105 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11106 return NULL;
11107 }
11108
11109
11110 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
11111 {
11112 if (pos == 4)
11113 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
11114
11115 return NULL;
11116 }
11117
11118
11119 static int sip_show_channel(int fd, int argc, char *argv[])
11120 {
11121 struct sip_pvt *cur;
11122 size_t len;
11123 int found = 0;
11124
11125 if (argc != 4)
11126 return RESULT_SHOWUSAGE;
11127 len = strlen(argv[3]);
11128 ast_mutex_lock(&iflock);
11129 for (cur = iflist; cur; cur = cur->next) {
11130 if (!strncasecmp(cur->callid, argv[3], len)) {
11131 char formatbuf[SIPBUFSIZE/2];
11132 ast_cli(fd,"\n");
11133 if (cur->subscribed != NONE)
11134 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
11135 else
11136 ast_cli(fd, " * SIP Call\n");
11137 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
11138 ast_cli(fd, " Call-ID: %s\n", cur->callid);
11139 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
11140 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
11141 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
11142 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
11143 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
11144 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
11145 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
11146 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
11147 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
11148 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
11149 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
11150 ast_cli(fd, " Audio IP: %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
11151 ast_cli(fd, " Our Tag: %s\n", cur->tag);
11152 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
11153 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
11154 if (!ast_strlen_zero(cur->username))
11155 ast_cli(fd, " Username: %s\n", cur->username);
11156 if (!ast_strlen_zero(cur->peername))
11157 ast_cli(fd, " Peername: %s\n", cur->peername);
11158 if (!ast_strlen_zero(cur->uri))
11159 ast_cli(fd, " Original uri: %s\n", cur->uri);
11160 if (!ast_strlen_zero(cur->cid_num))
11161 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
11162 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
11163 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
11164 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
11165 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
11166 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
11167 ast_cli(fd, " SIP Options: ");
11168 if (cur->sipoptions) {
11169 int x;
11170 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
11171 if (cur->sipoptions & sip_options[x].id)
11172 ast_cli(fd, "%s ", sip_options[x].text);
11173 }
11174 } else
11175 ast_cli(fd, "(none)\n");
11176 ast_cli(fd, "\n\n");
11177 found++;
11178 }
11179 }
11180 ast_mutex_unlock(&iflock);
11181 if (!found)
11182 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11183 return RESULT_SUCCESS;
11184 }
11185
11186
11187 static int sip_show_history(int fd, int argc, char *argv[])
11188 {
11189 struct sip_pvt *cur;
11190 size_t len;
11191 int found = 0;
11192
11193 if (argc != 4)
11194 return RESULT_SHOWUSAGE;
11195 if (!recordhistory)
11196 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
11197 len = strlen(argv[3]);
11198 ast_mutex_lock(&iflock);
11199 for (cur = iflist; cur; cur = cur->next) {
11200 if (!strncasecmp(cur->callid, argv[3], len)) {
11201 struct sip_history *hist;
11202 int x = 0;
11203
11204 ast_cli(fd,"\n");
11205 if (cur->subscribed != NONE)
11206 ast_cli(fd, " * Subscription\n");
11207 else
11208 ast_cli(fd, " * SIP Call\n");
11209 if (cur->history)
11210 AST_LIST_TRAVERSE(cur->history, hist, list)
11211 ast_cli(fd, "%d. %s\n", ++x, hist->event);
11212 if (x == 0)
11213 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
11214 found++;
11215 }
11216 }
11217 ast_mutex_unlock(&iflock);
11218 if (!found)
11219 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11220 return RESULT_SUCCESS;
11221 }
11222
11223
11224 static void sip_dump_history(struct sip_pvt *dialog)
11225 {
11226 int x = 0;
11227 struct sip_history *hist;
11228 static int errmsg = 0;
11229
11230 if (!dialog)
11231 return;
11232
11233 if (!option_debug && !sipdebug) {
11234 if (!errmsg) {
11235 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
11236 errmsg = 1;
11237 }
11238 return;
11239 }
11240
11241 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
11242 if (dialog->subscribed)
11243 ast_log(LOG_DEBUG, " * Subscription\n");
11244 else
11245 ast_log(LOG_DEBUG, " * SIP Call\n");
11246 if (dialog->history)
11247 AST_LIST_TRAVERSE(dialog->history, hist, list)
11248 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
11249 if (!x)
11250 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
11251 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
11252 }
11253
11254
11255
11256
11257 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
11258 {
11259 char buf[1024];
11260 unsigned int event;
11261 const char *c = get_header(req, "Content-Type");
11262
11263
11264 if (!strcasecmp(c, "application/dtmf-relay") ||
11265 !strcasecmp(c, "application/DTMF") ||
11266 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
11267 unsigned int duration = 0;
11268
11269
11270 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
11271 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
11272 transmit_response(p, "200 OK", req);
11273 return;
11274 } else {
11275 ast_copy_string(buf, c, sizeof(buf));
11276 }
11277
11278 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
11279 duration = atoi(c);
11280 if (!duration)
11281 duration = 100;
11282
11283 if (!p->owner) {
11284 transmit_response(p, "481 Call leg/transaction does not exist", req);
11285 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11286 return;
11287 }
11288
11289 if (ast_strlen_zero(buf)) {
11290 transmit_response(p, "200 OK", req);
11291 return;
11292 }
11293
11294 if (buf[0] == '*')
11295 event = 10;
11296 else if (buf[0] == '#')
11297 event = 11;
11298 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
11299 event = 12 + buf[0] - 'A';
11300 else
11301 event = atoi(buf);
11302 if (event == 16) {
11303
11304 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
11305 ast_queue_frame(p->owner, &f);
11306 if (sipdebug)
11307 ast_verbose("* DTMF-relay event received: FLASH\n");
11308 } else {
11309
11310 struct ast_frame f = { AST_FRAME_DTMF, };
11311 if (event < 10) {
11312 f.subclass = '0' + event;
11313 } else if (event < 11) {
11314 f.subclass = '*';
11315 } else if (event < 12) {
11316 f.subclass = '#';
11317 } else if (event < 16) {
11318 f.subclass = 'A' + (event - 12);
11319 }
11320 f.len = duration;
11321 ast_queue_frame(p->owner, &f);
11322 if (sipdebug)
11323 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
11324 }
11325 transmit_response(p, "200 OK", req);
11326 return;
11327 } else if (!strcasecmp(c, "application/media_control+xml")) {
11328
11329 if (p->owner)
11330 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
11331 transmit_response(p, "200 OK", req);
11332 return;
11333 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
11334
11335 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
11336 if (p->owner && p->owner->cdr)
11337 ast_cdr_setuserfield(p->owner, c);
11338 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
11339 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
11340 transmit_response(p, "200 OK", req);
11341 } else {
11342 transmit_response(p, "403 Unauthorized", req);
11343 }
11344 return;
11345 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
11346
11347 transmit_response(p, "200 OK", req);
11348 return;
11349 }
11350
11351
11352
11353
11354
11355 if (!strcasecmp(get_header(req, "Content-Length"), "0")) {
11356 transmit_response(p, "200 OK", req);
11357 return;
11358 }
11359
11360 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
11361 transmit_response(p, "415 Unsupported media type", req);
11362 return;
11363 }
11364
11365
11366 static int sip_do_debug_ip(int fd, int argc, char *argv[])
11367 {
11368 struct hostent *hp;
11369 struct ast_hostent ahp;
11370 int port = 0;
11371 char *p, *arg;
11372
11373
11374 if (argc != 5)
11375 return RESULT_SHOWUSAGE;
11376 p = arg = argv[4];
11377 strsep(&p, ":");
11378 if (p)
11379 port = atoi(p);
11380 hp = ast_gethostbyname(arg, &ahp);
11381 if (hp == NULL)
11382 return RESULT_SHOWUSAGE;
11383
11384 debugaddr.sin_family = AF_INET;
11385 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
11386 debugaddr.sin_port = htons(port);
11387 if (port == 0)
11388 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
11389 else
11390 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
11391
11392 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11393
11394 return RESULT_SUCCESS;
11395 }
11396
11397
11398 static int sip_do_debug_peer(int fd, int argc, char *argv[])
11399 {
11400 struct sip_peer *peer;
11401 if (argc != 5)
11402 return RESULT_SHOWUSAGE;
11403 peer = find_peer(argv[4], NULL, 1);
11404 if (peer) {
11405 if (peer->addr.sin_addr.s_addr) {
11406 debugaddr.sin_family = AF_INET;
11407 debugaddr.sin_addr = peer->addr.sin_addr;
11408 debugaddr.sin_port = peer->addr.sin_port;
11409 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
11410 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11411 } else
11412 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
11413 ASTOBJ_UNREF(peer,sip_destroy_peer);
11414 } else
11415 ast_cli(fd, "No such peer '%s'\n", argv[4]);
11416 return RESULT_SUCCESS;
11417 }
11418
11419
11420 static int sip_do_debug(int fd, int argc, char *argv[])
11421 {
11422 int oldsipdebug = sipdebug_console;
11423 if (argc != 3) {
11424 if (argc != 5)
11425 return RESULT_SHOWUSAGE;
11426 else if (strcmp(argv[3], "ip") == 0)
11427 return sip_do_debug_ip(fd, argc, argv);
11428 else if (strcmp(argv[3], "peer") == 0)
11429 return sip_do_debug_peer(fd, argc, argv);
11430 else
11431 return RESULT_SHOWUSAGE;
11432 }
11433 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11434 memset(&debugaddr, 0, sizeof(debugaddr));
11435 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11436 return RESULT_SUCCESS;
11437 }
11438
11439 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
11440 {
11441 int oldsipdebug = sipdebug_console;
11442 char *newargv[6] = { "sip", "set", "debug", NULL };
11443 if (argc != 2) {
11444 if (argc != 4)
11445 return RESULT_SHOWUSAGE;
11446 else if (strcmp(argv[2], "ip") == 0) {
11447 newargv[3] = argv[2];
11448 newargv[4] = argv[3];
11449 return sip_do_debug_ip(fd, argc + 1, newargv);
11450 } else if (strcmp(argv[2], "peer") == 0) {
11451 newargv[3] = argv[2];
11452 newargv[4] = argv[3];
11453 return sip_do_debug_peer(fd, argc + 1, newargv);
11454 } else
11455 return RESULT_SHOWUSAGE;
11456 }
11457 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11458 memset(&debugaddr, 0, sizeof(debugaddr));
11459 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11460 return RESULT_SUCCESS;
11461 }
11462
11463
11464 static int sip_notify(int fd, int argc, char *argv[])
11465 {
11466 struct ast_variable *varlist;
11467 int i;
11468
11469 if (argc < 4)
11470 return RESULT_SHOWUSAGE;
11471
11472 if (!notify_types) {
11473 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
11474 return RESULT_FAILURE;
11475 }
11476
11477 varlist = ast_variable_browse(notify_types, argv[2]);
11478
11479 if (!varlist) {
11480 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
11481 return RESULT_FAILURE;
11482 }
11483
11484 for (i = 3; i < argc; i++) {
11485 struct sip_pvt *p;
11486 struct sip_request req;
11487 struct ast_variable *var;
11488
11489 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
11490 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
11491 return RESULT_FAILURE;
11492 }
11493
11494 if (create_addr(p, argv[i])) {
11495
11496 sip_destroy(p);
11497 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
11498 continue;
11499 }
11500
11501 initreqprep(&req, p, SIP_NOTIFY);
11502
11503 for (var = varlist; var; var = var->next)
11504 add_header(&req, var->name, ast_unescape_semicolon(var->value));
11505
11506
11507 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
11508 p->ourip = __ourip;
11509 build_via(p);
11510 build_callid_pvt(p);
11511 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
11512 transmit_sip_request(p, &req);
11513 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11514 }
11515
11516 return RESULT_SUCCESS;
11517 }
11518
11519
11520 static int sip_no_debug(int fd, int argc, char *argv[])
11521 {
11522 if (argc != 4)
11523 return RESULT_SHOWUSAGE;
11524 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11525 ast_cli(fd, "SIP Debugging Disabled\n");
11526 return RESULT_SUCCESS;
11527 }
11528
11529 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
11530 {
11531 if (argc != 3)
11532 return RESULT_SHOWUSAGE;
11533 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11534 ast_cli(fd, "SIP Debugging Disabled\n");
11535 return RESULT_SUCCESS;
11536 }
11537
11538
11539 static int sip_do_history(int fd, int argc, char *argv[])
11540 {
11541 if (argc != 2) {
11542 return RESULT_SHOWUSAGE;
11543 }
11544 recordhistory = TRUE;
11545 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
11546 return RESULT_SUCCESS;
11547 }
11548
11549
11550 static int sip_no_history(int fd, int argc, char *argv[])
11551 {
11552 if (argc != 3) {
11553 return RESULT_SHOWUSAGE;
11554 }
11555 recordhistory = FALSE;
11556 ast_cli(fd, "SIP History Recording Disabled\n");
11557 return RESULT_SUCCESS;
11558 }
11559
11560
11561 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11562 {
11563 char digest[1024];
11564 p->authtries++;
11565 memset(digest,0,sizeof(digest));
11566 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11567
11568
11569 if (sip_debug_test_pvt(p) && p->registry)
11570 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11571
11572 return -1;
11573 }
11574 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11575 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11576 if (sip_debug_test_pvt(p) && p->registry)
11577 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11578 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11579 }
11580
11581
11582 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11583 {
11584 char digest[1024];
11585
11586 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11587 return -2;
11588
11589 p->authtries++;
11590 if (option_debug > 1)
11591 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11592 memset(digest, 0, sizeof(digest));
11593 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11594
11595 return -1;
11596 }
11597
11598 p->options->auth = digest;
11599 p->options->authheader = respheader;
11600 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11601 }
11602
11603
11604
11605
11606
11607 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11608 {
11609 char tmp[512];
11610 char *c;
11611 char oldnonce[256];
11612
11613
11614 const struct x {
11615 const char *key;
11616 int field_index;
11617 } *i, keys[] = {
11618 { "realm=", ast_string_field_index(p, realm) },
11619 { "nonce=", ast_string_field_index(p, nonce) },
11620 { "opaque=", ast_string_field_index(p, opaque) },
11621 { "qop=", ast_string_field_index(p, qop) },
11622 { "domain=", ast_string_field_index(p, domain) },
11623 { NULL, 0 },
11624 };
11625
11626 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11627 if (ast_strlen_zero(tmp))
11628 return -1;
11629 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11630 ast_log(LOG_WARNING, "missing Digest.\n");
11631 return -1;
11632 }
11633 c = tmp + strlen("Digest ");
11634 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11635 while (c && *(c = ast_skip_blanks(c))) {
11636 for (i = keys; i->key != NULL; i++) {
11637 char *src, *separator;
11638 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11639 continue;
11640
11641 c += strlen(i->key);
11642 if (*c == '"') {
11643 src = ++c;
11644 separator = "\"";
11645 } else {
11646 src = c;
11647 separator = ",";
11648 }
11649 strsep(&c, separator);
11650 ast_string_field_index_set(p, i->field_index, src);
11651 break;
11652 }
11653 if (i->key == NULL)
11654 strsep(&c, ",");
11655 }
11656
11657 if (strcmp(p->nonce, oldnonce))
11658 p->noncecount = 0;
11659
11660
11661 if (p->registry) {
11662 struct sip_registry *r = p->registry;
11663
11664 if (strcmp(r->nonce, p->nonce)) {
11665 ast_string_field_set(r, realm, p->realm);
11666 ast_string_field_set(r, nonce, p->nonce);
11667 ast_string_field_set(r, domain, p->domain);
11668 ast_string_field_set(r, opaque, p->opaque);
11669 ast_string_field_set(r, qop, p->qop);
11670 r->noncecount = 0;
11671 }
11672 }
11673 return build_reply_digest(p, sipmethod, digest, digest_len);
11674 }
11675
11676
11677
11678
11679
11680
11681 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11682 {
11683 char a1[256];
11684 char a2[256];
11685 char a1_hash[256];
11686 char a2_hash[256];
11687 char resp[256];
11688 char resp_hash[256];
11689 char uri[256];
11690 char opaque[256] = "";
11691 char cnonce[80];
11692 const char *username;
11693 const char *secret;
11694 const char *md5secret;
11695 struct sip_auth *auth = NULL;
11696
11697 if (!ast_strlen_zero(p->domain))
11698 ast_copy_string(uri, p->domain, sizeof(uri));
11699 else if (!ast_strlen_zero(p->uri))
11700 ast_copy_string(uri, p->uri, sizeof(uri));
11701 else
11702 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11703
11704 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11705
11706
11707 if ((auth = find_realm_authentication(authl, p->realm))) {
11708 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
11709 auth->username, p->peername, p->username);
11710 username = auth->username;
11711 secret = auth->secret;
11712 md5secret = auth->md5secret;
11713 if (sipdebug)
11714 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11715 } else {
11716
11717 username = p->authname;
11718 secret = p->peersecret;
11719 md5secret = p->peermd5secret;
11720 }
11721 if (ast_strlen_zero(username))
11722 return -1;
11723
11724
11725 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11726 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11727 if (!ast_strlen_zero(md5secret))
11728 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11729 else
11730 ast_md5_hash(a1_hash,a1);
11731 ast_md5_hash(a2_hash,a2);
11732
11733 p->noncecount++;
11734 if (!ast_strlen_zero(p->qop))
11735 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11736 else
11737 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11738 ast_md5_hash(resp_hash, resp);
11739
11740
11741 if (!ast_strlen_zero(p->opaque)) {
11742 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
11743 }
11744
11745
11746 if (!ast_strlen_zero(p->qop))
11747 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
11748 else
11749 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
11750
11751 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11752
11753 return 0;
11754 }
11755
11756 static char show_domains_usage[] =
11757 "Usage: sip show domains\n"
11758 " Lists all configured SIP local domains.\n"
11759 " Asterisk only responds to SIP messages to local domains.\n";
11760
11761 static char notify_usage[] =
11762 "Usage: sip notify <type> <peer> [<peer>...]\n"
11763 " Send a NOTIFY message to a SIP peer or peers\n"
11764 " Message types are defined in sip_notify.conf\n";
11765
11766 static char show_users_usage[] =
11767 "Usage: sip show users [like <pattern>]\n"
11768 " Lists all known SIP users.\n"
11769 " Optional regular expression pattern is used to filter the user list.\n";
11770
11771 static char show_user_usage[] =
11772 "Usage: sip show user <name> [load]\n"
11773 " Shows all details on one SIP user and the current status.\n"
11774 " Option \"load\" forces lookup of peer in realtime storage.\n";
11775
11776 static char show_inuse_usage[] =
11777 "Usage: sip show inuse [all]\n"
11778 " List all SIP users and peers usage counters and limits.\n"
11779 " Add option \"all\" to show all devices, not only those with a limit.\n";
11780
11781 static char show_channels_usage[] =
11782 "Usage: sip show channels\n"
11783 " Lists all currently active SIP channels.\n";
11784
11785 static char show_channel_usage[] =
11786 "Usage: sip show channel <channel>\n"
11787 " Provides detailed status on a given SIP channel.\n";
11788
11789 static char show_history_usage[] =
11790 "Usage: sip show history <channel>\n"
11791 " Provides detailed dialog history on a given SIP channel.\n";
11792
11793 static char show_peers_usage[] =
11794 "Usage: sip show peers [like <pattern>]\n"
11795 " Lists all known SIP peers.\n"
11796 " Optional regular expression pattern is used to filter the peer list.\n";
11797
11798 static char show_peer_usage[] =
11799 "Usage: sip show peer <name> [load]\n"
11800 " Shows all details on one SIP peer and the current status.\n"
11801 " Option \"load\" forces lookup of peer in realtime storage.\n";
11802
11803 static char prune_realtime_usage[] =
11804 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11805 " Prunes object(s) from the cache.\n"
11806 " Optional regular expression pattern is used to filter the objects.\n";
11807
11808 static char show_reg_usage[] =
11809 "Usage: sip show registry\n"
11810 " Lists all registration requests and status.\n";
11811
11812 static char debug_usage[] =
11813 "Usage: sip set debug\n"
11814 " Enables dumping of SIP packets for debugging purposes\n\n"
11815 " sip set debug ip <host[:PORT]>\n"
11816 " Enables dumping of SIP packets to and from host.\n\n"
11817 " sip set debug peer <peername>\n"
11818 " Enables dumping of SIP packets to and from host.\n"
11819 " Require peer to be registered.\n";
11820
11821 static char no_debug_usage[] =
11822 "Usage: sip set debug off\n"
11823 " Disables dumping of SIP packets for debugging purposes\n";
11824
11825 static char no_history_usage[] =
11826 "Usage: sip history off\n"
11827 " Disables recording of SIP dialog history for debugging purposes\n";
11828
11829 static char history_usage[] =
11830 "Usage: sip history\n"
11831 " Enables recording of SIP dialog history for debugging purposes.\n"
11832 "Use 'sip show history' to view the history of a call number.\n";
11833
11834 static char sip_reload_usage[] =
11835 "Usage: sip reload\n"
11836 " Reloads SIP configuration from sip.conf\n";
11837
11838 static char show_subscriptions_usage[] =
11839 "Usage: sip show subscriptions\n"
11840 " Lists active SIP subscriptions for extension states\n";
11841
11842 static char show_objects_usage[] =
11843 "Usage: sip show objects\n"
11844 " Lists status of known SIP objects\n";
11845
11846 static char show_settings_usage[] =
11847 "Usage: sip show settings\n"
11848 " Provides detailed list of the configuration of the SIP channel.\n";
11849
11850
11851 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11852 {
11853 struct sip_pvt *p;
11854 const char *content = NULL;
11855 AST_DECLARE_APP_ARGS(args,
11856 AST_APP_ARG(header);
11857 AST_APP_ARG(number);
11858 );
11859 int i, number, start = 0;
11860
11861 if (ast_strlen_zero(data)) {
11862 ast_log(LOG_WARNING, "This function requires a header name.\n");
11863 return -1;
11864 }
11865
11866 ast_channel_lock(chan);
11867 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11868 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11869 ast_channel_unlock(chan);
11870 return -1;
11871 }
11872
11873 AST_STANDARD_APP_ARGS(args, data);
11874 if (!args.number) {
11875 number = 1;
11876 } else {
11877 sscanf(args.number, "%d", &number);
11878 if (number < 1)
11879 number = 1;
11880 }
11881
11882 p = chan->tech_pvt;
11883
11884
11885 if (!p) {
11886 ast_channel_unlock(chan);
11887 return -1;
11888 }
11889
11890 for (i = 0; i < number; i++)
11891 content = __get_header(&p->initreq, args.header, &start);
11892
11893 if (ast_strlen_zero(content)) {
11894 ast_channel_unlock(chan);
11895 return -1;
11896 }
11897
11898 ast_copy_string(buf, content, len);
11899 ast_channel_unlock(chan);
11900
11901 return 0;
11902 }
11903
11904 static struct ast_custom_function sip_header_function = {
11905 .name = "SIP_HEADER",
11906 .synopsis = "Gets the specified SIP header",
11907 .syntax = "SIP_HEADER(<name>[,<number>])",
11908 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11909 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11910 "that name to retrieve. Headers start at offset 1.\n",
11911 .read = func_header_read,
11912 };
11913
11914
11915 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11916 {
11917 if (ast_strlen_zero(data)) {
11918 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11919 return -1;
11920 }
11921 if (check_sip_domain(data, NULL, 0))
11922 ast_copy_string(buf, data, len);
11923 else
11924 buf[0] = '\0';
11925 return 0;
11926 }
11927
11928 static struct ast_custom_function checksipdomain_function = {
11929 .name = "CHECKSIPDOMAIN",
11930 .synopsis = "Checks if domain is a local domain",
11931 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11932 .read = func_check_sipdomain,
11933 .desc = "This function checks if the domain in the argument is configured\n"
11934 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11935 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11936 "Check the domain= configuration in sip.conf\n",
11937 };
11938
11939
11940 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11941 {
11942 struct sip_peer *peer;
11943 char *colname;
11944
11945 if ((colname = strchr(data, ':')))
11946 *colname++ = '\0';
11947 else if ((colname = strchr(data, '|')))
11948 *colname++ = '\0';
11949 else
11950 colname = "ip";
11951
11952 if (!(peer = find_peer(data, NULL, 1)))
11953 return -1;
11954
11955 if (!strcasecmp(colname, "ip")) {
11956 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11957 } else if (!strcasecmp(colname, "status")) {
11958 peer_status(peer, buf, len);
11959 } else if (!strcasecmp(colname, "language")) {
11960 ast_copy_string(buf, peer->language, len);
11961 } else if (!strcasecmp(colname, "regexten")) {
11962 ast_copy_string(buf, peer->regexten, len);
11963 } else if (!strcasecmp(colname, "limit")) {
11964 snprintf(buf, len, "%d", peer->call_limit);
11965 } else if (!strcasecmp(colname, "curcalls")) {
11966 snprintf(buf, len, "%d", peer->inUse);
11967 } else if (!strcasecmp(colname, "accountcode")) {
11968 ast_copy_string(buf, peer->accountcode, len);
11969 } else if (!strcasecmp(colname, "useragent")) {
11970 ast_copy_string(buf, peer->useragent, len);
11971 } else if (!strcasecmp(colname, "mailbox")) {
11972 ast_copy_string(buf, peer->mailbox, len);
11973 } else if (!strcasecmp(colname, "context")) {
11974 ast_copy_string(buf, peer->context, len);
11975 } else if (!strcasecmp(colname, "expire")) {
11976 snprintf(buf, len, "%d", peer->expire);
11977 } else if (!strcasecmp(colname, "dynamic")) {
11978 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11979 } else if (!strcasecmp(colname, "callerid_name")) {
11980 ast_copy_string(buf, peer->cid_name, len);
11981 } else if (!strcasecmp(colname, "callerid_num")) {
11982 ast_copy_string(buf, peer->cid_num, len);
11983 } else if (!strcasecmp(colname, "codecs")) {
11984 ast_getformatname_multiple(buf, len -1, peer->capability);
11985 } else if (!strncasecmp(colname, "codec[", 6)) {
11986 char *codecnum;
11987 int index = 0, codec = 0;
11988
11989 codecnum = colname + 6;
11990 codecnum = strsep(&codecnum, "]");
11991 index = atoi(codecnum);
11992 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11993 ast_copy_string(buf, ast_getformatname(codec), len);
11994 }
11995 }
11996
11997 ASTOBJ_UNREF(peer, sip_destroy_peer);
11998
11999 return 0;
12000 }
12001
12002
12003 struct ast_custom_function sippeer_function = {
12004 .name = "SIPPEER",
12005 .synopsis = "Gets SIP peer information",
12006 .syntax = "SIPPEER(<peername>[|item])",
12007 .read = function_sippeer,
12008 .desc = "Valid items are:\n"
12009 "- ip (default) The IP address.\n"
12010 "- mailbox The configured mailbox.\n"
12011 "- context The configured context.\n"
12012 "- expire The epoch time of the next expire.\n"
12013 "- dynamic Is it dynamic? (yes/no).\n"
12014 "- callerid_name The configured Caller ID name.\n"
12015 "- callerid_num The configured Caller ID number.\n"
12016 "- codecs The configured codecs.\n"
12017 "- status Status (if qualify=yes).\n"
12018 "- regexten Registration extension\n"
12019 "- limit Call limit (call-limit)\n"
12020 "- curcalls Current amount of calls \n"
12021 " Only available if call-limit is set\n"
12022 "- language Default language for peer\n"
12023 "- accountcode Account code for this peer\n"
12024 "- useragent Current user agent id for peer\n"
12025 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
12026 "\n"
12027 };
12028
12029
12030 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
12031 {
12032 struct sip_pvt *p;
12033
12034 *buf = 0;
12035
12036 if (!data) {
12037 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
12038 return -1;
12039 }
12040
12041 ast_channel_lock(chan);
12042 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
12043 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
12044 ast_channel_unlock(chan);
12045 return -1;
12046 }
12047
12048 p = chan->tech_pvt;
12049
12050
12051 if (!p) {
12052 ast_channel_unlock(chan);
12053 return -1;
12054 }
12055
12056 if (!strcasecmp(data, "peerip")) {
12057 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
12058 } else if (!strcasecmp(data, "recvip")) {
12059 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
12060 } else if (!strcasecmp(data, "from")) {
12061 ast_copy_string(buf, p->from, len);
12062 } else if (!strcasecmp(data, "uri")) {
12063 ast_copy_string(buf, p->uri, len);
12064 } else if (!strcasecmp(data, "useragent")) {
12065 ast_copy_string(buf, p->useragent, len);
12066 } else if (!strcasecmp(data, "peername")) {
12067 ast_copy_string(buf, p->peername, len);
12068 } else if (!strcasecmp(data, "t38passthrough")) {
12069 if (p->t38.state == T38_DISABLED)
12070 ast_copy_string(buf, "0", sizeof("0"));
12071 else
12072 ast_copy_string(buf, "1", sizeof("1"));
12073 } else {
12074 ast_channel_unlock(chan);
12075 return -1;
12076 }
12077 ast_channel_unlock(chan);
12078
12079 return 0;
12080 }
12081
12082
12083 static struct ast_custom_function sipchaninfo_function = {
12084 .name = "SIPCHANINFO",
12085 .synopsis = "Gets the specified SIP parameter from the current channel",
12086 .syntax = "SIPCHANINFO(item)",
12087 .read = function_sipchaninfo_read,
12088 .desc = "Valid items are:\n"
12089 "- peerip The IP address of the peer.\n"
12090 "- recvip The source IP address of the peer.\n"
12091 "- from The URI from the From: header.\n"
12092 "- uri The URI from the Contact: header.\n"
12093 "- useragent The useragent.\n"
12094 "- peername The name of the peer.\n"
12095 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
12096 };
12097
12098
12099 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
12100 {
12101 char tmp[SIPBUFSIZE];
12102 char *s, *e, *uri, *t;
12103 char *domain;
12104
12105 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
12106 if ((t = strchr(tmp, ',')))
12107 *t = '\0';
12108 s = get_in_brackets(tmp);
12109 uri = ast_strdupa(s);
12110 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
12111 if (!strncasecmp(s, "sip:", 4))
12112 s += 4;
12113 e = strchr(s, ';');
12114 if (e)
12115 *e = '\0';
12116 if (option_debug)
12117 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
12118 if (p->owner)
12119 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
12120 } else {
12121 e = strchr(tmp, '@');
12122 if (e) {
12123 *e++ = '\0';
12124 domain = e;
12125 } else {
12126
12127 domain = tmp;
12128 }
12129 e = strchr(s, ';');
12130 if (e)
12131 *e = '\0';
12132 e = strchr(domain, ';');
12133 if (e)
12134 *e = '\0';
12135
12136 if (!strncasecmp(s, "sip:", 4))
12137 s += 4;
12138 if (option_debug > 1)
12139 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
12140 if (p->owner) {
12141 pbx_builtin_setvar_helper(p->owner, "SIPREDIRECTURI", uri);
12142 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
12143 ast_string_field_set(p->owner, call_forward, s);
12144 }
12145 }
12146 }
12147
12148
12149 static void check_pendings(struct sip_pvt *p)
12150 {
12151 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
12152
12153 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
12154 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
12155
12156
12157 else {
12158
12159
12160 if (p->pendinginvite)
12161 return;
12162
12163
12164 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
12165 }
12166 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
12167 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12168 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
12169
12170 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
12171 if (option_debug)
12172 ast_log(LOG_DEBUG, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
12173 } else {
12174 if (option_debug)
12175 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
12176
12177 transmit_reinvite_with_sdp(p);
12178 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
12179 }
12180 }
12181 }
12182
12183
12184
12185
12186
12187 static int sip_reinvite_retry(const void *data)
12188 {
12189 struct sip_pvt *p = (struct sip_pvt *) data;
12190
12191 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12192 p->waitid = -1;
12193 return 0;
12194 }
12195
12196
12197
12198 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12199 {
12200 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
12201 int res = 0;
12202 int xmitres = 0;
12203 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
12204 struct ast_channel *bridgepeer = NULL;
12205
12206 if (option_debug > 3) {
12207 if (reinvite)
12208 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
12209 else
12210 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
12211 }
12212
12213 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
12214 if (option_debug)
12215 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
12216 return;
12217 }
12218
12219
12220
12221 AST_SCHED_DEL(sched, p->initid);
12222
12223
12224
12225
12226 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
12227 resp = 183;
12228
12229
12230 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
12231 p->invitestate = INV_PROCEEDING;
12232
12233
12234 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
12235 p->invitestate = INV_COMPLETED;
12236
12237
12238 switch (resp) {
12239 case 100:
12240 case 101:
12241 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12242 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12243 check_pendings(p);
12244 break;
12245
12246 case 180:
12247 case 182:
12248 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12249 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12250 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12251 ast_queue_control(p->owner, AST_CONTROL_RINGING);
12252 if (p->owner->_state != AST_STATE_UP) {
12253 ast_setstate(p->owner, AST_STATE_RINGING);
12254 }
12255 }
12256 if (find_sdp(req)) {
12257 if (p->invitestate != INV_CANCELLED)
12258 p->invitestate = INV_EARLY_MEDIA;
12259 res = process_sdp(p, req);
12260 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12261
12262 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12263 }
12264 }
12265 check_pendings(p);
12266 break;
12267
12268 case 183:
12269 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12270 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12271
12272 if (find_sdp(req)) {
12273 if (p->invitestate != INV_CANCELLED)
12274 p->invitestate = INV_EARLY_MEDIA;
12275 res = process_sdp(p, req);
12276 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12277
12278 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12279 }
12280 }
12281 check_pendings(p);
12282 break;
12283
12284 case 200:
12285 if (!ast_test_flag(req, SIP_PKT_IGNORE) && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
12286 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12287 p->authtries = 0;
12288 if (find_sdp(req)) {
12289 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
12290 if (!reinvite)
12291
12292
12293 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12294 }
12295
12296
12297
12298
12299 if (outgoing) {
12300 update_call_counter(p, DEC_CALL_RINGING);
12301 parse_ok_contact(p, req);
12302 if(set_address_from_contact(p)) {
12303
12304
12305
12306
12307
12308
12309
12310 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12311 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12312 }
12313
12314
12315 if (!reinvite)
12316 build_route(p, req, 1);
12317 }
12318
12319 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) {
12320 struct sip_pvt *bridgepvt = NULL;
12321
12322 if (!bridgepeer->tech) {
12323 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
12324 break;
12325 }
12326 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
12327 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
12328 if (bridgepvt->udptl) {
12329 if (p->t38.state == T38_PEER_REINVITE) {
12330 sip_handle_t38_reinvite(bridgepeer, p, 0);
12331 ast_rtp_set_rtptimers_onhold(p->rtp);
12332 if (p->vrtp)
12333 ast_rtp_set_rtptimers_onhold(p->vrtp);
12334 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
12335 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
12336
12337
12338 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12339 }
12340 } else {
12341 if (option_debug > 1)
12342 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
12343 ast_mutex_lock(&bridgepvt->lock);
12344 bridgepvt->t38.state = T38_DISABLED;
12345 ast_mutex_unlock(&bridgepvt->lock);
12346 if (option_debug)
12347 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
12348 p->t38.state = T38_DISABLED;
12349 if (option_debug > 1)
12350 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12351 }
12352 } else {
12353
12354 if (option_debug > 1)
12355 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
12356 p->t38.state = T38_DISABLED;
12357 if (option_debug > 1)
12358 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12359 }
12360 }
12361 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
12362
12363 p->t38.state = T38_ENABLED;
12364 if (option_debug)
12365 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12366 }
12367
12368 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12369 if (!reinvite) {
12370 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
12371 } else {
12372 ast_queue_frame(p->owner, &ast_null_frame);
12373 }
12374 } else {
12375
12376
12377
12378 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12379 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12380 }
12381
12382 p->invitestate = INV_TERMINATED;
12383 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
12384 check_pendings(p);
12385 break;
12386 case 407:
12387 case 401:
12388
12389 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12390 if (p->options)
12391 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
12392
12393
12394 ast_string_field_free(p, theirtag);
12395 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12396 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
12397 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
12398 if (p->authtries < MAX_AUTHTRIES)
12399 p->invitestate = INV_CALLING;
12400 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
12401 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
12402 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12403 sip_alreadygone(p);
12404 if (p->owner)
12405 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12406 }
12407 }
12408 break;
12409
12410 case 403:
12411
12412 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12413 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
12414 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
12415 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12416 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12417 sip_alreadygone(p);
12418 break;
12419
12420 case 404:
12421 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12422 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12423 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12424 sip_alreadygone(p);
12425 break;
12426
12427 case 408:
12428 case 481:
12429
12430 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
12431 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12432 if (p->owner)
12433 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12434 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12435 break;
12436 case 487:
12437
12438
12439
12440 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12441 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12442 ast_queue_hangup(p->owner);
12443 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
12444 } else if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12445 update_call_counter(p, DEC_CALL_LIMIT);
12446 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
12447 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12448 sip_alreadygone(p);
12449 }
12450 break;
12451 case 488:
12452 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12453 if (reinvite && p->udptl) {
12454
12455
12456
12457
12458
12459 p->t38.state = T38_DISABLED;
12460
12461 ast_rtp_set_rtptimers_onhold(p->rtp);
12462 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
12463
12464
12465
12466
12467
12468 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12469 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12470 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12471 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
12472
12473
12474
12475 p->t38.state = T38_DISABLED;
12476
12477 ast_rtp_set_rtptimers_onhold(p->rtp);
12478 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
12479
12480
12481 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12482 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12483 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12484 sip_alreadygone(p);
12485 } else {
12486
12487 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12488 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12489 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12490
12491 if (!reinvite)
12492 sip_alreadygone(p);
12493 }
12494 break;
12495 case 491:
12496
12497
12498
12499
12500 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12501 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12502 if (p->owner->_state != AST_STATE_UP) {
12503 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12504 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12505 } else {
12506
12507
12508
12509 int wait = 3 + ast_random() % 5;
12510 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, p);
12511 if (option_debug > 2)
12512 ast_log(LOG_DEBUG, "Reinvite race. Waiting %d secs before retry\n", wait);
12513 }
12514 }
12515 break;
12516
12517 case 501:
12518 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12519 if (p->owner)
12520 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12521 break;
12522 }
12523 if (xmitres == XMIT_ERROR)
12524 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
12525 }
12526
12527
12528
12529
12530 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12531 {
12532 char *auth = "Proxy-Authenticate";
12533 char *auth2 = "Proxy-Authorization";
12534
12535
12536 if (!p->refer)
12537 return;
12538
12539 switch (resp) {
12540 case 202:
12541
12542
12543 p->refer->status = REFER_ACCEPTED;
12544
12545 if (option_debug > 2)
12546 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
12547
12548 break;
12549
12550 case 401:
12551 case 407:
12552 if (ast_strlen_zero(p->authname)) {
12553 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
12554 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12555 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12556 }
12557 if (resp == 401) {
12558 auth = "WWW-Authenticate";
12559 auth2 = "Authorization";
12560 }
12561 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
12562 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
12563 p->refer->status = REFER_NOAUTH;
12564 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12565 }
12566 break;
12567 case 481:
12568
12569
12570
12571
12572 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
12573 if (p->owner)
12574 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12575 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12576 break;
12577
12578 case 500:
12579 case 501:
12580
12581
12582 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
12583 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12584 p->refer->status = REFER_FAILED;
12585 break;
12586 case 603:
12587 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
12588 p->refer->status = REFER_FAILED;
12589 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12590 break;
12591 }
12592 }
12593
12594
12595 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12596 {
12597 int expires, expires_ms;
12598 struct sip_registry *r;
12599 r=p->registry;
12600
12601 switch (resp) {
12602 case 401:
12603 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
12604 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
12605 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12606 }
12607 break;
12608 case 403:
12609 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
12610 if (global_regattempts_max)
12611 p->registry->regattempts = global_regattempts_max+1;
12612 AST_SCHED_DEL(sched, r->timeout);
12613 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12614 break;
12615 case 404:
12616 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
12617 if (global_regattempts_max)
12618 p->registry->regattempts = global_regattempts_max+1;
12619 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12620 r->call = NULL;
12621 AST_SCHED_DEL(sched, r->timeout);
12622 break;
12623 case 407:
12624 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12625 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12626 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12627 }
12628 break;
12629 case 408:
12630 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12631 r->call = NULL;
12632 AST_SCHED_DEL(sched, r->timeout);
12633 break;
12634 case 479:
12635 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12636 if (global_regattempts_max)
12637 p->registry->regattempts = global_regattempts_max+1;
12638 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12639 r->call = NULL;
12640 AST_SCHED_DEL(sched, r->timeout);
12641 break;
12642 case 200:
12643 if (!r) {
12644 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12645 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12646 return 0;
12647 }
12648
12649 r->regstate = REG_STATE_REGISTERED;
12650 r->regtime = time(NULL);
12651 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12652 r->regattempts = 0;
12653 if (option_debug)
12654 ast_log(LOG_DEBUG, "Registration successful\n");
12655 if (r->timeout > -1) {
12656 if (option_debug)
12657 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12658 }
12659 AST_SCHED_DEL(sched, r->timeout);
12660 r->call = NULL;
12661 p->registry = NULL;
12662
12663 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12664
12665
12666
12667
12668 AST_SCHED_DEL(sched, r->expire);
12669
12670
12671 expires = 0;
12672
12673
12674 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12675 const char *contact = NULL;
12676 const char *tmptmp = NULL;
12677 int start = 0;
12678 for(;;) {
12679 contact = __get_header(req, "Contact", &start);
12680
12681 if(!ast_strlen_zero(contact)) {
12682 if( (tmptmp=strstr(contact, p->our_contact))) {
12683 contact=tmptmp;
12684 break;
12685 }
12686 } else
12687 break;
12688 }
12689 tmptmp = strcasestr(contact, "expires=");
12690 if (tmptmp) {
12691 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12692 expires = 0;
12693 }
12694
12695 }
12696 if (!expires)
12697 expires=atoi(get_header(req, "expires"));
12698 if (!expires)
12699 expires=default_expiry;
12700
12701 expires_ms = expires * 1000;
12702 if (expires <= EXPIRY_GUARD_LIMIT)
12703 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12704 else
12705 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12706 if (sipdebug)
12707 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12708
12709 r->refresh= (int) expires_ms / 1000;
12710
12711
12712 AST_SCHED_DEL(sched, r->expire);
12713 r->expire = ast_sched_add(sched, expires_ms, sip_reregister, r);
12714 ASTOBJ_UNREF(r, sip_registry_destroy);
12715 }
12716 return 1;
12717 }
12718
12719
12720 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12721 {
12722 struct sip_peer *peer = p->relatedpeer;
12723 int statechanged, is_reachable, was_reachable;
12724 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12725
12726
12727
12728
12729
12730
12731 if (pingtime < 1)
12732 pingtime = 1;
12733
12734
12735
12736
12737
12738 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12739 is_reachable = pingtime <= peer->maxms;
12740 statechanged = peer->lastms == 0
12741 || was_reachable != is_reachable;
12742
12743 peer->lastms = pingtime;
12744 peer->call = NULL;
12745 if (statechanged) {
12746 const char *s = is_reachable ? "Reachable" : "Lagged";
12747
12748 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12749 peer->name, s, pingtime, peer->maxms);
12750 ast_device_state_changed("SIP/%s", peer->name);
12751 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12752 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12753 peer->name, s, pingtime);
12754 }
12755
12756 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12757 struct sip_peer *peer_ptr = peer;
12758 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
12759 }
12760
12761 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12762
12763
12764 peer->pokeexpire = ast_sched_add(sched,
12765 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12766 sip_poke_peer_s, ASTOBJ_REF(peer));
12767
12768 if (peer->pokeexpire == -1) {
12769 ASTOBJ_UNREF(peer, sip_destroy_peer);
12770 }
12771 }
12772
12773
12774 static void stop_media_flows(struct sip_pvt *p)
12775 {
12776
12777 if (p->rtp)
12778 ast_rtp_stop(p->rtp);
12779 if (p->vrtp)
12780 ast_rtp_stop(p->vrtp);
12781 if (p->udptl)
12782 ast_udptl_stop(p->udptl);
12783 }
12784
12785
12786
12787 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12788 {
12789 struct ast_channel *owner;
12790 int sipmethod;
12791 int res = 1;
12792 const char *c = get_header(req, "Cseq");
12793 const char *msg = strchr(c, ' ');
12794
12795 if (!msg)
12796 msg = "";
12797 else
12798 msg++;
12799 sipmethod = find_sip_method(msg);
12800
12801 owner = p->owner;
12802 if (owner)
12803 owner->hangupcause = hangup_sip2cause(resp);
12804
12805
12806 if ((resp >= 100) && (resp <= 199))
12807 __sip_semi_ack(p, seqno, 0, sipmethod);
12808 else
12809 __sip_ack(p, seqno, 0, sipmethod);
12810
12811
12812 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
12813 p->pendinginvite = 0;
12814
12815
12816 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12817 char tag[128];
12818
12819 gettag(req, "To", tag, sizeof(tag));
12820 ast_string_field_set(p, theirtag, tag);
12821 }
12822 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12823
12824
12825
12826 if (resp != 100)
12827 handle_response_peerpoke(p, resp, req);
12828 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12829 switch(resp) {
12830 case 100:
12831 case 101:
12832 if (sipmethod == SIP_INVITE)
12833 handle_response_invite(p, resp, rest, req, seqno);
12834 break;
12835 case 183:
12836 if (sipmethod == SIP_INVITE)
12837 handle_response_invite(p, resp, rest, req, seqno);
12838 break;
12839 case 180:
12840 if (sipmethod == SIP_INVITE)
12841 handle_response_invite(p, resp, rest, req, seqno);
12842 break;
12843 case 182:
12844 if (sipmethod == SIP_INVITE)
12845 handle_response_invite(p, resp, rest, req, seqno);
12846 break;
12847 case 200:
12848 p->authtries = 0;
12849 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
12850
12851
12852
12853 } else if (sipmethod == SIP_INVITE) {
12854 handle_response_invite(p, resp, rest, req, seqno);
12855 } else if (sipmethod == SIP_NOTIFY) {
12856
12857 if (p->owner) {
12858 if (!p->refer) {
12859 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12860 ast_queue_hangup(p->owner);
12861 } else if (option_debug > 3)
12862 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12863 } else {
12864 if (p->subscribed == NONE)
12865 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12866 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
12867
12868 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12869 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
12870 }
12871 }
12872 } else if (sipmethod == SIP_REGISTER)
12873 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12874 else if (sipmethod == SIP_BYE)
12875 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12876 break;
12877 case 202:
12878 if (sipmethod == SIP_REFER)
12879 handle_response_refer(p, resp, rest, req, seqno);
12880 break;
12881 case 401:
12882 if (sipmethod == SIP_INVITE)
12883 handle_response_invite(p, resp, rest, req, seqno);
12884 else if (sipmethod == SIP_REFER)
12885 handle_response_refer(p, resp, rest, req, seqno);
12886 else if (p->registry && sipmethod == SIP_REGISTER)
12887 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12888 else if (sipmethod == SIP_BYE) {
12889 if (ast_strlen_zero(p->authname)) {
12890 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12891 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12892 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12893 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", sipmethod, 0)) {
12894 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12895 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12896
12897
12898 }
12899 } else {
12900 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12901 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12902 }
12903 break;
12904 case 403:
12905 if (sipmethod == SIP_INVITE)
12906 handle_response_invite(p, resp, rest, req, seqno);
12907 else if (p->registry && sipmethod == SIP_REGISTER)
12908 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12909 else {
12910 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12911 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12912 }
12913 break;
12914 case 404:
12915 if (p->registry && sipmethod == SIP_REGISTER)
12916 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12917 else if (sipmethod == SIP_INVITE)
12918 handle_response_invite(p, resp, rest, req, seqno);
12919 else if (owner)
12920 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12921 break;
12922 case 407:
12923 if (sipmethod == SIP_INVITE)
12924 handle_response_invite(p, resp, rest, req, seqno);
12925 else if (sipmethod == SIP_REFER)
12926 handle_response_refer(p, resp, rest, req, seqno);
12927 else if (p->registry && sipmethod == SIP_REGISTER)
12928 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12929 else if (sipmethod == SIP_BYE) {
12930 if (ast_strlen_zero(p->authname)) {
12931 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12932 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12933 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12934 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12935 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12936 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12937 }
12938 } else
12939 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12940
12941 break;
12942 case 408:
12943 if (sipmethod == SIP_INVITE)
12944 handle_response_invite(p, resp, rest, req, seqno);
12945 else if (sipmethod == SIP_REGISTER)
12946 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12947 else if (sipmethod == SIP_BYE) {
12948 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12949 if (option_debug)
12950 ast_log(LOG_DEBUG, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
12951 } else {
12952 if (owner)
12953 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12954 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12955 }
12956 break;
12957 case 481:
12958 if (sipmethod == SIP_INVITE) {
12959 handle_response_invite(p, resp, rest, req, seqno);
12960 } else if (sipmethod == SIP_REFER) {
12961 handle_response_refer(p, resp, rest, req, seqno);
12962 } else if (sipmethod == SIP_BYE) {
12963
12964
12965 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12966 } else if (sipmethod == SIP_CANCEL) {
12967
12968
12969 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12970 } else {
12971 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12972
12973 }
12974 break;
12975 case 487:
12976 if (sipmethod == SIP_INVITE)
12977 handle_response_invite(p, resp, rest, req, seqno);
12978 break;
12979 case 488:
12980 if (sipmethod == SIP_INVITE)
12981 handle_response_invite(p, resp, rest, req, seqno);
12982 break;
12983 case 491:
12984 if (sipmethod == SIP_INVITE)
12985 handle_response_invite(p, resp, rest, req, seqno);
12986 else {
12987 if (option_debug)
12988 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
12989 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12990 }
12991 break;
12992 case 501:
12993 if (sipmethod == SIP_INVITE)
12994 handle_response_invite(p, resp, rest, req, seqno);
12995 else if (sipmethod == SIP_REFER)
12996 handle_response_refer(p, resp, rest, req, seqno);
12997 else
12998 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
12999 break;
13000 case 603:
13001 if (sipmethod == SIP_REFER) {
13002 handle_response_refer(p, resp, rest, req, seqno);
13003 break;
13004 }
13005
13006 default:
13007 if ((resp >= 300) && (resp < 700)) {
13008
13009 if ((option_verbose > 2) && (resp != 487))
13010 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
13011
13012 if (sipmethod == SIP_INVITE)
13013 stop_media_flows(p);
13014
13015
13016 switch(resp) {
13017 case 300:
13018 case 301:
13019 case 302:
13020 case 305:
13021 parse_moved_contact(p, req);
13022
13023 case 486:
13024 case 600:
13025 case 603:
13026 if (p->owner)
13027 ast_queue_control(p->owner, AST_CONTROL_BUSY);
13028 break;
13029 case 482:
13030
13031
13032
13033
13034 if (option_debug)
13035 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
13036 if (p->owner)
13037 ast_string_field_build(p->owner, call_forward,
13038 "Local/%s@%s", p->username, p->context);
13039
13040 case 480:
13041 case 404:
13042 case 410:
13043 case 400:
13044 case 500:
13045 if (sipmethod == SIP_REFER) {
13046 handle_response_refer(p, resp, rest, req, seqno);
13047 break;
13048 }
13049
13050 case 502:
13051 case 503:
13052 case 504:
13053 if (owner)
13054 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
13055 break;
13056 default:
13057
13058 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
13059 ast_queue_hangup(p->owner);
13060 break;
13061 }
13062
13063 if (sipmethod == SIP_INVITE)
13064 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
13065 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
13066 sip_alreadygone(p);
13067 if (!p->owner)
13068 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13069 } else if ((resp >= 100) && (resp < 200)) {
13070 if (sipmethod == SIP_INVITE) {
13071 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13072 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13073 if (find_sdp(req))
13074 process_sdp(p, req);
13075 if (p->owner) {
13076
13077 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
13078 }
13079 }
13080 } else
13081 ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
13082 }
13083 } else {
13084
13085
13086 if (ast_test_flag(req, SIP_PKT_DEBUG))
13087 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
13088
13089 if (sipmethod == SIP_INVITE && resp == 200) {
13090
13091
13092 char tag[128];
13093
13094 gettag(req, "To", tag, sizeof(tag));
13095 ast_string_field_set(p, theirtag, tag);
13096 }
13097
13098 switch(resp) {
13099 case 200:
13100 if (sipmethod == SIP_INVITE) {
13101 handle_response_invite(p, resp, rest, req, seqno);
13102 } else if (sipmethod == SIP_CANCEL) {
13103 if (option_debug)
13104 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
13105
13106
13107 } else if (sipmethod == SIP_NOTIFY) {
13108
13109 if (p->owner) {
13110 if (p->refer) {
13111 if (option_debug)
13112 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
13113 } else
13114 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
13115
13116 } else {
13117 if (!p->subscribed && !p->refer)
13118 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13119 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
13120
13121 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13122 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
13123 }
13124 }
13125 } else if (sipmethod == SIP_BYE)
13126 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13127 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
13128
13129
13130 ;
13131 else if (sipmethod == SIP_BYE)
13132
13133 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13134 break;
13135 case 202:
13136 if (sipmethod == SIP_REFER)
13137 handle_response_refer(p, resp, rest, req, seqno);
13138 break;
13139 case 401:
13140 case 407:
13141 if (sipmethod == SIP_REFER)
13142 handle_response_refer(p, resp, rest, req, seqno);
13143 else if (sipmethod == SIP_INVITE)
13144 handle_response_invite(p, resp, rest, req, seqno);
13145 else if (sipmethod == SIP_BYE) {
13146 char *auth, *auth2;
13147
13148 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
13149 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
13150 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
13151 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
13152 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13153 }
13154 }
13155 break;
13156 case 481:
13157 if (sipmethod == SIP_INVITE) {
13158
13159 handle_response_invite(p, resp, rest, req, seqno);
13160 } else if (sipmethod == SIP_BYE) {
13161 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13162 } else if (sipdebug) {
13163 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
13164 }
13165 break;
13166 case 501:
13167 if (sipmethod == SIP_INVITE)
13168 handle_response_invite(p, resp, rest, req, seqno);
13169 else if (sipmethod == SIP_REFER)
13170 handle_response_refer(p, resp, rest, req, seqno);
13171 break;
13172 case 603:
13173 if (sipmethod == SIP_REFER) {
13174 handle_response_refer(p, resp, rest, req, seqno);
13175 break;
13176 }
13177
13178 default:
13179 if ((resp >= 100) && (resp < 200)) {
13180 if (sipmethod == SIP_INVITE) {
13181 if (!ast_test_flag(req, SIP_PKT_IGNORE) && sip_cancel_destroy(p))
13182 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13183 }
13184 }
13185 if ((resp >= 300) && (resp < 700)) {
13186 if ((option_verbose > 2) && (resp != 487))
13187 ast_verbose(VERBOSE_PREFIX_3 "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
13188 switch(resp) {
13189 case 488:
13190 case 603:
13191 case 500:
13192 case 502:
13193 case 503:
13194 case 504:
13195
13196
13197 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
13198 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13199 break;
13200 }
13201 }
13202 break;
13203 }
13204 }
13205 }
13206
13207
13208
13209
13210
13211
13212
13213 static void *sip_park_thread(void *stuff)
13214 {
13215 struct ast_channel *transferee, *transferer;
13216 struct sip_dual *d;
13217 struct sip_request req;
13218 int ext;
13219 int res;
13220
13221 d = stuff;
13222 transferee = d->chan1;
13223 transferer = d->chan2;
13224 copy_request(&req, &d->req);
13225 free(d);
13226
13227 if (!transferee || !transferer) {
13228 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
13229 return NULL;
13230 }
13231 if (option_debug > 3)
13232 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
13233
13234 ast_channel_lock(transferee);
13235 if (ast_do_masquerade(transferee)) {
13236 ast_log(LOG_WARNING, "Masquerade failed.\n");
13237 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
13238 ast_channel_unlock(transferee);
13239 return NULL;
13240 }
13241 ast_channel_unlock(transferee);
13242
13243 res = ast_park_call(transferee, transferer, 0, &ext);
13244
13245
13246 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
13247 if (!res) {
13248 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
13249 } else {
13250
13251 sprintf(buf, "Call parked on extension '%d'", ext);
13252 transmit_message_with_text(transferer->tech_pvt, buf);
13253 }
13254 #endif
13255
13256
13257
13258 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
13259 if (!res) {
13260
13261 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
13262 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
13263 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13264 ast_hangup(transferer);
13265 if (option_debug)
13266 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
13267 } else {
13268 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
13269 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
13270 if (option_debug)
13271 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
13272
13273 }
13274 return NULL;
13275 }
13276
13277
13278
13279
13280 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
13281 {
13282 struct sip_dual *d;
13283 struct ast_channel *transferee, *transferer;
13284
13285 pthread_t th;
13286
13287 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
13288 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
13289 if ((!transferer) || (!transferee)) {
13290 if (transferee) {
13291 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13292 ast_hangup(transferee);
13293 }
13294 if (transferer) {
13295 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13296 ast_hangup(transferer);
13297 }
13298 return -1;
13299 }
13300
13301
13302 transferee->readformat = chan1->readformat;
13303 transferee->writeformat = chan1->writeformat;
13304
13305
13306 ast_channel_masquerade(transferee, chan1);
13307
13308
13309 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
13310 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
13311 transferee->priority = chan1->priority;
13312
13313
13314
13315
13316
13317 transferer->readformat = chan2->readformat;
13318 transferer->writeformat = chan2->writeformat;
13319
13320
13321
13322
13323 while (ast_channel_trylock(chan2)) {
13324 struct sip_pvt *pvt = chan2->tech_pvt;
13325 DEADLOCK_AVOIDANCE(&pvt->lock);
13326 }
13327 ast_channel_masquerade(transferer, chan2);
13328 ast_channel_unlock(chan2);
13329
13330
13331 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
13332 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
13333 transferer->priority = chan2->priority;
13334
13335 ast_channel_lock(transferer);
13336 if (ast_do_masquerade(transferer)) {
13337 ast_log(LOG_WARNING, "Masquerade failed :(\n");
13338 ast_channel_unlock(transferer);
13339 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13340 ast_hangup(transferer);
13341 return -1;
13342 }
13343 ast_channel_unlock(transferer);
13344 if (!transferer || !transferee) {
13345 if (!transferer) {
13346 if (option_debug)
13347 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
13348 }
13349 if (!transferee) {
13350 if (option_debug)
13351 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
13352 }
13353 return -1;
13354 }
13355 if ((d = ast_calloc(1, sizeof(*d)))) {
13356 pthread_attr_t attr;
13357
13358 pthread_attr_init(&attr);
13359 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13360
13361
13362 copy_request(&d->req, req);
13363 d->chan1 = transferee;
13364 d->chan2 = transferer;
13365 d->seqno = seqno;
13366 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
13367
13368 free(d);
13369
13370 pthread_attr_destroy(&attr);
13371 return 0;
13372 }
13373 pthread_attr_destroy(&attr);
13374 }
13375 return -1;
13376 }
13377
13378
13379
13380
13381 static void ast_quiet_chan(struct ast_channel *chan)
13382 {
13383 if (chan && chan->_state == AST_STATE_UP) {
13384 if (ast_test_flag(chan, AST_FLAG_MOH))
13385 ast_moh_stop(chan);
13386 else if (chan->generatordata)
13387 ast_deactivate_generator(chan);
13388 }
13389 }
13390
13391
13392
13393 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
13394 {
13395 int res = 0;
13396 struct ast_channel *peera = NULL,
13397 *peerb = NULL,
13398 *peerc = NULL,
13399 *peerd = NULL;
13400
13401
13402
13403
13404 if (option_debug > 3) {
13405 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
13406 if (transferer->chan1)
13407 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
13408 else
13409 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
13410 if (target->chan1)
13411 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
13412 else
13413 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
13414 if (transferer->chan2)
13415 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
13416 else
13417 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
13418 if (target->chan2)
13419 ast_log(LOG_DEBUG, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
13420 else
13421 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
13422 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
13423 }
13424 if (transferer->chan2) {
13425 peera = transferer->chan1;
13426 peerb = target->chan1;
13427 peerc = transferer->chan2;
13428 peerd = target->chan2;
13429 if (option_debug > 2)
13430 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
13431 } else if (target->chan2) {
13432 peera = target->chan1;
13433 peerb = transferer->chan1;
13434 peerc = target->chan2;
13435 peerd = transferer->chan2;
13436 if (option_debug > 2)
13437 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
13438 }
13439
13440 if (peera && peerb && peerc && (peerb != peerc)) {
13441 ast_quiet_chan(peera);
13442 ast_quiet_chan(peerb);
13443 ast_quiet_chan(peerc);
13444 if (peerd)
13445 ast_quiet_chan(peerd);
13446
13447
13448 if (peera->cdr && peerb->cdr)
13449 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
13450 else if (peera->cdr)
13451 peerb->cdr = peera->cdr;
13452 peera->cdr = NULL;
13453
13454 if (peerb->cdr && peerc->cdr)
13455 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
13456 else if (peerc->cdr)
13457 peerb->cdr = peerc->cdr;
13458 peerc->cdr = NULL;
13459
13460 if (option_debug > 3)
13461 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
13462 if (ast_channel_masquerade(peerb, peerc)) {
13463 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
13464 res = -1;
13465 } else
13466 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
13467 return res;
13468 } else {
13469 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
13470 if (transferer->chan1)
13471 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
13472 if (target->chan1)
13473 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
13474 return -2;
13475 }
13476 return 0;
13477 }
13478
13479
13480
13481
13482
13483
13484 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
13485 {
13486 const char *thetag;
13487
13488 if (!tagbuf)
13489 return NULL;
13490 tagbuf[0] = '\0';
13491 thetag = get_header(req, header);
13492 thetag = strcasestr(thetag, ";tag=");
13493 if (thetag) {
13494 thetag += 5;
13495 ast_copy_string(tagbuf, thetag, tagbufsize);
13496 return strsep(&tagbuf, ";");
13497 }
13498 return NULL;
13499 }
13500
13501
13502 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13503 {
13504
13505
13506 int res = 0;
13507 const char *event = get_header(req, "Event");
13508 char *eventid = NULL;
13509 char *sep;
13510
13511 if( (sep = strchr(event, ';')) ) {
13512 *sep++ = '\0';
13513 eventid = sep;
13514 }
13515
13516 if (option_debug > 1 && sipdebug)
13517 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
13518
13519 if (strcmp(event, "refer")) {
13520
13521
13522 transmit_response(p, "489 Bad event", req);
13523 res = -1;
13524 } else {
13525
13526
13527
13528
13529
13530 char buf[1024];
13531 char *cmd, *code;
13532 int respcode;
13533 int success = TRUE;
13534
13535
13536
13537
13538
13539
13540
13541
13542 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
13543
13544 transmit_response(p, "400 Bad request", req);
13545 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13546 return -1;
13547 }
13548
13549
13550 if (get_msg_text(buf, sizeof(buf), req)) {
13551 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
13552 transmit_response(p, "400 Bad request", req);
13553 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13554 return -1;
13555 }
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577 if (option_debug > 2)
13578 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
13579 cmd = ast_skip_blanks(buf);
13580 code = cmd;
13581
13582 while(*code && (*code > 32)) {
13583 code++;
13584 }
13585 *code++ = '\0';
13586 code = ast_skip_blanks(code);
13587 sep = code;
13588 sep++;
13589 while(*sep && (*sep > 32)) {
13590 sep++;
13591 }
13592 *sep++ = '\0';
13593 respcode = atoi(code);
13594 switch (respcode) {
13595 case 100:
13596 case 101:
13597
13598 break;
13599 case 183:
13600
13601 break;
13602 case 200:
13603
13604 break;
13605 case 301:
13606 case 302:
13607
13608 success = FALSE;
13609 break;
13610 case 503:
13611
13612 success = FALSE;
13613 break;
13614 case 603:
13615
13616 success = FALSE;
13617 break;
13618 }
13619 if (!success) {
13620 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
13621 }
13622
13623
13624 transmit_response(p, "200 OK", req);
13625 };
13626
13627 if (!p->lastinvite)
13628 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13629
13630 return res;
13631 }
13632
13633
13634 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
13635 {
13636 int res;
13637
13638 res = get_destination(p, req);
13639 build_contact(p);
13640
13641
13642
13643 if (ast_strlen_zero(p->context))
13644 ast_string_field_set(p, context, default_context);
13645
13646 if (ast_shutting_down())
13647 transmit_response_with_allow(p, "503 Unavailable", req, 0);
13648 else if (res < 0)
13649 transmit_response_with_allow(p, "404 Not Found", req, 0);
13650 else
13651 transmit_response_with_allow(p, "200 OK", req, 0);
13652
13653
13654
13655 if (!p->lastinvite)
13656 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13657
13658 return res;
13659 }
13660
13661
13662
13663 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
13664 {
13665 struct ast_frame *f;
13666 int earlyreplace = 0;
13667 int oneleggedreplace = 0;
13668 struct ast_channel *c = p->owner;
13669 struct ast_channel *replacecall = p->refer->refer_call->owner;
13670 struct ast_channel *targetcall;
13671
13672
13673 if (replacecall->_state == AST_STATE_RING)
13674 earlyreplace = 1;
13675
13676
13677 if (!(targetcall = ast_bridged_channel(replacecall))) {
13678
13679 if (!earlyreplace) {
13680 if (option_debug > 1)
13681 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
13682 oneleggedreplace = 1;
13683 }
13684 }
13685 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
13686 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
13687
13688 if (option_debug > 3) {
13689 if (targetcall)
13690 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
13691 else
13692 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
13693 }
13694
13695 if (ignore) {
13696 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
13697
13698
13699
13700 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13701
13702 ast_channel_unlock(c);
13703 ast_mutex_unlock(&p->refer->refer_call->lock);
13704 return 1;
13705 }
13706 if (!c) {
13707
13708 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13709 transmit_response_reliable(p, "503 Service Unavailable", req);
13710 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13711 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13712 ast_mutex_unlock(&p->refer->refer_call->lock);
13713 return 1;
13714 }
13715 append_history(p, "Xfer", "INVITE/Replace received");
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727 transmit_response(p, "100 Trying", req);
13728 ast_setstate(c, AST_STATE_RING);
13729
13730
13731
13732
13733
13734 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13735
13736 ast_setstate(c, AST_STATE_UP);
13737
13738
13739 ast_quiet_chan(replacecall);
13740 ast_quiet_chan(targetcall);
13741 if (option_debug > 3)
13742 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13743
13744 if (!oneleggedreplace)
13745 ast_channel_unlock(c);
13746
13747
13748 ast_mutex_unlock(&p->refer->refer_call->lock);
13749
13750
13751 if (! earlyreplace && ! oneleggedreplace )
13752 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
13753
13754
13755 if(ast_channel_masquerade(replacecall, c))
13756 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13757 else if (option_debug > 3)
13758 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13759
13760
13761
13762
13763
13764 ast_channel_unlock(c);
13765
13766 if (earlyreplace || oneleggedreplace ) {
13767
13768 if ((f = ast_read(replacecall))) {
13769 ast_frfree(f);
13770 f = NULL;
13771 if (option_debug > 3)
13772 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13773 } else {
13774 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13775 }
13776 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13777 if (!oneleggedreplace)
13778 ast_channel_unlock(replacecall);
13779 } else {
13780 if ((f = ast_read(replacecall))) {
13781
13782 ast_frfree(f);
13783 f = NULL;
13784 if (option_debug > 2)
13785 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13786 } else {
13787 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13788 }
13789 ast_channel_unlock(replacecall);
13790 }
13791 ast_mutex_unlock(&p->refer->refer_call->lock);
13792
13793 ast_setstate(c, AST_STATE_DOWN);
13794 if (option_debug > 3) {
13795 struct ast_channel *test;
13796 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13797 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13798 if (replacecall)
13799 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13800 if (p->owner) {
13801 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13802 test = ast_bridged_channel(p->owner);
13803 if (test)
13804 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13805 else
13806 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13807 } else
13808 ast_log(LOG_DEBUG, " -- No channel yet \n");
13809 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13810 }
13811
13812 ast_channel_unlock(p->owner);
13813 if (!oneleggedreplace)
13814 ast_mutex_unlock(&p->lock);
13815
13816
13817 c->tech_pvt = NULL;
13818 ast_hangup(c);
13819 return 0;
13820 }
13821
13822
13823
13824
13825
13826
13827
13828
13829 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock)
13830 {
13831 int res = 1;
13832 int gotdest;
13833 const char *p_replaces;
13834 char *replace_id = NULL;
13835 const char *required;
13836 unsigned int required_profile = 0;
13837 struct ast_channel *c = NULL;
13838 int reinvite = 0;
13839
13840
13841 if (!p->sipoptions) {
13842 const char *supported = get_header(req, "Supported");
13843 if (!ast_strlen_zero(supported))
13844 parse_sip_options(p, supported);
13845 }
13846
13847
13848 required = get_header(req, "Require");
13849 if (!ast_strlen_zero(required)) {
13850 required_profile = parse_sip_options(NULL, required);
13851 if (required_profile && required_profile != SIP_OPT_REPLACES) {
13852
13853 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
13854 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
13855 p->invitestate = INV_COMPLETED;
13856 if (!p->lastinvite)
13857 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13858 return -1;
13859 }
13860 }
13861
13862
13863 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
13864
13865
13866
13867
13868
13869 transmit_response(p, "482 Loop Detected", req);
13870 p->invitestate = INV_COMPLETED;
13871 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13872 return 0;
13873 }
13874
13875 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
13876
13877 transmit_response(p, "491 Request Pending", req);
13878 if (option_debug)
13879 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
13880
13881 return 0;
13882 }
13883
13884 p_replaces = get_header(req, "Replaces");
13885 if (!ast_strlen_zero(p_replaces)) {
13886
13887 char *ptr;
13888 char *fromtag = NULL;
13889 char *totag = NULL;
13890 char *start, *to;
13891 int error = 0;
13892
13893 if (p->owner) {
13894 if (option_debug > 2)
13895 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
13896 transmit_response(p, "400 Bad request", req);
13897
13898 return -1;
13899 }
13900
13901 if (sipdebug && option_debug > 2)
13902 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
13903
13904 replace_id = ast_strdupa(p_replaces);
13905 ast_uri_decode(replace_id);
13906
13907 if (!p->refer && !sip_refer_allocate(p)) {
13908 transmit_response(p, "500 Server Internal Error", req);
13909 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
13910 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13911 p->invitestate = INV_COMPLETED;
13912 return -1;
13913 }
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924 replace_id = ast_skip_blanks(replace_id);
13925
13926 start = replace_id;
13927 while ( (ptr = strsep(&start, ";")) ) {
13928 ptr = ast_skip_blanks(ptr);
13929 if ( (to = strcasestr(ptr, "to-tag=") ) )
13930 totag = to + 7;
13931 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
13932 fromtag = to + 9;
13933 fromtag = strsep(&fromtag, "&");
13934 }
13935 }
13936
13937 if (sipdebug && option_debug > 3)
13938 ast_log(LOG_DEBUG,"Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n", replace_id, fromtag ? fromtag : "<no from tag>", totag ? totag : "<no to tag>");
13939
13940
13941
13942
13943
13944 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
13945 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
13946 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
13947 error = 1;
13948 }
13949
13950
13951
13952
13953
13954
13955
13956 if (p->refer->refer_call == p) {
13957 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
13958 p->refer->refer_call = NULL;
13959 transmit_response(p, "400 Bad request", req);
13960 error = 1;
13961 }
13962
13963 if (!error && !p->refer->refer_call->owner) {
13964
13965 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
13966
13967 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
13968 error = 1;
13969 }
13970
13971 if (!error && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
13972 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
13973 transmit_response(p, "603 Declined (Replaces)", req);
13974 error = 1;
13975 }
13976
13977 if (error) {
13978 append_history(p, "Xfer", "INVITE/Replace Failed.");
13979 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13980 ast_mutex_unlock(&p->lock);
13981 if (p->refer->refer_call) {
13982 ast_mutex_unlock(&p->refer->refer_call->lock);
13983 ast_channel_unlock(p->refer->refer_call->owner);
13984 }
13985 p->invitestate = INV_COMPLETED;
13986 return -1;
13987 }
13988 }
13989
13990
13991
13992
13993
13994 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13995 int newcall = (p->initreq.headers ? TRUE : FALSE);
13996
13997 if (sip_cancel_destroy(p))
13998 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13999
14000 p->pendinginvite = seqno;
14001 check_via(p, req);
14002
14003 copy_request(&p->initreq, req);
14004 if (!p->owner) {
14005 if (debug)
14006 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
14007 if (newcall)
14008 append_history(p, "Invite", "New call: %s", p->callid);
14009 parse_ok_contact(p, req);
14010 } else {
14011 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
14012
14013 if (find_sdp(req)) {
14014 if (process_sdp(p, req)) {
14015 transmit_response(p, "488 Not acceptable here", req);
14016 if (!p->lastinvite)
14017 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14018 return -1;
14019 }
14020 } else {
14021 p->jointcapability = p->capability;
14022 if (option_debug > 2)
14023 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
14024
14025
14026
14027 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
14028 change_hold_state(p, req, FALSE, 0);
14029 }
14030 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14031 append_history(p, "ReInv", "Re-invite received");
14032 }
14033 } else if (debug)
14034 ast_verbose("Ignoring this INVITE request\n");
14035
14036
14037 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
14038
14039
14040 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
14041 if (res == AUTH_CHALLENGE_SENT) {
14042 p->invitestate = INV_COMPLETED;
14043 return 0;
14044 }
14045 if (res < 0) {
14046 if (res == AUTH_FAKE_AUTH) {
14047 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
14048 transmit_fake_auth_response(p, req, 1);
14049 } else {
14050 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
14051 transmit_response_reliable(p, "403 Forbidden", req);
14052 }
14053 p->invitestate = INV_COMPLETED;
14054 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14055 ast_string_field_free(p, theirtag);
14056 return 0;
14057 }
14058
14059
14060 if (find_sdp(req)) {
14061 if (process_sdp(p, req)) {
14062
14063 transmit_response_reliable(p, "488 Not acceptable here", req);
14064 p->invitestate = INV_COMPLETED;
14065 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14066 if (option_debug)
14067 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
14068 return -1;
14069 }
14070 } else {
14071 p->jointcapability = p->capability;
14072 if (option_debug > 1)
14073 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
14074 }
14075
14076
14077
14078 if (p->owner)
14079 ast_queue_frame(p->owner, &ast_null_frame);
14080
14081
14082
14083 if (ast_strlen_zero(p->context))
14084 ast_string_field_set(p, context, default_context);
14085
14086
14087
14088 if (option_debug)
14089 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
14090 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
14091 if (res < 0) {
14092 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
14093 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
14094 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14095 p->invitestate = INV_COMPLETED;
14096 }
14097 return 0;
14098 }
14099 gotdest = get_destination(p, NULL);
14100 get_rdnis(p, NULL);
14101 extract_uri(p, req);
14102 build_contact(p);
14103
14104 if (p->rtp) {
14105 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
14106 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
14107 }
14108
14109 if (!replace_id && gotdest) {
14110 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
14111 transmit_response_reliable(p, "484 Address Incomplete", req);
14112 else {
14113 transmit_response_reliable(p, "404 Not Found", req);
14114 ast_log(LOG_NOTICE, "Call from '%s' to extension"
14115 " '%s' rejected because extension not found.\n",
14116 S_OR(p->username, p->peername), p->exten);
14117 }
14118 p->invitestate = INV_COMPLETED;
14119 update_call_counter(p, DEC_CALL_LIMIT);
14120 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14121 return 0;
14122 } else {
14123
14124
14125 if (ast_strlen_zero(p->exten))
14126 ast_string_field_set(p, exten, "s");
14127
14128
14129 make_our_tag(p->tag, sizeof(p->tag));
14130
14131 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
14132 *recount = 1;
14133
14134
14135 build_route(p, req, 0);
14136
14137 if (c) {
14138
14139 ast_channel_lock(c);
14140 }
14141 }
14142 } else {
14143 if (option_debug > 1 && sipdebug) {
14144 if (!ast_test_flag(req, SIP_PKT_IGNORE))
14145 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
14146 else
14147 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
14148 }
14149 reinvite = 1;
14150 c = p->owner;
14151 }
14152
14153 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14154 p->lastinvite = seqno;
14155
14156 if (replace_id) {
14157
14158 if (sipdebug && option_debug > 3)
14159 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
14160 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
14161 }
14162
14163
14164 if (c) {
14165 switch(c->_state) {
14166 case AST_STATE_DOWN:
14167 if (option_debug > 1)
14168 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
14169 transmit_response(p, "100 Trying", req);
14170 p->invitestate = INV_PROCEEDING;
14171 ast_setstate(c, AST_STATE_RING);
14172 if (strcmp(p->exten, ast_pickup_ext())) {
14173 enum ast_pbx_result res;
14174
14175 res = ast_pbx_start(c);
14176
14177 switch(res) {
14178 case AST_PBX_FAILED:
14179 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
14180 p->invitestate = INV_COMPLETED;
14181 if (ast_test_flag(req, SIP_PKT_IGNORE))
14182 transmit_response(p, "503 Unavailable", req);
14183 else
14184 transmit_response_reliable(p, "503 Unavailable", req);
14185 break;
14186 case AST_PBX_CALL_LIMIT:
14187 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
14188 p->invitestate = INV_COMPLETED;
14189 if (ast_test_flag(req, SIP_PKT_IGNORE))
14190 transmit_response(p, "480 Temporarily Unavailable", req);
14191 else
14192 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
14193 break;
14194 case AST_PBX_SUCCESS:
14195
14196 break;
14197 }
14198
14199 if (res) {
14200
14201
14202 ast_mutex_unlock(&c->lock);
14203 ast_mutex_unlock(&p->lock);
14204 ast_hangup(c);
14205 ast_mutex_lock(&p->lock);
14206 c = NULL;
14207 }
14208 } else {
14209 ast_channel_unlock(c);
14210 *nounlock = 1;
14211 if (ast_pickup_call(c)) {
14212 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
14213 if (ast_test_flag(req, SIP_PKT_IGNORE))
14214 transmit_response(p, "503 Unavailable", req);
14215 else
14216 transmit_response_reliable(p, "503 Unavailable", req);
14217 sip_alreadygone(p);
14218
14219 ast_mutex_unlock(&p->lock);
14220 c->hangupcause = AST_CAUSE_CALL_REJECTED;
14221 } else {
14222 ast_mutex_unlock(&p->lock);
14223 ast_setstate(c, AST_STATE_DOWN);
14224 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14225 }
14226 p->invitestate = INV_COMPLETED;
14227 ast_hangup(c);
14228 ast_mutex_lock(&p->lock);
14229 c = NULL;
14230 }
14231 break;
14232 case AST_STATE_RING:
14233 transmit_response(p, "100 Trying", req);
14234 p->invitestate = INV_PROCEEDING;
14235 break;
14236 case AST_STATE_RINGING:
14237 transmit_response(p, "180 Ringing", req);
14238 p->invitestate = INV_PROCEEDING;
14239 break;
14240 case AST_STATE_UP:
14241 if (option_debug > 1)
14242 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
14243
14244 transmit_response(p, "100 Trying", req);
14245
14246 if (p->t38.state == T38_PEER_REINVITE) {
14247 struct ast_channel *bridgepeer = NULL;
14248 struct sip_pvt *bridgepvt = NULL;
14249
14250 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14251
14252
14253 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
14254 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14255 if (bridgepvt->t38.state == T38_DISABLED) {
14256 if (bridgepvt->udptl) {
14257
14258 sip_handle_t38_reinvite(bridgepeer, p, 1);
14259 } else {
14260 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
14261 ast_mutex_lock(&bridgepvt->lock);
14262 bridgepvt->t38.state = T38_DISABLED;
14263 ast_mutex_unlock(&bridgepvt->lock);
14264 if (option_debug > 1)
14265 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
14266 if (ast_test_flag(req, SIP_PKT_IGNORE))
14267 transmit_response(p, "488 Not acceptable here", req);
14268 else
14269 transmit_response_reliable(p, "488 Not acceptable here", req);
14270
14271 }
14272 } else {
14273
14274 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14275 p->t38.state = T38_ENABLED;
14276 if (option_debug)
14277 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14278 }
14279 } else {
14280
14281 if (ast_test_flag(req, SIP_PKT_IGNORE))
14282 transmit_response(p, "488 Not acceptable here", req);
14283 else
14284 transmit_response_reliable(p, "488 Not acceptable here", req);
14285 p->t38.state = T38_DISABLED;
14286 if (option_debug > 1)
14287 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14288
14289 if (!p->lastinvite)
14290 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14291 }
14292 } else {
14293
14294 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14295 p->t38.state = T38_ENABLED;
14296 if (option_debug)
14297 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14298 }
14299 } else if (p->t38.state == T38_DISABLED) {
14300 int sendok = TRUE;
14301
14302
14303
14304 struct ast_channel *bridgepeer = NULL;
14305 struct sip_pvt *bridgepvt = NULL;
14306 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14307 if ((bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) && !ast_check_hangup(bridgepeer)) {
14308 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14309
14310 if (bridgepvt->t38.state == T38_ENABLED) {
14311 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
14312
14313 if (ast_test_flag(req, SIP_PKT_IGNORE))
14314 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
14315 else
14316 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
14317 sendok = FALSE;
14318 }
14319
14320 }
14321 }
14322
14323 if (sendok)
14324
14325 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (ast_test_flag(req, SIP_PKT_IGNORE) ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
14326 }
14327 p->invitestate = INV_TERMINATED;
14328 break;
14329 default:
14330 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
14331 transmit_response(p, "100 Trying", req);
14332 break;
14333 }
14334 } else {
14335 if (p && (p->autokillid == -1)) {
14336 const char *msg;
14337
14338 if (!p->jointcapability)
14339 msg = "488 Not Acceptable Here (codec error)";
14340 else {
14341 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
14342 msg = "503 Unavailable";
14343 }
14344 if (ast_test_flag(req, SIP_PKT_IGNORE))
14345 transmit_response(p, msg, req);
14346 else
14347 transmit_response_reliable(p, msg, req);
14348 p->invitestate = INV_COMPLETED;
14349 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14350 }
14351 }
14352 return res;
14353 }
14354
14355
14356
14357 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
14358 {
14359 struct sip_dual target;
14360
14361 int res = 0;
14362 struct sip_pvt *targetcall_pvt;
14363
14364
14365 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
14366 transferer->refer->replaces_callid_fromtag))) {
14367 if (transferer->refer->localtransfer) {
14368
14369 transmit_response(transferer, "202 Accepted", req);
14370
14371
14372 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
14373 append_history(transferer, "Xfer", "Refer failed");
14374 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14375 transferer->refer->status = REFER_FAILED;
14376 return -1;
14377 }
14378
14379 if (option_debug > 2)
14380 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
14381 return 0;
14382 }
14383
14384
14385 transmit_response(transferer, "202 Accepted", req);
14386 append_history(transferer, "Xfer", "Refer accepted");
14387 if (!targetcall_pvt->owner) {
14388 if (option_debug > 3)
14389 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
14390
14391 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
14392 append_history(transferer, "Xfer", "Refer failed");
14393 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14394 transferer->refer->status = REFER_FAILED;
14395 ast_mutex_unlock(&targetcall_pvt->lock);
14396 ast_channel_unlock(current->chan1);
14397 return -1;
14398 }
14399
14400
14401 target.chan1 = targetcall_pvt->owner;
14402 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
14403
14404 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
14405
14406 if (option_debug > 3) {
14407 if (target.chan2)
14408 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
14409 else if (target.chan1->_state != AST_STATE_RING)
14410 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
14411 else
14412 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
14413 }
14414 }
14415
14416
14417 if (option_debug > 3 && sipdebug) {
14418 if (current->chan2)
14419 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
14420 else
14421 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
14422 }
14423
14424 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14425
14426
14427 res = attempt_transfer(current, &target);
14428 ast_mutex_unlock(&targetcall_pvt->lock);
14429 if (res) {
14430
14431 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
14432 append_history(transferer, "Xfer", "Refer failed");
14433 transferer->refer->status = REFER_FAILED;
14434 if (targetcall_pvt->owner)
14435 ast_channel_unlock(targetcall_pvt->owner);
14436
14437 if (res != -2)
14438 ast_hangup(transferer->owner);
14439 else
14440 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14441 } else {
14442
14443
14444
14445 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
14446 append_history(transferer, "Xfer", "Refer succeeded");
14447 transferer->refer->status = REFER_200OK;
14448 if (targetcall_pvt->owner) {
14449 if (option_debug)
14450 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
14451 ast_channel_unlock(targetcall_pvt->owner);
14452 }
14453 }
14454 return 1;
14455 }
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
14522 {
14523 struct sip_dual current;
14524
14525
14526 int res = 0;
14527
14528 if (ast_test_flag(req, SIP_PKT_DEBUG))
14529 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
14530
14531 if (!p->owner) {
14532
14533
14534 if (option_debug > 2)
14535 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
14536 transmit_response(p, "603 Declined (No dialog)", req);
14537 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14538 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
14539 sip_alreadygone(p);
14540 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14541 }
14542 return 0;
14543 }
14544
14545
14546
14547 if (p->allowtransfer == TRANSFER_CLOSED ) {
14548
14549 transmit_response(p, "603 Declined (policy)", req);
14550 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
14551
14552 return 0;
14553 }
14554
14555 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
14556
14557 transmit_response(p, "491 Request pending", req);
14558 append_history(p, "Xfer", "Refer failed. Request pending.");
14559 return 0;
14560 }
14561
14562
14563 if (!p->refer && !sip_refer_allocate(p)) {
14564 transmit_response(p, "500 Internal Server Error", req);
14565 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
14566 return -3;
14567 }
14568
14569 res = get_refer_info(p, req);
14570
14571 p->refer->status = REFER_SENT;
14572
14573 if (res != 0) {
14574 switch (res) {
14575 case -2:
14576 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
14577 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
14578 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14579 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
14580 break;
14581 case -3:
14582 transmit_response(p, "603 Declined (Non sip: uri)", req);
14583 append_history(p, "Xfer", "Refer failed. Non SIP uri");
14584 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14585 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
14586 break;
14587 default:
14588
14589 transmit_response(p, "202 Accepted", req);
14590 append_history(p, "Xfer", "Refer failed. Bad extension.");
14591 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
14592 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14593 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14594 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
14595 break;
14596 }
14597 return 0;
14598 }
14599 if (ast_strlen_zero(p->context))
14600 ast_string_field_set(p, context, default_context);
14601
14602
14603 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14604 p->refer->localtransfer = 1;
14605 if (sipdebug && option_debug > 2)
14606 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
14607 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14608
14609 p->refer->localtransfer = 1;
14610 } else if (sipdebug && option_debug > 2)
14611 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
14612
14613
14614
14615 if (ignore)
14616 return res;
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644 current.chan1 = p->owner;
14645
14646
14647 current.chan2 = ast_bridged_channel(current.chan1);
14648
14649 if (sipdebug && option_debug > 2)
14650 ast_log(LOG_DEBUG, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");
14651
14652 if (!current.chan2 && !p->refer->attendedtransfer) {
14653
14654
14655
14656 if (sipdebug && option_debug > 2)
14657 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
14658 p->refer->status = REFER_FAILED;
14659 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
14660 transmit_response(p, "603 Declined", req);
14661 return -1;
14662 }
14663
14664 if (current.chan2) {
14665 if (sipdebug && option_debug > 3)
14666 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
14667
14668 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
14669 }
14670
14671 ast_set_flag(&p->flags[0], SIP_GOTREFER);
14672
14673
14674 if (p->refer->attendedtransfer) {
14675 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
14676 return res;
14677
14678 if (sipdebug && option_debug > 3)
14679 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14680
14681 }
14682
14683
14684
14685 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
14686
14687 *nounlock = 1;
14688 ast_channel_unlock(current.chan1);
14689 copy_request(¤t.req, req);
14690 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14691 p->refer->status = REFER_200OK;
14692 append_history(p, "Xfer", "REFER to call parking.");
14693 if (sipdebug && option_debug > 3)
14694 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
14695 sip_park(current.chan2, current.chan1, req, seqno);
14696 return res;
14697 }
14698
14699
14700 transmit_response(p, "202 Accepted", req);
14701
14702 if (current.chan1 && current.chan2) {
14703 if (option_debug > 2)
14704 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
14705 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
14706 }
14707 if (current.chan2) {
14708 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
14709 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
14710 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
14711
14712 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
14713
14714 if (p->refer->referred_by)
14715 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
14716 }
14717
14718 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
14719 char tempheader[SIPBUFSIZE];
14720 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
14721 p->refer->replaces_callid_totag ? ";to-tag=" : "",
14722 p->refer->replaces_callid_totag,
14723 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
14724 p->refer->replaces_callid_fromtag);
14725 if (current.chan2)
14726 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
14727 }
14728
14729
14730 *nounlock = 1;
14731 ast_channel_unlock(current.chan1);
14732
14733
14734
14735
14736 if (!p->refer->attendedtransfer)
14737 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
14738
14739
14740
14741
14742
14743 if (!current.chan2) {
14744
14745
14746
14747
14748
14749
14750
14751 p->refer->status = REFER_FAILED;
14752 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
14753 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14754 append_history(p, "Xfer", "Refer failed (only bridged calls).");
14755 return -1;
14756 }
14757 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14758
14759
14760
14761 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
14762
14763 if (!res) {
14764
14765 if (option_debug > 2)
14766 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14767 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
14768 if (p->refer->localtransfer)
14769 p->refer->status = REFER_200OK;
14770 if (p->owner)
14771 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14772 append_history(p, "Xfer", "Refer succeeded.");
14773 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14774
14775
14776 res = 0;
14777 } else {
14778 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14779 if (option_debug > 2)
14780 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14781 append_history(p, "Xfer", "Refer failed.");
14782
14783 p->refer->status = REFER_FAILED;
14784 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
14785 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14786 res = -1;
14787 }
14788 return res;
14789 }
14790
14791
14792 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
14793 {
14794
14795 check_via(p, req);
14796 sip_alreadygone(p);
14797
14798
14799
14800
14801
14802
14803 if (p->invitestate == INV_TERMINATED)
14804 __sip_pretend_ack(p);
14805 else
14806 p->invitestate = INV_CANCELLED;
14807
14808 if (p->owner && p->owner->_state == AST_STATE_UP) {
14809
14810 transmit_response(p, "200 OK", req);
14811 if (option_debug)
14812 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
14813 return 0;
14814 }
14815
14816 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
14817 update_call_counter(p, DEC_CALL_LIMIT);
14818
14819 stop_media_flows(p);
14820 if (p->owner)
14821 ast_queue_hangup(p->owner);
14822 else
14823 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14824 if (p->initreq.len > 0) {
14825 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14826 transmit_response(p, "200 OK", req);
14827 return 1;
14828 } else {
14829 transmit_response(p, "481 Call Leg Does Not Exist", req);
14830 return 0;
14831 }
14832 }
14833
14834 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen)
14835 {
14836 struct ast_rtp_quality qos;
14837 struct sip_pvt *p = chan->tech_pvt;
14838 char *all = "", *parse = ast_strdupa(preparse);
14839 AST_DECLARE_APP_ARGS(args,
14840 AST_APP_ARG(param);
14841 AST_APP_ARG(type);
14842 AST_APP_ARG(field);
14843 );
14844 AST_STANDARD_APP_ARGS(args, parse);
14845
14846
14847 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
14848 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
14849 return 0;
14850 }
14851
14852 if (strcasecmp(args.param, "rtpqos"))
14853 return 0;
14854
14855
14856 if (ast_strlen_zero(args.type))
14857 args.type = "audio";
14858 if (ast_strlen_zero(args.field))
14859 args.field = "all";
14860
14861 memset(buf, 0, buflen);
14862 memset(&qos, 0, sizeof(qos));
14863
14864 if (strcasecmp(args.type, "AUDIO") == 0) {
14865 all = ast_rtp_get_quality(p->rtp, &qos);
14866 } else if (strcasecmp(args.type, "VIDEO") == 0) {
14867 all = ast_rtp_get_quality(p->vrtp, &qos);
14868 }
14869
14870 if (strcasecmp(args.field, "local_ssrc") == 0)
14871 snprintf(buf, buflen, "%u", qos.local_ssrc);
14872 else if (strcasecmp(args.field, "local_lostpackets") == 0)
14873 snprintf(buf, buflen, "%u", qos.local_lostpackets);
14874 else if (strcasecmp(args.field, "local_jitter") == 0)
14875 snprintf(buf, buflen, "%.0lf", qos.local_jitter * 1000.0);
14876 else if (strcasecmp(args.field, "local_count") == 0)
14877 snprintf(buf, buflen, "%u", qos.local_count);
14878 else if (strcasecmp(args.field, "remote_ssrc") == 0)
14879 snprintf(buf, buflen, "%u", qos.remote_ssrc);
14880 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
14881 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
14882 else if (strcasecmp(args.field, "remote_jitter") == 0)
14883 snprintf(buf, buflen, "%.0lf", qos.remote_jitter * 1000.0);
14884 else if (strcasecmp(args.field, "remote_count") == 0)
14885 snprintf(buf, buflen, "%u", qos.remote_count);
14886 else if (strcasecmp(args.field, "rtt") == 0)
14887 snprintf(buf, buflen, "%.0lf", qos.rtt * 1000.0);
14888 else if (strcasecmp(args.field, "all") == 0)
14889 ast_copy_string(buf, all, buflen);
14890 else {
14891 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
14892 return -1;
14893 }
14894 return 0;
14895 }
14896
14897
14898 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
14899 {
14900 struct ast_channel *c=NULL;
14901 int res;
14902 struct ast_channel *bridged_to;
14903
14904
14905 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
14906 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14907
14908 p->invitestate = INV_TERMINATED;
14909
14910 copy_request(&p->initreq, req);
14911 check_via(p, req);
14912 sip_alreadygone(p);
14913
14914
14915 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
14916 char *audioqos, *videoqos;
14917 if (p->rtp) {
14918 audioqos = ast_rtp_get_quality(p->rtp, NULL);
14919 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14920 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
14921 if (p->owner)
14922 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
14923 }
14924 if (p->vrtp) {
14925 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
14926 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14927 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
14928 if (p->owner)
14929 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
14930 }
14931 }
14932
14933 stop_media_flows(p);
14934
14935 if (!ast_strlen_zero(get_header(req, "Also"))) {
14936 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14937 ast_inet_ntoa(p->recv.sin_addr));
14938 if (ast_strlen_zero(p->context))
14939 ast_string_field_set(p, context, default_context);
14940 res = get_also_info(p, req);
14941 if (!res) {
14942 c = p->owner;
14943 if (c) {
14944 bridged_to = ast_bridged_channel(c);
14945 if (bridged_to) {
14946
14947 ast_queue_control(c, AST_CONTROL_UNHOLD);
14948 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
14949 } else
14950 ast_queue_hangup(p->owner);
14951 }
14952 } else {
14953 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
14954 if (p->owner)
14955 ast_queue_hangup(p->owner);
14956 }
14957 } else if (p->owner) {
14958 ast_queue_hangup(p->owner);
14959 if (option_debug > 2)
14960 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
14961 } else {
14962 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14963 if (option_debug > 2)
14964 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
14965 }
14966 transmit_response(p, "200 OK", req);
14967
14968 return 1;
14969 }
14970
14971
14972 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
14973 {
14974 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14975 if (ast_test_flag(req, SIP_PKT_DEBUG))
14976 ast_verbose("Receiving message!\n");
14977 receive_message(p, req);
14978 } else
14979 transmit_response(p, "202 Accepted", req);
14980 return 1;
14981 }
14982
14983
14984 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
14985 {
14986 int gotdest;
14987 int res = 0;
14988 int firststate = AST_EXTENSION_REMOVED;
14989 struct sip_peer *authpeer = NULL;
14990 const char *eventheader = get_header(req, "Event");
14991 const char *accept = get_header(req, "Accept");
14992 int resubscribe = (p->subscribed != NONE);
14993 char *temp, *event;
14994
14995 if (p->initreq.headers) {
14996
14997 if (p->initreq.method != SIP_SUBSCRIBE) {
14998
14999
15000 transmit_response(p, "403 Forbidden (within dialog)", req);
15001
15002 if (option_debug)
15003 ast_log(LOG_DEBUG, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
15004 return 0;
15005 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
15006 if (option_debug) {
15007 if (resubscribe)
15008 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
15009 else
15010 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
15011 }
15012 }
15013 }
15014
15015
15016
15017
15018 if (!global_allowsubscribe) {
15019 transmit_response(p, "403 Forbidden (policy)", req);
15020 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15021 return 0;
15022 }
15023
15024 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) {
15025 const char *to = get_header(req, "To");
15026 char totag[128];
15027
15028
15029 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
15030 if (ast_test_flag(req, SIP_PKT_DEBUG))
15031 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
15032 transmit_response(p, "481 Subscription does not exist", req);
15033 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15034 return 0;
15035 }
15036
15037
15038 if (ast_test_flag(req, SIP_PKT_DEBUG))
15039 ast_verbose("Creating new subscription\n");
15040
15041 copy_request(&p->initreq, req);
15042 check_via(p, req);
15043 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
15044 ast_verbose("Ignoring this SUBSCRIBE request\n");
15045
15046
15047 if (ast_strlen_zero(eventheader)) {
15048 transmit_response(p, "489 Bad Event", req);
15049 if (option_debug > 1)
15050 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
15051 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15052 return 0;
15053 }
15054
15055 if ( (strchr(eventheader, ';'))) {
15056 event = ast_strdupa(eventheader);
15057 temp = strchr(event, ';');
15058 *temp = '\0';
15059
15060 } else
15061 event = (char *) eventheader;
15062
15063
15064 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
15065
15066 if (res == AUTH_CHALLENGE_SENT) {
15067 if (authpeer)
15068 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15069 return 0;
15070 }
15071 if (res < 0) {
15072 if (res == AUTH_FAKE_AUTH) {
15073 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
15074 transmit_fake_auth_response(p, req, 1);
15075 } else {
15076 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
15077 transmit_response_reliable(p, "403 Forbidden", req);
15078 }
15079 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15080 if (authpeer)
15081 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15082 return 0;
15083 }
15084
15085
15086 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
15087 transmit_response(p, "403 Forbidden (policy)", req);
15088 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15089 if (authpeer)
15090 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15091 return 0;
15092 }
15093
15094
15095 gotdest = get_destination(p, NULL);
15096
15097
15098 parse_ok_contact(p, req);
15099
15100 build_contact(p);
15101 if (strcmp(event, "message-summary") && gotdest) {
15102 transmit_response(p, "404 Not Found", req);
15103 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15104 if (authpeer)
15105 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15106 return 0;
15107 }
15108
15109
15110 if (ast_strlen_zero(p->tag))
15111 make_our_tag(p->tag, sizeof(p->tag));
15112
15113 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
15114 if (authpeer)
15115 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15116
15117
15118
15119
15120
15121 if (strstr(p->useragent, "Polycom")) {
15122 p->subscribed = XPIDF_XML;
15123 } else if (strstr(accept, "application/pidf+xml")) {
15124 p->subscribed = PIDF_XML;
15125 } else if (strstr(accept, "application/dialog-info+xml")) {
15126 p->subscribed = DIALOG_INFO_XML;
15127
15128 } else if (strstr(accept, "application/cpim-pidf+xml")) {
15129 p->subscribed = CPIM_PIDF_XML;
15130 } else if (strstr(accept, "application/xpidf+xml")) {
15131 p->subscribed = XPIDF_XML;
15132 } else if (ast_strlen_zero(accept)) {
15133 if (p->subscribed == NONE) {
15134 transmit_response(p, "489 Bad Event", req);
15135
15136 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15137 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15138 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15139 return 0;
15140 }
15141
15142
15143 } else {
15144
15145 char mybuf[200];
15146 snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
15147 transmit_response(p, mybuf, req);
15148
15149 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
15150 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
15151 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15152 return 0;
15153 }
15154 } else if (!strcmp(event, "message-summary")) {
15155 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
15156
15157 transmit_response(p, "406 Not Acceptable", req);
15158 if (option_debug > 1)
15159 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
15160 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15161 if (authpeer)
15162 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15163 return 0;
15164 }
15165
15166
15167
15168
15169
15170 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
15171 transmit_response(p, "404 Not found (no mailbox)", req);
15172 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15173 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
15174 if (authpeer)
15175 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15176 return 0;
15177 }
15178
15179 p->subscribed = MWI_NOTIFICATION;
15180 if (authpeer->mwipvt && authpeer->mwipvt != p)
15181
15182 sip_destroy(authpeer->mwipvt);
15183 authpeer->mwipvt = p;
15184 p->relatedpeer = ASTOBJ_REF(authpeer);
15185 } else {
15186 transmit_response(p, "489 Bad Event", req);
15187 if (option_debug > 1)
15188 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
15189 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15190 if (authpeer)
15191 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15192 return 0;
15193 }
15194
15195 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
15196 if (p->stateid > -1)
15197 ast_extension_state_del(p->stateid, cb_extensionstate);
15198 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
15199 }
15200
15201 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
15202 p->lastinvite = seqno;
15203 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
15204 p->expiry = atoi(get_header(req, "Expires"));
15205
15206
15207 if (p->expiry > max_expiry)
15208 p->expiry = max_expiry;
15209 if (p->expiry < min_expiry && p->expiry > 0)
15210 p->expiry = min_expiry;
15211
15212 if (sipdebug || option_debug > 1) {
15213 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
15214 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
15215 else
15216 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
15217 }
15218 if (p->autokillid > -1 && sip_cancel_destroy(p))
15219 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15220 if (p->expiry > 0)
15221 sip_scheddestroy(p, (p->expiry + 10) * 1000);
15222
15223 if (p->subscribed == MWI_NOTIFICATION) {
15224 transmit_response(p, "200 OK", req);
15225 if (p->relatedpeer) {
15226 ASTOBJ_WRLOCK(p->relatedpeer);
15227 sip_send_mwi_to_peer(p->relatedpeer);
15228 ASTOBJ_UNLOCK(p->relatedpeer);
15229 }
15230 } else {
15231 struct sip_pvt *p_old;
15232
15233 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
15234
15235 ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_inet_ntoa(p->sa.sin_addr));
15236 transmit_response(p, "404 Not found", req);
15237 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15238 return 0;
15239 }
15240
15241 transmit_response(p, "200 OK", req);
15242 transmit_state_notify(p, firststate, 1, FALSE);
15243 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
15244
15245 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
15246
15247
15248
15249
15250
15251
15252 ast_mutex_lock(&iflock);
15253 for (p_old = iflist; p_old; p_old = p_old->next) {
15254 if (p_old == p)
15255 continue;
15256 if (p_old->initreq.method != SIP_SUBSCRIBE)
15257 continue;
15258 if (p_old->subscribed == NONE)
15259 continue;
15260 ast_mutex_lock(&p_old->lock);
15261 if (!strcmp(p_old->username, p->username)) {
15262 if (!strcmp(p_old->exten, p->exten) &&
15263 !strcmp(p_old->context, p->context)) {
15264 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
15265 ast_mutex_unlock(&p_old->lock);
15266 break;
15267 }
15268 }
15269 ast_mutex_unlock(&p_old->lock);
15270 }
15271 ast_mutex_unlock(&iflock);
15272 }
15273 if (!p->expiry)
15274 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15275 }
15276 return 1;
15277 }
15278
15279
15280 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
15281 {
15282 enum check_auth_result res;
15283
15284
15285 if (ast_test_flag(req, SIP_PKT_DEBUG))
15286 ast_verbose("Using latest REGISTER request as basis request\n");
15287 copy_request(&p->initreq, req);
15288 check_via(p, req);
15289 if ((res = register_verify(p, sin, req, e)) < 0) {
15290 const char *reason;
15291
15292 switch (res) {
15293 case AUTH_SECRET_FAILED:
15294 reason = "Wrong password";
15295 break;
15296 case AUTH_USERNAME_MISMATCH:
15297 reason = "Username/auth name mismatch";
15298 break;
15299 case AUTH_NOT_FOUND:
15300 reason = "No matching peer found";
15301 break;
15302 case AUTH_UNKNOWN_DOMAIN:
15303 reason = "Not a local domain";
15304 break;
15305 case AUTH_PEER_NOT_DYNAMIC:
15306 reason = "Peer is not supposed to register";
15307 break;
15308 case AUTH_ACL_FAILED:
15309 reason = "Device does not match ACL";
15310 break;
15311 default:
15312 reason = "Unknown failure";
15313 break;
15314 }
15315 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
15316 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
15317 reason);
15318 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
15319 } else
15320 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
15321
15322 if (res < 1) {
15323
15324
15325 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15326 }
15327 return res;
15328 }
15329
15330
15331
15332
15333 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
15334 {
15335
15336
15337 const char *cmd;
15338 const char *cseq;
15339 const char *useragent;
15340 int seqno;
15341 int len;
15342 int ignore = FALSE;
15343 int respid;
15344 int res = 0;
15345 int debug = sip_debug_test_pvt(p);
15346 char *e;
15347 int error = 0;
15348
15349
15350 cseq = get_header(req, "Cseq");
15351 cmd = req->header[0];
15352
15353
15354 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
15355 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
15356 error = 1;
15357 }
15358 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
15359 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
15360 error = 1;
15361 }
15362 if (error) {
15363 if (!p->initreq.headers)
15364 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15365 return -1;
15366 }
15367
15368
15369 cmd = req->rlPart1;
15370 e = req->rlPart2;
15371
15372
15373 useragent = get_header(req, "User-Agent");
15374 if (!ast_strlen_zero(useragent))
15375 ast_string_field_set(p, useragent, useragent);
15376
15377
15378 if (req->method == SIP_RESPONSE) {
15379
15380 if (!p->initreq.headers) {
15381 if (option_debug)
15382 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
15383 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15384 return 0;
15385 } else if (p->ocseq && (p->ocseq < seqno) && (seqno != p->lastnoninvite)) {
15386 if (option_debug)
15387 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
15388 return -1;
15389 } else if (p->ocseq && (p->ocseq != seqno) && (seqno != p->lastnoninvite)) {
15390
15391
15392 ignore = TRUE;
15393 ast_set_flag(req, SIP_PKT_IGNORE);
15394 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
15395 append_history(p, "Ignore", "Ignoring this retransmit\n");
15396 } else if (e) {
15397 e = ast_skip_blanks(e);
15398 if (sscanf(e, "%d %n", &respid, &len) != 1) {
15399 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
15400 } else {
15401 if (respid <= 0) {
15402 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
15403 return 0;
15404 }
15405
15406 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
15407 extract_uri(p, req);
15408 handle_response(p, respid, e + len, req, ignore, seqno);
15409 }
15410 }
15411 return 0;
15412 }
15413
15414
15415
15416
15417
15418 p->method = req->method;
15419 if (option_debug > 3)
15420 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
15421
15422 if (p->icseq && (p->icseq > seqno) ) {
15423 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
15424 if (option_debug > 2)
15425 ast_log(LOG_DEBUG, "Got CANCEL or ACK on INVITE with transactions in between.\n");
15426 } else {
15427 if (option_debug)
15428 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
15429 if (req->method != SIP_ACK)
15430 transmit_response(p, "503 Server error", req);
15431 return -1;
15432 }
15433 } else if (p->icseq &&
15434 p->icseq == seqno &&
15435 req->method != SIP_ACK &&
15436 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
15437
15438
15439
15440 ignore = 2;
15441 ast_set_flag(req, SIP_PKT_IGNORE);
15442 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
15443 if (option_debug > 2)
15444 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
15445 }
15446
15447 if (seqno >= p->icseq)
15448
15449
15450
15451 p->icseq = seqno;
15452
15453
15454 if (ast_strlen_zero(p->theirtag)) {
15455 char tag[128];
15456
15457 gettag(req, "From", tag, sizeof(tag));
15458 ast_string_field_set(p, theirtag, tag);
15459 }
15460 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
15461
15462 if (pedanticsipchecking) {
15463
15464
15465
15466
15467 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
15468
15469 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
15470 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
15471
15472 } else if (req->method != SIP_ACK) {
15473 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
15474 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15475 }
15476 return res;
15477 }
15478 }
15479
15480 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
15481 transmit_response(p, "400 Bad request", req);
15482 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15483 return -1;
15484 }
15485
15486
15487 switch (p->method) {
15488 case SIP_OPTIONS:
15489 res = handle_request_options(p, req);
15490 break;
15491 case SIP_INVITE:
15492 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
15493 break;
15494 case SIP_REFER:
15495 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
15496 break;
15497 case SIP_CANCEL:
15498 res = handle_request_cancel(p, req);
15499 break;
15500 case SIP_BYE:
15501 res = handle_request_bye(p, req);
15502 break;
15503 case SIP_MESSAGE:
15504 res = handle_request_message(p, req);
15505 break;
15506 case SIP_SUBSCRIBE:
15507 res = handle_request_subscribe(p, req, sin, seqno, e);
15508 break;
15509 case SIP_REGISTER:
15510 res = handle_request_register(p, req, sin, e);
15511 break;
15512 case SIP_INFO:
15513 if (ast_test_flag(req, SIP_PKT_DEBUG))
15514 ast_verbose("Receiving INFO!\n");
15515 if (!ignore)
15516 handle_request_info(p, req);
15517 else
15518 transmit_response(p, "200 OK", req);
15519 break;
15520 case SIP_NOTIFY:
15521 res = handle_request_notify(p, req, sin, seqno, e);
15522 break;
15523 case SIP_ACK:
15524
15525 if (seqno == p->pendinginvite) {
15526 p->invitestate = INV_TERMINATED;
15527 p->pendinginvite = 0;
15528 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
15529 if (find_sdp(req)) {
15530 if (process_sdp(p, req))
15531 return -1;
15532 }
15533 check_pendings(p);
15534 }
15535
15536 if (!p->lastinvite && ast_strlen_zero(p->randdata))
15537 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15538 break;
15539 default:
15540 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
15541 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
15542 cmd, ast_inet_ntoa(p->sa.sin_addr));
15543
15544 if (!p->initreq.headers)
15545 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15546 break;
15547 }
15548 return res;
15549 }
15550
15551
15552
15553
15554
15555
15556 static int sipsock_read(int *id, int fd, short events, void *ignore)
15557 {
15558 struct sip_request req;
15559 struct sockaddr_in sin = { 0, };
15560 struct sip_pvt *p;
15561 int res;
15562 socklen_t len = sizeof(sin);
15563 int nounlock;
15564 int recount = 0;
15565 int lockretry;
15566
15567 memset(&req, 0, sizeof(req));
15568 if (fd == sipsock)
15569 res = recvfrom(fd, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
15570 else {
15571 if (getpeername(fd, (struct sockaddr *)&sin, &len) < 0) {
15572 close(fd);
15573 return 1;
15574 }
15575 if ((res = read(fd, req.data, sizeof(req.data) - 1)) == 0) {
15576 close(fd);
15577 return 1;
15578 }
15579 }
15580 if (res < 0) {
15581 #if !defined(__FreeBSD__)
15582 if (errno == EAGAIN)
15583 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
15584 else
15585 #endif
15586 if (errno != ECONNREFUSED)
15587 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
15588 return 1;
15589 }
15590 if (option_debug && res == sizeof(req.data) - 1)
15591 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
15592
15593 req.data[res] = '\0';
15594 req.len = res;
15595 if(sip_debug_test_addr(&sin))
15596 ast_set_flag(&req, SIP_PKT_DEBUG);
15597 if (pedanticsipchecking)
15598 req.len = lws2sws(req.data, req.len);
15599 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15600 ast_verbose("\n<--- SIP read from %s:%d:%s --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
15601 fd == sipsock ? "UDP" : "TCP",req.data);
15602
15603 if(parse_request(&req) == -1)
15604 return 1;
15605
15606 req.method = find_sip_method(req.rlPart1);
15607
15608 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15609 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
15610
15611 if (req.headers < 2)
15612 return 1;
15613
15614
15615 for (lockretry = 100; lockretry > 0; lockretry--) {
15616 ast_mutex_lock(&netlock);
15617
15618
15619 p = find_call(&req, &sin, req.method);
15620 if (p == NULL) {
15621 if (option_debug)
15622 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
15623 ast_mutex_unlock(&netlock);
15624 return 1;
15625 }
15626
15627
15628 if (!p->owner || !ast_channel_trylock(p->owner))
15629 break;
15630 if (option_debug)
15631 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
15632 ast_mutex_unlock(&p->lock);
15633 ast_mutex_unlock(&netlock);
15634
15635 usleep(1);
15636 }
15637 p->recv = sin;
15638
15639 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
15640 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
15641
15642 if (!lockretry) {
15643 if (p->owner)
15644 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
15645 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
15646 if (req.method != SIP_ACK)
15647 transmit_response(p, "503 Server error", &req);
15648
15649 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
15650 return 1;
15651 }
15652 nounlock = 0;
15653
15654 if (fd != sipsock) {
15655 p->sockfd=fd;
15656 ast_set_flag(&p->flags[1], SIP_PAGE2_TCP);
15657 } else {
15658 p->sockfd=-1;
15659 }
15660 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
15661
15662 if (option_debug)
15663 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
15664 }
15665
15666 if (p->owner && !nounlock)
15667 ast_channel_unlock(p->owner);
15668 ast_mutex_unlock(&p->lock);
15669 ast_mutex_unlock(&netlock);
15670 if (recount)
15671 ast_update_use_count();
15672
15673 return 1;
15674 }
15675
15676
15677 static int siptcpsock_accept(int *id, int fd, short events, void *ignore)
15678 {
15679 struct sockaddr_in sa;
15680 socklen_t sa_len=sizeof(sa);
15681 int newfd;
15682
15683 if ((newfd=accept(siptcpsock, (struct sockaddr *)&sa, &sa_len)) >= 0)
15684 ast_io_add(io, newfd, sipsock_read, AST_IO_IN, NULL);
15685 return 1;
15686 }
15687
15688
15689 static int sip_send_mwi_to_peer(struct sip_peer *peer)
15690 {
15691
15692 struct sip_pvt *p;
15693 int newmsgs, oldmsgs;
15694
15695
15696 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
15697 return 0;
15698
15699
15700 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
15701
15702 peer->lastmsgcheck = time(NULL);
15703
15704
15705 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
15706 return 0;
15707 }
15708
15709
15710 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
15711
15712 if (peer->mwipvt) {
15713
15714 p = peer->mwipvt;
15715 } else {
15716
15717 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
15718 return -1;
15719 if (create_addr_from_peer(p, peer)) {
15720
15721 sip_destroy(p);
15722 return 0;
15723 }
15724
15725 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15726 p->ourip = __ourip;
15727 build_via(p);
15728 build_callid_pvt(p);
15729
15730 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15731 }
15732
15733 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15734 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
15735 return 0;
15736 }
15737
15738
15739 static int does_peer_need_mwi(struct sip_peer *peer)
15740 {
15741 time_t t = time(NULL);
15742
15743 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
15744 !peer->mwipvt) {
15745 peer->lastmsgcheck = t;
15746 return FALSE;
15747 }
15748
15749 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
15750 return TRUE;
15751
15752 return FALSE;
15753 }
15754
15755
15756
15757
15758
15759
15760 static void *do_monitor(void *data)
15761 {
15762 int res;
15763 struct sip_pvt *sip;
15764 struct sip_peer *peer = NULL;
15765 time_t t;
15766 int fastrestart = FALSE;
15767 int lastpeernum = -1;
15768 int curpeernum;
15769 int reloading;
15770
15771
15772 if (sipsock > -1)
15773 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15774 if (siptcpsock > -1)
15775 siptcpsock_read_id = ast_io_add(io, siptcpsock, siptcpsock_accept, AST_IO_IN, NULL);
15776
15777
15778 for(;;) {
15779
15780 ast_mutex_lock(&sip_reload_lock);
15781 reloading = sip_reloading;
15782 sip_reloading = FALSE;
15783 ast_mutex_unlock(&sip_reload_lock);
15784 if (reloading) {
15785 if (option_verbose > 0)
15786 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
15787 sip_do_reload(sip_reloadreason);
15788
15789
15790 if (sipsock > -1) {
15791 if (sipsock_read_id)
15792 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
15793 else
15794 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15795 } else if (sipsock_read_id) {
15796 ast_io_remove(io, sipsock_read_id);
15797 sipsock_read_id = NULL;
15798 }
15799
15800 if (siptcpsock > -1) {
15801 if (siptcpsock_read_id)
15802 siptcpsock_read_id = ast_io_change(io, siptcpsock_read_id, siptcpsock, NULL, 0, NULL);
15803 else
15804 siptcpsock_read_id = ast_io_add(io, siptcpsock, siptcpsock_accept, AST_IO_IN, NULL);
15805 }
15806 }
15807 restartsearch:
15808
15809 ast_mutex_lock(&iflock);
15810 t = time(NULL);
15811
15812
15813
15814
15815 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
15816
15817
15818
15819
15820
15821 if (ast_mutex_trylock(&sip->lock))
15822 continue;
15823
15824
15825 if (sip->rtp && sip->owner &&
15826 (sip->owner->_state == AST_STATE_UP) &&
15827 !sip->redirip.sin_addr.s_addr &&
15828 sip->t38.state != T38_ENABLED) {
15829 if (sip->lastrtptx &&
15830 ast_rtp_get_rtpkeepalive(sip->rtp) &&
15831 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
15832
15833 sip->lastrtptx = time(NULL);
15834 ast_rtp_sendcng(sip->rtp, 0);
15835 }
15836 if (sip->lastrtprx &&
15837 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
15838 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
15839
15840 struct sockaddr_in sin;
15841 ast_rtp_get_peer(sip->rtp, &sin);
15842 if (sin.sin_addr.s_addr ||
15843 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
15844 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
15845
15846 if (ast_rtp_get_rtptimeout(sip->rtp)) {
15847 while (sip->owner && ast_channel_trylock(sip->owner)) {
15848 DEADLOCK_AVOIDANCE(&sip->lock);
15849 }
15850 if (sip->owner) {
15851 ast_log(LOG_NOTICE,
15852 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
15853 sip->owner->name,
15854 (long) (t - sip->lastrtprx));
15855
15856 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
15857 ast_channel_unlock(sip->owner);
15858
15859
15860
15861
15862 ast_rtp_set_rtptimeout(sip->rtp, 0);
15863 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
15864 if (sip->vrtp) {
15865 ast_rtp_set_rtptimeout(sip->vrtp, 0);
15866 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
15867 }
15868 }
15869 }
15870 }
15871 }
15872 }
15873
15874 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
15875 !sip->owner) {
15876 ast_mutex_unlock(&sip->lock);
15877 __sip_destroy(sip, 1);
15878 ast_mutex_unlock(&iflock);
15879 usleep(1);
15880 goto restartsearch;
15881 }
15882 ast_mutex_unlock(&sip->lock);
15883 }
15884 ast_mutex_unlock(&iflock);
15885
15886 pthread_testcancel();
15887
15888 res = ast_sched_wait(sched);
15889 if ((res < 0) || (res > 1000))
15890 res = 1000;
15891
15892 if (fastrestart)
15893 res = 1;
15894 res = ast_io_wait(io, res);
15895 if (option_debug && res > 20)
15896 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
15897 ast_mutex_lock(&monlock);
15898 if (res >= 0) {
15899 res = ast_sched_runq(sched);
15900 if (option_debug && res >= 20)
15901 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
15902 }
15903
15904
15905 t = time(NULL);
15906 fastrestart = FALSE;
15907 curpeernum = 0;
15908 peer = NULL;
15909
15910 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
15911 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
15912 fastrestart = TRUE;
15913 lastpeernum = curpeernum;
15914 peer = ASTOBJ_REF(iterator);
15915 };
15916 curpeernum++;
15917 } while (0)
15918 );
15919
15920 if (peer) {
15921 ASTOBJ_WRLOCK(peer);
15922 sip_send_mwi_to_peer(peer);
15923 ASTOBJ_UNLOCK(peer);
15924 ASTOBJ_UNREF(peer,sip_destroy_peer);
15925 } else {
15926
15927 lastpeernum = -1;
15928 }
15929 ast_mutex_unlock(&monlock);
15930 }
15931
15932 return NULL;
15933
15934 }
15935
15936
15937 static int restart_monitor(void)
15938 {
15939
15940 if (monitor_thread == AST_PTHREADT_STOP)
15941 return 0;
15942 ast_mutex_lock(&monlock);
15943 if (monitor_thread == pthread_self()) {
15944 ast_mutex_unlock(&monlock);
15945 ast_log(LOG_WARNING, "Cannot kill myself\n");
15946 return -1;
15947 }
15948 if (monitor_thread != AST_PTHREADT_NULL) {
15949
15950 pthread_kill(monitor_thread, SIGURG);
15951 } else {
15952
15953 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
15954 ast_mutex_unlock(&monlock);
15955 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
15956 return -1;
15957 }
15958 }
15959 ast_mutex_unlock(&monlock);
15960 return 0;
15961 }
15962
15963
15964 static int sip_poke_noanswer(const void *data)
15965 {
15966 struct sip_peer *peer = (struct sip_peer *)data;
15967
15968 peer->pokeexpire = -1;
15969 if (peer->lastms > -1) {
15970 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
15971 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
15972 }
15973 if (peer->call)
15974 sip_destroy(peer->call);
15975 peer->call = NULL;
15976 peer->lastms = -1;
15977 ast_device_state_changed("SIP/%s", peer->name);
15978
15979
15980 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
15981 struct sip_peer *peer_ptr = peer;
15982 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
15983 }
15984
15985
15986
15987 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
15988 if (peer->pokeexpire == -1) {
15989 ASTOBJ_UNREF(peer, sip_destroy_peer);
15990 }
15991
15992 return 0;
15993 }
15994
15995
15996
15997
15998 static int sip_poke_peer(struct sip_peer *peer)
15999 {
16000 struct sip_pvt *p;
16001 int xmitres = 0;
16002
16003 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
16004
16005
16006 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16007 struct sip_peer *peer_ptr = peer;
16008 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16009 }
16010 peer->lastms = 0;
16011 peer->call = NULL;
16012 return 0;
16013 }
16014 if (peer->call) {
16015 if (sipdebug)
16016 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
16017 sip_destroy(peer->call);
16018 }
16019 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
16020 return -1;
16021
16022 p->sa = peer->addr;
16023 p->recv = peer->addr;
16024 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16025 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16026 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_TCP | SIP_PAGE2_TCP_CONNECTED);
16027 p->sockfd = peer->sockfd;
16028
16029
16030 if (!ast_strlen_zero(peer->fullcontact))
16031 ast_string_field_set(p, fullcontact, peer->fullcontact);
16032
16033 if (!ast_strlen_zero(peer->tohost))
16034 ast_string_field_set(p, tohost, peer->tohost);
16035 else
16036 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
16037
16038
16039 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16040 p->ourip = __ourip;
16041 build_via(p);
16042 build_callid_pvt(p);
16043
16044 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16045 struct sip_peer *peer_ptr = peer;
16046 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16047 }
16048
16049 p->relatedpeer = ASTOBJ_REF(peer);
16050 ast_set_flag(&p->flags[0], SIP_OUTGOING);
16051 #ifdef VOCAL_DATA_HACK
16052 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
16053 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
16054 #else
16055 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
16056 #endif
16057 gettimeofday(&peer->ps, NULL);
16058 if (xmitres == XMIT_ERROR) {
16059 sip_poke_noanswer(ASTOBJ_REF(peer));
16060 } else {
16061 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
16062 struct sip_peer *peer_ptr = peer;
16063 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16064 }
16065 peer->pokeexpire = ast_sched_add(sched, peer->maxms * 2, sip_poke_noanswer, ASTOBJ_REF(peer));
16066 if (peer->pokeexpire == -1) {
16067 struct sip_peer *peer_ptr = peer;
16068 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16069 }
16070 }
16071
16072 return 0;
16073 }
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108 static int sip_devicestate(void *data)
16109 {
16110 char *host;
16111 char *tmp;
16112
16113 struct hostent *hp;
16114 struct ast_hostent ahp;
16115 struct sip_peer *p;
16116
16117 int res = AST_DEVICE_INVALID;
16118
16119
16120 host = ast_strdupa(data ? data : "");
16121 if ((tmp = strchr(host, '@')))
16122 host = tmp + 1;
16123
16124 if (option_debug > 2)
16125 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
16126
16127 if ((p = find_peer(host, NULL, 1))) {
16128 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140 if (p->onHold)
16141
16142 res = AST_DEVICE_ONHOLD;
16143 else if (p->inRinging) {
16144 if (p->inRinging == p->inUse)
16145 res = AST_DEVICE_RINGING;
16146 else
16147 res = AST_DEVICE_RINGINUSE;
16148 } else if (p->call_limit && (p->inUse == p->call_limit))
16149
16150 res = AST_DEVICE_BUSY;
16151 else if (p->call_limit && p->inUse)
16152
16153 res = AST_DEVICE_INUSE;
16154 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
16155
16156 res = AST_DEVICE_UNAVAILABLE;
16157 else
16158 res = AST_DEVICE_NOT_INUSE;
16159 } else {
16160
16161 res = AST_DEVICE_UNAVAILABLE;
16162 }
16163 ASTOBJ_UNREF(p,sip_destroy_peer);
16164 } else {
16165 char *port = strchr(host, ':');
16166 if (port)
16167 *port = '\0';
16168 hp = ast_gethostbyname(host, &ahp);
16169 if (hp)
16170 res = AST_DEVICE_UNKNOWN;
16171 }
16172
16173 return res;
16174 }
16175
16176
16177
16178 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
16179 {
16180 int oldformat;
16181 struct sip_pvt *p;
16182 struct ast_channel *tmpc = NULL;
16183 char *ext, *host;
16184 char tmp[256];
16185 char *dest = data;
16186
16187 oldformat = format;
16188 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
16189 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
16190 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
16191 return NULL;
16192 }
16193 if (option_debug)
16194 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
16195
16196 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
16197 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
16198 *cause = AST_CAUSE_SWITCH_CONGESTION;
16199 return NULL;
16200 }
16201
16202 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
16203
16204 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
16205 sip_destroy(p);
16206 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
16207 *cause = AST_CAUSE_SWITCH_CONGESTION;
16208 return NULL;
16209 }
16210
16211 ast_copy_string(tmp, dest, sizeof(tmp));
16212 host = strchr(tmp, '@');
16213 if (host) {
16214 *host++ = '\0';
16215 ext = tmp;
16216 } else {
16217 ext = strchr(tmp, '/');
16218 if (ext)
16219 *ext++ = '\0';
16220 host = tmp;
16221 }
16222
16223 if (create_addr(p, host)) {
16224 *cause = AST_CAUSE_UNREGISTERED;
16225 if (option_debug > 2)
16226 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
16227 sip_destroy(p);
16228 return NULL;
16229 }
16230 if (ast_strlen_zero(p->peername) && ext)
16231 ast_string_field_set(p, peername, ext);
16232
16233 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16234 p->ourip = __ourip;
16235 build_via(p);
16236 build_callid_pvt(p);
16237
16238
16239
16240
16241
16242 if (ext) {
16243 ast_string_field_set(p, username, ext);
16244 ast_string_field_free(p, fullcontact);
16245 }
16246 #if 0
16247 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
16248 #endif
16249 p->prefcodec = oldformat;
16250 ast_mutex_lock(&p->lock);
16251 tmpc = sip_new(p, AST_STATE_DOWN, host);
16252 ast_mutex_unlock(&p->lock);
16253 if (!tmpc)
16254 sip_destroy(p);
16255 ast_update_use_count();
16256 restart_monitor();
16257 return tmpc;
16258 }
16259
16260
16261
16262
16263
16264
16265
16266 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno)
16267 {
16268 static int dep_insecure_very = 0;
16269 static int dep_insecure_yes = 0;
16270
16271 if (ast_strlen_zero(value))
16272 return;
16273
16274 if (!strcasecmp(value, "very")) {
16275 ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16276 if(!dep_insecure_very) {
16277 if(lineno != -1)
16278 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", lineno);
16279 else
16280 ast_log(LOG_WARNING, "insecure=very is deprecated; use insecure=port,invite instead\n");
16281 dep_insecure_very = 1;
16282 }
16283 }
16284 else if (ast_true(value)) {
16285 ast_set_flag(flags, SIP_INSECURE_PORT);
16286 if(!dep_insecure_yes) {
16287 if(lineno != -1)
16288 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", value, lineno);
16289 else
16290 ast_log(LOG_WARNING, "insecure=%s is deprecated; use insecure=port instead\n", value);
16291 dep_insecure_yes = 1;
16292 }
16293 }
16294 else if (!ast_false(value)) {
16295 char buf[64];
16296 char *word, *next;
16297 ast_copy_string(buf, value, sizeof(buf));
16298 next = buf;
16299 while ((word = strsep(&next, ","))) {
16300 if (!strcasecmp(word, "port"))
16301 ast_set_flag(flags, SIP_INSECURE_PORT);
16302 else if (!strcasecmp(word, "invite"))
16303 ast_set_flag(flags, SIP_INSECURE_INVITE);
16304 else
16305 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
16306 }
16307 }
16308 }
16309
16310
16311
16312
16313
16314
16315
16316
16317 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
16318 {
16319 int res = 1;
16320
16321 if (!strcasecmp(v->name, "trustrpid")) {
16322 ast_set_flag(&mask[0], SIP_TRUSTRPID);
16323 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
16324 } else if (!strcasecmp(v->name, "sendrpid")) {
16325 ast_set_flag(&mask[0], SIP_SENDRPID);
16326 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
16327 } else if (!strcasecmp(v->name, "g726nonstandard")) {
16328 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
16329 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
16330 } else if (!strcasecmp(v->name, "useclientcode")) {
16331 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
16332 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
16333 } else if (!strcasecmp(v->name, "dtmfmode")) {
16334 ast_set_flag(&mask[0], SIP_DTMF);
16335 ast_clear_flag(&flags[0], SIP_DTMF);
16336 if (!strcasecmp(v->value, "inband"))
16337 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
16338 else if (!strcasecmp(v->value, "rfc2833"))
16339 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16340 else if (!strcasecmp(v->value, "info"))
16341 ast_set_flag(&flags[0], SIP_DTMF_INFO);
16342 else if (!strcasecmp(v->value, "auto"))
16343 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
16344 else {
16345 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
16346 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16347 }
16348 } else if (!strcasecmp(v->name, "nat")) {
16349 ast_set_flag(&mask[0], SIP_NAT);
16350 ast_clear_flag(&flags[0], SIP_NAT);
16351 if (!strcasecmp(v->value, "never"))
16352 ast_set_flag(&flags[0], SIP_NAT_NEVER);
16353 else if (!strcasecmp(v->value, "route"))
16354 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
16355 else if (ast_true(v->value))
16356 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
16357 else
16358 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
16359 } else if (!strcasecmp(v->name, "canreinvite")) {
16360 ast_set_flag(&mask[0], SIP_REINVITE);
16361 ast_clear_flag(&flags[0], SIP_REINVITE);
16362 if(ast_true(v->value)) {
16363 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
16364 } else if (!ast_false(v->value)) {
16365 char buf[64];
16366 char *word, *next = buf;
16367
16368 ast_copy_string(buf, v->value, sizeof(buf));
16369 while ((word = strsep(&next, ","))) {
16370 if(!strcasecmp(word, "update")) {
16371 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
16372 } else if(!strcasecmp(word, "nonat")) {
16373 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
16374 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
16375 } else {
16376 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
16377 }
16378 }
16379 }
16380 } else if (!strcasecmp(v->name, "insecure")) {
16381 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16382 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16383 set_insecure_flags(flags, v->value, v->lineno);
16384 } else if (!strcasecmp(v->name, "progressinband")) {
16385 ast_set_flag(&mask[0], SIP_PROG_INBAND);
16386 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
16387 if (ast_true(v->value))
16388 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
16389 else if (strcasecmp(v->value, "never"))
16390 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
16391 } else if (!strcasecmp(v->name, "promiscredir")) {
16392 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
16393 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
16394 } else if (!strcasecmp(v->name, "videosupport")) {
16395 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
16396 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
16397 } else if (!strcasecmp(v->name, "allowoverlap")) {
16398 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
16399 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
16400 } else if (!strcasecmp(v->name, "allowsubscribe")) {
16401 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16402 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
16403 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
16404 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
16405 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
16406 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
16407 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
16408 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
16409 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
16410 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
16411 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
16412 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
16413 #endif
16414 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
16415 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
16416 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
16417 } else if (!strcasecmp(v->name, "buggymwi")) {
16418 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
16419 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
16420 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
16421 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
16422 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
16423 } else
16424 res = 0;
16425
16426 return res;
16427 }
16428
16429
16430 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
16431 {
16432 struct domain *d;
16433
16434 if (ast_strlen_zero(domain)) {
16435 ast_log(LOG_WARNING, "Zero length domain.\n");
16436 return 1;
16437 }
16438
16439 if (!(d = ast_calloc(1, sizeof(*d))))
16440 return 0;
16441
16442 ast_copy_string(d->domain, domain, sizeof(d->domain));
16443
16444 if (!ast_strlen_zero(context))
16445 ast_copy_string(d->context, context, sizeof(d->context));
16446
16447 d->mode = mode;
16448
16449 AST_LIST_LOCK(&domain_list);
16450 AST_LIST_INSERT_TAIL(&domain_list, d, list);
16451 AST_LIST_UNLOCK(&domain_list);
16452
16453 if (sipdebug)
16454 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
16455
16456 return 1;
16457 }
16458
16459
16460 static int check_sip_domain(const char *domain, char *context, size_t len)
16461 {
16462 struct domain *d;
16463 int result = 0;
16464
16465 AST_LIST_LOCK(&domain_list);
16466 AST_LIST_TRAVERSE(&domain_list, d, list) {
16467 if (strcasecmp(d->domain, domain))
16468 continue;
16469
16470 if (len && !ast_strlen_zero(d->context))
16471 ast_copy_string(context, d->context, len);
16472
16473 result = 1;
16474 break;
16475 }
16476 AST_LIST_UNLOCK(&domain_list);
16477
16478 return result;
16479 }
16480
16481
16482 static void clear_sip_domains(void)
16483 {
16484 struct domain *d;
16485
16486 AST_LIST_LOCK(&domain_list);
16487 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
16488 free(d);
16489 AST_LIST_UNLOCK(&domain_list);
16490 }
16491
16492
16493
16494 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
16495 {
16496 char authcopy[256];
16497 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
16498 char *stringp;
16499 struct sip_auth *a, *b, *auth;
16500
16501 if (ast_strlen_zero(configuration))
16502 return authlist;
16503
16504 if (option_debug)
16505 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
16506
16507 ast_copy_string(authcopy, configuration, sizeof(authcopy));
16508 stringp = authcopy;
16509
16510 username = stringp;
16511 realm = strrchr(stringp, '@');
16512 if (realm)
16513 *realm++ = '\0';
16514 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
16515 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
16516 return authlist;
16517 }
16518 stringp = username;
16519 username = strsep(&stringp, ":");
16520 if (username) {
16521 secret = strsep(&stringp, ":");
16522 if (!secret) {
16523 stringp = username;
16524 md5secret = strsep(&stringp,"#");
16525 }
16526 }
16527 if (!(auth = ast_calloc(1, sizeof(*auth))))
16528 return authlist;
16529
16530 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
16531 ast_copy_string(auth->username, username, sizeof(auth->username));
16532 if (secret)
16533 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
16534 if (md5secret)
16535 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
16536
16537
16538 for (b = NULL, a = authlist; a ; b = a, a = a->next)
16539 ;
16540 if (b)
16541 b->next = auth;
16542 else
16543 authlist = auth;
16544
16545 if (option_verbose > 2)
16546 ast_verbose("Added authentication for realm %s\n", realm);
16547
16548 return authlist;
16549
16550 }
16551
16552
16553 static int clear_realm_authentication(struct sip_auth *authlist)
16554 {
16555 struct sip_auth *a = authlist;
16556 struct sip_auth *b;
16557
16558 while (a) {
16559 b = a;
16560 a = a->next;
16561 free(b);
16562 }
16563
16564 return 1;
16565 }
16566
16567
16568 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
16569 {
16570 struct sip_auth *a;
16571
16572 for (a = authlist; a; a = a->next) {
16573 if (!strcasecmp(a->realm, realm))
16574 break;
16575 }
16576
16577 return a;
16578 }
16579
16580
16581 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16582 {
16583 struct sip_user *user;
16584 int format;
16585 struct ast_ha *oldha = NULL;
16586 char *varname = NULL, *varval = NULL;
16587 struct ast_variable *tmpvar = NULL;
16588 struct ast_flags userflags[2] = {{(0)}};
16589 struct ast_flags mask[2] = {{(0)}};
16590
16591
16592 if (!(user = ast_calloc(1, sizeof(*user))))
16593 return NULL;
16594
16595 suserobjs++;
16596 ASTOBJ_INIT(user);
16597 ast_copy_string(user->name, name, sizeof(user->name));
16598 oldha = user->ha;
16599 user->ha = NULL;
16600 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16601 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16602 user->capability = global_capability;
16603 user->allowtransfer = global_allowtransfer;
16604 user->maxcallbitrate = default_maxcallbitrate;
16605 user->autoframing = global_autoframing;
16606 user->prefs = default_prefs;
16607
16608 strcpy(user->context, default_context);
16609 strcpy(user->language, default_language);
16610 strcpy(user->mohinterpret, default_mohinterpret);
16611 strcpy(user->mohsuggest, default_mohsuggest);
16612
16613 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16614 if (handle_common_options(&userflags[0], &mask[0], v))
16615 continue;
16616
16617 if (!strcasecmp(v->name, "context")) {
16618 ast_copy_string(user->context, v->value, sizeof(user->context));
16619 } else if (!strcasecmp(v->name, "subscribecontext")) {
16620 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
16621 } else if (!strcasecmp(v->name, "setvar")) {
16622 varname = ast_strdupa(v->value);
16623 if ((varval = strchr(varname,'='))) {
16624 *varval++ = '\0';
16625 if ((tmpvar = ast_variable_new(varname, varval))) {
16626 tmpvar->next = user->chanvars;
16627 user->chanvars = tmpvar;
16628 }
16629 }
16630 } else if (!strcasecmp(v->name, "permit") ||
16631 !strcasecmp(v->name, "deny")) {
16632 user->ha = ast_append_ha(v->name, v->value, user->ha);
16633 } else if (!strcasecmp(v->name, "allowtransfer")) {
16634 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16635 } else if (!strcasecmp(v->name, "secret")) {
16636 ast_copy_string(user->secret, v->value, sizeof(user->secret));
16637 } else if (!strcasecmp(v->name, "md5secret")) {
16638 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
16639 } else if (!strcasecmp(v->name, "callerid")) {
16640 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
16641 } else if (!strcasecmp(v->name, "fullname")) {
16642 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
16643 } else if (!strcasecmp(v->name, "cid_number")) {
16644 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
16645 } else if (!strcasecmp(v->name, "callgroup")) {
16646 user->callgroup = ast_get_group(v->value);
16647 } else if (!strcasecmp(v->name, "pickupgroup")) {
16648 user->pickupgroup = ast_get_group(v->value);
16649 } else if (!strcasecmp(v->name, "language")) {
16650 ast_copy_string(user->language, v->value, sizeof(user->language));
16651 } else if (!strcasecmp(v->name, "mohinterpret")
16652 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16653 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
16654 } else if (!strcasecmp(v->name, "mohsuggest")) {
16655 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
16656 } else if (!strcasecmp(v->name, "accountcode")) {
16657 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
16658 } else if (!strcasecmp(v->name, "call-limit")) {
16659 user->call_limit = atoi(v->value);
16660 if (user->call_limit < 0)
16661 user->call_limit = 0;
16662 } else if (!strcasecmp(v->name, "amaflags")) {
16663 format = ast_cdr_amaflags2int(v->value);
16664 if (format < 0) {
16665 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
16666 } else {
16667 user->amaflags = format;
16668 }
16669 } else if (!strcasecmp(v->name, "allow")) {
16670 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
16671 } else if (!strcasecmp(v->name, "disallow")) {
16672 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
16673 } else if (!strcasecmp(v->name, "autoframing")) {
16674 user->autoframing = ast_true(v->value);
16675 } else if (!strcasecmp(v->name, "callingpres")) {
16676 user->callingpres = ast_parse_caller_presentation(v->value);
16677 if (user->callingpres == -1)
16678 user->callingpres = atoi(v->value);
16679 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16680 user->maxcallbitrate = atoi(v->value);
16681 if (user->maxcallbitrate < 0)
16682 user->maxcallbitrate = default_maxcallbitrate;
16683 }
16684
16685
16686
16687 }
16688 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
16689 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
16690 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16691 global_allowsubscribe = TRUE;
16692 ast_free_ha(oldha);
16693 return user;
16694 }
16695
16696
16697 static void set_peer_defaults(struct sip_peer *peer)
16698 {
16699 if (peer->expire == 0) {
16700
16701
16702
16703 peer->expire = -1;
16704 peer->pokeexpire = -1;
16705 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16706 }
16707 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16708 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16709 strcpy(peer->context, default_context);
16710 strcpy(peer->subscribecontext, default_subscribecontext);
16711 strcpy(peer->language, default_language);
16712 strcpy(peer->mohinterpret, default_mohinterpret);
16713 strcpy(peer->mohsuggest, default_mohsuggest);
16714 peer->addr.sin_family = AF_INET;
16715 peer->defaddr.sin_family = AF_INET;
16716 peer->capability = global_capability;
16717 peer->maxcallbitrate = default_maxcallbitrate;
16718 peer->rtptimeout = global_rtptimeout;
16719 peer->rtpholdtimeout = global_rtpholdtimeout;
16720 peer->rtpkeepalive = global_rtpkeepalive;
16721 peer->allowtransfer = global_allowtransfer;
16722 peer->autoframing = global_autoframing;
16723 strcpy(peer->vmexten, default_vmexten);
16724 peer->secret[0] = '\0';
16725 peer->md5secret[0] = '\0';
16726 peer->cid_num[0] = '\0';
16727 peer->cid_name[0] = '\0';
16728 peer->fromdomain[0] = '\0';
16729 peer->fromuser[0] = '\0';
16730 peer->regexten[0] = '\0';
16731 peer->mailbox[0] = '\0';
16732 peer->callgroup = 0;
16733 peer->pickupgroup = 0;
16734 peer->maxms = default_qualify;
16735 peer->prefs = default_prefs;
16736 }
16737
16738
16739 static struct sip_peer *temp_peer(const char *name)
16740 {
16741 struct sip_peer *peer;
16742
16743 if (!(peer = ast_calloc(1, sizeof(*peer))))
16744 return NULL;
16745
16746 apeerobjs++;
16747 ASTOBJ_INIT(peer);
16748 set_peer_defaults(peer);
16749
16750 ast_copy_string(peer->name, name, sizeof(peer->name));
16751
16752 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
16753 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16754 peer->prefs = default_prefs;
16755 reg_source_db(peer);
16756
16757 return peer;
16758 }
16759
16760
16761 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16762 {
16763 struct sip_peer *peer = NULL;
16764 struct ast_ha *oldha = NULL;
16765 int obproxyfound=0;
16766 int found=0;
16767 int firstpass=1;
16768 int format=0;
16769 time_t regseconds = 0;
16770 char *varname = NULL, *varval = NULL;
16771 struct ast_variable *tmpvar = NULL;
16772 struct ast_flags peerflags[2] = {{(0)}};
16773 struct ast_flags mask[2] = {{(0)}};
16774 char fullcontact[sizeof(peer->fullcontact)] = "";
16775
16776 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
16777
16778
16779
16780
16781
16782 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
16783
16784 if (peer) {
16785
16786 found = 1;
16787 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
16788 firstpass = 0;
16789 } else {
16790 if (!(peer = ast_calloc(1, sizeof(*peer))))
16791 return NULL;
16792
16793 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))
16794 rpeerobjs++;
16795 else
16796 speerobjs++;
16797 ASTOBJ_INIT(peer);
16798 }
16799
16800 if (firstpass) {
16801 peer->lastmsgssent = -1;
16802 oldha = peer->ha;
16803 peer->ha = NULL;
16804 set_peer_defaults(peer);
16805 }
16806 if (!found && name)
16807 ast_copy_string(peer->name, name, sizeof(peer->name));
16808
16809
16810 if (peer->chanvars) {
16811 ast_variables_destroy(peer->chanvars);
16812 peer->chanvars = NULL;
16813
16814 }
16815
16816
16817 clear_realm_authentication(peer->auth);
16818 peer->auth = NULL;
16819 peer->sockfd = -1;
16820
16821 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16822 if (handle_common_options(&peerflags[0], &mask[0], v))
16823 continue;
16824 if (realtime && !strcasecmp(v->name, "regseconds")) {
16825 ast_get_time_t(v->value, ®seconds, 0, NULL);
16826 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
16827 inet_aton(v->value, &(peer->addr.sin_addr));
16828 } else if (realtime && !strcasecmp(v->name, "name"))
16829 ast_copy_string(peer->name, v->value, sizeof(peer->name));
16830 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
16831
16832 if (!ast_strlen_zero(fullcontact)) {
16833 strncat(fullcontact, ";", sizeof(fullcontact) - strlen(fullcontact) - 1);
16834 strncat(fullcontact, v->value, sizeof(fullcontact) - strlen(fullcontact) - 1);
16835 } else {
16836 ast_copy_string(fullcontact, v->value, sizeof(fullcontact));
16837 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
16838 }
16839 } else if (!strcasecmp(v->name, "secret"))
16840 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
16841 else if (!strcasecmp(v->name, "md5secret"))
16842 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
16843 else if (!strcasecmp(v->name, "auth"))
16844 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
16845 else if (!strcasecmp(v->name, "callerid")) {
16846 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
16847 } else if (!strcasecmp(v->name, "fullname")) {
16848 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
16849 } else if (!strcasecmp(v->name, "cid_number")) {
16850 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
16851 } else if (!strcasecmp(v->name, "context")) {
16852 ast_copy_string(peer->context, v->value, sizeof(peer->context));
16853 } else if (!strcasecmp(v->name, "subscribecontext")) {
16854 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
16855 } else if (!strcasecmp(v->name, "fromdomain")) {
16856 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
16857 } else if (!strcasecmp(v->name, "usereqphone")) {
16858 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
16859 } else if (!strcasecmp(v->name, "fromuser")) {
16860 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
16861 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
16862 if (!strcasecmp(v->value, "dynamic")) {
16863 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
16864 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
16865 } else {
16866
16867 if (!found || !ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
16868
16869
16870 memset(&peer->addr.sin_addr, 0, 4);
16871 if (peer->addr.sin_port) {
16872
16873 peer->defaddr.sin_port = peer->addr.sin_port;
16874 peer->addr.sin_port = 0;
16875 }
16876 }
16877 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16878 }
16879 } else {
16880
16881 if (!AST_SCHED_DEL(sched, peer->expire)) {
16882 struct sip_peer *peer_ptr = peer;
16883 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
16884 }
16885 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16886 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
16887 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
16888 ASTOBJ_UNREF(peer, sip_destroy_peer);
16889 return NULL;
16890 }
16891 }
16892 if (!strcasecmp(v->name, "outboundproxy"))
16893 obproxyfound=1;
16894 else {
16895 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
16896 if (!peer->addr.sin_port)
16897 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16898 }
16899 }
16900 } else if (!strcasecmp(v->name, "defaultip")) {
16901 if (ast_get_ip(&peer->defaddr, v->value)) {
16902 ASTOBJ_UNREF(peer, sip_destroy_peer);
16903 return NULL;
16904 }
16905 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
16906 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
16907 } else if (!strcasecmp(v->name, "port")) {
16908 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
16909 peer->defaddr.sin_port = htons(atoi(v->value));
16910 else
16911 peer->addr.sin_port = htons(atoi(v->value));
16912 } else if (!strcasecmp(v->name, "callingpres")) {
16913 peer->callingpres = ast_parse_caller_presentation(v->value);
16914 if (peer->callingpres == -1)
16915 peer->callingpres = atoi(v->value);
16916 } else if (!strcasecmp(v->name, "username")) {
16917 ast_copy_string(peer->username, v->value, sizeof(peer->username));
16918 } else if (!strcasecmp(v->name, "language")) {
16919 ast_copy_string(peer->language, v->value, sizeof(peer->language));
16920 } else if (!strcasecmp(v->name, "regexten")) {
16921 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
16922 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
16923 peer->call_limit = atoi(v->value);
16924 if (peer->call_limit < 0)
16925 peer->call_limit = 0;
16926 } else if (!strcasecmp(v->name, "amaflags")) {
16927 format = ast_cdr_amaflags2int(v->value);
16928 if (format < 0) {
16929 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
16930 } else {
16931 peer->amaflags = format;
16932 }
16933 } else if (!strcasecmp(v->name, "accountcode")) {
16934 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
16935 } else if (!strcasecmp(v->name, "mohinterpret")
16936 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16937 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
16938 } else if (!strcasecmp(v->name, "mohsuggest")) {
16939 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
16940 } else if (!strcasecmp(v->name, "mailbox")) {
16941 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
16942 } else if (!strcasecmp(v->name, "subscribemwi")) {
16943 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
16944 } else if (!strcasecmp(v->name, "vmexten")) {
16945 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
16946 } else if (!strcasecmp(v->name, "callgroup")) {
16947 peer->callgroup = ast_get_group(v->value);
16948 } else if (!strcasecmp(v->name, "allowtransfer")) {
16949 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16950 } else if (!strcasecmp(v->name, "pickupgroup")) {
16951 peer->pickupgroup = ast_get_group(v->value);
16952 } else if (!strcasecmp(v->name, "allow")) {
16953 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
16954 } else if (!strcasecmp(v->name, "disallow")) {
16955 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
16956 } else if (!strcasecmp(v->name, "autoframing")) {
16957 peer->autoframing = ast_true(v->value);
16958 } else if (!strcasecmp(v->name, "rtptimeout")) {
16959 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
16960 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16961 peer->rtptimeout = global_rtptimeout;
16962 }
16963 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16964 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
16965 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16966 peer->rtpholdtimeout = global_rtpholdtimeout;
16967 }
16968 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16969 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
16970 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16971 peer->rtpkeepalive = global_rtpkeepalive;
16972 }
16973 } else if (!strcasecmp(v->name, "setvar")) {
16974
16975 varname = ast_strdupa(v->value);
16976 if ((varval = strchr(varname, '='))) {
16977 *varval++ = '\0';
16978 if ((tmpvar = ast_variable_new(varname, varval))) {
16979 tmpvar->next = peer->chanvars;
16980 peer->chanvars = tmpvar;
16981 }
16982 }
16983 } else if (!strcasecmp(v->name, "qualify")) {
16984 if (!strcasecmp(v->value, "no")) {
16985 peer->maxms = 0;
16986 } else if (!strcasecmp(v->value, "yes")) {
16987 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
16988 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
16989 ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
16990 peer->maxms = 0;
16991 }
16992 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16993 peer->maxcallbitrate = atoi(v->value);
16994 if (peer->maxcallbitrate < 0)
16995 peer->maxcallbitrate = default_maxcallbitrate;
16996 }
16997 }
16998 if (!ast_strlen_zero(fullcontact)) {
16999 ast_copy_string(peer->fullcontact, fullcontact, sizeof(peer->fullcontact));
17000 }
17001
17002 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
17003 time_t nowtime = time(NULL);
17004
17005 if ((nowtime - regseconds) > 0) {
17006 destroy_association(peer);
17007 memset(&peer->addr, 0, sizeof(peer->addr));
17008 if (option_debug)
17009 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
17010 }
17011 }
17012 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
17013 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
17014 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
17015 global_allowsubscribe = TRUE;
17016 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
17017 reg_source_db(peer);
17018 ASTOBJ_UNMARK(peer);
17019 ast_free_ha(oldha);
17020 return peer;
17021 }
17022
17023
17024
17025
17026
17027
17028
17029 static int reload_config(enum channelreloadreason reason)
17030 {
17031 struct ast_config *cfg, *ucfg;
17032 struct ast_variable *v;
17033 struct sip_peer *peer;
17034 struct sip_user *user;
17035 struct ast_hostent ahp;
17036 char *cat, *stringp, *context, *oldregcontext;
17037 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
17038 struct hostent *hp;
17039 int format;
17040 struct ast_flags dummy[2];
17041 int auto_sip_domains = FALSE;
17042 struct sockaddr_in old_bindaddr = bindaddr;
17043 int registry_count = 0, peer_count = 0, user_count = 0;
17044 unsigned int temp_tos = 0;
17045 struct ast_flags debugflag = {0};
17046
17047 cfg = ast_config_load(config);
17048
17049
17050 if (!cfg) {
17051 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
17052 return -1;
17053 }
17054
17055 if (option_debug > 3)
17056 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
17057
17058 clear_realm_authentication(authl);
17059 clear_sip_domains();
17060 authl = NULL;
17061
17062
17063
17064 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
17065 ASTOBJ_RDLOCK(iterator);
17066 if (iterator->call) {
17067 if (option_debug > 2)
17068 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
17069
17070 sip_destroy(iterator->call);
17071 }
17072 ASTOBJ_UNLOCK(iterator);
17073
17074 } while(0));
17075
17076
17077 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
17078 if (option_debug > 3)
17079 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
17080 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
17081 if (option_debug > 3)
17082 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
17083 ASTOBJ_CONTAINER_MARKALL(&peerl);
17084
17085
17086 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
17087 oldregcontext = oldcontexts;
17088
17089
17090
17091 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
17092 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
17093 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
17094 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
17095
17096
17097 memset(&bindaddr, 0, sizeof(bindaddr));
17098 ast_free_ha(localaddr);
17099 memset(&localaddr, 0, sizeof(localaddr));
17100 memset(&externip, 0, sizeof(externip));
17101 memset(&default_prefs, 0 , sizeof(default_prefs));
17102 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
17103 outboundproxyip.sin_family = AF_INET;
17104 ourport = STANDARD_SIP_PORT;
17105 srvlookup = DEFAULT_SRVLOOKUP;
17106 global_tos_sip = DEFAULT_TOS_SIP;
17107 global_tos_audio = DEFAULT_TOS_AUDIO;
17108 global_tos_video = DEFAULT_TOS_VIDEO;
17109 externhost[0] = '\0';
17110 externexpire = 0;
17111 externrefresh = 10;
17112 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
17113
17114
17115 allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
17116 global_regcontext[0] = '\0';
17117 expiry = DEFAULT_EXPIRY;
17118 global_notifyringing = DEFAULT_NOTIFYRINGING;
17119 global_limitonpeers = FALSE;
17120 global_directrtpsetup = FALSE;
17121 global_notifyhold = FALSE;
17122 global_alwaysauthreject = 0;
17123 global_allowsubscribe = FALSE;
17124 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
17125 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
17126 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
17127 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
17128 else
17129 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
17130 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
17131 compactheaders = DEFAULT_COMPACTHEADERS;
17132 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17133 global_regattempts_max = 0;
17134 pedanticsipchecking = DEFAULT_PEDANTIC;
17135 global_mwitime = DEFAULT_MWITIME;
17136 autocreatepeer = DEFAULT_AUTOCREATEPEER;
17137 global_autoframing = 0;
17138 global_allowguest = DEFAULT_ALLOWGUEST;
17139 global_rtptimeout = 0;
17140 global_rtpholdtimeout = 0;
17141 global_rtpkeepalive = 0;
17142 global_allowtransfer = TRANSFER_OPENFORALL;
17143 global_rtautoclear = 120;
17144 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
17145 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
17146 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
17147
17148
17149 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
17150 default_subscribecontext[0] = '\0';
17151 default_language[0] = '\0';
17152 default_fromdomain[0] = '\0';
17153 default_qualify = DEFAULT_QUALIFY;
17154 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17155 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
17156 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
17157 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
17158 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
17159 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
17160 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);
17161
17162
17163 dumphistory = FALSE;
17164 recordhistory = FALSE;
17165 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17166
17167
17168 global_relaxdtmf = FALSE;
17169 global_callevents = FALSE;
17170 global_t1min = DEFAULT_T1MIN;
17171
17172 global_matchexterniplocally = FALSE;
17173
17174
17175 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
17176
17177 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
17178
17179
17180 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
17181 if (handle_common_options(&global_flags[0], &dummy[0], v))
17182 continue;
17183
17184 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
17185 continue;
17186
17187
17188 if (!strcasecmp(v->name, "context")) {
17189 ast_copy_string(default_context, v->value, sizeof(default_context));
17190 } else if (!strcasecmp(v->name, "subscribecontext")) {
17191 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
17192 } else if (!strcasecmp(v->name, "allowguest")) {
17193 global_allowguest = ast_true(v->value) ? 1 : 0;
17194 } else if (!strcasecmp(v->name, "realm")) {
17195 ast_copy_string(global_realm, v->value, sizeof(global_realm));
17196 } else if (!strcasecmp(v->name, "useragent")) {
17197 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
17198 if (option_debug)
17199 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
17200 } else if (!strcasecmp(v->name, "allowtransfer")) {
17201 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
17202 } else if (!strcasecmp(v->name, "rtcachefriends")) {
17203 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
17204 } else if (!strcasecmp(v->name, "rtsavesysname")) {
17205 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
17206 } else if (!strcasecmp(v->name, "rtupdate")) {
17207 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
17208 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
17209 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
17210 } else if (!strcasecmp(v->name, "t1min")) {
17211 global_t1min = atoi(v->value);
17212 } else if (!strcasecmp(v->name, "rtautoclear")) {
17213 int i = atoi(v->value);
17214 if (i > 0)
17215 global_rtautoclear = i;
17216 else
17217 i = 0;
17218 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
17219 } else if (!strcasecmp(v->name, "usereqphone")) {
17220 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
17221 } else if (!strcasecmp(v->name, "relaxdtmf")) {
17222 global_relaxdtmf = ast_true(v->value);
17223 } else if (!strcasecmp(v->name, "checkmwi")) {
17224 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
17225 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
17226 global_mwitime = DEFAULT_MWITIME;
17227 }
17228 } else if (!strcasecmp(v->name, "vmexten")) {
17229 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
17230 } else if (!strcasecmp(v->name, "rtptimeout")) {
17231 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
17232 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17233 global_rtptimeout = 0;
17234 }
17235 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
17236 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
17237 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
17238 global_rtpholdtimeout = 0;
17239 }
17240 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
17241 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
17242 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
17243 global_rtpkeepalive = 0;
17244 }
17245 } else if (!strcasecmp(v->name, "compactheaders")) {
17246 compactheaders = ast_true(v->value);
17247 } else if (!strcasecmp(v->name, "notifymimetype")) {
17248 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
17249 } else if (!strncasecmp(v->name, "limitonpeer", 11)) {
17250 global_limitonpeers = ast_true(v->value);
17251 } else if (!strcasecmp(v->name, "directrtpsetup")) {
17252 global_directrtpsetup = ast_true(v->value);
17253 } else if (!strcasecmp(v->name, "notifyringing")) {
17254 global_notifyringing = ast_true(v->value);
17255 } else if (!strcasecmp(v->name, "notifyhold")) {
17256 global_notifyhold = ast_true(v->value);
17257 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
17258 global_alwaysauthreject = ast_true(v->value);
17259 } else if (!strcasecmp(v->name, "mohinterpret")
17260 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17261 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
17262 } else if (!strcasecmp(v->name, "mohsuggest")) {
17263 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
17264 } else if (!strcasecmp(v->name, "language")) {
17265 ast_copy_string(default_language, v->value, sizeof(default_language));
17266 } else if (!strcasecmp(v->name, "regcontext")) {
17267 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
17268 stringp = newcontexts;
17269
17270 cleanup_stale_contexts(stringp, oldregcontext);
17271
17272 while ((context = strsep(&stringp, "&"))) {
17273 if (!ast_context_find(context))
17274 ast_context_create(NULL, context,"SIP");
17275 }
17276 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
17277 } else if (!strcasecmp(v->name, "callerid")) {
17278 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
17279 } else if (!strcasecmp(v->name, "fromdomain")) {
17280 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
17281 } else if (!strcasecmp(v->name, "outboundproxy")) {
17282 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
17283 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
17284 } else if (!strcasecmp(v->name, "outboundproxyport")) {
17285
17286 sscanf(v->value, "%d", &format);
17287 outboundproxyip.sin_port = htons(format);
17288 } else if (!strcasecmp(v->name, "autocreatepeer")) {
17289 autocreatepeer = ast_true(v->value);
17290 } else if (!strcasecmp(v->name, "srvlookup")) {
17291 srvlookup = ast_true(v->value);
17292 } else if (!strcasecmp(v->name, "pedantic")) {
17293 pedanticsipchecking = ast_true(v->value);
17294 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
17295 max_expiry = atoi(v->value);
17296 if (max_expiry < 1)
17297 max_expiry = DEFAULT_MAX_EXPIRY;
17298 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
17299 min_expiry = atoi(v->value);
17300 if (min_expiry < 1)
17301 min_expiry = DEFAULT_MIN_EXPIRY;
17302 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
17303 default_expiry = atoi(v->value);
17304 if (default_expiry < 1)
17305 default_expiry = DEFAULT_DEFAULT_EXPIRY;
17306 } else if (!strcasecmp(v->name, "sipdebug")) {
17307 if (ast_true(v->value))
17308 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17309 } else if (!strcasecmp(v->name, "dumphistory")) {
17310 dumphistory = ast_true(v->value);
17311 } else if (!strcasecmp(v->name, "recordhistory")) {
17312 recordhistory = ast_true(v->value);
17313 } else if (!strcasecmp(v->name, "registertimeout")) {
17314 global_reg_timeout = atoi(v->value);
17315 if (global_reg_timeout < 1)
17316 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17317 } else if (!strcasecmp(v->name, "registerattempts")) {
17318 global_regattempts_max = atoi(v->value);
17319 } else if (!strcasecmp(v->name, "bindaddr")) {
17320 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
17321 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
17322 } else {
17323 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
17324 }
17325 } else if (!strcasecmp(v->name, "localnet")) {
17326 struct ast_ha *na;
17327 if (!(na = ast_append_ha("d", v->value, localaddr)))
17328 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
17329 else
17330 localaddr = na;
17331 } else if (!strcasecmp(v->name, "localmask")) {
17332 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
17333 } else if (!strcasecmp(v->name, "externip")) {
17334 if (!(hp = ast_gethostbyname(v->value, &ahp)))
17335 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
17336 else
17337 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17338 externexpire = 0;
17339 } else if (!strcasecmp(v->name, "externhost")) {
17340 ast_copy_string(externhost, v->value, sizeof(externhost));
17341 if (!(hp = ast_gethostbyname(externhost, &ahp)))
17342 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
17343 else
17344 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17345 externexpire = time(NULL);
17346 } else if (!strcasecmp(v->name, "externrefresh")) {
17347 if (sscanf(v->value, "%d", &externrefresh) != 1) {
17348 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
17349 externrefresh = 10;
17350 }
17351 } else if (!strcasecmp(v->name, "allow")) {
17352 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
17353 } else if (!strcasecmp(v->name, "disallow")) {
17354 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
17355 } else if (!strcasecmp(v->name, "autoframing")) {
17356 global_autoframing = ast_true(v->value);
17357 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
17358 allow_external_domains = ast_true(v->value);
17359 } else if (!strcasecmp(v->name, "autodomain")) {
17360 auto_sip_domains = ast_true(v->value);
17361 } else if (!strcasecmp(v->name, "domain")) {
17362 char *domain = ast_strdupa(v->value);
17363 char *context = strchr(domain, ',');
17364
17365 if (context)
17366 *context++ = '\0';
17367
17368 if (option_debug && ast_strlen_zero(context))
17369 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
17370 if (ast_strlen_zero(domain))
17371 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
17372 else
17373 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
17374 } else if (!strcasecmp(v->name, "register")) {
17375 if (sip_register(v->value, v->lineno) == 0)
17376 registry_count++;
17377 } else if (!strcasecmp(v->name, "tos")) {
17378 if (!ast_str2tos(v->value, &temp_tos)) {
17379 global_tos_sip = temp_tos;
17380 global_tos_audio = temp_tos;
17381 global_tos_video = temp_tos;
17382 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
17383 } else
17384 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
17385 } else if (!strcasecmp(v->name, "tos_sip")) {
17386 if (ast_str2tos(v->value, &global_tos_sip))
17387 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
17388 } else if (!strcasecmp(v->name, "tos_audio")) {
17389 if (ast_str2tos(v->value, &global_tos_audio))
17390 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
17391 } else if (!strcasecmp(v->name, "tos_video")) {
17392 if (ast_str2tos(v->value, &global_tos_video))
17393 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
17394 } else if (!strcasecmp(v->name, "bindport")) {
17395 if (sscanf(v->value, "%d", &ourport) == 1) {
17396 bindaddr.sin_port = htons(ourport);
17397 } else {
17398 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
17399 }
17400 } else if (!strcasecmp(v->name, "qualify")) {
17401 if (!strcasecmp(v->value, "no")) {
17402 default_qualify = 0;
17403 } else if (!strcasecmp(v->value, "yes")) {
17404 default_qualify = DEFAULT_MAXMS;
17405 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
17406 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
17407 default_qualify = 0;
17408 }
17409 } else if (!strcasecmp(v->name, "callevents")) {
17410 global_callevents = ast_true(v->value);
17411 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17412 default_maxcallbitrate = atoi(v->value);
17413 if (default_maxcallbitrate < 0)
17414 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17415 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
17416 global_matchexterniplocally = ast_true(v->value);
17417 }
17418 }
17419
17420 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
17421 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
17422 allow_external_domains = 1;
17423 }
17424
17425
17426 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
17427
17428 if (!strcasecmp(v->name, "auth"))
17429 authl = add_realm_authentication(authl, v->value, v->lineno);
17430 }
17431
17432 ucfg = ast_config_load("users.conf");
17433 if (ucfg) {
17434 struct ast_variable *gen;
17435 int genhassip, genregistersip;
17436 const char *hassip, *registersip;
17437
17438 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
17439 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
17440 gen = ast_variable_browse(ucfg, "general");
17441 cat = ast_category_browse(ucfg, NULL);
17442 while (cat) {
17443 if (strcasecmp(cat, "general")) {
17444 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
17445 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
17446 if (ast_true(hassip) || (!hassip && genhassip)) {
17447 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
17448 if (user) {
17449 ASTOBJ_CONTAINER_LINK(&userl,user);
17450 ASTOBJ_UNREF(user, sip_destroy_user);
17451 user_count++;
17452 }
17453 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
17454 if (peer) {
17455 ast_device_state_changed("SIP/%s", peer->name);
17456 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17457 ASTOBJ_UNREF(peer, sip_destroy_peer);
17458 peer_count++;
17459 }
17460 }
17461 if (ast_true(registersip) || (!registersip && genregistersip)) {
17462 char tmp[256];
17463 const char *host = ast_variable_retrieve(ucfg, cat, "host");
17464 const char *username = ast_variable_retrieve(ucfg, cat, "username");
17465 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
17466 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
17467 if (!host)
17468 host = ast_variable_retrieve(ucfg, "general", "host");
17469 if (!username)
17470 username = ast_variable_retrieve(ucfg, "general", "username");
17471 if (!secret)
17472 secret = ast_variable_retrieve(ucfg, "general", "secret");
17473 if (!contact)
17474 contact = "s";
17475 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
17476 if (!ast_strlen_zero(secret))
17477 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
17478 else
17479 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
17480 if (sip_register(tmp, 0) == 0)
17481 registry_count++;
17482 }
17483 }
17484 }
17485 cat = ast_category_browse(ucfg, cat);
17486 }
17487 ast_config_destroy(ucfg);
17488 }
17489
17490
17491
17492 cat = NULL;
17493 while ( (cat = ast_category_browse(cfg, cat)) ) {
17494 const char *utype;
17495 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
17496 continue;
17497 utype = ast_variable_retrieve(cfg, cat, "type");
17498 if (!utype) {
17499 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
17500 continue;
17501 } else {
17502 int is_user = 0, is_peer = 0;
17503 if (!strcasecmp(utype, "user"))
17504 is_user = 1;
17505 else if (!strcasecmp(utype, "friend"))
17506 is_user = is_peer = 1;
17507 else if (!strcasecmp(utype, "peer"))
17508 is_peer = 1;
17509 else {
17510 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
17511 continue;
17512 }
17513 if (is_user) {
17514 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
17515 if (user) {
17516 ASTOBJ_CONTAINER_LINK(&userl,user);
17517 ASTOBJ_UNREF(user, sip_destroy_user);
17518 user_count++;
17519 }
17520 }
17521 if (is_peer) {
17522 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
17523 if (peer) {
17524 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17525 ASTOBJ_UNREF(peer, sip_destroy_peer);
17526 peer_count++;
17527 }
17528 }
17529 }
17530 }
17531 if (ast_find_ourip(&__ourip, bindaddr)) {
17532 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
17533 ast_config_destroy(cfg);
17534 return 0;
17535 }
17536 if (!ntohs(bindaddr.sin_port))
17537 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
17538 bindaddr.sin_family = AF_INET;
17539 ast_mutex_lock(&netlock);
17540 if (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in))) {
17541 if (sipsock > -1) {
17542 close(sipsock);
17543 sipsock = -1;
17544 }
17545 if (siptcpsock > -1) {
17546 close(siptcpsock);
17547 siptcpsock = -1;
17548 }
17549 }
17550 if (sipsock < 0) {
17551 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
17552 if (sipsock < 0) {
17553 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
17554 } else {
17555
17556 const int reuseFlag = 1;
17557
17558 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
17559 (const char*)&reuseFlag,
17560 sizeof reuseFlag);
17561
17562 ast_enable_packet_fragmentation(sipsock);
17563
17564 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
17565 ast_log(LOG_WARNING, "Failed to bind to UDP %s:%d: %s\n",
17566 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
17567 strerror(errno));
17568 close(sipsock);
17569 sipsock = -1;
17570 } else {
17571 if (option_verbose > 1) {
17572 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on UDP %s:%d\n",
17573 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
17574 ast_verbose(VERBOSE_PREFIX_2 "Using SIP UDP TOS: %s\n", ast_tos2str(global_tos_sip));
17575 }
17576 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
17577 ast_log(LOG_WARNING, "Unable to set SIP UDP TOS to %s\n", ast_tos2str(global_tos_sip));
17578 }
17579 }
17580 }
17581 if (siptcpsock < 0) {
17582 siptcpsock = socket(AF_INET, SOCK_STREAM, 0);
17583 if (siptcpsock < 0) {
17584 ast_log(LOG_WARNING, "Unable to create SIP TCP socket: %s\n", strerror(errno));
17585 } else {
17586
17587 const int reuseFlag = 1;
17588
17589 setsockopt(siptcpsock, SOL_SOCKET, SO_REUSEADDR,
17590 (const char*)&reuseFlag,
17591 sizeof reuseFlag);
17592
17593 ast_enable_packet_fragmentation(sipsock);
17594
17595 if (bind(siptcpsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
17596 ast_log(LOG_WARNING, "Failed to bind to TCP %s:%d: %s\n",
17597 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
17598 strerror(errno));
17599 close(siptcpsock);
17600 siptcpsock = -1;
17601 } else {
17602 if (listen(siptcpsock, 30) < 0) {
17603 ast_log(LOG_WARNING, "Failed to listen on SIP TCP\n");
17604 } else {
17605 if (option_verbose > 1) {
17606 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on TCP %s:%d\n",
17607 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
17608 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TCP TOS: %s\n", ast_tos2str(global_tos_sip));
17609 }
17610 if (setsockopt(siptcpsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
17611 ast_log(LOG_WARNING, "Unable to set SIP TCP TOS to %s\n", ast_tos2str(global_tos_sip));
17612 }
17613 }
17614 }
17615 }
17616 if ((sipsock < 0) && (siptcpsock <0)) {
17617 ast_config_destroy(cfg);
17618 return -1;
17619 }
17620 ast_mutex_unlock(&netlock);
17621
17622
17623
17624
17625
17626 if (auto_sip_domains) {
17627 char temp[MAXHOSTNAMELEN];
17628
17629
17630 if (bindaddr.sin_addr.s_addr)
17631 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
17632 else
17633 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
17634
17635
17636 if (externip.sin_addr.s_addr)
17637 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
17638
17639
17640 if (!ast_strlen_zero(externhost))
17641 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
17642
17643
17644 if (!gethostname(temp, sizeof(temp)))
17645 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
17646 }
17647
17648
17649 ast_config_destroy(cfg);
17650
17651
17652 if (notify_types)
17653 ast_config_destroy(notify_types);
17654 notify_types = ast_config_load(notify_config);
17655
17656
17657 manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "Channel: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\nUser_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count, user_count);
17658
17659 return 0;
17660 }
17661
17662 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
17663 {
17664 struct sip_pvt *p;
17665 struct ast_udptl *udptl = NULL;
17666
17667 p = chan->tech_pvt;
17668 if (!p)
17669 return NULL;
17670
17671 ast_mutex_lock(&p->lock);
17672 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17673 udptl = p->udptl;
17674 ast_mutex_unlock(&p->lock);
17675 return udptl;
17676 }
17677
17678 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
17679 {
17680 struct sip_pvt *p;
17681
17682 p = chan->tech_pvt;
17683 if (!p)
17684 return -1;
17685 ast_mutex_lock(&p->lock);
17686 if (udptl)
17687 ast_udptl_get_peer(udptl, &p->udptlredirip);
17688 else
17689 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17690 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17691 if (!p->pendinginvite) {
17692 if (option_debug > 2) {
17693 ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
17694 }
17695 transmit_reinvite_with_t38_sdp(p);
17696 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17697 if (option_debug > 2) {
17698 ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
17699 }
17700 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17701 }
17702 }
17703
17704 p->lastrtprx = p->lastrtptx = time(NULL);
17705 ast_mutex_unlock(&p->lock);
17706 return 0;
17707 }
17708
17709
17710
17711
17712
17713
17714 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
17715 {
17716 struct sip_pvt *p;
17717 int flag = 0;
17718
17719 p = chan->tech_pvt;
17720 if (!p || !pvt->udptl)
17721 return -1;
17722
17723
17724 ast_mutex_lock(&p->lock);
17725
17726
17727
17728 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
17729
17730 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17731 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17732 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
17733
17734 if (reinvite) {
17735
17736
17737
17738
17739
17740 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17741 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17742 flag =1;
17743 } else {
17744 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17745 }
17746 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17747 if (!p->pendinginvite) {
17748 if (option_debug > 2) {
17749 if (flag)
17750 ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
17751 else
17752 ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
17753 }
17754 transmit_reinvite_with_t38_sdp(p);
17755 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17756 if (option_debug > 2) {
17757 if (flag)
17758 ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
17759 else
17760 ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
17761 }
17762 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17763 }
17764 }
17765
17766 p->lastrtprx = p->lastrtptx = time(NULL);
17767 ast_mutex_unlock(&p->lock);
17768 return 0;
17769 } else {
17770 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17771 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17772 flag = 1;
17773 } else {
17774 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17775 }
17776 if (option_debug > 2) {
17777 if (flag)
17778 ast_log(LOG_DEBUG, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
17779 else
17780 ast_log(LOG_DEBUG, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
17781 }
17782 pvt->t38.state = T38_ENABLED;
17783 p->t38.state = T38_ENABLED;
17784 if (option_debug > 1) {
17785 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
17786 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
17787 }
17788 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
17789 p->lastrtprx = p->lastrtptx = time(NULL);
17790 ast_mutex_unlock(&p->lock);
17791 return 0;
17792 }
17793 }
17794
17795
17796
17797 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17798 {
17799 struct sip_pvt *p = NULL;
17800 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17801
17802 if (!(p = chan->tech_pvt))
17803 return AST_RTP_GET_FAILED;
17804
17805 ast_mutex_lock(&p->lock);
17806 if (!(p->rtp)) {
17807 ast_mutex_unlock(&p->lock);
17808 return AST_RTP_GET_FAILED;
17809 }
17810
17811 *rtp = p->rtp;
17812
17813 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
17814 res = AST_RTP_TRY_PARTIAL;
17815 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17816 res = AST_RTP_TRY_NATIVE;
17817 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
17818 res = AST_RTP_GET_FAILED;
17819
17820 ast_mutex_unlock(&p->lock);
17821
17822 return res;
17823 }
17824
17825
17826 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17827 {
17828 struct sip_pvt *p = NULL;
17829 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17830
17831 if (!(p = chan->tech_pvt))
17832 return AST_RTP_GET_FAILED;
17833
17834 ast_mutex_lock(&p->lock);
17835 if (!(p->vrtp)) {
17836 ast_mutex_unlock(&p->lock);
17837 return AST_RTP_GET_FAILED;
17838 }
17839
17840 *rtp = p->vrtp;
17841
17842 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17843 res = AST_RTP_TRY_NATIVE;
17844
17845 ast_mutex_unlock(&p->lock);
17846
17847 return res;
17848 }
17849
17850
17851 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
17852 {
17853 struct sip_pvt *p;
17854 int changed = 0;
17855
17856 p = chan->tech_pvt;
17857 if (!p)
17858 return -1;
17859
17860
17861 if (chan->_state != AST_STATE_UP && !global_directrtpsetup)
17862 return 0;
17863
17864 ast_mutex_lock(&p->lock);
17865 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
17866
17867 ast_mutex_unlock(&p->lock);
17868 return 0;
17869 }
17870
17871
17872
17873
17874 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
17875 ast_mutex_unlock(&p->lock);
17876 return 0;
17877 }
17878
17879 if (rtp) {
17880 changed |= ast_rtp_get_peer(rtp, &p->redirip);
17881 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
17882 memset(&p->redirip, 0, sizeof(p->redirip));
17883 changed = 1;
17884 }
17885 if (vrtp) {
17886 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
17887 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
17888 memset(&p->vredirip, 0, sizeof(p->vredirip));
17889 changed = 1;
17890 }
17891 if (codecs) {
17892 if ((p->redircodecs != codecs)) {
17893 p->redircodecs = codecs;
17894 changed = 1;
17895 }
17896 if ((p->capability & codecs) != p->capability) {
17897 p->jointcapability &= codecs;
17898 p->capability &= codecs;
17899 changed = 1;
17900 }
17901 }
17902 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
17903 if (chan->_state != AST_STATE_UP) {
17904 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
17905 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
17906 if (option_debug)
17907 ast_log(LOG_DEBUG, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip));
17908 } else if (!p->pendinginvite) {
17909 if (option_debug > 2) {
17910 ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip));
17911 }
17912 transmit_reinvite_with_sdp(p);
17913 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17914 if (option_debug > 2) {
17915 ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip));
17916 }
17917
17918 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17919 }
17920 }
17921
17922 p->lastrtprx = p->lastrtptx = time(NULL);
17923 ast_mutex_unlock(&p->lock);
17924 return 0;
17925 }
17926
17927 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
17928 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
17929 static char *app_dtmfmode = "SIPDtmfMode";
17930
17931 static char *app_sipaddheader = "SIPAddHeader";
17932 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
17933
17934 static char *descrip_sipaddheader = ""
17935 " SIPAddHeader(Header: Content)\n"
17936 "Adds a header to a SIP call placed with DIAL.\n"
17937 "Remember to user the X-header if you are adding non-standard SIP\n"
17938 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
17939 "Adding the wrong headers may jeopardize the SIP dialog.\n"
17940 "Always returns 0\n";
17941
17942
17943
17944 static int sip_dtmfmode(struct ast_channel *chan, void *data)
17945 {
17946 struct sip_pvt *p;
17947 char *mode;
17948 if (data)
17949 mode = (char *)data;
17950 else {
17951 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
17952 return 0;
17953 }
17954 ast_channel_lock(chan);
17955 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
17956 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
17957 ast_channel_unlock(chan);
17958 return 0;
17959 }
17960 p = chan->tech_pvt;
17961 if (!p) {
17962 ast_channel_unlock(chan);
17963 return 0;
17964 }
17965 ast_mutex_lock(&p->lock);
17966 if (!strcasecmp(mode,"info")) {
17967 ast_clear_flag(&p->flags[0], SIP_DTMF);
17968 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
17969 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17970 } else if (!strcasecmp(mode,"rfc2833")) {
17971 ast_clear_flag(&p->flags[0], SIP_DTMF);
17972 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
17973 p->jointnoncodeccapability |= AST_RTP_DTMF;
17974 } else if (!strcasecmp(mode,"inband")) {
17975 ast_clear_flag(&p->flags[0], SIP_DTMF);
17976 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
17977 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17978 } else
17979 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
17980 if (p->rtp)
17981 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
17982 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
17983 if (!p->vad) {
17984 p->vad = ast_dsp_new();
17985 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
17986 }
17987 } else {
17988 if (p->vad) {
17989 ast_dsp_free(p->vad);
17990 p->vad = NULL;
17991 }
17992 }
17993 ast_mutex_unlock(&p->lock);
17994 ast_channel_unlock(chan);
17995 return 0;
17996 }
17997
17998
17999 static int sip_addheader(struct ast_channel *chan, void *data)
18000 {
18001 int no = 0;
18002 int ok = FALSE;
18003 char varbuf[30];
18004 char *inbuf = (char *) data;
18005
18006 if (ast_strlen_zero(inbuf)) {
18007 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
18008 return 0;
18009 }
18010 ast_channel_lock(chan);
18011
18012
18013 while (!ok && no <= 50) {
18014 no++;
18015 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
18016
18017
18018 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
18019 ok = TRUE;
18020 }
18021 if (ok) {
18022 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
18023 if (sipdebug)
18024 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
18025 } else {
18026 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
18027 }
18028 ast_channel_unlock(chan);
18029 return 0;
18030 }
18031
18032
18033
18034
18035
18036
18037
18038 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
18039 {
18040 char *cdest;
18041 char *extension, *host, *port;
18042 char tmp[80];
18043
18044 cdest = ast_strdupa(dest);
18045
18046 extension = strsep(&cdest, "@");
18047 host = strsep(&cdest, ":");
18048 port = strsep(&cdest, ":");
18049 if (ast_strlen_zero(extension)) {
18050 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
18051 return 0;
18052 }
18053
18054
18055 if (!host) {
18056 char *localtmp;
18057 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
18058 if (ast_strlen_zero(tmp)) {
18059 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
18060 return 0;
18061 }
18062 if ((localtmp = strcasestr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
18063 char lhost[80], lport[80];
18064 memset(lhost, 0, sizeof(lhost));
18065 memset(lport, 0, sizeof(lport));
18066 localtmp++;
18067
18068 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
18069 if (ast_strlen_zero(lhost)) {
18070 ast_log(LOG_ERROR, "Can't find the host address\n");
18071 return 0;
18072 }
18073 host = ast_strdupa(lhost);
18074 if (!ast_strlen_zero(lport)) {
18075 port = ast_strdupa(lport);
18076 }
18077 }
18078 }
18079
18080 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
18081 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
18082
18083 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
18084 sip_alreadygone(p);
18085 return 0;
18086 }
18087
18088
18089 static int sip_get_codec(struct ast_channel *chan)
18090 {
18091 struct sip_pvt *p = chan->tech_pvt;
18092 return p->peercapability ? p->peercapability : p->capability;
18093 }
18094
18095
18096
18097
18098
18099 static void sip_poke_all_peers(void)
18100 {
18101 int ms = 0;
18102
18103 if (!speerobjs)
18104 return;
18105
18106 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
18107 ASTOBJ_WRLOCK(iterator);
18108 if (!AST_SCHED_DEL(sched, iterator->pokeexpire)) {
18109 struct sip_peer *peer_ptr = iterator;
18110 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
18111 }
18112 ms += 100;
18113 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, ASTOBJ_REF(iterator));
18114 if (iterator->pokeexpire == -1) {
18115 struct sip_peer *peer_ptr = iterator;
18116 ASTOBJ_UNREF(peer_ptr, sip_destroy_peer);
18117 }
18118 ASTOBJ_UNLOCK(iterator);
18119 } while (0)
18120 );
18121 }
18122
18123
18124 static void sip_send_all_registers(void)
18125 {
18126 int ms;
18127 int regspacing;
18128 if (!regobjs)
18129 return;
18130 regspacing = default_expiry * 1000/regobjs;
18131 if (regspacing > 100)
18132 regspacing = 100;
18133 ms = regspacing;
18134 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
18135 ASTOBJ_WRLOCK(iterator);
18136 AST_SCHED_DEL(sched, iterator->expire);
18137 ms += regspacing;
18138 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
18139 ASTOBJ_UNLOCK(iterator);
18140 } while (0)
18141 );
18142 }
18143
18144
18145 static int sip_do_reload(enum channelreloadreason reason)
18146 {
18147 reload_config(reason);
18148
18149
18150 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
18151 if (option_debug > 3)
18152 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
18153
18154
18155 sip_poke_all_peers();
18156
18157
18158 sip_send_all_registers();
18159
18160 if (option_debug > 3)
18161 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
18162
18163 return 0;
18164 }
18165
18166
18167 static int sip_reload(int fd, int argc, char *argv[])
18168 {
18169 ast_mutex_lock(&sip_reload_lock);
18170 if (sip_reloading)
18171 ast_verbose("Previous SIP reload not yet done\n");
18172 else {
18173 sip_reloading = TRUE;
18174 if (fd)
18175 sip_reloadreason = CHANNEL_CLI_RELOAD;
18176 else
18177 sip_reloadreason = CHANNEL_MODULE_RELOAD;
18178 }
18179 ast_mutex_unlock(&sip_reload_lock);
18180 restart_monitor();
18181
18182 return 0;
18183 }
18184
18185
18186 static int reload(void)
18187 {
18188 return sip_reload(0, 0, NULL);
18189 }
18190
18191 static struct ast_cli_entry cli_sip_debug_deprecated =
18192 { { "sip", "debug", NULL },
18193 sip_do_debug_deprecated, "Enable SIP debugging",
18194 debug_usage };
18195
18196 static struct ast_cli_entry cli_sip_no_debug_deprecated =
18197 { { "sip", "no", "debug", NULL },
18198 sip_no_debug_deprecated, "Disable SIP debugging",
18199 debug_usage };
18200
18201 static struct ast_cli_entry cli_sip[] = {
18202 { { "sip", "show", "channels", NULL },
18203 sip_show_channels, "List active SIP channels",
18204 show_channels_usage },
18205
18206 { { "sip", "show", "domains", NULL },
18207 sip_show_domains, "List our local SIP domains.",
18208 show_domains_usage },
18209
18210 { { "sip", "show", "inuse", NULL },
18211 sip_show_inuse, "List all inuse/limits",
18212 show_inuse_usage },
18213
18214 { { "sip", "show", "objects", NULL },
18215 sip_show_objects, "List all SIP object allocations",
18216 show_objects_usage },
18217
18218 { { "sip", "show", "peers", NULL },
18219 sip_show_peers, "List defined SIP peers",
18220 show_peers_usage },
18221
18222 { { "sip", "show", "registry", NULL },
18223 sip_show_registry, "List SIP registration status",
18224 show_reg_usage },
18225
18226 { { "sip", "show", "settings", NULL },
18227 sip_show_settings, "Show SIP global settings",
18228 show_settings_usage },
18229
18230 { { "sip", "show", "subscriptions", NULL },
18231 sip_show_subscriptions, "List active SIP subscriptions",
18232 show_subscriptions_usage },
18233
18234 { { "sip", "show", "users", NULL },
18235 sip_show_users, "List defined SIP users",
18236 show_users_usage },
18237
18238 { { "sip", "notify", NULL },
18239 sip_notify, "Send a notify packet to a SIP peer",
18240 notify_usage, complete_sipnotify },
18241
18242 { { "sip", "show", "channel", NULL },
18243 sip_show_channel, "Show detailed SIP channel info",
18244 show_channel_usage, complete_sipch },
18245
18246 { { "sip", "show", "history", NULL },
18247 sip_show_history, "Show SIP dialog history",
18248 show_history_usage, complete_sipch },
18249
18250 { { "sip", "show", "peer", NULL },
18251 sip_show_peer, "Show details on specific SIP peer",
18252 show_peer_usage, complete_sip_show_peer },
18253
18254 { { "sip", "show", "user", NULL },
18255 sip_show_user, "Show details on specific SIP user",
18256 show_user_usage, complete_sip_show_user },
18257
18258 { { "sip", "prune", "realtime", NULL },
18259 sip_prune_realtime, "Prune cached Realtime object(s)",
18260 prune_realtime_usage },
18261
18262 { { "sip", "prune", "realtime", "peer", NULL },
18263 sip_prune_realtime, "Prune cached Realtime peer(s)",
18264 prune_realtime_usage, complete_sip_prune_realtime_peer },
18265
18266 { { "sip", "prune", "realtime", "user", NULL },
18267 sip_prune_realtime, "Prune cached Realtime user(s)",
18268 prune_realtime_usage, complete_sip_prune_realtime_user },
18269
18270 { { "sip", "set", "debug", NULL },
18271 sip_do_debug, "Enable SIP debugging",
18272 debug_usage, NULL, &cli_sip_debug_deprecated },
18273
18274 { { "sip", "set", "debug", "ip", NULL },
18275 sip_do_debug, "Enable SIP debugging on IP",
18276 debug_usage },
18277
18278 { { "sip", "set", "debug", "peer", NULL },
18279 sip_do_debug, "Enable SIP debugging on Peername",
18280 debug_usage, complete_sip_debug_peer },
18281
18282 { { "sip", "set", "debug", "off", NULL },
18283 sip_no_debug, "Disable SIP debugging",
18284 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
18285
18286 { { "sip", "history", NULL },
18287 sip_do_history, "Enable SIP history",
18288 history_usage },
18289
18290 { { "sip", "history", "off", NULL },
18291 sip_no_history, "Disable SIP history",
18292 no_history_usage },
18293
18294 { { "sip", "reload", NULL },
18295 sip_reload, "Reload SIP configuration",
18296 sip_reload_usage },
18297 };
18298
18299
18300 static int load_module(void)
18301 {
18302 ASTOBJ_CONTAINER_INIT(&userl);
18303 ASTOBJ_CONTAINER_INIT(&peerl);
18304 ASTOBJ_CONTAINER_INIT(®l);
18305
18306 if (!(sched = sched_context_create())) {
18307 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
18308 return AST_MODULE_LOAD_FAILURE;
18309 }
18310
18311 if (!(io = io_context_create())) {
18312 ast_log(LOG_ERROR, "Unable to create I/O context\n");
18313 sched_context_destroy(sched);
18314 return AST_MODULE_LOAD_FAILURE;
18315 }
18316
18317 sip_reloadreason = CHANNEL_MODULE_LOAD;
18318
18319 if(reload_config(sip_reloadreason))
18320 return AST_MODULE_LOAD_DECLINE;
18321
18322
18323 if (ast_channel_register(&sip_tech)) {
18324 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
18325 io_context_destroy(io);
18326 sched_context_destroy(sched);
18327 return AST_MODULE_LOAD_FAILURE;
18328 }
18329
18330
18331 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
18332
18333
18334 ast_rtp_proto_register(&sip_rtp);
18335
18336
18337 ast_udptl_proto_register(&sip_udptl);
18338
18339
18340 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
18341 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
18342
18343
18344 ast_custom_function_register(&sip_header_function);
18345 ast_custom_function_register(&sippeer_function);
18346 ast_custom_function_register(&sipchaninfo_function);
18347 ast_custom_function_register(&checksipdomain_function);
18348
18349
18350 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
18351 "List SIP peers (text format)", mandescr_show_peers);
18352 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
18353 "Show SIP peer (text format)", mandescr_show_peer);
18354
18355 sip_poke_all_peers();
18356 sip_send_all_registers();
18357
18358
18359 restart_monitor();
18360
18361 return AST_MODULE_LOAD_SUCCESS;
18362 }
18363
18364
18365 static int unload_module(void)
18366 {
18367 struct sip_pvt *p, *pl;
18368
18369
18370 ast_channel_unregister(&sip_tech);
18371
18372
18373 ast_custom_function_unregister(&sipchaninfo_function);
18374 ast_custom_function_unregister(&sippeer_function);
18375 ast_custom_function_unregister(&sip_header_function);
18376 ast_custom_function_unregister(&checksipdomain_function);
18377
18378
18379 ast_unregister_application(app_dtmfmode);
18380 ast_unregister_application(app_sipaddheader);
18381
18382
18383 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
18384
18385
18386 ast_rtp_proto_unregister(&sip_rtp);
18387
18388
18389 ast_udptl_proto_unregister(&sip_udptl);
18390
18391
18392 ast_manager_unregister("SIPpeers");
18393 ast_manager_unregister("SIPshowpeer");
18394
18395 ast_mutex_lock(&iflock);
18396
18397 for (p = iflist; p ; p = p->next) {
18398 if (p->owner)
18399 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
18400 }
18401 ast_mutex_unlock(&iflock);
18402
18403 ast_mutex_lock(&monlock);
18404 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
18405 pthread_cancel(monitor_thread);
18406 pthread_kill(monitor_thread, SIGURG);
18407 pthread_join(monitor_thread, NULL);
18408 }
18409 monitor_thread = AST_PTHREADT_STOP;
18410 ast_mutex_unlock(&monlock);
18411
18412 restartdestroy:
18413 ast_mutex_lock(&iflock);
18414
18415 p = iflist;
18416 while (p) {
18417 pl = p;
18418 p = p->next;
18419 if (__sip_destroy(pl, TRUE) < 0) {
18420
18421 iflist = p;
18422 ast_mutex_unlock(&iflock);
18423 usleep(1);
18424 goto restartdestroy;
18425 }
18426 }
18427 iflist = NULL;
18428 ast_mutex_unlock(&iflock);
18429
18430
18431 ast_free_ha(localaddr);
18432
18433 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
18434 ASTOBJ_CONTAINER_DESTROY(&userl);
18435 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
18436 ASTOBJ_CONTAINER_DESTROY(&peerl);
18437 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
18438 ASTOBJ_CONTAINER_DESTROY(®l);
18439
18440 clear_realm_authentication(authl);
18441 clear_sip_domains();
18442 close(sipsock);
18443 close(siptcpsock);
18444 sched_context_destroy(sched);
18445
18446 return 0;
18447 }
18448
18449 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
18450 .load = load_module,
18451 .unload = unload_module,
18452 .reload = reload,
18453 );