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
00095 #include "asterisk.h"
00096
00097 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 95946 $")
00098
00099 #include <stdio.h>
00100 #include <ctype.h>
00101 #include <string.h>
00102 #include <unistd.h>
00103 #include <sys/socket.h>
00104 #include <sys/ioctl.h>
00105 #include <net/if.h>
00106 #include <errno.h>
00107 #include <stdlib.h>
00108 #include <fcntl.h>
00109 #include <netdb.h>
00110 #include <signal.h>
00111 #include <sys/signal.h>
00112 #include <netinet/in.h>
00113 #include <netinet/in_systm.h>
00114 #include <arpa/inet.h>
00115 #include <netinet/ip.h>
00116 #include <regex.h>
00117
00118 #include "asterisk/lock.h"
00119 #include "asterisk/channel.h"
00120 #include "asterisk/config.h"
00121 #include "asterisk/logger.h"
00122 #include "asterisk/module.h"
00123 #include "asterisk/pbx.h"
00124 #include "asterisk/options.h"
00125 #include "asterisk/sched.h"
00126 #include "asterisk/io.h"
00127 #include "asterisk/rtp.h"
00128 #include "asterisk/udptl.h"
00129 #include "asterisk/acl.h"
00130 #include "asterisk/manager.h"
00131 #include "asterisk/callerid.h"
00132 #include "asterisk/cli.h"
00133 #include "asterisk/app.h"
00134 #include "asterisk/musiconhold.h"
00135 #include "asterisk/dsp.h"
00136 #include "asterisk/features.h"
00137 #include "asterisk/srv.h"
00138 #include "asterisk/astdb.h"
00139 #include "asterisk/causes.h"
00140 #include "asterisk/utils.h"
00141 #include "asterisk/file.h"
00142 #include "asterisk/astobj.h"
00143 #include "asterisk/devicestate.h"
00144 #include "asterisk/linkedlists.h"
00145 #include "asterisk/stringfields.h"
00146 #include "asterisk/monitor.h"
00147 #include "asterisk/localtime.h"
00148 #include "asterisk/abstract_jb.h"
00149 #include "asterisk/compiler.h"
00150 #include "asterisk/threadstorage.h"
00151 #include "asterisk/translate.h"
00152 #include "asterisk/dnsmgr.h"
00153
00154 #ifndef FALSE
00155 #define FALSE 0
00156 #endif
00157
00158 #ifndef TRUE
00159 #define TRUE 1
00160 #endif
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
00608 #define DEC_CALL_LIMIT 0
00609 #define INC_CALL_LIMIT 1
00610 #define DEC_CALL_RINGING 2
00611 #define INC_CALL_RINGING 3
00612
00613
00614 struct sip_request {
00615 char *rlPart1;
00616 char *rlPart2;
00617 int len;
00618 int headers;
00619 int method;
00620 int lines;
00621 unsigned int flags;
00622 char *header[SIP_MAX_HEADERS];
00623 char *line[SIP_MAX_LINES];
00624 char data[SIP_MAX_PACKET];
00625 unsigned int sdp_start;
00626 unsigned int sdp_end;
00627 };
00628
00629
00630
00631
00632
00633
00634
00635
00636
00637
00638
00639
00640
00641
00642
00643
00644
00645
00646
00647
00648
00649 struct sip_dual {
00650 struct ast_channel *chan1;
00651 struct ast_channel *chan2;
00652 struct sip_request req;
00653 int seqno;
00654 };
00655
00656 struct sip_pkt;
00657
00658
00659 struct sip_invite_param {
00660 const char *distinctive_ring;
00661 int addsipheaders;
00662 const char *uri_options;
00663 const char *vxml_url;
00664 char *auth;
00665 char *authheader;
00666 enum sip_auth_type auth_type;
00667 const char *replaces;
00668 int transfer;
00669 };
00670
00671
00672 struct sip_route {
00673 struct sip_route *next;
00674 char hop[0];
00675 };
00676
00677
00678 enum domain_mode {
00679 SIP_DOMAIN_AUTO,
00680 SIP_DOMAIN_CONFIG,
00681 };
00682
00683
00684
00685
00686
00687 struct domain {
00688 char domain[MAXHOSTNAMELEN];
00689 char context[AST_MAX_EXTENSION];
00690 enum domain_mode mode;
00691 AST_LIST_ENTRY(domain) list;
00692 };
00693
00694 static AST_LIST_HEAD_STATIC(domain_list, domain);
00695
00696
00697
00698 struct sip_history {
00699 AST_LIST_ENTRY(sip_history) list;
00700 char event[0];
00701 };
00702
00703 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00704
00705
00706 struct sip_auth {
00707 char realm[AST_MAX_EXTENSION];
00708 char username[256];
00709 char secret[256];
00710 char md5secret[256];
00711 struct sip_auth *next;
00712 };
00713
00714
00715 #define SIP_ALREADYGONE (1 << 0)
00716 #define SIP_NEEDDESTROY (1 << 1)
00717 #define SIP_NOVIDEO (1 << 2)
00718 #define SIP_RINGING (1 << 3)
00719 #define SIP_PROGRESS_SENT (1 << 4)
00720 #define SIP_NEEDREINVITE (1 << 5)
00721 #define SIP_PENDINGBYE (1 << 6)
00722 #define SIP_GOTREFER (1 << 7)
00723 #define SIP_PROMISCREDIR (1 << 8)
00724 #define SIP_TRUSTRPID (1 << 9)
00725 #define SIP_USEREQPHONE (1 << 10)
00726 #define SIP_REALTIME (1 << 11)
00727 #define SIP_USECLIENTCODE (1 << 12)
00728 #define SIP_OUTGOING (1 << 13)
00729 #define SIP_FREE_BIT (1 << 14)
00730 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15)
00731 #define SIP_DTMF (3 << 16)
00732 #define SIP_DTMF_RFC2833 (0 << 16)
00733 #define SIP_DTMF_INBAND (1 << 16)
00734 #define SIP_DTMF_INFO (2 << 16)
00735 #define SIP_DTMF_AUTO (3 << 16)
00736
00737 #define SIP_NAT (3 << 18)
00738 #define SIP_NAT_NEVER (0 << 18)
00739 #define SIP_NAT_RFC3581 (1 << 18)
00740 #define SIP_NAT_ROUTE (2 << 18)
00741 #define SIP_NAT_ALWAYS (3 << 18)
00742
00743 #define SIP_REINVITE (7 << 20)
00744 #define SIP_CAN_REINVITE (1 << 20)
00745 #define SIP_CAN_REINVITE_NAT (2 << 20)
00746 #define SIP_REINVITE_UPDATE (4 << 20)
00747
00748 #define SIP_INSECURE_PORT (1 << 23)
00749 #define SIP_INSECURE_INVITE (1 << 24)
00750
00751 #define SIP_PROG_INBAND (3 << 25)
00752 #define SIP_PROG_INBAND_NEVER (0 << 25)
00753 #define SIP_PROG_INBAND_NO (1 << 25)
00754 #define SIP_PROG_INBAND_YES (2 << 25)
00755 #define SIP_NO_HISTORY (1 << 27)
00756 #define SIP_CALL_LIMIT (1 << 28)
00757 #define SIP_SENDRPID (1 << 29)
00758 #define SIP_INC_COUNT (1 << 30)
00759 #define SIP_G726_NONSTANDARD (1 << 31)
00760
00761 #define SIP_FLAGS_TO_COPY \
00762 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
00763 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
00764 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
00765
00766
00767
00768 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
00769 #define SIP_PAGE2_RTUPDATE (1 << 1)
00770 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
00771 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
00772 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
00773
00774 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
00775 #define SIP_PAGE2_DEBUG (3 << 11)
00776 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
00777 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
00778 #define SIP_PAGE2_DYNAMIC (1 << 13)
00779 #define SIP_PAGE2_SELFDESTRUCT (1 << 14)
00780 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
00781 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)
00782 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17)
00783 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18)
00784 #define SIP_PAGE2_INC_RINGING (1 << 19)
00785 #define SIP_PAGE2_T38SUPPORT (7 << 20)
00786 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20)
00787 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20)
00788 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20)
00789 #define SIP_PAGE2_CALL_ONHOLD (3 << 23)
00790 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23)
00791 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23)
00792 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)
00793 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
00794 #define SIP_PAGE2_BUGGY_MWI (1 << 26)
00795 #define SIP_PAGE2_OUTGOING_CALL (1 << 27)
00796
00797 #define SIP_PAGE2_FLAGS_TO_COPY \
00798 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
00799 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI)
00800
00801
00802 #define SIP_PKT_DEBUG (1 << 0)
00803 #define SIP_PKT_WITH_TOTAG (1 << 1)
00804 #define SIP_PKT_IGNORE (1 << 2)
00805 #define SIP_PKT_IGNORE_RESP (1 << 3)
00806 #define SIP_PKT_IGNORE_REQ (1 << 4)
00807
00808
00809 #define T38FAX_FILL_BIT_REMOVAL (1 << 0)
00810 #define T38FAX_TRANSCODING_MMR (1 << 1)
00811 #define T38FAX_TRANSCODING_JBIG (1 << 2)
00812
00813 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
00814 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3)
00815
00816 #define T38FAX_UDP_EC_NONE (0 << 4)
00817 #define T38FAX_UDP_EC_FEC (1 << 4)
00818 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4)
00819
00820 #define T38FAX_VERSION (3 << 6)
00821 #define T38FAX_VERSION_0 (0 << 6)
00822 #define T38FAX_VERSION_1 (1 << 6)
00823
00824 #define T38FAX_RATE_2400 (1 << 8)
00825 #define T38FAX_RATE_4800 (1 << 9)
00826 #define T38FAX_RATE_7200 (1 << 10)
00827 #define T38FAX_RATE_9600 (1 << 11)
00828 #define T38FAX_RATE_12000 (1 << 12)
00829 #define T38FAX_RATE_14400 (1 << 13)
00830
00831
00832 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
00833
00834 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
00835 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
00836 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
00837
00838
00839 enum t38state {
00840 T38_DISABLED = 0,
00841 T38_LOCAL_DIRECT,
00842 T38_LOCAL_REINVITE,
00843 T38_PEER_DIRECT,
00844 T38_PEER_REINVITE,
00845 T38_ENABLED
00846 };
00847
00848
00849 struct t38properties {
00850 struct ast_flags t38support;
00851 int capability;
00852 int peercapability;
00853 int jointcapability;
00854 enum t38state state;
00855 };
00856
00857
00858 enum referstatus {
00859 REFER_IDLE,
00860 REFER_SENT,
00861 REFER_RECEIVED,
00862 REFER_CONFIRMED,
00863 REFER_ACCEPTED,
00864 REFER_RINGING,
00865 REFER_200OK,
00866 REFER_FAILED,
00867 REFER_NOAUTH
00868 };
00869
00870 static const struct c_referstatusstring {
00871 enum referstatus status;
00872 char *text;
00873 } referstatusstrings[] = {
00874 { REFER_IDLE, "<none>" },
00875 { REFER_SENT, "Request sent" },
00876 { REFER_RECEIVED, "Request received" },
00877 { REFER_ACCEPTED, "Accepted" },
00878 { REFER_RINGING, "Target ringing" },
00879 { REFER_200OK, "Done" },
00880 { REFER_FAILED, "Failed" },
00881 { REFER_NOAUTH, "Failed - auth failure" }
00882 } ;
00883
00884
00885
00886 struct sip_refer {
00887 char refer_to[AST_MAX_EXTENSION];
00888 char refer_to_domain[AST_MAX_EXTENSION];
00889 char refer_to_urioption[AST_MAX_EXTENSION];
00890 char refer_to_context[AST_MAX_EXTENSION];
00891 char referred_by[AST_MAX_EXTENSION];
00892 char referred_by_name[AST_MAX_EXTENSION];
00893 char refer_contact[AST_MAX_EXTENSION];
00894 char replaces_callid[BUFSIZ];
00895 char replaces_callid_totag[BUFSIZ/2];
00896 char replaces_callid_fromtag[BUFSIZ/2];
00897 struct sip_pvt *refer_call;
00898 int attendedtransfer;
00899 int localtransfer;
00900 enum referstatus status;
00901 };
00902
00903
00904 static struct sip_pvt {
00905 ast_mutex_t lock;
00906 int method;
00907 enum invitestates invitestate;
00908 AST_DECLARE_STRING_FIELDS(
00909 AST_STRING_FIELD(callid);
00910 AST_STRING_FIELD(randdata);
00911 AST_STRING_FIELD(accountcode);
00912 AST_STRING_FIELD(realm);
00913 AST_STRING_FIELD(nonce);
00914 AST_STRING_FIELD(opaque);
00915 AST_STRING_FIELD(qop);
00916 AST_STRING_FIELD(domain);
00917 AST_STRING_FIELD(from);
00918 AST_STRING_FIELD(useragent);
00919 AST_STRING_FIELD(exten);
00920 AST_STRING_FIELD(context);
00921 AST_STRING_FIELD(subscribecontext);
00922 AST_STRING_FIELD(subscribeuri);
00923 AST_STRING_FIELD(fromdomain);
00924 AST_STRING_FIELD(fromuser);
00925 AST_STRING_FIELD(fromname);
00926 AST_STRING_FIELD(tohost);
00927 AST_STRING_FIELD(language);
00928 AST_STRING_FIELD(mohinterpret);
00929 AST_STRING_FIELD(mohsuggest);
00930 AST_STRING_FIELD(rdnis);
00931 AST_STRING_FIELD(theirtag);
00932 AST_STRING_FIELD(username);
00933 AST_STRING_FIELD(peername);
00934 AST_STRING_FIELD(authname);
00935 AST_STRING_FIELD(uri);
00936 AST_STRING_FIELD(okcontacturi);
00937 AST_STRING_FIELD(peersecret);
00938 AST_STRING_FIELD(peermd5secret);
00939 AST_STRING_FIELD(cid_num);
00940 AST_STRING_FIELD(cid_name);
00941 AST_STRING_FIELD(via);
00942 AST_STRING_FIELD(fullcontact);
00943 AST_STRING_FIELD(our_contact);
00944 AST_STRING_FIELD(rpid);
00945 AST_STRING_FIELD(rpid_from);
00946 );
00947 unsigned int ocseq;
00948 unsigned int icseq;
00949 ast_group_t callgroup;
00950 ast_group_t pickupgroup;
00951 int lastinvite;
00952 int lastnoninvite;
00953 struct ast_flags flags[2];
00954 int timer_t1;
00955 unsigned int sipoptions;
00956 struct ast_codec_pref prefs;
00957 int capability;
00958 int jointcapability;
00959 int peercapability;
00960 int prefcodec;
00961 int noncodeccapability;
00962 int jointnoncodeccapability;
00963 int redircodecs;
00964 int maxcallbitrate;
00965 struct t38properties t38;
00966 struct sockaddr_in udptlredirip;
00967 struct ast_udptl *udptl;
00968 int callingpres;
00969 int authtries;
00970 int expiry;
00971 long branch;
00972 char tag[11];
00973 int sessionid;
00974 int sessionversion;
00975 struct sockaddr_in sa;
00976 struct sockaddr_in redirip;
00977 struct sockaddr_in vredirip;
00978 time_t lastrtprx;
00979 time_t lastrtptx;
00980 int rtptimeout;
00981 struct sockaddr_in recv;
00982 struct in_addr ourip;
00983 struct ast_channel *owner;
00984 struct sip_route *route;
00985 int route_persistant;
00986 struct sip_auth *peerauth;
00987 int noncecount;
00988 char lastmsg[256];
00989 int amaflags;
00990 int pendinginvite;
00991 struct sip_request initreq;
00992
00993
00994 int maxtime;
00995 int initid;
00996 int waitid;
00997 int autokillid;
00998 enum transfermodes allowtransfer;
00999 struct sip_refer *refer;
01000 enum subscriptiontype subscribed;
01001 int stateid;
01002 int laststate;
01003 int dialogver;
01004
01005 struct ast_dsp *vad;
01006
01007 struct sip_peer *relatedpeer;
01008
01009 struct sip_registry *registry;
01010 struct ast_rtp *rtp;
01011 struct ast_rtp *vrtp;
01012 struct sip_pkt *packets;
01013 struct sip_history_head *history;
01014 size_t history_entries;
01015 struct ast_variable *chanvars;
01016 struct sip_pvt *next;
01017 struct sip_invite_param *options;
01018 int autoframing;
01019 } *iflist = NULL;
01020
01021
01022 #define MAX_HISTORY_ENTRIES 50
01023
01024 #define FLAG_RESPONSE (1 << 0)
01025 #define FLAG_FATAL (1 << 1)
01026
01027
01028 struct sip_pkt {
01029 struct sip_pkt *next;
01030 int retrans;
01031 int method;
01032 int seqno;
01033 unsigned int flags;
01034 struct sip_pvt *owner;
01035 int retransid;
01036 int timer_a;
01037 int timer_t1;
01038 int packetlen;
01039 char data[0];
01040 };
01041
01042
01043 struct sip_user {
01044
01045 ASTOBJ_COMPONENTS(struct sip_user);
01046 char secret[80];
01047 char md5secret[80];
01048 char context[AST_MAX_CONTEXT];
01049 char subscribecontext[AST_MAX_CONTEXT];
01050 char cid_num[80];
01051 char cid_name[80];
01052 char accountcode[AST_MAX_ACCOUNT_CODE];
01053 char language[MAX_LANGUAGE];
01054 char mohinterpret[MAX_MUSICCLASS];
01055 char mohsuggest[MAX_MUSICCLASS];
01056 char useragent[256];
01057 struct ast_codec_pref prefs;
01058 ast_group_t callgroup;
01059 ast_group_t pickupgroup;
01060 unsigned int sipoptions;
01061 struct ast_flags flags[2];
01062 int amaflags;
01063 int callingpres;
01064 int capability;
01065 int inUse;
01066 int call_limit;
01067 enum transfermodes allowtransfer;
01068 struct ast_ha *ha;
01069 struct ast_variable *chanvars;
01070 int maxcallbitrate;
01071 int autoframing;
01072 };
01073
01074
01075
01076 struct sip_peer {
01077 ASTOBJ_COMPONENTS(struct sip_peer);
01078
01079 char secret[80];
01080 char md5secret[80];
01081 struct sip_auth *auth;
01082 char context[AST_MAX_CONTEXT];
01083 char subscribecontext[AST_MAX_CONTEXT];
01084 char username[80];
01085 char accountcode[AST_MAX_ACCOUNT_CODE];
01086 int amaflags;
01087 char tohost[MAXHOSTNAMELEN];
01088 char regexten[AST_MAX_EXTENSION];
01089 char fromuser[80];
01090 char fromdomain[MAXHOSTNAMELEN];
01091 char fullcontact[256];
01092 char cid_num[80];
01093 char cid_name[80];
01094 int callingpres;
01095 int inUse;
01096 int inRinging;
01097 int onHold;
01098 int call_limit;
01099 enum transfermodes allowtransfer;
01100 char vmexten[AST_MAX_EXTENSION];
01101 char mailbox[AST_MAX_EXTENSION];
01102 char language[MAX_LANGUAGE];
01103 char mohinterpret[MAX_MUSICCLASS];
01104 char mohsuggest[MAX_MUSICCLASS];
01105 char useragent[256];
01106 struct ast_codec_pref prefs;
01107 int lastmsgssent;
01108 time_t lastmsgcheck;
01109 unsigned int sipoptions;
01110 struct ast_flags flags[2];
01111 int expire;
01112 int capability;
01113 int rtptimeout;
01114 int rtpholdtimeout;
01115 int rtpkeepalive;
01116 ast_group_t callgroup;
01117 ast_group_t pickupgroup;
01118 struct sockaddr_in addr;
01119 int maxcallbitrate;
01120
01121
01122 struct sip_pvt *call;
01123 int pokeexpire;
01124 int lastms;
01125 int maxms;
01126 struct timeval ps;
01127
01128 struct sockaddr_in defaddr;
01129 struct ast_ha *ha;
01130 struct ast_variable *chanvars;
01131 struct sip_pvt *mwipvt;
01132 int lastmsg;
01133 int autoframing;
01134 };
01135
01136
01137
01138
01139 struct sip_registry {
01140 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01141 AST_DECLARE_STRING_FIELDS(
01142 AST_STRING_FIELD(callid);
01143 AST_STRING_FIELD(realm);
01144 AST_STRING_FIELD(nonce);
01145 AST_STRING_FIELD(opaque);
01146 AST_STRING_FIELD(qop);
01147 AST_STRING_FIELD(domain);
01148 AST_STRING_FIELD(username);
01149 AST_STRING_FIELD(authuser);
01150 AST_STRING_FIELD(hostname);
01151 AST_STRING_FIELD(secret);
01152 AST_STRING_FIELD(md5secret);
01153 AST_STRING_FIELD(contact);
01154 AST_STRING_FIELD(random);
01155 );
01156 int portno;
01157 int expire;
01158 int regattempts;
01159 int timeout;
01160 int refresh;
01161 struct sip_pvt *call;
01162 enum sipregistrystate regstate;
01163 time_t regtime;
01164 int callid_valid;
01165 unsigned int ocseq;
01166 struct sockaddr_in us;
01167 int noncecount;
01168 char lastmsg[256];
01169 };
01170
01171
01172
01173
01174 static struct ast_user_list {
01175 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
01176 } userl;
01177
01178
01179 static struct ast_peer_list {
01180 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
01181 } peerl;
01182
01183
01184 static struct ast_register_list {
01185 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01186 int recheck;
01187 } regl;
01188
01189 static void temp_pvt_cleanup(void *);
01190
01191
01192 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01193
01194
01195 static struct sip_auth *authl = NULL;
01196
01197
01198
01199 static int sipsock = -1;
01200 static struct sockaddr_in bindaddr = { 0, };
01201 static struct sockaddr_in externip;
01202 static char externhost[MAXHOSTNAMELEN];
01203 static time_t externexpire = 0;
01204 static int externrefresh = 10;
01205 static struct ast_ha *localaddr;
01206 static struct in_addr __ourip;
01207 static struct sockaddr_in outboundproxyip;
01208 static int ourport;
01209 static struct sockaddr_in debugaddr;
01210
01211 static struct ast_config *notify_types;
01212
01213
01214
01215
01216
01217
01218 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
01219 static int sip_devicestate(void *data);
01220 static int sip_sendtext(struct ast_channel *ast, const char *dest, const char *text, int ispdu);
01221 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01222 static int sip_hangup(struct ast_channel *ast);
01223 static int sip_answer(struct ast_channel *ast);
01224 static struct ast_frame *sip_read(struct ast_channel *ast);
01225 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01226 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01227 static int sip_transfer(struct ast_channel *ast, const char *dest);
01228 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01229 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01230 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01231
01232
01233 static int sipsock_read(int *id, int fd, short events, void *ignore);
01234 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
01235 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
01236 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01237 static int retrans_pkt(const void *data);
01238 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
01239 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);
01240 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01241 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01242 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01243 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01244 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01245 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);
01246 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01247
01248 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01249 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01250 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01251 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
01252 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
01253 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01254 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01255 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01256 static int transmit_refer(struct sip_pvt *p, const char *dest);
01257 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
01258 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01259 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01260 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01261 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01262 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01263 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01264 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
01265 static int sip_send_mwi_to_peer(struct sip_peer *peer);
01266 static int does_peer_need_mwi(struct sip_peer *peer);
01267
01268
01269 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
01270 int useglobal_nat, const int intended_method);
01271 static int __sip_autodestruct(const void *data);
01272 static void sip_scheddestroy(struct sip_pvt *p, int ms);
01273 static void sip_cancel_destroy(struct sip_pvt *p);
01274 static void sip_destroy(struct sip_pvt *p);
01275 static void __sip_destroy(struct sip_pvt *p, int lockowner);
01276 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01277 static void __sip_pretend_ack(struct sip_pvt *p);
01278 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01279 static int auto_congest(const void *nothing);
01280 static int update_call_counter(struct sip_pvt *fup, int event);
01281 static int hangup_sip2cause(int cause);
01282 static const char *hangup_cause2sip(int cause);
01283 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
01284 static void free_old_route(struct sip_route *route);
01285 static void list_route(struct sip_route *route);
01286 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01287 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
01288 struct sip_request *req, char *uri);
01289 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01290 static void check_pendings(struct sip_pvt *p);
01291 static void *sip_park_thread(void *stuff);
01292 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
01293 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01294
01295
01296 static void try_suggested_sip_codec(struct sip_pvt *p);
01297 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01298 static const char *get_sdp(struct sip_request *req, const char *name);
01299 static int find_sdp(struct sip_request *req);
01300 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
01301 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
01302 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
01303 int debug, int *min_packet_size);
01304 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
01305 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
01306 int debug);
01307 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
01308 static void stop_media_flows(struct sip_pvt *p);
01309
01310
01311 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01312 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01313 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01314 const char *secret, const char *md5secret, int sipmethod,
01315 char *uri, enum xmittype reliable, int ignore);
01316 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01317 int sipmethod, char *uri, enum xmittype reliable,
01318 struct sockaddr_in *sin, struct sip_peer **authpeer);
01319 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
01320
01321
01322 static int check_sip_domain(const char *domain, char *context, size_t len);
01323 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01324 static void clear_sip_domains(void);
01325
01326
01327 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
01328 static int clear_realm_authentication(struct sip_auth *authlist);
01329 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
01330
01331
01332 static int sip_do_reload(enum channelreloadreason reason);
01333 static int reload_config(enum channelreloadreason reason);
01334 static int expire_register(const void *data);
01335 static void *do_monitor(void *data);
01336 static int restart_monitor(void);
01337 static int sip_send_mwi_to_peer(struct sip_peer *peer);
01338 static int sip_addrcmp(char *name, struct sockaddr_in *sin);
01339 static int sip_refer_allocate(struct sip_pvt *p);
01340 static void ast_quiet_chan(struct ast_channel *chan);
01341 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01342
01343
01344 static int cb_extensionstate(char *context, char* exten, int state, void *data, char *cid_num, char *cid_name);
01345 static int sip_devicestate(void *data);
01346 static int sip_poke_noanswer(const void *data);
01347 static int sip_poke_peer(struct sip_peer *peer);
01348 static void sip_poke_all_peers(void);
01349 static void sip_peer_hold(struct sip_pvt *p, int hold);
01350
01351
01352 static const char *sip_nat_mode(const struct sip_pvt *p);
01353 static int sip_show_inuse(int fd, int argc, char *argv[]);
01354 static char *transfermode2str(enum transfermodes mode) attribute_const;
01355 static char *nat2str(int nat) attribute_const;
01356 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01357 static int sip_show_users(int fd, int argc, char *argv[]);
01358 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01359 static int sip_show_peers(int fd, int argc, char *argv[]);
01360 static int sip_show_objects(int fd, int argc, char *argv[]);
01361 static void print_group(int fd, ast_group_t group, int crlf);
01362 static const char *dtmfmode2str(int mode) attribute_const;
01363 static const char *insecure2str(int port, int invite) attribute_const;
01364 static void cleanup_stale_contexts(char *new, char *old);
01365 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01366 static const char *domain_mode_to_text(const enum domain_mode mode);
01367 static int sip_show_domains(int fd, int argc, char *argv[]);
01368 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01369 static int sip_show_peer(int fd, int argc, char *argv[]);
01370 static int sip_show_user(int fd, int argc, char *argv[]);
01371 static int sip_show_registry(int fd, int argc, char *argv[]);
01372 static int sip_show_settings(int fd, int argc, char *argv[]);
01373 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01374 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01375 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
01376 static int sip_show_channels(int fd, int argc, char *argv[]);
01377 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
01378 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
01379 static char *complete_sipch(const char *line, const char *word, int pos, int state);
01380 static char *complete_sip_peer(const char *word, int state, int flags2);
01381 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01382 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
01383 static char *complete_sip_user(const char *word, int state, int flags2);
01384 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
01385 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01386 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
01387 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
01388 static int sip_show_channel(int fd, int argc, char *argv[]);
01389 static int sip_show_history(int fd, int argc, char *argv[]);
01390 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
01391 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
01392 static int sip_do_debug(int fd, int argc, char *argv[]);
01393 static int sip_no_debug(int fd, int argc, char *argv[]);
01394 static int sip_notify(int fd, int argc, char *argv[]);
01395 static int sip_do_history(int fd, int argc, char *argv[]);
01396 static int sip_no_history(int fd, int argc, char *argv[]);
01397 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
01398 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01399 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01400 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01401 static int sip_dtmfmode(struct ast_channel *chan, void *data);
01402 static int sip_addheader(struct ast_channel *chan, void *data);
01403 static int sip_do_reload(enum channelreloadreason reason);
01404 static int sip_reload(int fd, int argc, char *argv[]);
01405 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen);
01406
01407
01408
01409
01410
01411 static void sip_dump_history(struct sip_pvt *dialog);
01412 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
01413 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01414 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01415 static void sip_dump_history(struct sip_pvt *dialog);
01416
01417
01418 static struct sip_peer *temp_peer(const char *name);
01419 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
01420 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
01421 static int update_call_counter(struct sip_pvt *fup, int event);
01422 static void sip_destroy_peer(struct sip_peer *peer);
01423 static void sip_destroy_user(struct sip_user *user);
01424 static int sip_poke_peer(struct sip_peer *peer);
01425 static int sip_poke_peer_s(const void *data);
01426 static void set_peer_defaults(struct sip_peer *peer);
01427 static struct sip_peer *temp_peer(const char *name);
01428 static void register_peer_exten(struct sip_peer *peer, int onoff);
01429 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
01430 static struct sip_user *find_user(const char *name, int realtime);
01431 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01432 static int expire_register(const void *data);
01433 static void reg_source_db(struct sip_peer *peer);
01434 static void destroy_association(struct sip_peer *peer);
01435 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01436
01437
01438 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
01439 static struct sip_user *realtime_user(const char *username);
01440 static void update_peer(struct sip_peer *p, int expiry);
01441 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
01442 static int sip_prune_realtime(int fd, int argc, char *argv[]);
01443
01444
01445 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
01446 static void sip_registry_destroy(struct sip_registry *reg);
01447 static int sip_register(char *value, int lineno);
01448 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
01449 static int sip_reregister(const void *data);
01450 static int __sip_do_register(struct sip_registry *r);
01451 static int sip_reg_timeout(const void *data);
01452 static void sip_send_all_registers(void);
01453
01454
01455 static void append_date(struct sip_request *req);
01456 static int determine_firstline_parts(struct sip_request *req);
01457 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01458 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01459 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01460 static int find_sip_method(const char *msg);
01461 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
01462 static void parse_request(struct sip_request *req);
01463 static const char *get_header(const struct sip_request *req, const char *name);
01464 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
01465 static int method_match(enum sipmethod id, const char *name);
01466 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01467 static char *get_in_brackets(char *tmp);
01468 static const char *find_alias(const char *name, const char *_default);
01469 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01470 static int lws2sws(char *msgbuf, int len);
01471 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01472 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01473 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01474 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01475 static int set_address_from_contact(struct sip_pvt *pvt);
01476 static void check_via(struct sip_pvt *p, struct sip_request *req);
01477 static char *get_calleridname(const char *input, char *output, size_t outputsize);
01478 static int get_rpid_num(const char *input, char *output, int maxlen);
01479 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
01480 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
01481 static int get_msg_text(char *buf, int len, struct sip_request *req);
01482 static void free_old_route(struct sip_route *route);
01483 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01484
01485
01486 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01487 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01488 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
01489 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
01490 static int init_resp(struct sip_request *resp, const char *msg);
01491 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01492 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
01493 static void build_via(struct sip_pvt *p);
01494 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01495 static int create_addr(struct sip_pvt *dialog, const char *opeer);
01496 static char *generate_random_string(char *buf, size_t size);
01497 static void build_callid_pvt(struct sip_pvt *pvt);
01498 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
01499 static void make_our_tag(char *tagbuf, size_t len);
01500 static int add_header(struct sip_request *req, const char *var, const char *value);
01501 static int add_header_contentLength(struct sip_request *req, int len);
01502 static int add_line(struct sip_request *req, const char *line);
01503 static int add_text(struct sip_request *req, const char *text);
01504 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
01505 static int add_vidupdate(struct sip_request *req);
01506 static void add_route(struct sip_request *req, struct sip_route *route);
01507 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01508 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01509 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01510 static void set_destination(struct sip_pvt *p, char *uri);
01511 static void append_date(struct sip_request *req);
01512 static void build_contact(struct sip_pvt *p);
01513 static void build_rpid(struct sip_pvt *p);
01514
01515
01516 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
01517 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);
01518 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
01519 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01520 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
01521 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01522 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01523 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
01524 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01525 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
01526 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
01527 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
01528 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
01529
01530
01531 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
01532 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
01533 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
01534 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
01535
01536
01537 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
01538 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
01539 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
01540 static int sip_get_codec(struct ast_channel *chan);
01541 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
01542
01543
01544 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
01545 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01546 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
01547 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01548 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01549
01550
01551 static const struct ast_channel_tech sip_tech = {
01552 .type = "SIP",
01553 .description = "Session Initiation Protocol (SIP)",
01554 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
01555 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01556 .requester = sip_request_call,
01557 .devicestate = sip_devicestate,
01558 .call = sip_call,
01559 .hangup = sip_hangup,
01560 .answer = sip_answer,
01561 .read = sip_read,
01562 .write = sip_write,
01563 .write_video = sip_write,
01564 .indicate = sip_indicate,
01565 .transfer = sip_transfer,
01566 .fixup = sip_fixup,
01567 .send_digit_begin = sip_senddigit_begin,
01568 .send_digit_end = sip_senddigit_end,
01569 .bridge = ast_rtp_bridge,
01570 .send_text = sip_sendtext,
01571 .func_channel_read = acf_channel_read,
01572 };
01573
01574
01575
01576
01577 static const struct ast_channel_tech sip_tech_info = {
01578 .type = "SIP",
01579 .description = "Session Initiation Protocol (SIP)",
01580 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
01581 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01582 .requester = sip_request_call,
01583 .devicestate = sip_devicestate,
01584 .call = sip_call,
01585 .hangup = sip_hangup,
01586 .answer = sip_answer,
01587 .read = sip_read,
01588 .write = sip_write,
01589 .write_video = sip_write,
01590 .indicate = sip_indicate,
01591 .transfer = sip_transfer,
01592 .fixup = sip_fixup,
01593 .send_digit_end = sip_senddigit_end,
01594 .bridge = ast_rtp_bridge,
01595 .send_text = sip_sendtext,
01596 .func_channel_read = acf_channel_read,
01597 };
01598
01599
01600
01601 #define UNLINK(element, head, prev) do { \
01602 if (prev) \
01603 (prev)->next = (element)->next; \
01604 else \
01605 (head) = (element)->next; \
01606 } while (0)
01607
01608
01609 static struct ast_rtp_protocol sip_rtp = {
01610 type: "SIP",
01611 get_rtp_info: sip_get_rtp_peer,
01612 get_vrtp_info: sip_get_vrtp_peer,
01613 set_rtp_peer: sip_set_rtp_peer,
01614 get_codec: sip_get_codec,
01615 };
01616
01617
01618 static struct ast_udptl_protocol sip_udptl = {
01619 type: "SIP",
01620 get_udptl_info: sip_get_udptl_peer,
01621 set_udptl_peer: sip_set_udptl_peer,
01622 };
01623
01624
01625 static char *referstatus2str(enum referstatus rstatus)
01626 {
01627 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
01628 int x;
01629
01630 for (x = 0; x < i; x++) {
01631 if (referstatusstrings[x].status == rstatus)
01632 return (char *) referstatusstrings[x].text;
01633 }
01634 return "";
01635 }
01636
01637
01638
01639
01640 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
01641 {
01642 if (p->initreq.headers && option_debug) {
01643 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
01644 }
01645
01646 copy_request(&p->initreq, req);
01647 parse_request(&p->initreq);
01648 if (ast_test_flag(req, SIP_PKT_DEBUG))
01649 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
01650 }
01651
01652 static void sip_alreadygone(struct sip_pvt *dialog)
01653 {
01654 if (option_debug > 2)
01655 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
01656 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
01657 }
01658
01659
01660
01661
01662
01663
01664
01665
01666 static int method_match(enum sipmethod id, const char *name)
01667 {
01668 int len = strlen(sip_methods[id].text);
01669 int l_name = name ? strlen(name) : 0;
01670
01671 return (l_name >= len && name[len] < 33 &&
01672 !strncasecmp(sip_methods[id].text, name, len));
01673 }
01674
01675
01676 static int find_sip_method(const char *msg)
01677 {
01678 int i, res = 0;
01679
01680 if (ast_strlen_zero(msg))
01681 return 0;
01682 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
01683 if (method_match(i, msg))
01684 res = sip_methods[i].id;
01685 }
01686 return res;
01687 }
01688
01689
01690 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
01691 {
01692 char *next, *sep;
01693 char *temp;
01694 unsigned int profile = 0;
01695 int i, found;
01696
01697 if (ast_strlen_zero(supported) )
01698 return 0;
01699 temp = ast_strdupa(supported);
01700
01701 if (option_debug > 2 && sipdebug)
01702 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
01703
01704 for (next = temp; next; next = sep) {
01705 found = FALSE;
01706 if ( (sep = strchr(next, ',')) != NULL)
01707 *sep++ = '\0';
01708 next = ast_skip_blanks(next);
01709 if (option_debug > 2 && sipdebug)
01710 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
01711 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
01712 if (!strcasecmp(next, sip_options[i].text)) {
01713 profile |= sip_options[i].id;
01714 found = TRUE;
01715 if (option_debug > 2 && sipdebug)
01716 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
01717 break;
01718 }
01719 }
01720 if (!found && option_debug > 2 && sipdebug) {
01721 if (!strncasecmp(next, "x-", 2))
01722 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
01723 else
01724 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
01725 }
01726 }
01727
01728 if (pvt)
01729 pvt->sipoptions = profile;
01730 return profile;
01731 }
01732
01733
01734 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
01735 {
01736 if (!sipdebug)
01737 return 0;
01738 if (debugaddr.sin_addr.s_addr) {
01739 if (((ntohs(debugaddr.sin_port) != 0)
01740 && (debugaddr.sin_port != addr->sin_port))
01741 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
01742 return 0;
01743 }
01744 return 1;
01745 }
01746
01747
01748 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
01749 {
01750 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
01751 }
01752
01753
01754 static const char *sip_nat_mode(const struct sip_pvt *p)
01755 {
01756 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
01757 }
01758
01759
01760 static inline int sip_debug_test_pvt(struct sip_pvt *p)
01761 {
01762 if (!sipdebug)
01763 return 0;
01764 return sip_debug_test_addr(sip_real_dst(p));
01765 }
01766
01767
01768 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
01769 {
01770 int res;
01771 const struct sockaddr_in *dst = sip_real_dst(p);
01772 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
01773
01774 if (res == -1) {
01775 switch (errno) {
01776 case EBADF:
01777 case EHOSTUNREACH:
01778 case ENETDOWN:
01779 case ENETUNREACH:
01780 res = XMIT_ERROR;
01781 }
01782 }
01783 if (res != len)
01784 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));
01785 return res;
01786 }
01787
01788
01789
01790 static void build_via(struct sip_pvt *p)
01791 {
01792
01793 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
01794
01795
01796 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
01797 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
01798 }
01799
01800
01801
01802
01803
01804
01805
01806 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
01807 {
01808 struct sockaddr_in theirs, ours;
01809
01810
01811 ast_ouraddrfor(them, us);
01812 theirs.sin_addr = *them;
01813 ours.sin_addr = *us;
01814
01815 if (localaddr && externip.sin_addr.s_addr &&
01816 (ast_apply_ha(localaddr, &theirs)) &&
01817 (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
01818 if (externexpire && time(NULL) >= externexpire) {
01819 struct ast_hostent ahp;
01820 struct hostent *hp;
01821
01822 externexpire = time(NULL) + externrefresh;
01823 if ((hp = ast_gethostbyname(externhost, &ahp))) {
01824 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
01825 } else
01826 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
01827 }
01828 *us = externip.sin_addr;
01829 if (option_debug) {
01830 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
01831 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
01832 }
01833 } else if (bindaddr.sin_addr.s_addr)
01834 *us = bindaddr.sin_addr;
01835 return AST_SUCCESS;
01836 }
01837
01838
01839
01840 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
01841
01842 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
01843 __attribute__ ((format (printf, 2, 3)));
01844
01845
01846 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
01847 {
01848 char buf[80], *c = buf;
01849 struct sip_history *hist;
01850 int l;
01851
01852 vsnprintf(buf, sizeof(buf), fmt, ap);
01853 strsep(&c, "\r\n");
01854 l = strlen(buf) + 1;
01855 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
01856 return;
01857 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
01858 free(hist);
01859 return;
01860 }
01861 memcpy(hist->event, buf, l);
01862 if (p->history_entries == MAX_HISTORY_ENTRIES) {
01863 struct sip_history *oldest;
01864 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
01865 p->history_entries--;
01866 free(oldest);
01867 }
01868 AST_LIST_INSERT_TAIL(p->history, hist, list);
01869 p->history_entries++;
01870 }
01871
01872
01873 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
01874 {
01875 va_list ap;
01876
01877 if (!p)
01878 return;
01879
01880 if (ast_test_flag(&p->flags[0], SIP_NO_HISTORY)
01881 && !recordhistory && !dumphistory) {
01882 return;
01883 }
01884
01885 va_start(ap, fmt);
01886 append_history_va(p, fmt, ap);
01887 va_end(ap);
01888
01889 return;
01890 }
01891
01892
01893 static int retrans_pkt(const void *data)
01894 {
01895 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
01896 int reschedule = DEFAULT_RETRANS;
01897 int xmitres = 0;
01898
01899
01900 ast_mutex_lock(&pkt->owner->lock);
01901
01902 if (pkt->retrans < MAX_RETRANS) {
01903 pkt->retrans++;
01904 if (!pkt->timer_t1) {
01905 if (sipdebug && option_debug > 3)
01906 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);
01907 } else {
01908 int siptimer_a;
01909
01910 if (sipdebug && option_debug > 3)
01911 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
01912 if (!pkt->timer_a)
01913 pkt->timer_a = 2 ;
01914 else
01915 pkt->timer_a = 2 * pkt->timer_a;
01916
01917
01918 siptimer_a = pkt->timer_t1 * pkt->timer_a;
01919 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
01920 siptimer_a = 4000;
01921
01922
01923 reschedule = siptimer_a;
01924 if (option_debug > 3)
01925 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);
01926 }
01927
01928 if (sip_debug_test_pvt(pkt->owner)) {
01929 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
01930 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
01931 pkt->retrans, sip_nat_mode(pkt->owner),
01932 ast_inet_ntoa(dst->sin_addr),
01933 ntohs(dst->sin_port), pkt->data);
01934 }
01935
01936 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
01937 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
01938 ast_mutex_unlock(&pkt->owner->lock);
01939 if (xmitres == XMIT_ERROR)
01940 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
01941 else
01942 return reschedule;
01943 }
01944
01945 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
01946 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug)
01947 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
01948 } else if ((pkt->method == SIP_OPTIONS) && sipdebug) {
01949 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
01950 }
01951 if (xmitres == XMIT_ERROR) {
01952 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission of transaction in call id %s \n", pkt->owner->callid);
01953 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
01954 } else
01955 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
01956
01957 pkt->retransid = -1;
01958
01959 if (ast_test_flag(pkt, FLAG_FATAL)) {
01960 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
01961 ast_mutex_unlock(&pkt->owner->lock);
01962 usleep(1);
01963 ast_mutex_lock(&pkt->owner->lock);
01964 }
01965
01966 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
01967 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
01968
01969 if (pkt->owner->owner) {
01970 sip_alreadygone(pkt->owner);
01971 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
01972 ast_queue_hangup(pkt->owner->owner);
01973 ast_channel_unlock(pkt->owner->owner);
01974 } else {
01975
01976
01977
01978 if (pkt->method != SIP_OPTIONS) {
01979 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
01980 sip_alreadygone(pkt->owner);
01981 if (option_debug)
01982 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
01983 }
01984 }
01985 }
01986
01987 if (pkt->method == SIP_BYE) {
01988
01989 if (pkt->owner->owner)
01990 ast_channel_unlock(pkt->owner->owner);
01991 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
01992 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
01993 }
01994
01995
01996 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
01997 if (cur == pkt)
01998 break;
01999 }
02000 if (cur) {
02001 if (prev)
02002 prev->next = cur->next;
02003 else
02004 pkt->owner->packets = cur->next;
02005 ast_mutex_unlock(&pkt->owner->lock);
02006 free(cur);
02007 pkt = NULL;
02008 } else
02009 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
02010 if (pkt)
02011 ast_mutex_unlock(&pkt->owner->lock);
02012 return 0;
02013 }
02014
02015
02016
02017
02018 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
02019 {
02020 struct sip_pkt *pkt;
02021 int siptimer_a = DEFAULT_RETRANS;
02022 int xmitres = 0;
02023
02024 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
02025 return AST_FAILURE;
02026 memcpy(pkt->data, data, len);
02027 pkt->method = sipmethod;
02028 pkt->packetlen = len;
02029 pkt->next = p->packets;
02030 pkt->owner = p;
02031 pkt->seqno = seqno;
02032 if (resp)
02033 ast_set_flag(pkt, FLAG_RESPONSE);
02034 pkt->data[len] = '\0';
02035 pkt->timer_t1 = p->timer_t1;
02036 if (fatal)
02037 ast_set_flag(pkt, FLAG_FATAL);
02038 if (pkt->timer_t1)
02039 siptimer_a = pkt->timer_t1 * 2;
02040
02041
02042 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
02043 if (option_debug > 3 && sipdebug)
02044 ast_log(LOG_DEBUG, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
02045 pkt->next = p->packets;
02046 p->packets = pkt;
02047 if (sipmethod == SIP_INVITE) {
02048
02049 p->pendinginvite = seqno;
02050 }
02051
02052 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
02053
02054 if (xmitres == XMIT_ERROR) {
02055 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
02056 ast_sched_del(sched, pkt->retransid);
02057 pkt->retransid = -1;
02058 return AST_FAILURE;
02059 } else
02060 return AST_SUCCESS;
02061 }
02062
02063
02064 static int __sip_autodestruct(const void *data)
02065 {
02066 struct sip_pvt *p = (struct sip_pvt *)data;
02067
02068
02069 if (p->subscribed) {
02070 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
02071 p->subscribed = NONE;
02072 append_history(p, "Subscribestatus", "timeout");
02073 if (option_debug > 2)
02074 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
02075 return 10000;
02076 }
02077
02078
02079 if (p->packets) {
02080 if (option_debug > 2)
02081 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
02082 append_history(p, "ReliableXmit", "timeout");
02083 return 10000;
02084 }
02085
02086
02087 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
02088 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
02089
02090
02091 p->autokillid = -1;
02092
02093 if (option_debug)
02094 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
02095 append_history(p, "AutoDestroy", "%s", p->callid);
02096 if (p->owner) {
02097 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
02098 ast_queue_hangup(p->owner);
02099 } else if (p->refer) {
02100 if (option_debug > 2)
02101 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
02102 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
02103 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
02104 } else
02105 sip_destroy(p);
02106 return 0;
02107 }
02108
02109
02110 static void sip_scheddestroy(struct sip_pvt *p, int ms)
02111 {
02112 if (ms < 0) {
02113 if (p->timer_t1 == 0)
02114 p->timer_t1 = 500;
02115 ms = p->timer_t1 * 64;
02116 }
02117 if (sip_debug_test_pvt(p))
02118 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
02119 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
02120 append_history(p, "SchedDestroy", "%d ms", ms);
02121
02122 if (p->autokillid > -1)
02123 ast_sched_del(sched, p->autokillid);
02124 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
02125 }
02126
02127
02128 static void sip_cancel_destroy(struct sip_pvt *p)
02129 {
02130 if (p->autokillid > -1) {
02131 ast_sched_del(sched, p->autokillid);
02132 append_history(p, "CancelDestroy", "");
02133 p->autokillid = -1;
02134 }
02135 }
02136
02137
02138 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
02139 {
02140 struct sip_pkt *cur, *prev = NULL;
02141
02142
02143 char *msg;
02144 int res = FALSE;
02145
02146 msg = sip_methods[sipmethod].text;
02147
02148 ast_mutex_lock(&p->lock);
02149 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
02150 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
02151 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
02152 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
02153 if (!resp && (seqno == p->pendinginvite)) {
02154 if (option_debug)
02155 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
02156 p->pendinginvite = 0;
02157 }
02158
02159 res = TRUE;
02160 UNLINK(cur, p->packets, prev);
02161 if (cur->retransid > -1) {
02162 if (sipdebug && option_debug > 3)
02163 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
02164 ast_sched_del(sched, cur->retransid);
02165 cur->retransid = -1;
02166 }
02167 free(cur);
02168 break;
02169 }
02170 }
02171 ast_mutex_unlock(&p->lock);
02172 if (option_debug)
02173 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
02174 }
02175
02176
02177
02178 static void __sip_pretend_ack(struct sip_pvt *p)
02179 {
02180 struct sip_pkt *cur = NULL;
02181
02182 while (p->packets) {
02183 int method;
02184 if (cur == p->packets) {
02185 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
02186 return;
02187 }
02188 cur = p->packets;
02189 method = (cur->method) ? cur->method : find_sip_method(cur->data);
02190 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
02191 }
02192 }
02193
02194
02195 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
02196 {
02197 struct sip_pkt *cur;
02198 int res = -1;
02199
02200 for (cur = p->packets; cur; cur = cur->next) {
02201 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
02202 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
02203
02204 if (cur->retransid > -1) {
02205 if (option_debug > 3 && sipdebug)
02206 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
02207 ast_sched_del(sched, cur->retransid);
02208 cur->retransid = -1;
02209 }
02210 res = 0;
02211 break;
02212 }
02213 }
02214 if (option_debug)
02215 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
02216 return res;
02217 }
02218
02219
02220
02221 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
02222 {
02223 memset(dst, 0, sizeof(*dst));
02224 memcpy(dst->data, src->data, sizeof(dst->data));
02225 dst->len = src->len;
02226 parse_request(dst);
02227 }
02228
02229
02230 static void add_blank(struct sip_request *req)
02231 {
02232 if (!req->lines) {
02233
02234 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
02235 req->len += strlen(req->data + req->len);
02236 }
02237 }
02238
02239
02240 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
02241 {
02242 int res;
02243
02244 add_blank(req);
02245 if (sip_debug_test_pvt(p)) {
02246 const struct sockaddr_in *dst = sip_real_dst(p);
02247
02248 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
02249 reliable ? "Reliably " : "", sip_nat_mode(p),
02250 ast_inet_ntoa(dst->sin_addr),
02251 ntohs(dst->sin_port), req->data);
02252 }
02253 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
02254 struct sip_request tmp;
02255 parse_copy(&tmp, req);
02256 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
02257 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
02258 }
02259 res = (reliable) ?
02260 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
02261 __sip_xmit(p, req->data, req->len);
02262 if (res > 0)
02263 return 0;
02264 return res;
02265 }
02266
02267
02268 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
02269 {
02270 int res;
02271
02272 add_blank(req);
02273 if (sip_debug_test_pvt(p)) {
02274 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
02275 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);
02276 else
02277 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);
02278 }
02279 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
02280 struct sip_request tmp;
02281 parse_copy(&tmp, req);
02282 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
02283 }
02284 res = (reliable) ?
02285 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
02286 __sip_xmit(p, req->data, req->len);
02287 return res;
02288 }
02289
02290
02291
02292
02293
02294 static const char *find_closing_quote(const char *start, const char *lim)
02295 {
02296 char last_char = '\0';
02297 const char *s;
02298 for (s = start; *s && s != lim; last_char = *s++) {
02299 if (*s == '"' && last_char != '\\')
02300 break;
02301 }
02302 return s;
02303 }
02304
02305
02306
02307
02308
02309
02310
02311
02312
02313
02314
02315
02316 static char *get_in_brackets(char *tmp)
02317 {
02318 const char *parse = tmp;
02319 char *first_bracket;
02320
02321
02322
02323
02324
02325 while ( (first_bracket = strchr(parse, '<')) ) {
02326 char *first_quote = strchr(parse, '"');
02327
02328 if (!first_quote || first_quote > first_bracket)
02329 break;
02330
02331 parse = find_closing_quote(first_quote + 1, NULL);
02332 if (!*parse) {
02333
02334 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
02335 break;
02336 }
02337 parse++;
02338 }
02339 if (first_bracket) {
02340 char *second_bracket = strchr(first_bracket + 1, '>');
02341 if (second_bracket) {
02342 *second_bracket = '\0';
02343 tmp = first_bracket + 1;
02344 } else {
02345 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
02346 }
02347 }
02348 return tmp;
02349 }
02350
02351
02352
02353 static int sip_sendtext(struct ast_channel *ast, const char *dest, const char *text, int ispdu)
02354 {
02355 struct sip_pvt *p = ast->tech_pvt;
02356 int debug = sip_debug_test_pvt(p);
02357
02358 if (debug)
02359 ast_verbose("Sending text %s on %s\n", text, ast->name);
02360 if (!p)
02361 return -1;
02362 if (ast_strlen_zero(text))
02363 return 0;
02364 if (debug)
02365 ast_verbose("Really sending text %s on %s\n", text, ast->name);
02366 transmit_message_with_text(p, text);
02367 return 0;
02368 }
02369
02370
02371
02372
02373
02374
02375 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
02376 {
02377 char port[10];
02378 char ipaddr[INET_ADDRSTRLEN];
02379 char regseconds[20];
02380
02381 char *sysname = ast_config_AST_SYSTEM_NAME;
02382 char *syslabel = NULL;
02383
02384 time_t nowtime = time(NULL) + expirey;
02385 const char *fc = fullcontact ? "fullcontact" : NULL;
02386
02387 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
02388 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
02389 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
02390
02391 if (ast_strlen_zero(sysname))
02392 sysname = NULL;
02393 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
02394 syslabel = "regserver";
02395
02396 if (fc)
02397 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
02398 "port", port, "regseconds", regseconds,
02399 "username", username, fc, fullcontact, syslabel, sysname, NULL);
02400 else
02401 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
02402 "port", port, "regseconds", regseconds,
02403 "username", username, syslabel, sysname, NULL);
02404 }
02405
02406
02407 static void register_peer_exten(struct sip_peer *peer, int onoff)
02408 {
02409 char multi[256];
02410 char *stringp, *ext, *context;
02411
02412
02413
02414
02415
02416 if (ast_strlen_zero(global_regcontext))
02417 return;
02418
02419 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
02420 stringp = multi;
02421 while ((ext = strsep(&stringp, "&"))) {
02422 if ((context = strchr(ext, '@'))) {
02423 *context++ = '\0';
02424 if (!ast_context_find(context)) {
02425 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
02426 continue;
02427 }
02428 } else {
02429 context = global_regcontext;
02430 }
02431 if (onoff)
02432 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
02433 ast_strdup(peer->name), ast_free, "SIP");
02434 else
02435 ast_context_remove_extension(context, ext, 1, NULL);
02436 }
02437 }
02438
02439
02440 static void sip_destroy_peer(struct sip_peer *peer)
02441 {
02442 if (option_debug > 2)
02443 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
02444
02445
02446 if (peer->call)
02447 sip_destroy(peer->call);
02448
02449 if (peer->mwipvt)
02450 sip_destroy(peer->mwipvt);
02451
02452 if (peer->chanvars) {
02453 ast_variables_destroy(peer->chanvars);
02454 peer->chanvars = NULL;
02455 }
02456 if (peer->expire > -1)
02457 ast_sched_del(sched, peer->expire);
02458
02459 if (peer->pokeexpire > -1)
02460 ast_sched_del(sched, peer->pokeexpire);
02461 register_peer_exten(peer, FALSE);
02462 ast_free_ha(peer->ha);
02463 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
02464 apeerobjs--;
02465 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
02466 rpeerobjs--;
02467 else
02468 speerobjs--;
02469 clear_realm_authentication(peer->auth);
02470 peer->auth = NULL;
02471 free(peer);
02472 }
02473
02474
02475 static void update_peer(struct sip_peer *p, int expiry)
02476 {
02477 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
02478 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
02479 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
02480 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
02481 }
02482 }
02483
02484
02485
02486
02487
02488
02489
02490 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
02491 {
02492 struct sip_peer *peer=NULL;
02493 struct ast_variable *var = NULL;
02494 struct ast_config *peerlist = NULL;
02495 struct ast_variable *tmp;
02496 struct ast_flags flags = {0};
02497 const char *iabuf = NULL;
02498 char portstring[6];
02499 const char *insecure;
02500 char *cat = NULL;
02501 unsigned short portnum;
02502
02503
02504 if (newpeername) {
02505 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
02506 if (!var && sin)
02507 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
02508 if (!var) {
02509 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
02510
02511
02512
02513
02514
02515
02516 if (var) {
02517 for (tmp = var; tmp; tmp = tmp->next) {
02518 if (!strcasecmp(var->name, "host")) {
02519 struct in_addr sin2 = { 0, };
02520 struct ast_dnsmgr_entry *dnsmgr = NULL;
02521 if ((ast_dnsmgr_lookup(tmp->value, &sin2, &dnsmgr) < 0) || (memcmp(&sin2, &sin->sin_addr, sizeof(sin2)) != 0)) {
02522
02523 ast_variables_destroy(var);
02524 var = NULL;
02525 }
02526 break;
02527 }
02528 }
02529 }
02530 }
02531 }
02532
02533 if (!var && sin) {
02534 iabuf = ast_inet_ntoa(sin->sin_addr);
02535 portnum = ntohs(sin->sin_port);
02536 sprintf(portstring, "%d", portnum);
02537 var = ast_load_realtime("sippeers", "host", iabuf, "port", portstring, NULL);
02538 if (!var)
02539 var = ast_load_realtime("sippeers", "ipaddr", iabuf, "port", portstring, NULL);
02540 if (!var) {
02541 peerlist = ast_load_realtime_multientry("sippeers", "host", iabuf, NULL);
02542 if(peerlist){
02543 while((cat = ast_category_browse(peerlist, cat)))
02544 {
02545 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
02546 set_insecure_flags(&flags, insecure, -1);
02547 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
02548 var = ast_category_root(peerlist, cat);
02549 break;
02550 }
02551 }
02552 }
02553 if(!var) {
02554 ast_config_destroy(peerlist);
02555 peerlist = NULL;
02556 cat = NULL;
02557 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", iabuf, NULL);
02558 if(peerlist) {
02559 while((cat = ast_category_browse(peerlist, cat)))
02560 {
02561 insecure = ast_variable_retrieve(peerlist, cat, "insecure");
02562 set_insecure_flags(&flags, insecure, -1);
02563 if(ast_test_flag(&flags, SIP_INSECURE_PORT)) {
02564 var = ast_category_root(peerlist, cat);
02565 break;
02566 }
02567 }
02568 }
02569 }
02570 }
02571 }
02572
02573 if (!var) {
02574 if(peerlist)
02575 ast_config_destroy(peerlist);
02576 return NULL;
02577 }
02578
02579 for (tmp = var; tmp; tmp = tmp->next) {
02580
02581 if (!strcasecmp(tmp->name, "type") &&
02582 !strcasecmp(tmp->value, "user")) {
02583 ast_variables_destroy(var);
02584 return NULL;
02585 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
02586 newpeername = tmp->value;
02587 }
02588 }
02589
02590 if (!newpeername) {
02591 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
02592 if(peerlist)
02593 ast_config_destroy(peerlist);
02594 else
02595 ast_variables_destroy(var);
02596 return NULL;
02597 }
02598
02599
02600 peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
02601 if (!peer) {
02602 if(peerlist)
02603 ast_config_destroy(peerlist);
02604 else
02605 ast_variables_destroy(var);
02606 return NULL;
02607 }
02608
02609 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
02610
02611 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
02612 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
02613 if (peer->expire > -1) {
02614 ast_sched_del(sched, peer->expire);
02615 }
02616 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
02617 }
02618 ASTOBJ_CONTAINER_LINK(&peerl,peer);
02619 } else {
02620 ast_set_flag(&peer->flags[0], SIP_REALTIME);
02621 }
02622 if(peerlist)
02623 ast_config_destroy(peerlist);
02624 else
02625 ast_variables_destroy(var);
02626 return peer;
02627 }
02628
02629
02630 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
02631 {
02632
02633 struct sip_peer *p = (struct sip_peer *) name;
02634 return !(!inaddrcmp(&p->addr, sin) ||
02635 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
02636 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
02637 }
02638
02639
02640
02641
02642 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
02643 {
02644 struct sip_peer *p = NULL;
02645
02646 if (peer)
02647 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
02648 else
02649 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
02650
02651 if (!p && realtime)
02652 p = realtime_peer(peer, sin);
02653
02654 return p;
02655 }
02656
02657
02658 static void sip_destroy_user(struct sip_user *user)
02659 {
02660 if (option_debug > 2)
02661 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
02662 ast_free_ha(user->ha);
02663 if (user->chanvars) {
02664 ast_variables_destroy(user->chanvars);
02665 user->chanvars = NULL;
02666 }
02667 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
02668 ruserobjs--;
02669 else
02670 suserobjs--;
02671 free(user);
02672 }
02673
02674
02675
02676
02677 static struct sip_user *realtime_user(const char *username)
02678 {
02679 struct ast_variable *var;
02680 struct ast_variable *tmp;
02681 struct sip_user *user = NULL;
02682
02683 var = ast_load_realtime("sipusers", "name", username, NULL);
02684
02685 if (!var)
02686 return NULL;
02687
02688 for (tmp = var; tmp; tmp = tmp->next) {
02689 if (!strcasecmp(tmp->name, "type") &&
02690 !strcasecmp(tmp->value, "peer")) {
02691 ast_variables_destroy(var);
02692 return NULL;
02693 }
02694 }
02695
02696 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
02697
02698 if (!user) {
02699 ast_variables_destroy(var);
02700 return NULL;
02701 }
02702
02703 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
02704 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
02705 suserobjs++;
02706 ASTOBJ_CONTAINER_LINK(&userl,user);
02707 } else {
02708
02709 suserobjs--;
02710 ruserobjs++;
02711 ast_set_flag(&user->flags[0], SIP_REALTIME);
02712 }
02713 ast_variables_destroy(var);
02714 return user;
02715 }
02716
02717
02718
02719
02720
02721 static struct sip_user *find_user(const char *name, int realtime)
02722 {
02723 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
02724 if (!u && realtime)
02725 u = realtime_user(name);
02726 return u;
02727 }
02728
02729
02730 static void do_setnat(struct sip_pvt *p, int natflags)
02731 {
02732 const char *mode = natflags ? "On" : "Off";
02733
02734 if (p->rtp) {
02735 if (option_debug)
02736 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
02737 ast_rtp_setnat(p->rtp, natflags);
02738 }
02739 if (p->vrtp) {
02740 if (option_debug)
02741 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
02742 ast_rtp_setnat(p->vrtp, natflags);
02743 }
02744 if (p->udptl) {
02745 if (option_debug)
02746 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
02747 ast_udptl_setnat(p->udptl, natflags);
02748 }
02749 }
02750
02751
02752
02753
02754 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
02755 {
02756 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
02757 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
02758 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
02759 dialog->recv = dialog->sa;
02760 } else
02761 return -1;
02762
02763 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
02764 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
02765 dialog->capability = peer->capability;
02766 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
02767 ast_rtp_destroy(dialog->vrtp);
02768 dialog->vrtp = NULL;
02769 }
02770 dialog->prefs = peer->prefs;
02771 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
02772 dialog->t38.capability = global_t38_capability;
02773 if (dialog->udptl) {
02774 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
02775 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
02776 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
02777 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
02778 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
02779 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
02780 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
02781 if (option_debug > 1)
02782 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
02783 }
02784 dialog->t38.jointcapability = dialog->t38.capability;
02785 } else if (dialog->udptl) {
02786 ast_udptl_destroy(dialog->udptl);
02787 dialog->udptl = NULL;
02788 }
02789 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
02790
02791 if (dialog->rtp) {
02792 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
02793 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
02794 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
02795 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
02796 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
02797
02798 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
02799 dialog->autoframing = peer->autoframing;
02800 }
02801 if (dialog->vrtp) {
02802 ast_rtp_setdtmf(dialog->vrtp, 0);
02803 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
02804 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
02805 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
02806 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
02807 }
02808
02809 ast_string_field_set(dialog, peername, peer->name);
02810 ast_string_field_set(dialog, authname, peer->username);
02811 ast_string_field_set(dialog, username, peer->username);
02812 ast_string_field_set(dialog, peersecret, peer->secret);
02813 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
02814 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
02815 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
02816 ast_string_field_set(dialog, tohost, peer->tohost);
02817 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
02818 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
02819 char *tmpcall;
02820 char *c;
02821 tmpcall = ast_strdupa(dialog->callid);
02822 c = strchr(tmpcall, '@');
02823 if (c) {
02824 *c = '\0';
02825 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
02826 }
02827 }
02828 if (ast_strlen_zero(dialog->tohost))
02829 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
02830 if (!ast_strlen_zero(peer->fromdomain))
02831 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
02832 if (!ast_strlen_zero(peer->fromuser))
02833 ast_string_field_set(dialog, fromuser, peer->fromuser);
02834 if (!ast_strlen_zero(peer->language))
02835 ast_string_field_set(dialog, language, peer->language);
02836 dialog->maxtime = peer->maxms;
02837 dialog->callgroup = peer->callgroup;
02838 dialog->pickupgroup = peer->pickupgroup;
02839 dialog->allowtransfer = peer->allowtransfer;
02840
02841
02842 if (peer->maxms && peer->lastms)
02843 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
02844 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
02845 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
02846 dialog->noncodeccapability |= AST_RTP_DTMF;
02847 else
02848 dialog->noncodeccapability &= ~AST_RTP_DTMF;
02849 dialog->jointnoncodeccapability = dialog->noncodeccapability;
02850 ast_string_field_set(dialog, context, peer->context);
02851 dialog->rtptimeout = peer->rtptimeout;
02852 if (peer->call_limit)
02853 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
02854 dialog->maxcallbitrate = peer->maxcallbitrate;
02855
02856 return 0;
02857 }
02858
02859
02860
02861
02862 static int create_addr(struct sip_pvt *dialog, const char *opeer)
02863 {
02864 struct hostent *hp;
02865 struct ast_hostent ahp;
02866 struct sip_peer *p;
02867 char *port;
02868 int portno;
02869 char host[MAXHOSTNAMELEN], *hostn;
02870 char peer[256];
02871
02872 ast_copy_string(peer, opeer, sizeof(peer));
02873 port = strchr(peer, ':');
02874 if (port)
02875 *port++ = '\0';
02876 dialog->sa.sin_family = AF_INET;
02877 dialog->timer_t1 = 500;
02878 p = find_peer(peer, NULL, 1);
02879
02880 if (p) {
02881 int res = create_addr_from_peer(dialog, p);
02882 ASTOBJ_UNREF(p, sip_destroy_peer);
02883 return res;
02884 }
02885 hostn = peer;
02886 portno = port ? atoi(port) : STANDARD_SIP_PORT;
02887 if (srvlookup) {
02888 char service[MAXHOSTNAMELEN];
02889 int tportno;
02890 int ret;
02891
02892 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
02893 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
02894 if (ret > 0) {
02895 hostn = host;
02896 portno = tportno;
02897 }
02898 }
02899 hp = ast_gethostbyname(hostn, &ahp);
02900 if (!hp) {
02901 ast_log(LOG_WARNING, "No such host: %s\n", peer);
02902 return -1;
02903 }
02904 ast_string_field_set(dialog, tohost, peer);
02905 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
02906 dialog->sa.sin_port = htons(portno);
02907 dialog->recv = dialog->sa;
02908 return 0;
02909 }
02910
02911
02912 static int auto_congest(const void *nothing)
02913 {
02914 struct sip_pvt *p = (struct sip_pvt *)nothing;
02915
02916 ast_mutex_lock(&p->lock);
02917 p->initid = -1;
02918 if (p->owner) {
02919
02920 if (!ast_channel_trylock(p->owner)) {
02921 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
02922 append_history(p, "Cong", "Auto-congesting (timer)");
02923 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
02924 ast_channel_unlock(p->owner);
02925 }
02926 }
02927 ast_mutex_unlock(&p->lock);
02928 return 0;
02929 }
02930
02931
02932
02933
02934 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
02935 {
02936 int res, xmitres = 0;
02937 struct sip_pvt *p;
02938 struct varshead *headp;
02939 struct ast_var_t *current;
02940 const char *referer = NULL;
02941
02942 p = ast->tech_pvt;
02943 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
02944 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
02945 return -1;
02946 }
02947
02948
02949 headp=&ast->varshead;
02950 AST_LIST_TRAVERSE(headp,current,entries) {
02951
02952 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
02953 p->options->vxml_url = ast_var_value(current);
02954 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
02955 p->options->uri_options = ast_var_value(current);
02956 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
02957
02958 p->options->distinctive_ring = ast_var_value(current);
02959 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
02960
02961 p->options->addsipheaders = 1;
02962 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
02963
02964 p->options->transfer = 1;
02965 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
02966
02967 referer = ast_var_value(current);
02968 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
02969
02970 p->options->replaces = ast_var_value(current);
02971 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
02972 p->t38.state = T38_LOCAL_DIRECT;
02973 if (option_debug)
02974 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
02975 }
02976
02977 }
02978
02979 res = 0;
02980 ast_set_flag(&p->flags[0], SIP_OUTGOING);
02981
02982 if (p->options->transfer) {
02983 char buf[BUFSIZ/2];
02984
02985 if (referer) {
02986 if (sipdebug && option_debug > 2)
02987 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
02988 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
02989 } else
02990 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
02991 ast_string_field_set(p, cid_name, buf);
02992 }
02993 if (option_debug)
02994 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
02995
02996 res = update_call_counter(p, INC_CALL_RINGING);
02997 if ( res != -1 ) {
02998 p->callingpres = ast->cid.cid_pres;
02999 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
03000 p->jointnoncodeccapability = p->noncodeccapability;
03001
03002
03003 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
03004 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
03005 res = -1;
03006 } else {
03007 p->t38.jointcapability = p->t38.capability;
03008 if (option_debug > 1)
03009 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
03010 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
03011 if (xmitres == XMIT_ERROR)
03012 return -1;
03013
03014 p->invitestate = INV_CALLING;
03015
03016
03017 if (p->initid > -1)
03018 ast_sched_del(sched, p->initid);
03019 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
03020 }
03021 }
03022 return res;
03023 }
03024
03025
03026
03027 static void sip_registry_destroy(struct sip_registry *reg)
03028 {
03029
03030 if (option_debug > 2)
03031 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
03032
03033 if (reg->call) {
03034
03035
03036 reg->call->registry = NULL;
03037 if (option_debug > 2)
03038 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
03039 sip_destroy(reg->call);
03040 }
03041 if (reg->expire > -1)
03042 ast_sched_del(sched, reg->expire);
03043 if (reg->timeout > -1)
03044 ast_sched_del(sched, reg->timeout);
03045 ast_string_field_free_memory(reg);
03046 regobjs--;
03047 free(reg);
03048
03049 }
03050
03051
03052 static void __sip_destroy(struct sip_pvt *p, int lockowner)
03053 {
03054 struct sip_pvt *cur, *prev = NULL;
03055 struct sip_pkt *cp;
03056
03057 if (sip_debug_test_pvt(p) || option_debug > 2)
03058 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
03059
03060 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
03061 update_call_counter(p, DEC_CALL_LIMIT);
03062 if (option_debug > 1)
03063 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
03064 }
03065
03066
03067 if (p->relatedpeer && p->relatedpeer->mwipvt)
03068 p->relatedpeer->mwipvt = NULL;
03069
03070 if (dumphistory)
03071 sip_dump_history(p);
03072
03073 if (p->options)
03074 free(p->options);
03075
03076 if (p->stateid > -1)
03077 ast_extension_state_del(p->stateid, NULL);
03078 if (p->initid > -1)
03079 ast_sched_del(sched, p->initid);
03080 if (p->waitid > -1)
03081 ast_sched_del(sched, p->waitid);
03082 if (p->autokillid > -1)
03083 ast_sched_del(sched, p->autokillid);
03084
03085 if (p->rtp)
03086 ast_rtp_destroy(p->rtp);
03087 if (p->vrtp)
03088 ast_rtp_destroy(p->vrtp);
03089 if (p->udptl)
03090 ast_udptl_destroy(p->udptl);
03091 if (p->refer)
03092 free(p->refer);
03093 if (p->route) {
03094 free_old_route(p->route);
03095 p->route = NULL;
03096 }
03097 if (p->registry) {
03098 if (p->registry->call == p)
03099 p->registry->call = NULL;
03100 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
03101 }
03102
03103
03104 if (p->owner) {
03105 if (lockowner)
03106 ast_channel_lock(p->owner);
03107 if (option_debug)
03108 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
03109 p->owner->tech_pvt = NULL;
03110 if (lockowner)
03111 ast_channel_unlock(p->owner);
03112 }
03113
03114 if (p->history) {
03115 struct sip_history *hist;
03116 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
03117 free(hist);
03118 p->history_entries--;
03119 }
03120 free(p->history);
03121 p->history = NULL;
03122 }
03123
03124 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
03125 if (cur == p) {
03126 UNLINK(cur, iflist, prev);
03127 break;
03128 }
03129 }
03130 if (!cur) {
03131 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
03132 return;
03133 }
03134
03135
03136 while((cp = p->packets)) {
03137 p->packets = p->packets->next;
03138 if (cp->retransid > -1)
03139 ast_sched_del(sched, cp->retransid);
03140 free(cp);
03141 }
03142 if (p->chanvars) {
03143 ast_variables_destroy(p->chanvars);
03144 p->chanvars = NULL;
03145 }
03146 ast_mutex_destroy(&p->lock);
03147
03148 ast_string_field_free_memory(p);
03149
03150 free(p);
03151 }
03152
03153
03154
03155
03156
03157
03158
03159
03160
03161
03162
03163
03164
03165
03166
03167 static int update_call_counter(struct sip_pvt *fup, int event)
03168 {
03169 char name[256];
03170 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
03171 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
03172 struct sip_user *u = NULL;
03173 struct sip_peer *p = NULL;
03174
03175 if (option_debug > 2)
03176 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
03177
03178
03179
03180 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
03181 return 0;
03182
03183 ast_copy_string(name, fup->username, sizeof(name));
03184
03185
03186 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
03187 inuse = &u->inUse;
03188 call_limit = &u->call_limit;
03189 inringing = NULL;
03190 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) {
03191 inuse = &p->inUse;
03192 call_limit = &p->call_limit;
03193 inringing = &p->inRinging;
03194 ast_copy_string(name, fup->peername, sizeof(name));
03195 }
03196 if (!p && !u) {
03197 if (option_debug > 1)
03198 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
03199 return 0;
03200 }
03201
03202 switch(event) {
03203
03204 case DEC_CALL_LIMIT:
03205 if ( *inuse > 0 ) {
03206 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
03207 (*inuse)--;
03208 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
03209 }
03210 } else {
03211 *inuse = 0;
03212 }
03213 if (inringing) {
03214 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03215 if (*inringing > 0)
03216 (*inringing)--;
03217 else if (!ast_test_flag(&fup->flags[0], SIP_REALTIME) || ast_test_flag(&fup->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
03218 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
03219 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03220 }
03221 }
03222 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
03223 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
03224 sip_peer_hold(fup, 0);
03225 }
03226 if (option_debug > 1 || sipdebug) {
03227 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
03228 }
03229 break;
03230
03231 case INC_CALL_RINGING:
03232 case INC_CALL_LIMIT:
03233 if (*call_limit > 0 ) {
03234 if (*inuse >= *call_limit) {
03235 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);
03236 if (u)
03237 ASTOBJ_UNREF(u, sip_destroy_user);
03238 else
03239 ASTOBJ_UNREF(p, sip_destroy_peer);
03240 return -1;
03241 }
03242 }
03243 if (inringing && (event == INC_CALL_RINGING)) {
03244 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03245 (*inringing)++;
03246 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03247 }
03248 }
03249
03250 (*inuse)++;
03251 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
03252 if (option_debug > 1 || sipdebug) {
03253 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
03254 }
03255 break;
03256
03257 case DEC_CALL_RINGING:
03258 if (inringing) {
03259 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03260 if (*inringing > 0)
03261 (*inringing)--;
03262 else if (!ast_test_flag(&fup->flags[0], SIP_REALTIME) || ast_test_flag(&fup->flags[1], SIP_PAGE2_RTCACHEFRIENDS))
03263 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
03264 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03265 }
03266 }
03267 break;
03268
03269 default:
03270 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
03271 }
03272 if (p) {
03273 ast_device_state_changed("SIP/%s", p->name);
03274 ASTOBJ_UNREF(p, sip_destroy_peer);
03275 } else
03276 ASTOBJ_UNREF(u, sip_destroy_user);
03277 return 0;
03278 }
03279
03280
03281 static void sip_destroy(struct sip_pvt *p)
03282 {
03283 ast_mutex_lock(&iflock);
03284 if (option_debug > 2)
03285 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
03286 __sip_destroy(p, 1);
03287 ast_mutex_unlock(&iflock);
03288 }
03289
03290
03291 static int hangup_sip2cause(int cause)
03292 {
03293
03294
03295 switch(cause) {
03296 case 401:
03297 return AST_CAUSE_CALL_REJECTED;
03298 case 403:
03299 return AST_CAUSE_CALL_REJECTED;
03300 case 404:
03301 return AST_CAUSE_UNALLOCATED;
03302 case 405:
03303 return AST_CAUSE_INTERWORKING;
03304 case 407:
03305 return AST_CAUSE_CALL_REJECTED;
03306 case 408:
03307 return AST_CAUSE_NO_USER_RESPONSE;
03308 case 409:
03309 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
03310 case 410:
03311 return AST_CAUSE_UNALLOCATED;
03312 case 411:
03313 return AST_CAUSE_INTERWORKING;
03314 case 413:
03315 return AST_CAUSE_INTERWORKING;
03316 case 414:
03317 return AST_CAUSE_INTERWORKING;
03318 case 415:
03319 return AST_CAUSE_INTERWORKING;
03320 case 420:
03321 return AST_CAUSE_NO_ROUTE_DESTINATION;
03322 case 480:
03323 return AST_CAUSE_NO_ANSWER;
03324 case 481:
03325 return AST_CAUSE_INTERWORKING;
03326 case 482:
03327 return AST_CAUSE_INTERWORKING;
03328 case 483:
03329 return AST_CAUSE_NO_ANSWER;
03330 case 484:
03331 return AST_CAUSE_INVALID_NUMBER_FORMAT;
03332 case 485:
03333 return AST_CAUSE_UNALLOCATED;
03334 case 486:
03335 return AST_CAUSE_BUSY;
03336 case 487:
03337 return AST_CAUSE_INTERWORKING;
03338 case 488:
03339 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
03340 case 491:
03341 return AST_CAUSE_INTERWORKING;
03342 case 493:
03343 return AST_CAUSE_INTERWORKING;
03344 case 500:
03345 return AST_CAUSE_FAILURE;
03346 case 501:
03347 return AST_CAUSE_FACILITY_REJECTED;
03348 case 502:
03349 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03350 case 503:
03351 return AST_CAUSE_CONGESTION;
03352 case 504:
03353 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
03354 case 505:
03355 return AST_CAUSE_INTERWORKING;
03356 case 600:
03357 return AST_CAUSE_USER_BUSY;
03358 case 603:
03359 return AST_CAUSE_CALL_REJECTED;
03360 case 604:
03361 return AST_CAUSE_UNALLOCATED;
03362 case 606:
03363 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
03364 default:
03365 return AST_CAUSE_NORMAL;
03366 }
03367
03368 return 0;
03369 }
03370
03371
03372
03373
03374
03375
03376
03377
03378
03379
03380
03381
03382
03383
03384
03385
03386
03387
03388
03389
03390
03391
03392
03393
03394
03395
03396
03397
03398
03399
03400
03401
03402
03403 static const char *hangup_cause2sip(int cause)
03404 {
03405 switch (cause) {
03406 case AST_CAUSE_UNALLOCATED:
03407 case AST_CAUSE_NO_ROUTE_DESTINATION:
03408 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
03409 return "404 Not Found";
03410 case AST_CAUSE_CONGESTION:
03411 case AST_CAUSE_SWITCH_CONGESTION:
03412 return "503 Service Unavailable";
03413 case AST_CAUSE_NO_USER_RESPONSE:
03414 return "408 Request Timeout";
03415 case AST_CAUSE_NO_ANSWER:
03416 return "480 Temporarily unavailable";
03417 case AST_CAUSE_CALL_REJECTED:
03418 return "403 Forbidden";
03419 case AST_CAUSE_NUMBER_CHANGED:
03420 return "410 Gone";
03421 case AST_CAUSE_NORMAL_UNSPECIFIED:
03422 return "480 Temporarily unavailable";
03423 case AST_CAUSE_INVALID_NUMBER_FORMAT:
03424 return "484 Address incomplete";
03425 case AST_CAUSE_USER_BUSY:
03426 return "486 Busy here";
03427 case AST_CAUSE_FAILURE:
03428 return "500 Server internal failure";
03429 case AST_CAUSE_FACILITY_REJECTED:
03430 return "501 Not Implemented";
03431 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
03432 return "503 Service Unavailable";
03433
03434 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
03435 return "502 Bad Gateway";
03436 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
03437 return "488 Not Acceptable Here";
03438
03439 case AST_CAUSE_NOTDEFINED:
03440 default:
03441 if (option_debug)
03442 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
03443 return NULL;
03444 }
03445
03446
03447 return 0;
03448 }
03449
03450
03451
03452
03453 static int sip_hangup(struct ast_channel *ast)
03454 {
03455 struct sip_pvt *p = ast->tech_pvt;
03456 int needcancel = FALSE;
03457 int needdestroy = 0;
03458 struct ast_channel *oldowner = ast;
03459
03460 if (!p) {
03461 if (option_debug)
03462 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
03463 return 0;
03464 }
03465
03466 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
03467 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
03468 if (option_debug && sipdebug)
03469 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
03470 update_call_counter(p, DEC_CALL_LIMIT);
03471 }
03472 if (option_debug >3)
03473 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
03474 if (p->autokillid > -1)
03475 sip_cancel_destroy(p);
03476 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03477 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
03478 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
03479 p->owner->tech_pvt = NULL;
03480 p->owner = NULL;
03481 return 0;
03482 }
03483 if (option_debug) {
03484 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
03485 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
03486 else {
03487 if (option_debug)
03488 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
03489 }
03490 }
03491 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
03492 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
03493
03494 ast_mutex_lock(&p->lock);
03495 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
03496 if (option_debug && sipdebug)
03497 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
03498 update_call_counter(p, DEC_CALL_LIMIT);
03499 }
03500
03501
03502 if (p->owner != ast) {
03503 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
03504 ast_mutex_unlock(&p->lock);
03505 return 0;
03506 }
03507
03508 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
03509 needcancel = TRUE;
03510 if (option_debug > 3)
03511 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
03512 }
03513
03514 stop_media_flows(p);
03515
03516 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
03517
03518
03519 if (p->vad)
03520 ast_dsp_free(p->vad);
03521
03522 p->owner = NULL;
03523 ast->tech_pvt = NULL;
03524
03525 ast_module_unref(ast_module_info->self);
03526
03527
03528
03529
03530
03531
03532
03533 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
03534 needdestroy = 1;
03535 else if (p->invitestate != INV_CALLING)
03536 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03537
03538
03539 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
03540 if (needcancel) {
03541 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03542
03543 __sip_pretend_ack(p);
03544
03545
03546 if (p->invitestate == INV_CALLING) {
03547
03548 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
03549
03550 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03551 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
03552 } else {
03553
03554 transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
03555
03556
03557 needdestroy = 0;
03558 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03559 p->invitestate = INV_CANCELLED;
03560 }
03561 if ( p->initid != -1 ) {
03562
03563
03564 update_call_counter(p, INC_CALL_LIMIT);
03565 }
03566 } else {
03567 const char *res;
03568 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
03569 transmit_response_reliable(p, res, &p->initreq);
03570 else
03571 transmit_response_reliable(p, "603 Declined", &p->initreq);
03572 p->invitestate = INV_TERMINATED;
03573 }
03574 } else {
03575 if (!p->pendinginvite) {
03576 char *audioqos = "";
03577 char *videoqos = "";
03578 if (p->rtp)
03579 audioqos = ast_rtp_get_quality(p->rtp, NULL);
03580 if (p->vrtp)
03581 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
03582
03583 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03584
03585
03586 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
03587 if (p->rtp)
03588 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
03589 if (p->vrtp)
03590 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
03591 }
03592 if (p->rtp && oldowner)
03593 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
03594 if (p->vrtp && oldowner)
03595 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
03596 } else {
03597
03598
03599 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
03600 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
03601 if (p->waitid)
03602 ast_sched_del(sched, p->waitid);
03603 p->waitid = -1;
03604 sip_cancel_destroy(p);
03605 }
03606 }
03607 }
03608 if (needdestroy)
03609 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
03610 ast_mutex_unlock(&p->lock);
03611 return 0;
03612 }
03613
03614
03615 static void try_suggested_sip_codec(struct sip_pvt *p)
03616 {
03617 int fmt;
03618 const char *codec;
03619
03620 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
03621 if (!codec)
03622 return;
03623
03624 fmt = ast_getformatbyname(codec);
03625 if (fmt) {
03626 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
03627 if (p->jointcapability & fmt) {
03628 p->jointcapability &= fmt;
03629 p->capability &= fmt;
03630 } else
03631 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
03632 } else
03633 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
03634 return;
03635 }
03636
03637
03638
03639 static int sip_answer(struct ast_channel *ast)
03640 {
03641 int res = 0;
03642 struct sip_pvt *p = ast->tech_pvt;
03643
03644 ast_mutex_lock(&p->lock);
03645 if (ast->_state != AST_STATE_UP) {
03646 try_suggested_sip_codec(p);
03647
03648 ast_setstate(ast, AST_STATE_UP);
03649 if (option_debug)
03650 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
03651 if (p->t38.state == T38_PEER_DIRECT) {
03652 p->t38.state = T38_ENABLED;
03653 if (option_debug > 1)
03654 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
03655 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
03656 } else
03657 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
03658 }
03659 ast_mutex_unlock(&p->lock);
03660 return res;
03661 }
03662
03663
03664 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
03665 {
03666 struct sip_pvt *p = ast->tech_pvt;
03667 int res = 0;
03668
03669 switch (frame->frametype) {
03670 case AST_FRAME_VOICE:
03671 if (!(frame->subclass & ast->nativeformats)) {
03672 char s1[512], s2[512], s3[512];
03673 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
03674 frame->subclass,
03675 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
03676 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
03677 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
03678 ast->readformat,
03679 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
03680 ast->writeformat);
03681 return 0;
03682 }
03683 if (p) {
03684 ast_mutex_lock(&p->lock);
03685 if (p->rtp) {
03686
03687 if ((ast->_state != AST_STATE_UP) &&
03688 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03689 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03690 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03691 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03692 }
03693 p->lastrtptx = time(NULL);
03694 res = ast_rtp_write(p->rtp, frame);
03695 }
03696 ast_mutex_unlock(&p->lock);
03697 }
03698 break;
03699 case AST_FRAME_VIDEO:
03700 if (p) {
03701 ast_mutex_lock(&p->lock);
03702 if (p->vrtp) {
03703
03704 if ((ast->_state != AST_STATE_UP) &&
03705 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03706 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03707 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03708 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03709 }
03710 p->lastrtptx = time(NULL);
03711 res = ast_rtp_write(p->vrtp, frame);
03712 }
03713 ast_mutex_unlock(&p->lock);
03714 }
03715 break;
03716 case AST_FRAME_IMAGE:
03717 return 0;
03718 break;
03719 case AST_FRAME_MODEM:
03720 if (p) {
03721 ast_mutex_lock(&p->lock);
03722
03723
03724
03725
03726 if (p->udptl && ast->_state == AST_STATE_UP)
03727 res = ast_udptl_write(p->udptl, frame);
03728 ast_mutex_unlock(&p->lock);
03729 }
03730 break;
03731 default:
03732 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
03733 return 0;
03734 }
03735
03736 return res;
03737 }
03738
03739
03740
03741 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
03742 {
03743 int ret = -1;
03744 struct sip_pvt *p;
03745
03746 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
03747 ast_log(LOG_DEBUG, "New channel is zombie\n");
03748 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
03749 ast_log(LOG_DEBUG, "Old channel is zombie\n");
03750
03751 if (!newchan || !newchan->tech_pvt) {
03752 if (!newchan)
03753 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
03754 else
03755 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
03756 return -1;
03757 }
03758 p = newchan->tech_pvt;
03759
03760 if (!p) {
03761 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
03762 return -1;
03763 }
03764
03765 ast_mutex_lock(&p->lock);
03766 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
03767 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
03768 if (p->owner != oldchan)
03769 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
03770 else {
03771 p->owner = newchan;
03772 ret = 0;
03773 }
03774 if (option_debug > 2)
03775 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
03776
03777 ast_mutex_unlock(&p->lock);
03778 return ret;
03779 }
03780
03781 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
03782 {
03783 struct sip_pvt *p = ast->tech_pvt;
03784 int res = 0;
03785
03786 ast_mutex_lock(&p->lock);
03787 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
03788 case SIP_DTMF_INBAND:
03789 res = -1;
03790 break;
03791 case SIP_DTMF_RFC2833:
03792 if (p->rtp)
03793 ast_rtp_senddigit_begin(p->rtp, digit);
03794 break;
03795 default:
03796 break;
03797 }
03798 ast_mutex_unlock(&p->lock);
03799
03800 return res;
03801 }
03802
03803
03804
03805 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
03806 {
03807 struct sip_pvt *p = ast->tech_pvt;
03808 int res = 0;
03809
03810 ast_mutex_lock(&p->lock);
03811 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
03812 case SIP_DTMF_INFO:
03813 transmit_info_with_digit(p, digit, duration);
03814 break;
03815 case SIP_DTMF_RFC2833:
03816 if (p->rtp)
03817 ast_rtp_senddigit_end(p->rtp, digit);
03818 break;
03819 case SIP_DTMF_INBAND:
03820 res = -1;
03821 break;
03822 }
03823 ast_mutex_unlock(&p->lock);
03824
03825 return res;
03826 }
03827
03828
03829 static int sip_transfer(struct ast_channel *ast, const char *dest)
03830 {
03831 struct sip_pvt *p = ast->tech_pvt;
03832 int res;
03833
03834 if (dest == NULL)
03835 dest = "";
03836 ast_mutex_lock(&p->lock);
03837 if (ast->_state == AST_STATE_RING)
03838 res = sip_sipredirect(p, dest);
03839 else
03840 res = transmit_refer(p, dest);
03841 ast_mutex_unlock(&p->lock);
03842 return res;
03843 }
03844
03845
03846
03847
03848
03849
03850 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
03851 {
03852 struct sip_pvt *p = ast->tech_pvt;
03853 int res = 0;
03854
03855 ast_mutex_lock(&p->lock);
03856 switch(condition) {
03857 case AST_CONTROL_RINGING:
03858 if (ast->_state == AST_STATE_RING) {
03859 p->invitestate = INV_EARLY_MEDIA;
03860 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
03861 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
03862
03863 transmit_response(p, "180 Ringing", &p->initreq);
03864 ast_set_flag(&p->flags[0], SIP_RINGING);
03865 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
03866 break;
03867 } else {
03868
03869 }
03870 }
03871 res = -1;
03872 break;
03873 case AST_CONTROL_BUSY:
03874 if (ast->_state != AST_STATE_UP) {
03875 transmit_response(p, "486 Busy Here", &p->initreq);
03876 p->invitestate = INV_COMPLETED;
03877 sip_alreadygone(p);
03878 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
03879 break;
03880 }
03881 res = -1;
03882 break;
03883 case AST_CONTROL_CONGESTION:
03884 if (ast->_state != AST_STATE_UP) {
03885 transmit_response(p, "503 Service Unavailable", &p->initreq);
03886 p->invitestate = INV_COMPLETED;
03887 sip_alreadygone(p);
03888 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
03889 break;
03890 }
03891 res = -1;
03892 break;
03893 case AST_CONTROL_PROCEEDING:
03894 if ((ast->_state != AST_STATE_UP) &&
03895 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03896 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03897 transmit_response(p, "100 Trying", &p->initreq);
03898 p->invitestate = INV_PROCEEDING;
03899 break;
03900 }
03901 res = -1;
03902 break;
03903 case AST_CONTROL_PROGRESS:
03904 if ((ast->_state != AST_STATE_UP) &&
03905 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03906 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03907 p->invitestate = INV_EARLY_MEDIA;
03908 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03909 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03910 break;
03911 }
03912 res = -1;
03913 break;
03914 case AST_CONTROL_HOLD:
03915 ast_moh_start(ast, data, p->mohinterpret);
03916 break;
03917 case AST_CONTROL_UNHOLD:
03918 ast_moh_stop(ast);
03919 break;
03920 case AST_CONTROL_VIDUPDATE:
03921 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
03922 transmit_info_with_vidupdate(p);
03923
03924 } else
03925 res = -1;
03926 break;
03927 case -1:
03928 res = -1;
03929 break;
03930 default:
03931 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
03932 res = -1;
03933 break;
03934 }
03935 ast_mutex_unlock(&p->lock);
03936 return res;
03937 }
03938
03939
03940
03941
03942
03943
03944
03945 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
03946 {
03947 struct ast_channel *tmp;
03948 struct ast_variable *v = NULL;
03949 int fmt;
03950 int what;
03951 int needvideo = 0, video = 0;
03952 char *decoded_exten;
03953 {
03954 const char *my_name;
03955
03956 if (title)
03957 my_name = title;
03958 else if ( (my_name = strchr(i->fromdomain,':')) )
03959 my_name++;
03960 else
03961 my_name = i->fromdomain;
03962
03963 ast_mutex_unlock(&i->lock);
03964
03965 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);
03966
03967 }
03968 if (!tmp) {
03969 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
03970 return NULL;
03971 }
03972 ast_mutex_lock(&i->lock);
03973
03974 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
03975 tmp->tech = &sip_tech_info;
03976 else
03977 tmp->tech = &sip_tech;
03978
03979
03980
03981 if (i->jointcapability) {
03982 what = i->jointcapability;
03983 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
03984 } else if (i->capability) {
03985 what = i->capability;
03986 video = i->capability & AST_FORMAT_VIDEO_MASK;
03987 } else {
03988 what = global_capability;
03989 video = global_capability & AST_FORMAT_VIDEO_MASK;
03990 }
03991
03992
03993 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video;
03994 if (option_debug > 2) {
03995 char buf[BUFSIZ];
03996 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, tmp->nativeformats));
03997 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->jointcapability));
03998 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->capability));
03999 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, ast_codec_choose(&i->prefs, what, 1)));
04000 if (i->prefcodec)
04001 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->prefcodec));
04002 }
04003
04004
04005 fmt = ast_best_codec(tmp->nativeformats);
04006
04007
04008
04009
04010
04011 if (i->vrtp) {
04012 if (i->prefcodec)
04013 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
04014 else
04015 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
04016 }
04017
04018 if (option_debug > 2) {
04019 if (needvideo)
04020 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
04021 else
04022 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
04023 }
04024
04025
04026
04027 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
04028 i->vad = ast_dsp_new();
04029 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
04030 if (global_relaxdtmf)
04031 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04032 }
04033 if (i->rtp) {
04034 tmp->fds[0] = ast_rtp_fd(i->rtp);
04035 tmp->fds[1] = ast_rtcp_fd(i->rtp);
04036 }
04037 if (needvideo && i->vrtp) {
04038 tmp->fds[2] = ast_rtp_fd(i->vrtp);
04039 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
04040 }
04041 if (i->udptl) {
04042 tmp->fds[5] = ast_udptl_fd(i->udptl);
04043 }
04044 if (state == AST_STATE_RING)
04045 tmp->rings = 1;
04046 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
04047 tmp->writeformat = fmt;
04048 tmp->rawwriteformat = fmt;
04049 tmp->readformat = fmt;
04050 tmp->rawreadformat = fmt;
04051 tmp->tech_pvt = i;
04052
04053 tmp->callgroup = i->callgroup;
04054 tmp->pickupgroup = i->pickupgroup;
04055 tmp->cid.cid_pres = i->callingpres;
04056 if (!ast_strlen_zero(i->accountcode))
04057 ast_string_field_set(tmp, accountcode, i->accountcode);
04058 if (i->amaflags)
04059 tmp->amaflags = i->amaflags;
04060 if (!ast_strlen_zero(i->language))
04061 ast_string_field_set(tmp, language, i->language);
04062 i->owner = tmp;
04063 ast_module_ref(ast_module_info->self);
04064 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
04065
04066
04067
04068
04069 decoded_exten = ast_strdupa(i->exten);
04070 ast_uri_decode(decoded_exten);
04071 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
04072
04073
04074
04075 tmp->cid.cid_ani = ast_strdup(i->cid_num);
04076 if (!ast_strlen_zero(i->rdnis))
04077 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
04078
04079 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
04080 tmp->cid.cid_dnid = ast_strdup(i->exten);
04081
04082 tmp->priority = 1;
04083 if (!ast_strlen_zero(i->uri))
04084 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
04085 if (!ast_strlen_zero(i->domain))
04086 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
04087 if (!ast_strlen_zero(i->useragent))
04088 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
04089 if (!ast_strlen_zero(i->callid))
04090 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
04091 if (i->rtp)
04092 ast_jb_configure(tmp, &global_jbconf);
04093
04094
04095 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
04096 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
04097
04098
04099 for (v = i->chanvars ; v ; v = v->next)
04100 pbx_builtin_setvar_helper(tmp, v->name, v->value);
04101
04102 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
04103 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
04104 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
04105 ast_hangup(tmp);
04106 tmp = NULL;
04107 }
04108
04109 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
04110 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
04111
04112 return tmp;
04113 }
04114
04115
04116 static char *get_body_by_line(const char *line, const char *name, int nameLen)
04117 {
04118 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
04119 return ast_skip_blanks(line + nameLen + 1);
04120
04121 return "";
04122 }
04123
04124
04125
04126
04127
04128 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
04129 {
04130 int len = strlen(name);
04131
04132 while (*start < req->sdp_end) {
04133 const char *r = get_body_by_line(req->line[(*start)++], name, len);
04134 if (r[0] != '\0')
04135 return r;
04136 }
04137
04138 return "";
04139 }
04140
04141
04142 static const char *get_sdp(struct sip_request *req, const char *name)
04143 {
04144 int dummy = 0;
04145
04146 return get_sdp_iterate(&dummy, req, name);
04147 }
04148
04149
04150 static char *get_body(struct sip_request *req, char *name)
04151 {
04152 int x;
04153 int len = strlen(name);
04154 char *r;
04155
04156 for (x = 0; x < req->lines; x++) {
04157 r = get_body_by_line(req->line[x], name, len);
04158 if (r[0] != '\0')
04159 return r;
04160 }
04161
04162 return "";
04163 }
04164
04165
04166 static const char *find_alias(const char *name, const char *_default)
04167 {
04168
04169 static const struct cfalias {
04170 char * const fullname;
04171 char * const shortname;
04172 } aliases[] = {
04173 { "Content-Type", "c" },
04174 { "Content-Encoding", "e" },
04175 { "From", "f" },
04176 { "Call-ID", "i" },
04177 { "Contact", "m" },
04178 { "Content-Length", "l" },
04179 { "Subject", "s" },
04180 { "To", "t" },
04181 { "Supported", "k" },
04182 { "Refer-To", "r" },
04183 { "Referred-By", "b" },
04184 { "Allow-Events", "u" },
04185 { "Event", "o" },
04186 { "Via", "v" },
04187 { "Accept-Contact", "a" },
04188 { "Reject-Contact", "j" },
04189 { "Request-Disposition", "d" },
04190 { "Session-Expires", "x" },
04191 { "Identity", "y" },
04192 { "Identity-Info", "n" },
04193 };
04194 int x;
04195
04196 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
04197 if (!strcasecmp(aliases[x].fullname, name))
04198 return aliases[x].shortname;
04199
04200 return _default;
04201 }
04202
04203 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
04204 {
04205 int pass;
04206
04207
04208
04209
04210
04211
04212
04213
04214
04215
04216 for (pass = 0; name && pass < 2;pass++) {
04217 int x, len = strlen(name);
04218 for (x=*start; x<req->headers; x++) {
04219 if (!strncasecmp(req->header[x], name, len)) {
04220 char *r = req->header[x] + len;
04221 if (pedanticsipchecking)
04222 r = ast_skip_blanks(r);
04223
04224 if (*r == ':') {
04225 *start = x+1;
04226 return ast_skip_blanks(r+1);
04227 }
04228 }
04229 }
04230 if (pass == 0)
04231 name = find_alias(name, NULL);
04232 }
04233
04234
04235 return "";
04236 }
04237
04238
04239 static const char *get_header(const struct sip_request *req, const char *name)
04240 {
04241 int start = 0;
04242 return __get_header(req, name, &start);
04243 }
04244
04245
04246 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
04247 {
04248
04249 struct ast_frame *f;
04250
04251 if (!p->rtp) {
04252
04253 return &ast_null_frame;
04254 }
04255
04256 switch(ast->fdno) {
04257 case 0:
04258 f = ast_rtp_read(p->rtp);
04259 break;
04260 case 1:
04261 f = ast_rtcp_read(p->rtp);
04262 break;
04263 case 2:
04264 f = ast_rtp_read(p->vrtp);
04265 break;
04266 case 3:
04267 f = ast_rtcp_read(p->vrtp);
04268 break;
04269 case 5:
04270 f = ast_udptl_read(p->udptl);
04271 break;
04272 default:
04273 f = &ast_null_frame;
04274 }
04275
04276 if (f && (f->frametype == AST_FRAME_DTMF) &&
04277 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
04278 return &ast_null_frame;
04279
04280
04281 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
04282 return f;
04283
04284 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
04285 if (!(f->subclass & p->jointcapability)) {
04286 if (option_debug) {
04287 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
04288 ast_getformatname(f->subclass), p->owner->name);
04289 }
04290 return &ast_null_frame;
04291 }
04292 if (option_debug)
04293 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
04294 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
04295 ast_set_read_format(p->owner, p->owner->readformat);
04296 ast_set_write_format(p->owner, p->owner->writeformat);
04297 }
04298
04299 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
04300 f = ast_dsp_process(p->owner, p->vad, f);
04301 if (f && f->frametype == AST_FRAME_DTMF) {
04302 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
04303 if (option_debug)
04304 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
04305 *faxdetect = 1;
04306 } else if (option_debug) {
04307 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
04308 }
04309 }
04310 }
04311
04312 return f;
04313 }
04314
04315
04316 static struct ast_frame *sip_read(struct ast_channel *ast)
04317 {
04318 struct ast_frame *fr;
04319 struct sip_pvt *p = ast->tech_pvt;
04320 int faxdetected = FALSE;
04321
04322 ast_mutex_lock(&p->lock);
04323 fr = sip_rtp_read(ast, p, &faxdetected);
04324 p->lastrtprx = time(NULL);
04325
04326
04327
04328 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
04329 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
04330 if (!p->pendinginvite) {
04331 if (option_debug > 2)
04332 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
04333 p->t38.state = T38_LOCAL_REINVITE;
04334 transmit_reinvite_with_t38_sdp(p);
04335 if (option_debug > 1)
04336 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
04337 }
04338 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04339 if (option_debug > 2)
04340 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
04341 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04342 }
04343 }
04344
04345 ast_mutex_unlock(&p->lock);
04346 return fr;
04347 }
04348
04349
04350
04351 static char *generate_random_string(char *buf, size_t size)
04352 {
04353 long val[4];
04354 int x;
04355
04356 for (x=0; x<4; x++)
04357 val[x] = ast_random();
04358 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
04359
04360 return buf;
04361 }
04362
04363
04364 static void build_callid_pvt(struct sip_pvt *pvt)
04365 {
04366 char buf[33];
04367
04368 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
04369
04370 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
04371
04372 }
04373
04374
04375 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
04376 {
04377 char buf[33];
04378
04379 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
04380
04381 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
04382 }
04383
04384
04385 static void make_our_tag(char *tagbuf, size_t len)
04386 {
04387 snprintf(tagbuf, len, "as%08lx", ast_random());
04388 }
04389
04390
04391 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
04392 int useglobal_nat, const int intended_method)
04393 {
04394 struct sip_pvt *p;
04395
04396 if (!(p = ast_calloc(1, sizeof(*p))))
04397 return NULL;
04398
04399 if (ast_string_field_init(p, 512)) {
04400 free(p);
04401 return NULL;
04402 }
04403
04404 ast_mutex_init(&p->lock);
04405
04406 p->method = intended_method;
04407 p->initid = -1;
04408 p->waitid = -1;
04409 p->autokillid = -1;
04410 p->subscribed = NONE;
04411 p->stateid = -1;
04412 p->prefs = default_prefs;
04413
04414 if (intended_method != SIP_OPTIONS)
04415 p->timer_t1 = 500;
04416
04417 if (sin) {
04418 p->sa = *sin;
04419 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
04420 p->ourip = __ourip;
04421 } else
04422 p->ourip = __ourip;
04423
04424
04425 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
04426 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04427
04428 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
04429
04430 p->branch = ast_random();
04431 make_our_tag(p->tag, sizeof(p->tag));
04432 p->ocseq = INITIAL_CSEQ;
04433
04434 if (sip_methods[intended_method].need_rtp) {
04435 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
04436
04437 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
04438 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
04439 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
04440 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
04441 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
04442 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
04443 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
04444 ast_mutex_destroy(&p->lock);
04445 if (p->chanvars) {
04446 ast_variables_destroy(p->chanvars);
04447 p->chanvars = NULL;
04448 }
04449 free(p);
04450 return NULL;
04451 }
04452 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04453 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04454 ast_rtp_settos(p->rtp, global_tos_audio);
04455 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
04456 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
04457 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
04458 if (p->vrtp) {
04459 ast_rtp_settos(p->vrtp, global_tos_video);
04460 ast_rtp_setdtmf(p->vrtp, 0);
04461 ast_rtp_setdtmfcompensate(p->vrtp, 0);
04462 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
04463 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
04464 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
04465 }
04466 if (p->udptl)
04467 ast_udptl_settos(p->udptl, global_tos_audio);
04468 p->maxcallbitrate = default_maxcallbitrate;
04469 }
04470
04471 if (useglobal_nat && sin) {
04472
04473 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
04474 p->recv = *sin;
04475 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04476 }
04477
04478 if (p->method != SIP_REGISTER)
04479 ast_string_field_set(p, fromdomain, default_fromdomain);
04480 build_via(p);
04481 if (!callid)
04482 build_callid_pvt(p);
04483 else
04484 ast_string_field_set(p, callid, callid);
04485
04486 ast_string_field_set(p, mohinterpret, default_mohinterpret);
04487 ast_string_field_set(p, mohsuggest, default_mohsuggest);
04488 p->capability = global_capability;
04489 p->allowtransfer = global_allowtransfer;
04490 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
04491 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
04492 p->noncodeccapability |= AST_RTP_DTMF;
04493 if (p->udptl) {
04494 p->t38.capability = global_t38_capability;
04495 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
04496 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
04497 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
04498 p->t38.capability |= T38FAX_UDP_EC_FEC;
04499 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
04500 p->t38.capability |= T38FAX_UDP_EC_NONE;
04501 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
04502 p->t38.jointcapability = p->t38.capability;
04503 }
04504 ast_string_field_set(p, context, default_context);
04505
04506
04507 ast_mutex_lock(&iflock);
04508 p->next = iflist;
04509 iflist = p;
04510 ast_mutex_unlock(&iflock);
04511 if (option_debug)
04512 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");
04513 return p;
04514 }
04515
04516
04517
04518 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
04519 {
04520 struct sip_pvt *p = NULL;
04521 char *tag = "";
04522 char totag[128];
04523 char fromtag[128];
04524 const char *callid = get_header(req, "Call-ID");
04525 const char *from = get_header(req, "From");
04526 const char *to = get_header(req, "To");
04527 const char *cseq = get_header(req, "Cseq");
04528
04529
04530
04531 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
04532 ast_strlen_zero(from) || ast_strlen_zero(cseq))
04533 return NULL;
04534
04535 if (pedanticsipchecking) {
04536
04537
04538
04539
04540
04541
04542 if (gettag(req, "To", totag, sizeof(totag)))
04543 ast_set_flag(req, SIP_PKT_WITH_TOTAG);
04544 gettag(req, "From", fromtag, sizeof(fromtag));
04545
04546 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
04547
04548 if (option_debug > 4 )
04549 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);
04550 }
04551
04552 ast_mutex_lock(&iflock);
04553 for (p = iflist; p; p = p->next) {
04554
04555 int found = FALSE;
04556 if (ast_strlen_zero(p->callid))
04557 continue;
04558 if (req->method == SIP_REGISTER)
04559 found = (!strcmp(p->callid, callid));
04560 else
04561 found = (!strcmp(p->callid, callid) &&
04562 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
04563
04564 if (option_debug > 4)
04565 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);
04566
04567
04568 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) {
04569 if (p->tag[0] == '\0' && totag[0]) {
04570
04571 found = FALSE;
04572 } else if (totag[0]) {
04573 if (strcmp(totag, p->tag)) {
04574 found = FALSE;
04575 }
04576 }
04577 if (!found && option_debug > 4)
04578 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);
04579 }
04580
04581
04582 if (found) {
04583
04584 ast_mutex_lock(&p->lock);
04585 ast_mutex_unlock(&iflock);
04586 return p;
04587 }
04588 }
04589 ast_mutex_unlock(&iflock);
04590
04591
04592 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
04593 if (intended_method == SIP_REFER) {
04594
04595 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
04596 } else if (intended_method == SIP_NOTIFY) {
04597
04598
04599 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
04600 } else {
04601
04602 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
04603
04604 ast_mutex_lock(&p->lock);
04605 } else {
04606
04607
04608
04609
04610
04611
04612
04613
04614 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
04615 if (option_debug > 3)
04616 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
04617 }
04618 }
04619 return p;
04620 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
04621
04622 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
04623 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
04624
04625
04626
04627 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
04628 }
04629
04630
04631
04632 return p;
04633 }
04634
04635
04636 static int sip_register(char *value, int lineno)
04637 {
04638 struct sip_registry *reg;
04639 int portnum = 0;
04640 char username[256] = "";
04641 char *hostname=NULL, *secret=NULL, *authuser=NULL;
04642 char *porta=NULL;
04643 char *contact=NULL;
04644
04645 if (!value)
04646 return -1;
04647 ast_copy_string(username, value, sizeof(username));
04648
04649 hostname = strrchr(username, '@');
04650 if (hostname)
04651 *hostname++ = '\0';
04652 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
04653 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
04654 return -1;
04655 }
04656
04657 secret = strchr(username, ':');
04658 if (secret) {
04659 *secret++ = '\0';
04660 authuser = strchr(secret, ':');
04661 if (authuser)
04662 *authuser++ = '\0';
04663 }
04664
04665 contact = strchr(hostname, '/');
04666 if (contact)
04667 *contact++ = '\0';
04668 if (ast_strlen_zero(contact))
04669 contact = "s";
04670 porta = strchr(hostname, ':');
04671 if (porta) {
04672 *porta++ = '\0';
04673 portnum = atoi(porta);
04674 if (portnum == 0) {
04675 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
04676 return -1;
04677 }
04678 }
04679 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
04680 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
04681 return -1;
04682 }
04683
04684 if (ast_string_field_init(reg, 256)) {
04685 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
04686 free(reg);
04687 return -1;
04688 }
04689
04690 regobjs++;
04691 ASTOBJ_INIT(reg);
04692 ast_string_field_set(reg, contact, contact);
04693 if (!ast_strlen_zero(username))
04694 ast_string_field_set(reg, username, username);
04695 if (hostname)
04696 ast_string_field_set(reg, hostname, hostname);
04697 if (authuser)
04698 ast_string_field_set(reg, authuser, authuser);
04699 if (secret)
04700 ast_string_field_set(reg, secret, secret);
04701 reg->expire = -1;
04702 reg->timeout = -1;
04703 reg->refresh = default_expiry;
04704 reg->portno = portnum;
04705 reg->callid_valid = FALSE;
04706 reg->ocseq = INITIAL_CSEQ;
04707 ASTOBJ_CONTAINER_LINK(®l, reg);
04708 ASTOBJ_UNREF(reg,sip_registry_destroy);
04709 return 0;
04710 }
04711
04712
04713
04714 static int lws2sws(char *msgbuf, int len)
04715 {
04716 int h = 0, t = 0;
04717 int lws = 0;
04718
04719 for (; h < len;) {
04720
04721 if (msgbuf[h] == '\r') {
04722 h++;
04723 continue;
04724 }
04725
04726 if (msgbuf[h] == '\n') {
04727
04728 if (h + 1 == len)
04729 break;
04730
04731 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
04732
04733 h++;
04734 continue;
04735 }
04736
04737 msgbuf[t++] = msgbuf[h++];
04738 lws = 0;
04739 continue;
04740 }
04741 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
04742 if (lws) {
04743 h++;
04744 continue;
04745 }
04746 msgbuf[t++] = msgbuf[h++];
04747 lws = 1;
04748 continue;
04749 }
04750 msgbuf[t++] = msgbuf[h++];
04751 if (lws)
04752 lws = 0;
04753 }
04754 msgbuf[t] = '\0';
04755 return t;
04756 }
04757
04758
04759
04760
04761 static void parse_request(struct sip_request *req)
04762 {
04763
04764 char *c;
04765 int f = 0;
04766
04767 c = req->data;
04768
04769
04770 req->header[f] = c;
04771 while(*c) {
04772 if (*c == '\n') {
04773
04774 *c = 0;
04775
04776 if (sipdebug && option_debug > 3)
04777 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
04778 if (ast_strlen_zero(req->header[f])) {
04779
04780 c++;
04781 break;
04782 }
04783 if (f >= SIP_MAX_HEADERS - 1) {
04784 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
04785 } else
04786 f++;
04787 req->header[f] = c + 1;
04788 } else if (*c == '\r') {
04789
04790 *c = 0;
04791 }
04792 c++;
04793 }
04794
04795 if (!ast_strlen_zero(req->header[f])) {
04796 if (sipdebug && option_debug > 3)
04797 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
04798 f++;
04799 }
04800 req->headers = f;
04801
04802 f = 0;
04803 req->line[f] = c;
04804 while(*c) {
04805 if (*c == '\n') {
04806
04807 *c = 0;
04808 if (sipdebug && option_debug > 3)
04809 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
04810 if (f >= SIP_MAX_LINES - 1) {
04811 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
04812 } else
04813 f++;
04814 req->line[f] = c + 1;
04815 } else if (*c == '\r') {
04816
04817 *c = 0;
04818 }
04819 c++;
04820 }
04821
04822 if (!ast_strlen_zero(req->line[f]))
04823 f++;
04824 req->lines = f;
04825 if (*c)
04826 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
04827
04828 determine_firstline_parts(req);
04829 }
04830
04831
04832
04833
04834
04835
04836
04837
04838
04839 static int find_sdp(struct sip_request *req)
04840 {
04841 const char *content_type;
04842 const char *search;
04843 char *boundary;
04844 unsigned int x;
04845 int boundaryisquoted = FALSE;
04846 int found_application_sdp = FALSE;
04847 int found_end_of_headers = FALSE;
04848
04849 content_type = get_header(req, "Content-Type");
04850
04851
04852 if (!strcasecmp(content_type, "application/sdp")) {
04853 req->sdp_start = 0;
04854 req->sdp_end = req->lines;
04855 return req->lines ? 1 : 0;
04856 }
04857
04858
04859 if (strncasecmp(content_type, "multipart/mixed", 15))
04860 return 0;
04861
04862
04863 if (!(search = strcasestr(content_type, ";boundary=")))
04864 return 0;
04865
04866 search += 10;
04867 if (ast_strlen_zero(search))
04868 return 0;
04869
04870
04871 if (*search == '\"') {
04872 search++;
04873 boundaryisquoted = TRUE;
04874 }
04875
04876
04877
04878 boundary = ast_strdupa(search - 2);
04879 boundary[0] = boundary[1] = '-';
04880
04881 if (boundaryisquoted)
04882 boundary[strlen(boundary) - 1] = '\0';
04883
04884
04885
04886
04887 for (x = 0; x < (req->lines ); x++) {
04888 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
04889 if(found_application_sdp && found_end_of_headers){
04890 req->sdp_end = x-1;
04891 return 1;
04892 }
04893 found_application_sdp = FALSE;
04894 }
04895 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
04896 found_application_sdp = TRUE;
04897
04898 if(strlen(req->line[x]) == 0 ){
04899 if(found_application_sdp && !found_end_of_headers){
04900 req->sdp_start = x;
04901 found_end_of_headers = TRUE;
04902 }
04903 }
04904 }
04905 if(found_application_sdp && found_end_of_headers) {
04906 req->sdp_end = x;
04907 return TRUE;
04908 }
04909 return FALSE;
04910 }
04911
04912
04913 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
04914 {
04915 if (global_notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
04916 sip_peer_hold(dialog, holdstate);
04917 if (global_callevents)
04918 manager_event(EVENT_FLAG_CALL, holdstate ? "Hold" : "Unhold",
04919 "Channel: %s\r\n"
04920 "Uniqueid: %s\r\n",
04921 dialog->owner->name,
04922 dialog->owner->uniqueid);
04923 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data);
04924 if (!holdstate) {
04925 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
04926 return;
04927 }
04928
04929
04930 if (sendonly == 1)
04931 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
04932 else if (sendonly == 2)
04933 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
04934 else
04935 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
04936 return;
04937 }
04938
04939
04940
04941
04942
04943
04944 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
04945 {
04946 const char *m;
04947 const char *c;
04948 const char *a;
04949 char host[258];
04950 int len = -1;
04951 int portno = -1;
04952 int vportno = -1;
04953 int udptlportno = -1;
04954 int peert38capability = 0;
04955 char s[256];
04956 int old = 0;
04957
04958
04959 int peercapability = 0, peernoncodeccapability = 0;
04960 int vpeercapability = 0, vpeernoncodeccapability = 0;
04961 struct sockaddr_in sin;
04962 struct sockaddr_in vsin;
04963
04964 const char *codecs;
04965 struct hostent *hp;
04966 struct hostent *vhp = NULL;
04967 struct ast_hostent audiohp;
04968 struct ast_hostent videohp;
04969 int codec;
04970 int destiterator = 0;
04971 int iterator;
04972 int sendonly = -1;
04973 int numberofports;
04974 struct ast_rtp *newaudiortp, *newvideortp;
04975 int newjointcapability;
04976 int newpeercapability;
04977 int newnoncodeccapability;
04978 int numberofmediastreams = 0;
04979 int debug = sip_debug_test_pvt(p);
04980
04981 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
04982 int last_rtpmap_codec=0;
04983
04984 if (!p->rtp) {
04985 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
04986 return -1;
04987 }
04988
04989
04990 newaudiortp = alloca(ast_rtp_alloc_size());
04991 memset(newaudiortp, 0, ast_rtp_alloc_size());
04992 ast_rtp_new_init(newaudiortp);
04993 ast_rtp_pt_clear(newaudiortp);
04994
04995 newvideortp = alloca(ast_rtp_alloc_size());
04996 memset(newvideortp, 0, ast_rtp_alloc_size());
04997 ast_rtp_new_init(newvideortp);
04998 ast_rtp_pt_clear(newvideortp);
04999
05000
05001 p->lastrtprx = p->lastrtptx = time(NULL);
05002
05003
05004
05005 m = get_sdp(req, "m");
05006 destiterator = req->sdp_start;
05007 c = get_sdp_iterate(&destiterator, req, "c");
05008 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
05009 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
05010 return -1;
05011 }
05012
05013
05014 if (sscanf(c, "IN IP4 %256s", host) != 1) {
05015 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
05016 return -1;
05017 }
05018
05019
05020 hp = ast_gethostbyname(host, &audiohp);
05021 if (!hp) {
05022 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
05023 return -1;
05024 }
05025 vhp = hp;
05026
05027 iterator = req->sdp_start;
05028 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
05029
05030
05031
05032 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
05033 int x;
05034 int audio = FALSE;
05035
05036 numberofports = 1;
05037 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
05038 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
05039 audio = TRUE;
05040 numberofmediastreams++;
05041
05042 portno = x;
05043
05044 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
05045 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
05046 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
05047 return -1;
05048 }
05049 if (debug)
05050 ast_verbose("Found RTP audio format %d\n", codec);
05051 ast_rtp_set_m_type(newaudiortp, codec);
05052 }
05053 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
05054 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
05055
05056 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
05057 numberofmediastreams++;
05058 vportno = x;
05059
05060 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
05061 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
05062 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
05063 return -1;
05064 }
05065 if (debug)
05066 ast_verbose("Found RTP video format %d\n", codec);
05067 ast_rtp_set_m_type(newvideortp, codec);
05068 }
05069 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
05070 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
05071 if (debug)
05072 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
05073 udptlportno = x;
05074 numberofmediastreams++;
05075
05076 if (p->owner && p->lastinvite) {
05077 p->t38.state = T38_PEER_REINVITE;
05078 if (option_debug > 1)
05079 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
05080 } else {
05081 p->t38.state = T38_PEER_DIRECT;
05082 if (option_debug > 1)
05083 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
05084 }
05085 } else
05086 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
05087 if (numberofports > 1)
05088 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
05089
05090
05091
05092 c = get_sdp_iterate(&destiterator, req, "c");
05093 if (!ast_strlen_zero(c)) {
05094 if (sscanf(c, "IN IP4 %256s", host) != 1) {
05095 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
05096 } else {
05097
05098 if (audio) {
05099 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
05100 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
05101 return -2;
05102 }
05103 } else if (!(vhp = ast_gethostbyname(host, &videohp))) {
05104 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
05105 return -2;
05106 }
05107 }
05108
05109 }
05110 }
05111 if (portno == -1 && vportno == -1 && udptlportno == -1)
05112
05113
05114 return -2;
05115
05116 if (numberofmediastreams > 2)
05117
05118 return -3;
05119
05120
05121 sin.sin_family = AF_INET;
05122 vsin.sin_family = AF_INET;
05123 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
05124 if (vhp)
05125 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
05126
05127
05128 if (p->udptl) {
05129 if (udptlportno > 0) {
05130 sin.sin_port = htons(udptlportno);
05131 ast_udptl_set_peer(p->udptl, &sin);
05132 if (debug)
05133 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
05134 } else {
05135 ast_udptl_stop(p->udptl);
05136 if (debug)
05137 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
05138 }
05139 }
05140
05141
05142 if (p->rtp) {
05143 if (portno > 0) {
05144 sin.sin_port = htons(portno);
05145 ast_rtp_set_peer(p->rtp, &sin);
05146 if (debug)
05147 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
05148 } else {
05149 if (udptlportno > 0) {
05150 if (debug)
05151 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
05152 } else {
05153 ast_rtp_stop(p->rtp);
05154 if (debug)
05155 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
05156 }
05157 }
05158 }
05159
05160 if (vportno != -1)
05161 vsin.sin_port = htons(vportno);
05162
05163
05164
05165
05166
05167 iterator = req->sdp_start;
05168 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
05169 char* mimeSubtype = ast_strdupa(a);
05170 if (option_debug > 1) {
05171 int breakout = FALSE;
05172
05173
05174 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
05175 if (debug)
05176 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
05177 breakout = TRUE;
05178 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
05179
05180
05181
05182
05183 if (debug)
05184 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
05185 breakout = TRUE;
05186 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
05187
05188 if (debug)
05189 ast_verbose("Got unsupported a:framerate in SDP offer \n");
05190 breakout = TRUE;
05191 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
05192
05193 if (debug)
05194 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
05195 breakout = TRUE;
05196 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
05197
05198 if (debug)
05199 ast_verbose("Got unsupported a:crypto in SDP offer \n");
05200 breakout = TRUE;
05201 }
05202 if (breakout)
05203 continue;
05204 }
05205 if (!strcasecmp(a, "sendonly")) {
05206 if (sendonly == -1)
05207 sendonly = 1;
05208 continue;
05209 } else if (!strcasecmp(a, "inactive")) {
05210 if (sendonly == -1)
05211 sendonly = 2;
05212 continue;
05213 } else if (!strcasecmp(a, "sendrecv")) {
05214 if (sendonly == -1)
05215 sendonly = 0;
05216 continue;
05217 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
05218 char *tmp = strrchr(a, ':');
05219 long int framing = 0;
05220 if (tmp) {
05221 tmp++;
05222 framing = strtol(tmp, NULL, 10);
05223 if (framing == LONG_MIN || framing == LONG_MAX) {
05224 framing = 0;
05225 if (option_debug)
05226 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
05227 }
05228 }
05229 if (framing && last_rtpmap_codec) {
05230 if (p->autoframing) {
05231 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
05232 int codec_n;
05233 int format = 0;
05234 for (codec_n = 0; codec_n < last_rtpmap_codec; codec_n++) {
05235 format = ast_rtp_codec_getformat(found_rtpmap_codecs[codec_n]);
05236 if (!format)
05237 continue;
05238 if (option_debug)
05239 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
05240 ast_codec_pref_setsize(pref, format, framing);
05241 }
05242 ast_rtp_codec_setpref(p->rtp, pref);
05243 }
05244 }
05245 memset(&found_rtpmap_codecs, 0, sizeof(found_rtpmap_codecs));
05246 last_rtpmap_codec = 0;
05247 continue;
05248 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
05249
05250 int found = FALSE;
05251
05252
05253
05254 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
05255
05256 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
05257 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
05258 if (debug)
05259 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
05260 found_rtpmap_codecs[last_rtpmap_codec] = codec;
05261 last_rtpmap_codec++;
05262 found = TRUE;
05263
05264 } else if (p->vrtp) {
05265 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
05266 if (debug)
05267 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
05268 found_rtpmap_codecs[last_rtpmap_codec] = codec;
05269 last_rtpmap_codec++;
05270 found = TRUE;
05271 }
05272 }
05273 } else {
05274 if (debug)
05275 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
05276 }
05277
05278 if (!found) {
05279
05280
05281
05282 ast_rtp_unset_m_type(newaudiortp, codec);
05283 ast_rtp_unset_m_type(newvideortp, codec);
05284 if (debug)
05285 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
05286 }
05287 }
05288 }
05289
05290 if (udptlportno != -1) {
05291 int found = 0, x;
05292
05293 old = 0;
05294
05295
05296 iterator = req->sdp_start;
05297 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
05298 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
05299 found = 1;
05300 if (option_debug > 2)
05301 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
05302 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
05303 found = 1;
05304 if (option_debug > 2)
05305 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
05306 switch (x) {
05307 case 14400:
05308 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05309 break;
05310 case 12000:
05311 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05312 break;
05313 case 9600:
05314 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05315 break;
05316 case 7200:
05317 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05318 break;
05319 case 4800:
05320 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
05321 break;
05322 case 2400:
05323 peert38capability |= T38FAX_RATE_2400;
05324 break;
05325 }
05326 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
05327 found = 1;
05328 if (option_debug > 2)
05329 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
05330 if (x == 0)
05331 peert38capability |= T38FAX_VERSION_0;
05332 else if (x == 1)
05333 peert38capability |= T38FAX_VERSION_1;
05334 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
05335 found = 1;
05336 if (option_debug > 2)
05337 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
05338 ast_udptl_set_far_max_datagram(p->udptl, x);
05339 ast_udptl_set_local_max_datagram(p->udptl, x);
05340 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
05341 found = 1;
05342 if (option_debug > 2)
05343 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
05344 if (x == 1)
05345 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
05346 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
05347 found = 1;
05348 if (option_debug > 2)
05349 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
05350 if (x == 1)
05351 peert38capability |= T38FAX_TRANSCODING_MMR;
05352 }
05353 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
05354 found = 1;
05355 if (option_debug > 2)
05356 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
05357 if (x == 1)
05358 peert38capability |= T38FAX_TRANSCODING_JBIG;
05359 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
05360 found = 1;
05361 if (option_debug > 2)
05362 ast_log(LOG_DEBUG, "RateManagement: %s\n", s);
05363 if (!strcasecmp(s, "localTCF"))
05364 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
05365 else if (!strcasecmp(s, "transferredTCF"))
05366 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
05367 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
05368 found = 1;
05369 if (option_debug > 2)
05370 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
05371 if (!strcasecmp(s, "t38UDPRedundancy")) {
05372 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
05373 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05374 } else if (!strcasecmp(s, "t38UDPFEC")) {
05375 peert38capability |= T38FAX_UDP_EC_FEC;
05376 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05377 } else {
05378 peert38capability |= T38FAX_UDP_EC_NONE;
05379 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05380 }
05381 }
05382 }
05383 if (found) {
05384 p->t38.peercapability = peert38capability;
05385 p->t38.jointcapability = (peert38capability & 255);
05386 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
05387 p->t38.jointcapability |= (peert38capability & p->t38.capability);
05388 }
05389 if (debug)
05390 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
05391 p->t38.capability,
05392 p->t38.peercapability,
05393 p->t38.jointcapability);
05394 } else {
05395 p->t38.state = T38_DISABLED;
05396 if (option_debug > 2)
05397 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
05398 }
05399
05400
05401 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
05402 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
05403
05404 newjointcapability = p->capability & (peercapability | vpeercapability);
05405 newpeercapability = (peercapability | vpeercapability);
05406 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
05407
05408
05409 if (debug) {
05410
05411 char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ], s4[BUFSIZ];
05412
05413 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
05414 ast_getformatname_multiple(s1, BUFSIZ, p->capability),
05415 ast_getformatname_multiple(s2, BUFSIZ, newpeercapability),
05416 ast_getformatname_multiple(s3, BUFSIZ, vpeercapability),
05417 ast_getformatname_multiple(s4, BUFSIZ, newjointcapability));
05418
05419 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
05420 ast_rtp_lookup_mime_multiple(s1, BUFSIZ, p->noncodeccapability, 0, 0),
05421 ast_rtp_lookup_mime_multiple(s2, BUFSIZ, peernoncodeccapability, 0, 0),
05422 ast_rtp_lookup_mime_multiple(s3, BUFSIZ, newnoncodeccapability, 0, 0));
05423 }
05424 if (!newjointcapability) {
05425
05426 if (!p->t38.jointcapability) {
05427 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
05428
05429 return -1;
05430 } else {
05431 if (option_debug > 2)
05432 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
05433 return 0;
05434 }
05435 }
05436
05437
05438
05439 p->jointcapability = newjointcapability;
05440 p->peercapability = newpeercapability;
05441 p->jointnoncodeccapability = newnoncodeccapability;
05442
05443 ast_rtp_pt_copy(p->rtp, newaudiortp);
05444 if (p->vrtp)
05445 ast_rtp_pt_copy(p->vrtp, newvideortp);
05446
05447 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
05448 ast_clear_flag(&p->flags[0], SIP_DTMF);
05449 if (newnoncodeccapability & AST_RTP_DTMF) {
05450
05451 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
05452
05453 ast_rtp_setdtmf(p->rtp, 1);
05454 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05455 } else {
05456 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
05457 }
05458 }
05459
05460
05461 if (p->rtp && sin.sin_port) {
05462 ast_rtp_set_peer(p->rtp, &sin);
05463 if (debug)
05464 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
05465 }
05466
05467
05468 if (p->vrtp && vsin.sin_port) {
05469 ast_rtp_set_peer(p->vrtp, &vsin);
05470 if (debug)
05471 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
05472 }
05473
05474
05475 if (option_debug > 1) {
05476 char buf[BUFSIZ];
05477 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, BUFSIZ, p->jointcapability));
05478 }
05479
05480 if (!p->owner)
05481 return 0;
05482
05483 if (option_debug > 3)
05484 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
05485
05486 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05487 if (debug) {
05488 char s1[BUFSIZ], s2[BUFSIZ];
05489 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
05490 ast_getformatname_multiple(s1, BUFSIZ, p->jointcapability),
05491 ast_getformatname_multiple(s2, BUFSIZ, p->owner->nativeformats));
05492 }
05493 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
05494 ast_set_read_format(p->owner, p->owner->readformat);
05495 ast_set_write_format(p->owner, p->owner->writeformat);
05496 }
05497
05498 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
05499 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
05500
05501 ast_queue_frame(p->owner, &ast_null_frame);
05502 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
05503 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
05504 S_OR(p->mohsuggest, NULL),
05505 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
05506 if (sendonly)
05507 ast_rtp_stop(p->rtp);
05508
05509
05510 ast_queue_frame(p->owner, &ast_null_frame);
05511 }
05512
05513
05514 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1))
05515 change_hold_state(p, req, FALSE, sendonly);
05516 else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1))
05517 change_hold_state(p, req, TRUE, sendonly);
05518 return 0;
05519 }
05520
05521
05522
05523 static int add_header(struct sip_request *req, const char *var, const char *value)
05524 {
05525 int maxlen = sizeof(req->data) - 4 - req->len;
05526
05527 if (req->headers == SIP_MAX_HEADERS) {
05528 ast_log(LOG_WARNING, "Out of SIP header space\n");
05529 return -1;
05530 }
05531
05532 if (req->lines) {
05533 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
05534 return -1;
05535 }
05536
05537 if (maxlen <= 0) {
05538 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
05539 return -1;
05540 }
05541
05542 req->header[req->headers] = req->data + req->len;
05543
05544 if (compactheaders)
05545 var = find_alias(var, var);
05546
05547 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
05548 req->len += strlen(req->header[req->headers]);
05549 req->headers++;
05550
05551 return 0;
05552 }
05553
05554
05555 static int add_header_contentLength(struct sip_request *req, int len)
05556 {
05557 char clen[10];
05558
05559 snprintf(clen, sizeof(clen), "%d", len);
05560 return add_header(req, "Content-Length", clen);
05561 }
05562
05563
05564 static int add_line(struct sip_request *req, const char *line)
05565 {
05566 if (req->lines == SIP_MAX_LINES) {
05567 ast_log(LOG_WARNING, "Out of SIP line space\n");
05568 return -1;
05569 }
05570 if (!req->lines) {
05571
05572 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
05573 req->len += strlen(req->data + req->len);
05574 }
05575 if (req->len >= sizeof(req->data) - 4) {
05576 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
05577 return -1;
05578 }
05579 req->line[req->lines] = req->data + req->len;
05580 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
05581 req->len += strlen(req->line[req->lines]);
05582 req->lines++;
05583 return 0;
05584 }
05585
05586
05587 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
05588 {
05589 const char *tmp = get_header(orig, field);
05590
05591 if (!ast_strlen_zero(tmp))
05592 return add_header(req, field, tmp);
05593 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
05594 return -1;
05595 }
05596
05597
05598 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
05599 {
05600 int start = 0;
05601 int copied = 0;
05602 for (;;) {
05603 const char *tmp = __get_header(orig, field, &start);
05604
05605 if (ast_strlen_zero(tmp))
05606 break;
05607
05608 add_header(req, field, tmp);
05609 copied++;
05610 }
05611 return copied ? 0 : -1;
05612 }
05613
05614
05615
05616
05617
05618
05619
05620 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
05621 {
05622 int copied = 0;
05623 int start = 0;
05624
05625 for (;;) {
05626 char new[256];
05627 const char *oh = __get_header(orig, field, &start);
05628
05629 if (ast_strlen_zero(oh))
05630 break;
05631
05632 if (!copied) {
05633 char leftmost[256], *others, *rport;
05634
05635
05636 ast_copy_string(leftmost, oh, sizeof(leftmost));
05637 others = strchr(leftmost, ',');
05638 if (others)
05639 *others++ = '\0';
05640
05641
05642 rport = strstr(leftmost, ";rport");
05643 if (rport && *(rport+6) == '=')
05644 rport = NULL;
05645
05646
05647 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
05648
05649 char *end;
05650
05651 rport = strstr(leftmost, ";rport");
05652
05653 if (rport) {
05654 end = strchr(rport + 1, ';');
05655 if (end)
05656 memmove(rport, end, strlen(end) + 1);
05657 else
05658 *rport = '\0';
05659 }
05660
05661
05662 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
05663 leftmost, ast_inet_ntoa(p->recv.sin_addr),
05664 ntohs(p->recv.sin_port),
05665 others ? "," : "", others ? others : "");
05666 } else {
05667
05668 snprintf(new, sizeof(new), "%s;received=%s%s%s",
05669 leftmost, ast_inet_ntoa(p->recv.sin_addr),
05670 others ? "," : "", others ? others : "");
05671 }
05672 oh = new;
05673 }
05674 add_header(req, field, oh);
05675 copied++;
05676 }
05677 if (!copied) {
05678 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
05679 return -1;
05680 }
05681 return 0;
05682 }
05683
05684
05685 static void add_route(struct sip_request *req, struct sip_route *route)
05686 {
05687 char r[BUFSIZ*2], *p;
05688 int n, rem = sizeof(r);
05689
05690 if (!route)
05691 return;
05692
05693 p = r;
05694 for (;route ; route = route->next) {
05695 n = strlen(route->hop);
05696 if (rem < n+3)
05697 break;
05698 if (p != r) {
05699 *p++ = ',';
05700 --rem;
05701 }
05702 *p++ = '<';
05703 ast_copy_string(p, route->hop, rem);
05704 p += n;
05705 *p++ = '>';
05706 rem -= (n+2);
05707 }
05708 *p = '\0';
05709 add_header(req, "Route", r);
05710 }
05711
05712
05713 static void set_destination(struct sip_pvt *p, char *uri)
05714 {
05715 char *h, *maddr, hostname[256];
05716 int port, hn;
05717 struct hostent *hp;
05718 struct ast_hostent ahp;
05719 int debug=sip_debug_test_pvt(p);
05720
05721
05722
05723
05724 if (debug)
05725 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
05726
05727
05728 h = strchr(uri, '@');
05729 if (h)
05730 ++h;
05731 else {
05732 h = uri;
05733 if (strncasecmp(h, "sip:", 4) == 0)
05734 h += 4;
05735 else if (strncasecmp(h, "sips:", 5) == 0)
05736 h += 5;
05737 }
05738 hn = strcspn(h, ":;>") + 1;
05739 if (hn > sizeof(hostname))
05740 hn = sizeof(hostname);
05741 ast_copy_string(hostname, h, hn);
05742
05743 h += hn - 1;
05744
05745
05746 if (*h == ':') {
05747
05748 ++h;
05749 port = strtol(h, &h, 10);
05750 }
05751 else
05752 port = STANDARD_SIP_PORT;
05753
05754
05755 maddr = strstr(h, "maddr=");
05756 if (maddr) {
05757 maddr += 6;
05758 hn = strspn(maddr, "0123456789.") + 1;
05759 if (hn > sizeof(hostname))
05760 hn = sizeof(hostname);
05761 ast_copy_string(hostname, maddr, hn);
05762 }
05763
05764 hp = ast_gethostbyname(hostname, &ahp);
05765 if (hp == NULL) {
05766 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
05767 return;
05768 }
05769 p->sa.sin_family = AF_INET;
05770 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
05771 p->sa.sin_port = htons(port);
05772 if (debug)
05773 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
05774 }
05775
05776
05777 static int init_resp(struct sip_request *resp, const char *msg)
05778 {
05779
05780 memset(resp, 0, sizeof(*resp));
05781 resp->method = SIP_RESPONSE;
05782 resp->header[0] = resp->data;
05783 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
05784 resp->len = strlen(resp->header[0]);
05785 resp->headers++;
05786 return 0;
05787 }
05788
05789
05790 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
05791 {
05792
05793 memset(req, 0, sizeof(*req));
05794 req->method = sipmethod;
05795 req->header[0] = req->data;
05796 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
05797 req->len = strlen(req->header[0]);
05798 req->headers++;
05799 return 0;
05800 }
05801
05802
05803
05804 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
05805 {
05806 char newto[256];
05807 const char *ot;
05808
05809 init_resp(resp, msg);
05810 copy_via_headers(p, resp, req, "Via");
05811 if (msg[0] == '1' || msg[0] == '2')
05812 copy_all_header(resp, req, "Record-Route");
05813 copy_header(resp, req, "From");
05814 ot = get_header(req, "To");
05815 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
05816
05817
05818 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
05819 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
05820 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
05821 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
05822 else
05823 ast_copy_string(newto, ot, sizeof(newto));
05824 ot = newto;
05825 }
05826 add_header(resp, "To", ot);
05827 copy_header(resp, req, "Call-ID");
05828 copy_header(resp, req, "CSeq");
05829 if (!ast_strlen_zero(global_useragent))
05830 add_header(resp, "User-Agent", global_useragent);
05831 add_header(resp, "Allow", ALLOWED_METHODS);
05832 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
05833 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
05834
05835
05836 char tmp[256];
05837
05838 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
05839 add_header(resp, "Expires", tmp);
05840 if (p->expiry) {
05841 char contact[BUFSIZ];
05842 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
05843 add_header(resp, "Contact", contact);
05844 }
05845 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
05846 add_header(resp, "Contact", p->our_contact);
05847 }
05848 return 0;
05849 }
05850
05851
05852 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
05853 {
05854 struct sip_request *orig = &p->initreq;
05855 char stripped[80];
05856 char tmp[80];
05857 char newto[256];
05858 const char *c;
05859 const char *ot, *of;
05860 int is_strict = FALSE;
05861
05862 memset(req, 0, sizeof(struct sip_request));
05863
05864 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
05865
05866 if (!seqno) {
05867 p->ocseq++;
05868 seqno = p->ocseq;
05869 }
05870
05871 if (newbranch) {
05872 p->branch ^= ast_random();
05873 build_via(p);
05874 }
05875
05876
05877 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
05878 is_strict = TRUE;
05879 if (sipdebug)
05880 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
05881 }
05882
05883 if (sipmethod == SIP_CANCEL)
05884 c = p->initreq.rlPart2;
05885 else if (sipmethod == SIP_ACK) {
05886
05887
05888 if (!ast_strlen_zero(p->okcontacturi))
05889 c = is_strict ? p->route->hop : p->okcontacturi;
05890 else
05891 c = p->initreq.rlPart2;
05892 } else if (!ast_strlen_zero(p->okcontacturi))
05893 c = is_strict ? p->route->hop : p->okcontacturi;
05894 else if (!ast_strlen_zero(p->uri))
05895 c = p->uri;
05896 else {
05897 char *n;
05898
05899 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
05900 sizeof(stripped));
05901 n = get_in_brackets(stripped);
05902 c = strsep(&n, ";");
05903 }
05904 init_req(req, sipmethod, c);
05905
05906 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
05907
05908 add_header(req, "Via", p->via);
05909 if (p->route) {
05910 set_destination(p, p->route->hop);
05911 add_route(req, is_strict ? p->route->next : p->route);
05912 }
05913
05914 ot = get_header(orig, "To");
05915 of = get_header(orig, "From");
05916
05917
05918
05919 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
05920
05921
05922 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
05923 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
05924 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
05925 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
05926 else
05927 snprintf(newto, sizeof(newto), "%s", ot);
05928 ot = newto;
05929 }
05930
05931 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05932 add_header(req, "From", of);
05933 add_header(req, "To", ot);
05934 } else {
05935 add_header(req, "From", ot);
05936 add_header(req, "To", of);
05937 }
05938
05939 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
05940 add_header(req, "Contact", p->our_contact);
05941
05942 copy_header(req, orig, "Call-ID");
05943 add_header(req, "CSeq", tmp);
05944
05945 if (!ast_strlen_zero(global_useragent))
05946 add_header(req, "User-Agent", global_useragent);
05947 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
05948
05949 if (!ast_strlen_zero(p->rpid))
05950 add_header(req, "Remote-Party-ID", p->rpid);
05951
05952 return 0;
05953 }
05954
05955
05956 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
05957 {
05958 struct sip_request resp;
05959 int seqno = 0;
05960
05961 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
05962 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
05963 return -1;
05964 }
05965 respprep(&resp, p, msg, req);
05966 add_header_contentLength(&resp, 0);
05967
05968
05969 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
05970 char buf[10];
05971
05972 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
05973 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
05974 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
05975 }
05976 return send_response(p, &resp, reliable, seqno);
05977 }
05978
05979 static void temp_pvt_cleanup(void *data)
05980 {
05981 struct sip_pvt *p = data;
05982
05983 ast_string_field_free_memory(p);
05984
05985 free(data);
05986 }
05987
05988
05989 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)
05990 {
05991 struct sip_pvt *p = NULL;
05992
05993 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
05994 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
05995 return -1;
05996 }
05997
05998
05999 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
06000 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
06001 if (ast_string_field_init(p, 512))
06002 return -1;
06003 }
06004
06005
06006 p->method = intended_method;
06007
06008 if (sin) {
06009 p->sa = *sin;
06010 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
06011 p->ourip = __ourip;
06012 } else
06013 p->ourip = __ourip;
06014
06015 p->branch = ast_random();
06016 make_our_tag(p->tag, sizeof(p->tag));
06017 p->ocseq = INITIAL_CSEQ;
06018
06019 if (useglobal_nat && sin) {
06020 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
06021 p->recv = *sin;
06022 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
06023 }
06024
06025 ast_string_field_set(p, fromdomain, default_fromdomain);
06026 build_via(p);
06027 ast_string_field_set(p, callid, callid);
06028
06029
06030 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
06031
06032
06033 ast_string_field_reset_all(p);
06034
06035 return 0;
06036 }
06037
06038
06039 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
06040 {
06041 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
06042 }
06043
06044
06045 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
06046 {
06047 struct sip_request resp;
06048 respprep(&resp, p, msg, req);
06049 append_date(&resp);
06050 add_header(&resp, "Unsupported", unsupported);
06051 add_header_contentLength(&resp, 0);
06052 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
06053 }
06054
06055
06056
06057
06058 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
06059 {
06060 return __transmit_response(p, msg, req, XMIT_CRITICAL);
06061 }
06062
06063
06064 static void append_date(struct sip_request *req)
06065 {
06066 char tmpdat[256];
06067 struct tm tm;
06068 time_t t = time(NULL);
06069
06070 gmtime_r(&t, &tm);
06071 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
06072 add_header(req, "Date", tmpdat);
06073 }
06074
06075
06076 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
06077 {
06078 struct sip_request resp;
06079 respprep(&resp, p, msg, req);
06080 append_date(&resp);
06081 add_header_contentLength(&resp, 0);
06082 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
06083 }
06084
06085
06086 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
06087 {
06088 struct sip_request resp;
06089 respprep(&resp, p, msg, req);
06090 add_header(&resp, "Accept", "application/sdp");
06091 add_header_contentLength(&resp, 0);
06092 return send_response(p, &resp, reliable, 0);
06093 }
06094
06095
06096 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)
06097 {
06098 struct sip_request resp;
06099 char tmp[512];
06100 int seqno = 0;
06101
06102 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
06103 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
06104 return -1;
06105 }
06106
06107
06108 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
06109 respprep(&resp, p, msg, req);
06110 add_header(&resp, header, tmp);
06111 add_header_contentLength(&resp, 0);
06112 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
06113 return send_response(p, &resp, reliable, seqno);
06114 }
06115
06116
06117 static int add_text(struct sip_request *req, const char *text)
06118 {
06119
06120 add_header(req, "Content-Type", "text/plain");
06121 add_header_contentLength(req, strlen(text));
06122 add_line(req, text);
06123 return 0;
06124 }
06125
06126
06127
06128 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
06129 {
06130 char tmp[256];
06131
06132 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
06133 add_header(req, "Content-Type", "application/dtmf-relay");
06134 add_header_contentLength(req, strlen(tmp));
06135 add_line(req, tmp);
06136 return 0;
06137 }
06138
06139
06140
06141 static int add_vidupdate(struct sip_request *req)
06142 {
06143 const char *xml_is_a_huge_waste_of_space =
06144 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
06145 " <media_control>\r\n"
06146 " <vc_primitive>\r\n"
06147 " <to_encoder>\r\n"
06148 " <picture_fast_update>\r\n"
06149 " </picture_fast_update>\r\n"
06150 " </to_encoder>\r\n"
06151 " </vc_primitive>\r\n"
06152 " </media_control>\r\n";
06153 add_header(req, "Content-Type", "application/media_control+xml");
06154 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
06155 add_line(req, xml_is_a_huge_waste_of_space);
06156 return 0;
06157 }
06158
06159
06160 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
06161 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
06162 int debug, int *min_packet_size)
06163 {
06164 int rtp_code;
06165 struct ast_format_list fmt;
06166
06167
06168 if (debug)
06169 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
06170 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
06171 return;
06172
06173 if (p->rtp) {
06174 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
06175 fmt = ast_codec_pref_getsize(pref, codec);
06176 } else
06177 return;
06178 ast_build_string(m_buf, m_size, " %d", rtp_code);
06179 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
06180 ast_rtp_lookup_mime_subtype(1, codec,
06181 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
06182 sample_rate);
06183 if (codec == AST_FORMAT_G729A) {
06184
06185 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
06186 } else if (codec == AST_FORMAT_G723_1) {
06187
06188 ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
06189 } else if (codec == AST_FORMAT_ILBC) {
06190
06191 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
06192 }
06193
06194 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
06195 *min_packet_size = fmt.cur_ms;
06196
06197
06198 if ((*min_packet_size) == 0 && fmt.cur_ms)
06199 *min_packet_size = fmt.cur_ms;
06200 }
06201
06202
06203 static int t38_get_rate(int t38cap)
06204 {
06205 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
06206
06207 if (maxrate & T38FAX_RATE_14400) {
06208 if (option_debug > 1)
06209 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
06210 return 14400;
06211 } else if (maxrate & T38FAX_RATE_12000) {
06212 if (option_debug > 1)
06213 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
06214 return 12000;
06215 } else if (maxrate & T38FAX_RATE_9600) {
06216 if (option_debug > 1)
06217 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
06218 return 9600;
06219 } else if (maxrate & T38FAX_RATE_7200) {
06220 if (option_debug > 1)
06221 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
06222 return 7200;
06223 } else if (maxrate & T38FAX_RATE_4800) {
06224 if (option_debug > 1)
06225 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
06226 return 4800;
06227 } else if (maxrate & T38FAX_RATE_2400) {
06228 if (option_debug > 1)
06229 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
06230 return 2400;
06231 } else {
06232 if (option_debug > 1)
06233 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
06234 return 0;
06235 }
06236 }
06237
06238
06239 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
06240 {
06241 int len = 0;
06242 int x = 0;
06243 struct sockaddr_in udptlsin;
06244 char v[256] = "";
06245 char s[256] = "";
06246 char o[256] = "";
06247 char c[256] = "";
06248 char t[256] = "";
06249 char m_modem[256];
06250 char a_modem[1024];
06251 char *m_modem_next = m_modem;
06252 size_t m_modem_left = sizeof(m_modem);
06253 char *a_modem_next = a_modem;
06254 size_t a_modem_left = sizeof(a_modem);
06255 struct sockaddr_in udptldest = { 0, };
06256 int debug;
06257
06258 debug = sip_debug_test_pvt(p);
06259 len = 0;
06260 if (!p->udptl) {
06261 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
06262 return -1;
06263 }
06264
06265 if (!p->sessionid) {
06266 p->sessionid = getpid();
06267 p->sessionversion = p->sessionid;
06268 } else
06269 p->sessionversion++;
06270
06271
06272 ast_udptl_get_us(p->udptl, &udptlsin);
06273
06274
06275 if (p->udptlredirip.sin_addr.s_addr) {
06276 udptldest.sin_port = p->udptlredirip.sin_port;
06277 udptldest.sin_addr = p->udptlredirip.sin_addr;
06278 } else {
06279 udptldest.sin_addr = p->ourip;
06280 udptldest.sin_port = udptlsin.sin_port;
06281 }
06282
06283 if (debug)
06284 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
06285
06286
06287
06288
06289 if (debug) {
06290 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
06291 p->t38.capability,
06292 p->t38.peercapability,
06293 p->t38.jointcapability);
06294 }
06295 snprintf(v, sizeof(v), "v=0\r\n");
06296 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
06297 snprintf(s, sizeof(s), "s=session\r\n");
06298 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
06299 snprintf(t, sizeof(t), "t=0 0\r\n");
06300 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
06301
06302 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
06303 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
06304 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
06305 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
06306 if ((x = t38_get_rate(p->t38.jointcapability)))
06307 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
06308 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
06309 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
06310 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
06311 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
06312 x = ast_udptl_get_local_max_datagram(p->udptl);
06313 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
06314 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
06315 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
06316 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
06317 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
06318 add_header(resp, "Content-Type", "application/sdp");
06319 add_header_contentLength(resp, len);
06320 add_line(resp, v);
06321 add_line(resp, o);
06322 add_line(resp, s);
06323 add_line(resp, c);
06324 add_line(resp, t);
06325 add_line(resp, m_modem);
06326 add_line(resp, a_modem);
06327
06328
06329 p->lastrtprx = p->lastrtptx = time(NULL);
06330
06331 return 0;
06332 }
06333
06334
06335
06336 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
06337 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
06338 int debug)
06339 {
06340 int rtp_code;
06341
06342 if (debug)
06343 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
06344 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
06345 return;
06346
06347 ast_build_string(m_buf, m_size, " %d", rtp_code);
06348 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
06349 ast_rtp_lookup_mime_subtype(0, format, 0),
06350 sample_rate);
06351 if (format == AST_RTP_DTMF)
06352
06353 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
06354 }
06355
06356 #define SDP_SAMPLE_RATE(x) (x == AST_FORMAT_G722) ? 16000 : 8000
06357
06358
06359 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
06360 {
06361 int len = 0;
06362 int alreadysent = 0;
06363
06364 struct sockaddr_in sin;
06365 struct sockaddr_in vsin;
06366 struct sockaddr_in dest;
06367 struct sockaddr_in vdest = { 0, };
06368
06369
06370 char *version = "v=0\r\n";
06371 char *subject = "s=session\r\n";
06372 char owner[256];
06373 char connection[256];
06374 char *stime = "t=0 0\r\n";
06375 char bandwidth[256] = "";
06376 char *hold;
06377 char m_audio[256];
06378 char m_video[256];
06379 char a_audio[1024];
06380 char a_video[1024];
06381 char *m_audio_next = m_audio;
06382 char *m_video_next = m_video;
06383 size_t m_audio_left = sizeof(m_audio);
06384 size_t m_video_left = sizeof(m_video);
06385 char *a_audio_next = a_audio;
06386 char *a_video_next = a_video;
06387 size_t a_audio_left = sizeof(a_audio);
06388 size_t a_video_left = sizeof(a_video);
06389
06390 int x;
06391 int capability;
06392 int needvideo = FALSE;
06393 int debug = sip_debug_test_pvt(p);
06394 int min_audio_packet_size = 0;
06395 int min_video_packet_size = 0;
06396
06397 m_video[0] = '\0';
06398
06399 if (!p->rtp) {
06400 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
06401 return AST_FAILURE;
06402 }
06403
06404
06405 if (!p->sessionid) {
06406 p->sessionid = getpid();
06407 p->sessionversion = p->sessionid;
06408 } else
06409 p->sessionversion++;
06410
06411
06412 ast_rtp_get_us(p->rtp, &sin);
06413 if (p->vrtp)
06414 ast_rtp_get_us(p->vrtp, &vsin);
06415
06416
06417 if (p->redirip.sin_addr.s_addr) {
06418 dest.sin_port = p->redirip.sin_port;
06419 dest.sin_addr = p->redirip.sin_addr;
06420 } else {
06421 dest.sin_addr = p->ourip;
06422 dest.sin_port = sin.sin_port;
06423 }
06424
06425 capability = p->jointcapability;
06426
06427
06428 if (option_debug > 1) {
06429 char codecbuf[BUFSIZ];
06430 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");
06431 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
06432 }
06433
06434 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
06435 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
06436 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
06437 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
06438 }
06439 #endif
06440
06441
06442 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
06443 if (p->vrtp) {
06444 needvideo = TRUE;
06445 if (option_debug > 1)
06446 ast_log(LOG_DEBUG, "This call needs video offers!\n");
06447 } else if (option_debug > 1)
06448 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
06449 }
06450
06451
06452
06453
06454 if (needvideo) {
06455
06456 if (p->vredirip.sin_addr.s_addr) {
06457 vdest.sin_addr = p->vredirip.sin_addr;
06458 vdest.sin_port = p->vredirip.sin_port;
06459 } else {
06460 vdest.sin_addr = p->ourip;
06461 vdest.sin_port = vsin.sin_port;
06462 }
06463 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
06464
06465
06466 if (p->maxcallbitrate)
06467 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
06468 if (debug)
06469 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
06470 }
06471
06472 if (debug)
06473 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
06474
06475
06476
06477
06478
06479
06480 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
06481 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
06482 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
06483
06484 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
06485 hold = "a=recvonly\r\n";
06486 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
06487 hold = "a=inactive\r\n";
06488 else
06489 hold = "a=sendrecv\r\n";
06490
06491
06492
06493
06494
06495
06496
06497
06498
06499
06500 if (capability & p->prefcodec) {
06501 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
06502
06503 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
06504 &m_audio_next, &m_audio_left,
06505 &a_audio_next, &a_audio_left,
06506 debug, &min_audio_packet_size);
06507 alreadysent |= codec;
06508 }
06509
06510
06511 for (x = 0; x < 32; x++) {
06512 int codec;
06513
06514 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
06515 break;
06516
06517 if (!(capability & codec))
06518 continue;
06519
06520 if (alreadysent & codec)
06521 continue;
06522
06523 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
06524 &m_audio_next, &m_audio_left,
06525 &a_audio_next, &a_audio_left,
06526 debug, &min_audio_packet_size);
06527 alreadysent |= codec;
06528 }
06529
06530
06531 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
06532 if (!(capability & x))
06533 continue;
06534
06535 if (alreadysent & x)
06536 continue;
06537
06538 if (x <= AST_FORMAT_MAX_AUDIO)
06539 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
06540 &m_audio_next, &m_audio_left,
06541 &a_audio_next, &a_audio_left,
06542 debug, &min_audio_packet_size);
06543 else
06544 add_codec_to_sdp(p, x, 90000,
06545 &m_video_next, &m_video_left,
06546 &a_video_next, &a_video_left,
06547 debug, &min_video_packet_size);
06548 }
06549
06550
06551 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
06552 if (!(p->jointnoncodeccapability & x))
06553 continue;
06554
06555 add_noncodec_to_sdp(p, x, 8000,
06556 &m_audio_next, &m_audio_left,
06557 &a_audio_next, &a_audio_left,
06558 debug);
06559 }
06560
06561 if (option_debug > 2)
06562 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
06563
06564 if (!p->owner || !ast_internal_timing_enabled(p->owner))
06565 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
06566
06567 if (min_audio_packet_size)
06568 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
06569
06570 if (min_video_packet_size)
06571 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
06572
06573 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
06574 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
06575
06576 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
06577 if (needvideo)
06578 ast_build_string(&m_video_next, &m_video_left, "\r\n");
06579
06580 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
06581 if (needvideo)
06582 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
06583
06584 add_header(resp, "Content-Type", "application/sdp");
06585 add_header_contentLength(resp, len);
06586 add_line(resp, version);
06587 add_line(resp, owner);
06588 add_line(resp, subject);
06589 add_line(resp, connection);
06590 if (needvideo)
06591 add_line(resp, bandwidth);
06592 add_line(resp, stime);
06593 add_line(resp, m_audio);
06594 add_line(resp, a_audio);
06595 add_line(resp, hold);
06596 if (needvideo) {
06597 add_line(resp, m_video);
06598 add_line(resp, a_video);
06599 add_line(resp, hold);
06600 }
06601
06602
06603 p->lastrtprx = p->lastrtptx = time(NULL);
06604
06605 if (option_debug > 2) {
06606 char buf[BUFSIZ];
06607 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, BUFSIZ, capability));
06608 }
06609
06610 return AST_SUCCESS;
06611 }
06612
06613
06614 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
06615 {
06616 struct sip_request resp;
06617 int seqno;
06618
06619 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
06620 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
06621 return -1;
06622 }
06623 respprep(&resp, p, msg, req);
06624 if (p->udptl) {
06625 ast_udptl_offered_from_local(p->udptl, 0);
06626 add_t38_sdp(&resp, p);
06627 } else
06628 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
06629 if (retrans && !p->pendinginvite)
06630 p->pendinginvite = seqno;
06631 return send_response(p, &resp, retrans, seqno);
06632 }
06633
06634
06635 static void copy_request(struct sip_request *dst, const struct sip_request *src)
06636 {
06637 long offset;
06638 int x;
06639 offset = ((void *)dst) - ((void *)src);
06640
06641 memcpy(dst, src, sizeof(*dst));
06642
06643 for (x=0; x < src->headers; x++)
06644 dst->header[x] += offset;
06645 for (x=0; x < src->lines; x++)
06646 dst->line[x] += offset;
06647 dst->rlPart1 += offset;
06648 dst->rlPart2 += offset;
06649 }
06650
06651
06652
06653
06654 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
06655 {
06656 struct sip_request resp;
06657 int seqno;
06658 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
06659 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
06660 return -1;
06661 }
06662 respprep(&resp, p, msg, req);
06663 if (p->rtp) {
06664 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06665 if (option_debug)
06666 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
06667 ast_rtp_codec_setpref(p->rtp, &p->prefs);
06668 }
06669 try_suggested_sip_codec(p);
06670 add_sdp(&resp, p);
06671 } else
06672 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
06673 if (reliable && !p->pendinginvite)
06674 p->pendinginvite = seqno;
06675 return send_response(p, &resp, reliable, seqno);
06676 }
06677
06678
06679 static int determine_firstline_parts(struct sip_request *req)
06680 {
06681 char *e = ast_skip_blanks(req->header[0]);
06682
06683 if (!*e)
06684 return -1;
06685 req->rlPart1 = e;
06686 e = ast_skip_nonblanks(e);
06687 if (*e)
06688 *e++ = '\0';
06689
06690 e = ast_skip_blanks(e);
06691 if ( !*e )
06692 return -1;
06693 ast_trim_blanks(e);
06694
06695 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) {
06696 if (strlen(e) < 3)
06697 return -1;
06698 req->rlPart2 = e;
06699 } else {
06700 if ( *e == '<' ) {
06701 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
06702 e++;
06703 if (!*e)
06704 return -1;
06705 }
06706 req->rlPart2 = e;
06707 e = ast_skip_nonblanks(e);
06708 if (*e)
06709 *e++ = '\0';
06710 e = ast_skip_blanks(e);
06711 if (strcasecmp(e, "SIP/2.0") ) {
06712 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
06713 return -1;
06714 }
06715 }
06716 return 1;
06717 }
06718
06719
06720
06721
06722
06723
06724
06725 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
06726 {
06727 struct sip_request req;
06728
06729 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
06730
06731 add_header(&req, "Allow", ALLOWED_METHODS);
06732 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
06733 if (sipdebug)
06734 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
06735 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
06736 append_history(p, "ReInv", "Re-invite sent");
06737 add_sdp(&req, p);
06738
06739 initialize_initreq(p, &req);
06740 p->lastinvite = p->ocseq;
06741 ast_set_flag(&p->flags[0], SIP_OUTGOING);
06742 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
06743 }
06744
06745
06746
06747
06748
06749 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
06750 {
06751 struct sip_request req;
06752
06753 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
06754
06755 add_header(&req, "Allow", ALLOWED_METHODS);
06756 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
06757 if (sipdebug)
06758 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
06759 ast_udptl_offered_from_local(p->udptl, 1);
06760 add_t38_sdp(&req, p);
06761
06762 initialize_initreq(p, &req);
06763 ast_set_flag(&p->flags[0], SIP_OUTGOING);
06764 p->lastinvite = p->ocseq;
06765 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
06766 }
06767
06768
06769 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
06770 {
06771 char stripped[BUFSIZ];
06772 char *c;
06773
06774 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
06775 c = get_in_brackets(stripped);
06776 c = strsep(&c, ";");
06777 if (!ast_strlen_zero(c))
06778 ast_string_field_set(p, uri, c);
06779 }
06780
06781
06782 static void build_contact(struct sip_pvt *p)
06783 {
06784
06785 if (ourport != STANDARD_SIP_PORT)
06786 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);
06787 else
06788 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
06789 }
06790
06791
06792 static void build_rpid(struct sip_pvt *p)
06793 {
06794 int send_pres_tags = TRUE;
06795 const char *privacy=NULL;
06796 const char *screen=NULL;
06797 char buf[256];
06798 const char *clid = default_callerid;
06799 const char *clin = NULL;
06800 const char *fromdomain;
06801
06802 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
06803 return;
06804
06805 if (p->owner && p->owner->cid.cid_num)
06806 clid = p->owner->cid.cid_num;
06807 if (p->owner && p->owner->cid.cid_name)
06808 clin = p->owner->cid.cid_name;
06809 if (ast_strlen_zero(clin))
06810 clin = clid;
06811
06812 switch (p->callingpres) {
06813 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
06814 privacy = "off";
06815 screen = "no";
06816 break;
06817 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
06818 privacy = "off";
06819 screen = "yes";
06820 break;
06821 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
06822 privacy = "off";
06823 screen = "no";
06824 break;
06825 case AST_PRES_ALLOWED_NETWORK_NUMBER:
06826 privacy = "off";
06827 screen = "yes";
06828 break;
06829 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
06830 privacy = "full";
06831 screen = "no";
06832 break;
06833 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
06834 privacy = "full";
06835 screen = "yes";
06836 break;
06837 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
06838 privacy = "full";
06839 screen = "no";
06840 break;
06841 case AST_PRES_PROHIB_NETWORK_NUMBER:
06842 privacy = "full";
06843 screen = "yes";
06844 break;
06845 case AST_PRES_NUMBER_NOT_AVAILABLE:
06846 send_pres_tags = FALSE;
06847 break;
06848 default:
06849 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
06850 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
06851 privacy = "full";
06852 else
06853 privacy = "off";
06854 screen = "no";
06855 break;
06856 }
06857
06858 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
06859
06860 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
06861 if (send_pres_tags)
06862 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
06863 ast_string_field_set(p, rpid, buf);
06864
06865 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
06866 S_OR(p->fromuser, clid),
06867 fromdomain, p->tag);
06868 }
06869
06870
06871 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
06872 {
06873 char invite_buf[256] = "";
06874 char *invite = invite_buf;
06875 size_t invite_max = sizeof(invite_buf);
06876 char from[256];
06877 char to[256];
06878 char tmp[BUFSIZ/2];
06879 char tmp2[BUFSIZ/2];
06880 const char *l = NULL, *n = NULL;
06881 const char *urioptions = "";
06882
06883 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
06884 const char *s = p->username;
06885
06886
06887
06888
06889
06890
06891 if (*s == '+')
06892 s++;
06893 for (; *s; s++) {
06894 if (!strchr(AST_DIGIT_ANYNUM, *s) )
06895 break;
06896 }
06897
06898 if (*s)
06899 urioptions = ";user=phone";
06900 }
06901
06902
06903 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
06904
06905 if (p->owner) {
06906 l = p->owner->cid.cid_num;
06907 n = p->owner->cid.cid_name;
06908 }
06909
06910 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
06911 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
06912 l = CALLERID_UNKNOWN;
06913 n = l;
06914 }
06915 if (ast_strlen_zero(l))
06916 l = default_callerid;
06917 if (ast_strlen_zero(n))
06918 n = l;
06919
06920 if (!ast_strlen_zero(p->fromuser))
06921 l = p->fromuser;
06922 else
06923 ast_string_field_set(p, fromuser, l);
06924
06925
06926 if (!ast_strlen_zero(p->fromname))
06927 n = p->fromname;
06928 else
06929 ast_string_field_set(p, fromname, n);
06930
06931 if (pedanticsipchecking) {
06932 ast_uri_encode(n, tmp, sizeof(tmp), 0);
06933 n = tmp;
06934 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
06935 l = tmp2;
06936 }
06937
06938 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
06939 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);
06940 else
06941 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
06942
06943
06944 if (!ast_strlen_zero(p->fullcontact)) {
06945
06946 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
06947 } else {
06948
06949 ast_build_string(&invite, &invite_max, "sip:");
06950 if (!ast_strlen_zero(p->username)) {
06951 n = p->username;
06952 if (pedanticsipchecking) {
06953 ast_uri_encode(n, tmp, sizeof(tmp), 0);
06954 n = tmp;
06955 }
06956 ast_build_string(&invite, &invite_max, "%s@", n);
06957 }
06958 ast_build_string(&invite, &invite_max, "%s", p->tohost);
06959 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
06960 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
06961 ast_build_string(&invite, &invite_max, "%s", urioptions);
06962 }
06963
06964
06965 if (p->options && p->options->uri_options)
06966 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
06967
06968 ast_string_field_set(p, uri, invite_buf);
06969
06970 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
06971
06972 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
06973 } else if (p->options && p->options->vxml_url) {
06974
06975 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
06976 } else
06977 snprintf(to, sizeof(to), "<%s>", p->uri);
06978
06979 init_req(req, sipmethod, p->uri);
06980 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
06981
06982 add_header(req, "Via", p->via);
06983
06984
06985
06986 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
06987 build_rpid(p);
06988 add_header(req, "From", p->rpid_from);
06989 } else
06990 add_header(req, "From", from);
06991 add_header(req, "To", to);
06992 ast_string_field_set(p, exten, l);
06993 build_contact(p);
06994 add_header(req, "Contact", p->our_contact);
06995 add_header(req, "Call-ID", p->callid);
06996 add_header(req, "CSeq", tmp);
06997 if (!ast_strlen_zero(global_useragent))
06998 add_header(req, "User-Agent", global_useragent);
06999 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
07000 if (!ast_strlen_zero(p->rpid))
07001 add_header(req, "Remote-Party-ID", p->rpid);
07002 }
07003
07004
07005 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
07006 {
07007 struct sip_request req;
07008
07009 req.method = sipmethod;
07010 if (init) {
07011
07012 p->branch ^= ast_random();
07013 build_via(p);
07014 if (init > 1)
07015 initreqprep(&req, p, sipmethod);
07016 else
07017 reqprep(&req, p, sipmethod, 0, 1);
07018 } else
07019 reqprep(&req, p, sipmethod, 0, 1);
07020
07021 if (p->options && p->options->auth)
07022 add_header(&req, p->options->authheader, p->options->auth);
07023 append_date(&req);
07024 if (sipmethod == SIP_REFER) {
07025 if (p->refer) {
07026 char buf[BUFSIZ];
07027 if (!ast_strlen_zero(p->refer->refer_to))
07028 add_header(&req, "Refer-To", p->refer->refer_to);
07029 if (!ast_strlen_zero(p->refer->referred_by)) {
07030 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
07031 add_header(&req, "Referred-By", buf);
07032 }
07033 }
07034 }
07035
07036
07037 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
07038 add_header(&req, "Replaces", p->options->replaces);
07039 add_header(&req, "Require", "replaces");
07040 }
07041
07042 add_header(&req, "Allow", ALLOWED_METHODS);
07043 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
07044 if (p->options && p->options->addsipheaders && p->owner) {
07045 struct ast_channel *chan = p->owner;
07046 struct varshead *headp;
07047
07048 ast_channel_lock(chan);
07049
07050 headp = &chan->varshead;
07051
07052 if (!headp)
07053 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
07054 else {
07055 const struct ast_var_t *current;
07056 AST_LIST_TRAVERSE(headp, current, entries) {
07057
07058 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
07059 char *content, *end;
07060 const char *header = ast_var_value(current);
07061 char *headdup = ast_strdupa(header);
07062
07063
07064 if (*headdup == '"')
07065 headdup++;
07066 if ((content = strchr(headdup, ':'))) {
07067 *content++ = '\0';
07068 content = ast_skip_blanks(content);
07069
07070 end = content + strlen(content) -1;
07071 if (*end == '"')
07072 *end = '\0';
07073
07074 add_header(&req, headdup, content);
07075 if (sipdebug)
07076 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
07077 }
07078 }
07079 }
07080 }
07081
07082 ast_channel_unlock(chan);
07083 }
07084 if (sdp) {
07085 if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
07086 ast_udptl_offered_from_local(p->udptl, 1);
07087 if (option_debug)
07088 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
07089 add_t38_sdp(&req, p);
07090 } else if (p->rtp)
07091 add_sdp(&req, p);
07092 } else {
07093 add_header_contentLength(&req, 0);
07094 }
07095
07096 if (!p->initreq.headers)
07097 initialize_initreq(p, &req);
07098 p->lastinvite = p->ocseq;
07099 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
07100 }
07101
07102
07103 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
07104 {
07105 char tmp[4000], from[256], to[256];
07106 char *t = tmp, *c, *mfrom, *mto;
07107 size_t maxbytes = sizeof(tmp);
07108 struct sip_request req;
07109 char hint[AST_MAX_EXTENSION];
07110 char *statestring = "terminated";
07111 const struct cfsubscription_types *subscriptiontype;
07112 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
07113 char *pidfstate = "--";
07114 char *pidfnote= "Ready";
07115
07116 memset(from, 0, sizeof(from));
07117 memset(to, 0, sizeof(to));
07118 memset(tmp, 0, sizeof(tmp));
07119
07120 switch (state) {
07121 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
07122 statestring = (global_notifyringing) ? "early" : "confirmed";
07123 local_state = NOTIFY_INUSE;
07124 pidfstate = "busy";
07125 pidfnote = "Ringing";
07126 break;
07127 case AST_EXTENSION_RINGING:
07128 statestring = "early";
07129 local_state = NOTIFY_INUSE;
07130 pidfstate = "busy";
07131 pidfnote = "Ringing";
07132 break;
07133 case AST_EXTENSION_INUSE:
07134 statestring = "confirmed";
07135 local_state = NOTIFY_INUSE;
07136 pidfstate = "busy";
07137 pidfnote = "On the phone";
07138 break;
07139 case AST_EXTENSION_BUSY:
07140 statestring = "confirmed";
07141 local_state = NOTIFY_CLOSED;
07142 pidfstate = "busy";
07143 pidfnote = "On the phone";
07144 break;
07145 case AST_EXTENSION_UNAVAILABLE:
07146 statestring = "terminated";
07147 local_state = NOTIFY_CLOSED;
07148 pidfstate = "away";
07149 pidfnote = "Unavailable";
07150 break;
07151 case AST_EXTENSION_ONHOLD:
07152 statestring = "confirmed";
07153 local_state = NOTIFY_INUSE;
07154 pidfstate = "busy";
07155 pidfnote = "On Hold";
07156 break;
07157 case AST_EXTENSION_NOT_INUSE:
07158 default:
07159
07160 break;
07161 }
07162
07163 subscriptiontype = find_subscription_type(p->subscribed);
07164
07165
07166 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
07167 char *hint2 = hint, *individual_hint = NULL;
07168 int hint_count = 0, unavailable_count = 0;
07169
07170 while ((individual_hint = strsep(&hint2, "&"))) {
07171 hint_count++;
07172
07173 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
07174 unavailable_count++;
07175 }
07176
07177
07178
07179
07180 if (hint_count > 0 && hint_count == unavailable_count) {
07181 local_state = NOTIFY_CLOSED;
07182 pidfstate = "away";
07183 pidfnote = "Not online";
07184 }
07185 }
07186
07187 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
07188 c = get_in_brackets(from);
07189 if (strncasecmp(c, "sip:", 4)) {
07190 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
07191 return -1;
07192 }
07193 mfrom = strsep(&c, ";");
07194
07195 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
07196 c = get_in_brackets(to);
07197 if (strncasecmp(c, "sip:", 4)) {
07198 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
07199 return -1;
07200 }
07201 mto = strsep(&c, ";");
07202
07203 reqprep(&req, p, SIP_NOTIFY, 0, 1);
07204
07205
07206 add_header(&req, "Event", subscriptiontype->event);
07207 add_header(&req, "Content-Type", subscriptiontype->mediatype);
07208 switch(state) {
07209 case AST_EXTENSION_DEACTIVATED:
07210 if (timeout)
07211 add_header(&req, "Subscription-State", "terminated;reason=timeout");
07212 else {
07213 add_header(&req, "Subscription-State", "terminated;reason=probation");
07214 add_header(&req, "Retry-After", "60");
07215 }
07216 break;
07217 case AST_EXTENSION_REMOVED:
07218 add_header(&req, "Subscription-State", "terminated;reason=noresource");
07219 break;
07220 default:
07221 if (p->expiry)
07222 add_header(&req, "Subscription-State", "active");
07223 else
07224 add_header(&req, "Subscription-State", "terminated;reason=timeout");
07225 }
07226 switch (p->subscribed) {
07227 case XPIDF_XML:
07228 case CPIM_PIDF_XML:
07229 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
07230 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
07231 ast_build_string(&t, &maxbytes, "<presence>\n");
07232 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
07233 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
07234 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
07235 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
07236 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
07237 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
07238 break;
07239 case PIDF_XML:
07240 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
07241 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);
07242 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
07243 if (pidfstate[0] != '-')
07244 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
07245 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
07246 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote);
07247 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten);
07248 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
07249 if (pidfstate[0] == 'b')
07250 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
07251 else
07252 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
07253 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
07254 break;
07255 case DIALOG_INFO_XML:
07256 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
07257 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);
07258 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
07259 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
07260 else
07261 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
07262 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
07263 if (state == AST_EXTENSION_ONHOLD) {
07264 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
07265 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
07266 "</target>\n</local>\n", mto);
07267 }
07268 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
07269 break;
07270 case NONE:
07271 default:
07272 break;
07273 }
07274
07275 if (t > tmp + sizeof(tmp))
07276 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
07277
07278 add_header_contentLength(&req, strlen(tmp));
07279 add_line(&req, tmp);
07280
07281 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07282 }
07283
07284
07285
07286
07287
07288
07289
07290 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
07291 {
07292 struct sip_request req;
07293 char tmp[500];
07294 char *t = tmp;
07295 size_t maxbytes = sizeof(tmp);
07296
07297 initreqprep(&req, p, SIP_NOTIFY);
07298 add_header(&req, "Event", "message-summary");
07299 add_header(&req, "Content-Type", default_notifymime);
07300
07301 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
07302 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
07303 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
07304
07305
07306
07307 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)"));
07308
07309 if (p->subscribed) {
07310 if (p->expiry)
07311 add_header(&req, "Subscription-State", "active");
07312 else
07313 add_header(&req, "Subscription-State", "terminated;reason=timeout");
07314 }
07315
07316 if (t > tmp + sizeof(tmp))
07317 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
07318
07319 add_header_contentLength(&req, strlen(tmp));
07320 add_line(&req, tmp);
07321
07322 if (!p->initreq.headers)
07323 initialize_initreq(p, &req);
07324 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07325 }
07326
07327
07328 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
07329 {
07330 if (!p->initreq.headers)
07331 initialize_initreq(p, req);
07332 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
07333 }
07334
07335
07336 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
07337 {
07338 struct sip_request req;
07339 char tmp[BUFSIZ/2];
07340
07341 reqprep(&req, p, SIP_NOTIFY, 0, 1);
07342 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
07343 add_header(&req, "Event", tmp);
07344 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
07345 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
07346 add_header(&req, "Allow", ALLOWED_METHODS);
07347 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
07348
07349 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
07350 add_header_contentLength(&req, strlen(tmp));
07351 add_line(&req, tmp);
07352
07353 if (!p->initreq.headers)
07354 initialize_initreq(p, &req);
07355
07356 p->lastnoninvite = p->ocseq;
07357
07358 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07359 }
07360
07361
07362 static char *regstate2str(enum sipregistrystate regstate)
07363 {
07364 switch(regstate) {
07365 case REG_STATE_FAILED:
07366 return "Failed";
07367 case REG_STATE_UNREGISTERED:
07368 return "Unregistered";
07369 case REG_STATE_REGSENT:
07370 return "Request Sent";
07371 case REG_STATE_AUTHSENT:
07372 return "Auth. Sent";
07373 case REG_STATE_REGISTERED:
07374 return "Registered";
07375 case REG_STATE_REJECTED:
07376 return "Rejected";
07377 case REG_STATE_TIMEOUT:
07378 return "Timeout";
07379 case REG_STATE_NOAUTH:
07380 return "No Authentication";
07381 default:
07382 return "Unknown";
07383 }
07384 }
07385
07386
07387 static int sip_reregister(const void *data)
07388 {
07389
07390 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
07391
07392
07393 if (!r)
07394 return 0;
07395
07396 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
07397 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
07398
07399
07400 if (sipdebug)
07401 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
07402
07403 r->expire = -1;
07404 __sip_do_register(r);
07405 ASTOBJ_UNREF(r, sip_registry_destroy);
07406 return 0;
07407 }
07408
07409
07410 static int __sip_do_register(struct sip_registry *r)
07411 {
07412 int res;
07413
07414 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
07415 return res;
07416 }
07417
07418
07419 static int sip_reg_timeout(const void *data)
07420 {
07421
07422
07423 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
07424 struct sip_pvt *p;
07425 int res;
07426
07427
07428 if (!r)
07429 return 0;
07430
07431 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
07432 if (r->call) {
07433
07434
07435 p = r->call;
07436 if (p->registry)
07437 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
07438 r->call = NULL;
07439 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
07440
07441 __sip_pretend_ack(p);
07442 }
07443
07444 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
07445
07446
07447
07448 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
07449 r->regstate = REG_STATE_FAILED;
07450 } else {
07451 r->regstate = REG_STATE_UNREGISTERED;
07452 r->timeout = -1;
07453 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
07454 }
07455 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));
07456 ASTOBJ_UNREF(r, sip_registry_destroy);
07457 return 0;
07458 }
07459
07460
07461 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
07462 {
07463 struct sip_request req;
07464 char from[256];
07465 char to[256];
07466 char tmp[80];
07467 char addr[80];
07468 struct sip_pvt *p;
07469
07470
07471 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
07472 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
07473 return 0;
07474 }
07475
07476 if (r->call) {
07477 if (!auth) {
07478 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
07479 return 0;
07480 } else {
07481 p = r->call;
07482 make_our_tag(p->tag, sizeof(p->tag));
07483 ast_string_field_free(p, theirtag);
07484 }
07485 } else {
07486
07487 if (!r->callid_valid) {
07488 build_callid_registry(r, __ourip, default_fromdomain);
07489 r->callid_valid = TRUE;
07490 }
07491
07492 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
07493 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
07494 return 0;
07495 }
07496 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
07497 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
07498
07499 if (create_addr(p, r->hostname)) {
07500
07501
07502 sip_destroy(p);
07503 if (r->timeout > -1) {
07504 ast_sched_del(sched, r->timeout);
07505 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
07506 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
07507 } else {
07508 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
07509 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);
07510 }
07511 r->regattempts++;
07512 return 0;
07513 }
07514
07515 ast_string_field_set(r, callid, p->callid);
07516 if (r->portno) {
07517 p->sa.sin_port = htons(r->portno);
07518 p->recv.sin_port = htons(r->portno);
07519 } else
07520 r->portno = ntohs(p->sa.sin_port);
07521 ast_set_flag(&p->flags[0], SIP_OUTGOING);
07522 r->call=p;
07523 p->registry = ASTOBJ_REF(r);
07524 if (!ast_strlen_zero(r->secret))
07525 ast_string_field_set(p, peersecret, r->secret);
07526 if (!ast_strlen_zero(r->md5secret))
07527 ast_string_field_set(p, peermd5secret, r->md5secret);
07528
07529
07530 if (!ast_strlen_zero(r->authuser)) {
07531 ast_string_field_set(p, peername, r->authuser);
07532 ast_string_field_set(p, authname, r->authuser);
07533 } else if (!ast_strlen_zero(r->username)) {
07534 ast_string_field_set(p, peername, r->username);
07535 ast_string_field_set(p, authname, r->username);
07536 ast_string_field_set(p, fromuser, r->username);
07537 }
07538 if (!ast_strlen_zero(r->username))
07539 ast_string_field_set(p, username, r->username);
07540
07541 ast_string_field_set(p, exten, r->contact);
07542
07543
07544
07545
07546
07547
07548 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
07549 p->ourip = bindaddr.sin_addr;
07550 build_contact(p);
07551 }
07552
07553
07554 if (auth == NULL) {
07555 if (r->timeout > -1) {
07556 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
07557 ast_sched_del(sched, r->timeout);
07558 }
07559 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
07560 if (option_debug)
07561 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
07562 }
07563
07564 if (strchr(r->username, '@')) {
07565 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
07566 if (!ast_strlen_zero(p->theirtag))
07567 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
07568 else
07569 snprintf(to, sizeof(to), "<sip:%s>", r->username);
07570 } else {
07571 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
07572 if (!ast_strlen_zero(p->theirtag))
07573 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
07574 else
07575 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
07576 }
07577
07578
07579
07580 if (!ast_strlen_zero(p->fromdomain)) {
07581 if (r->portno && r->portno != STANDARD_SIP_PORT)
07582 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
07583 else
07584 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
07585 } else {
07586 if (r->portno && r->portno != STANDARD_SIP_PORT)
07587 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
07588 else
07589 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
07590 }
07591 ast_string_field_set(p, uri, addr);
07592
07593 p->branch ^= ast_random();
07594
07595 init_req(&req, sipmethod, addr);
07596
07597
07598 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
07599 p->ocseq = r->ocseq;
07600
07601 build_via(p);
07602 add_header(&req, "Via", p->via);
07603 add_header(&req, "From", from);
07604 add_header(&req, "To", to);
07605 add_header(&req, "Call-ID", p->callid);
07606 add_header(&req, "CSeq", tmp);
07607 if (!ast_strlen_zero(global_useragent))
07608 add_header(&req, "User-Agent", global_useragent);
07609 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
07610
07611
07612 if (auth)
07613 add_header(&req, authheader, auth);
07614 else if (!ast_strlen_zero(r->nonce)) {
07615 char digest[1024];
07616
07617
07618 if (sipdebug)
07619 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
07620 ast_string_field_set(p, realm, r->realm);
07621 ast_string_field_set(p, nonce, r->nonce);
07622 ast_string_field_set(p, domain, r->domain);
07623 ast_string_field_set(p, opaque, r->opaque);
07624 ast_string_field_set(p, qop, r->qop);
07625 r->noncecount++;
07626 p->noncecount = r->noncecount;
07627
07628 memset(digest,0,sizeof(digest));
07629 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
07630 add_header(&req, "Authorization", digest);
07631 else
07632 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
07633
07634 }
07635
07636 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
07637 add_header(&req, "Expires", tmp);
07638 add_header(&req, "Contact", p->our_contact);
07639 add_header(&req, "Event", "registration");
07640 add_header_contentLength(&req, 0);
07641
07642 initialize_initreq(p, &req);
07643 if (sip_debug_test_pvt(p))
07644 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
07645 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
07646 r->regattempts++;
07647 if (option_debug > 3)
07648 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
07649 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
07650 }
07651
07652
07653 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
07654 {
07655 struct sip_request req;
07656
07657 reqprep(&req, p, SIP_MESSAGE, 0, 1);
07658 add_text(&req, text);
07659 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07660 }
07661
07662
07663 static int sip_refer_allocate(struct sip_pvt *p)
07664 {
07665 p->refer = ast_calloc(1, sizeof(struct sip_refer));
07666 return p->refer ? 1 : 0;
07667 }
07668
07669
07670
07671
07672
07673
07674 static int transmit_refer(struct sip_pvt *p, const char *dest)
07675 {
07676 struct sip_request req = {
07677 .headers = 0,
07678 };
07679 char from[256];
07680 const char *of;
07681 char *c;
07682 char referto[256];
07683 char *ttag, *ftag;
07684 char *theirtag = ast_strdupa(p->theirtag);
07685
07686 if (option_debug || sipdebug)
07687 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
07688
07689
07690 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07691 of = get_header(&p->initreq, "To");
07692 ttag = theirtag;
07693 ftag = p->tag;
07694 } else {
07695 of = get_header(&p->initreq, "From");
07696 ftag = theirtag;
07697 ttag = p->tag;
07698 }
07699
07700 ast_copy_string(from, of, sizeof(from));
07701 of = get_in_brackets(from);
07702 ast_string_field_set(p, from, of);
07703 if (strncasecmp(of, "sip:", 4))
07704 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
07705 else
07706 of += 4;
07707
07708 if ((c = strchr(dest, '@')))
07709 c = NULL;
07710 else if ((c = strchr(of, '@')))
07711 *c++ = '\0';
07712 if (c)
07713 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
07714 else
07715 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
07716
07717
07718 sip_refer_allocate(p);
07719 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
07720 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
07721 p->refer->status = REFER_SENT;
07722
07723 reqprep(&req, p, SIP_REFER, 0, 1);
07724 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
07725
07726 add_header(&req, "Refer-To", referto);
07727 add_header(&req, "Allow", ALLOWED_METHODS);
07728 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
07729 if (!ast_strlen_zero(p->our_contact))
07730 add_header(&req, "Referred-By", p->our_contact);
07731
07732 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07733
07734
07735
07736
07737
07738
07739
07740
07741 }
07742
07743
07744
07745 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
07746 {
07747 struct sip_request req;
07748
07749 reqprep(&req, p, SIP_INFO, 0, 1);
07750 add_digit(&req, digit, duration);
07751 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07752 }
07753
07754
07755 static int transmit_info_with_vidupdate(struct sip_pvt *p)
07756 {
07757 struct sip_request req;
07758
07759 reqprep(&req, p, SIP_INFO, 0, 1);
07760 add_vidupdate(&req);
07761 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07762 }
07763
07764
07765
07766
07767 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
07768 {
07769 struct sip_request resp;
07770
07771 if (sipmethod == SIP_ACK)
07772 p->invitestate = INV_CONFIRMED;
07773
07774 reqprep(&resp, p, sipmethod, seqno, newbranch);
07775 add_header_contentLength(&resp, 0);
07776 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
07777 }
07778
07779
07780 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
07781 {
07782 struct sip_request resp;
07783
07784 reqprep(&resp, p, sipmethod, seqno, newbranch);
07785 if (!ast_strlen_zero(p->realm)) {
07786 char digest[1024];
07787
07788 memset(digest, 0, sizeof(digest));
07789 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
07790 if (p->options && p->options->auth_type == PROXY_AUTH)
07791 add_header(&resp, "Proxy-Authorization", digest);
07792 else if (p->options && p->options->auth_type == WWW_AUTH)
07793 add_header(&resp, "Authorization", digest);
07794 else
07795 add_header(&resp, "Proxy-Authorization", digest);
07796 } else
07797 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
07798 }
07799
07800
07801 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
07802 char buf[10];
07803
07804 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
07805 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
07806 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
07807 }
07808
07809 add_header_contentLength(&resp, 0);
07810 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
07811 }
07812
07813
07814 static void destroy_association(struct sip_peer *peer)
07815 {
07816 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
07817 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
07818 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
07819 else
07820 ast_db_del("SIP/Registry", peer->name);
07821 }
07822 }
07823
07824
07825 static int expire_register(const void *data)
07826 {
07827 struct sip_peer *peer = (struct sip_peer *)data;
07828
07829 if (!peer)
07830 return 0;
07831
07832 memset(&peer->addr, 0, sizeof(peer->addr));
07833
07834 destroy_association(peer);
07835
07836 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
07837 register_peer_exten(peer, FALSE);
07838 peer->expire = -1;
07839 ast_device_state_changed("SIP/%s", peer->name);
07840
07841
07842
07843
07844 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
07845 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
07846 peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
07847 ASTOBJ_UNREF(peer, sip_destroy_peer);
07848 }
07849
07850 return 0;
07851 }
07852
07853
07854 static int sip_poke_peer_s(const void *data)
07855 {
07856 struct sip_peer *peer = (struct sip_peer *)data;
07857
07858 peer->pokeexpire = -1;
07859 sip_poke_peer(peer);
07860 return 0;
07861 }
07862
07863
07864 static void reg_source_db(struct sip_peer *peer)
07865 {
07866 char data[256];
07867 struct in_addr in;
07868 int expiry;
07869 int port;
07870 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
07871
07872 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
07873 return;
07874 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
07875 return;
07876
07877 scan = data;
07878 addr = strsep(&scan, ":");
07879 port_str = strsep(&scan, ":");
07880 expiry_str = strsep(&scan, ":");
07881 username = strsep(&scan, ":");
07882 contact = scan;
07883
07884 if (!inet_aton(addr, &in))
07885 return;
07886
07887 if (port_str)
07888 port = atoi(port_str);
07889 else
07890 return;
07891
07892 if (expiry_str)
07893 expiry = atoi(expiry_str);
07894 else
07895 return;
07896
07897 if (username)
07898 ast_copy_string(peer->username, username, sizeof(peer->username));
07899 if (contact)
07900 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
07901
07902 if (option_debug > 1)
07903 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
07904 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
07905
07906 memset(&peer->addr, 0, sizeof(peer->addr));
07907 peer->addr.sin_family = AF_INET;
07908 peer->addr.sin_addr = in;
07909 peer->addr.sin_port = htons(port);
07910 if (sipsock < 0) {
07911
07912 if (peer->pokeexpire > -1)
07913 ast_sched_del(sched, peer->pokeexpire);
07914 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
07915 } else
07916 sip_poke_peer(peer);
07917 if (peer->expire > -1)
07918 ast_sched_del(sched, peer->expire);
07919 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
07920 register_peer_exten(peer, TRUE);
07921 }
07922
07923
07924 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
07925 {
07926 char contact[BUFSIZ];
07927 char *c;
07928
07929
07930 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
07931 c = get_in_brackets(contact);
07932
07933
07934 ast_string_field_set(pvt, fullcontact, c);
07935
07936
07937 ast_string_field_set(pvt, okcontacturi, c);
07938
07939
07940
07941 return TRUE;
07942 }
07943
07944
07945 static int set_address_from_contact(struct sip_pvt *pvt)
07946 {
07947 struct hostent *hp;
07948 struct ast_hostent ahp;
07949 int port;
07950 char *c, *host, *pt;
07951 char *contact;
07952
07953
07954 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
07955
07956
07957 pvt->sa = pvt->recv;
07958 return 0;
07959 }
07960
07961
07962
07963 contact = ast_strdupa(pvt->fullcontact);
07964
07965
07966 if (strncasecmp(contact, "sip:", 4)) {
07967 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
07968 } else
07969 contact += 4;
07970
07971
07972
07973
07974
07975 host = strchr(contact, '@');
07976 if (!host) {
07977 host = contact;
07978 c = NULL;
07979 } else {
07980 *host++ = '\0';
07981 }
07982 pt = strchr(host, ':');
07983 if (pt) {
07984 *pt++ = '\0';
07985 port = atoi(pt);
07986 } else
07987 port = STANDARD_SIP_PORT;
07988
07989 contact = strsep(&contact, ";");
07990 host = strsep(&host, ";");
07991
07992
07993
07994 hp = ast_gethostbyname(host, &ahp);
07995 if (!hp) {
07996 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
07997 return -1;
07998 }
07999 pvt->sa.sin_family = AF_INET;
08000 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
08001 pvt->sa.sin_port = htons(port);
08002
08003 return 0;
08004 }
08005
08006
08007
08008 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
08009 {
08010 char contact[BUFSIZ];
08011 char data[BUFSIZ];
08012 const char *expires = get_header(req, "Expires");
08013 int expiry = atoi(expires);
08014 char *curi, *n, *pt;
08015 int port;
08016 const char *useragent;
08017 struct hostent *hp;
08018 struct ast_hostent ahp;
08019 struct sockaddr_in oldsin;
08020
08021 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
08022
08023 if (ast_strlen_zero(expires)) {
08024 expires = strcasestr(contact, ";expires=");
08025 if (expires) {
08026
08027 expires = strsep((char **) &expires, ";");
08028 if (sscanf(expires + 9, "%d", &expiry) != 1)
08029 expiry = default_expiry;
08030 } else {
08031
08032 expiry = default_expiry;
08033 }
08034 }
08035
08036
08037 curi = contact;
08038 if (strchr(contact, '<') == NULL)
08039 strsep(&curi, ";");
08040 curi = get_in_brackets(contact);
08041
08042
08043
08044
08045
08046 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
08047
08048 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
08049 pvt->expiry = ast_sched_when(sched, peer->expire);
08050 return PARSE_REGISTER_QUERY;
08051 } else if (!strcasecmp(curi, "*") || !expiry) {
08052
08053 memset(&peer->addr, 0, sizeof(peer->addr));
08054 if (peer->expire > -1)
08055 ast_sched_del(sched, peer->expire);
08056 peer->expire = -1;
08057
08058 destroy_association(peer);
08059
08060 register_peer_exten(peer, 0);
08061 peer->fullcontact[0] = '\0';
08062 peer->useragent[0] = '\0';
08063 peer->sipoptions = 0;
08064 peer->lastms = 0;
08065
08066 if (option_verbose > 2)
08067 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
08068 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
08069 return PARSE_REGISTER_UPDATE;
08070 }
08071
08072
08073 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
08074
08075
08076 ast_string_field_build(pvt, our_contact, "<%s>", curi);
08077
08078
08079 if (strncasecmp(curi, "sip:", 4)) {
08080 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
08081 } else
08082 curi += 4;
08083
08084 curi = strsep(&curi, ";");
08085
08086 n = strchr(curi, '@');
08087 if (!n) {
08088 n = curi;
08089 curi = NULL;
08090 } else
08091 *n++ = '\0';
08092 pt = strchr(n, ':');
08093 if (pt) {
08094 *pt++ = '\0';
08095 port = atoi(pt);
08096 } else
08097 port = STANDARD_SIP_PORT;
08098 oldsin = peer->addr;
08099 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
08100
08101 hp = ast_gethostbyname(n, &ahp);
08102 if (!hp) {
08103 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
08104 return PARSE_REGISTER_FAILED;
08105 }
08106 peer->addr.sin_family = AF_INET;
08107 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
08108 peer->addr.sin_port = htons(port);
08109 } else {
08110
08111
08112 peer->addr = pvt->recv;
08113 }
08114
08115
08116 peer->sipoptions = pvt->sipoptions;
08117
08118 if (curi && ast_strlen_zero(peer->username))
08119 ast_copy_string(peer->username, curi, sizeof(peer->username));
08120
08121 if (peer->expire > -1) {
08122 ast_sched_del(sched, peer->expire);
08123 peer->expire = -1;
08124 }
08125 if (expiry > max_expiry)
08126 expiry = max_expiry;
08127 if (expiry < min_expiry)
08128 expiry = min_expiry;
08129 peer->expire = ast_test_flag(&peer->flags[0], SIP_REALTIME) ? -1 :
08130 ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
08131 pvt->expiry = expiry;
08132 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);
08133 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
08134 ast_db_put("SIP/Registry", peer->name, data);
08135 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
08136
08137
08138 if (inaddrcmp(&peer->addr, &oldsin)) {
08139 sip_poke_peer(peer);
08140 if (option_verbose > 2)
08141 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);
08142 register_peer_exten(peer, 1);
08143 }
08144
08145
08146 useragent = get_header(req, "User-Agent");
08147 if (strcasecmp(useragent, peer->useragent)) {
08148 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
08149 if (option_verbose > 3)
08150 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
08151 }
08152 return PARSE_REGISTER_UPDATE;
08153 }
08154
08155
08156 static void free_old_route(struct sip_route *route)
08157 {
08158 struct sip_route *next;
08159
08160 while (route) {
08161 next = route->next;
08162 free(route);
08163 route = next;
08164 }
08165 }
08166
08167
08168 static void list_route(struct sip_route *route)
08169 {
08170 if (!route)
08171 ast_verbose("list_route: no route\n");
08172 else {
08173 for (;route; route = route->next)
08174 ast_verbose("list_route: hop: <%s>\n", route->hop);
08175 }
08176 }
08177
08178
08179 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
08180 {
08181 struct sip_route *thishop, *head, *tail;
08182 int start = 0;
08183 int len;
08184 const char *rr, *contact, *c;
08185
08186
08187 if (p->route && p->route_persistant) {
08188 if (option_debug)
08189 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
08190 return;
08191 }
08192
08193 if (p->route) {
08194 free_old_route(p->route);
08195 p->route = NULL;
08196 }
08197
08198 p->route_persistant = backwards;
08199
08200
08201
08202
08203
08204
08205 head = NULL;
08206 tail = head;
08207
08208 for (;;) {
08209
08210 rr = __get_header(req, "Record-Route", &start);
08211 if (*rr == '\0')
08212 break;
08213 for (; (rr = strchr(rr, '<')) ; rr += len) {
08214 ++rr;
08215 len = strcspn(rr, ">") + 1;
08216
08217 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
08218
08219 ast_copy_string(thishop->hop, rr, len);
08220 if (option_debug > 1)
08221 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
08222
08223 if (backwards) {
08224
08225 thishop->next = head;
08226 head = thishop;
08227
08228 if (!tail)
08229 tail = thishop;
08230 } else {
08231 thishop->next = NULL;
08232
08233 if (tail)
08234 tail->next = thishop;
08235 else
08236 head = thishop;
08237 tail = thishop;
08238 }
08239 }
08240 }
08241 }
08242
08243
08244 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
08245
08246
08247 contact = get_header(req, "Contact");
08248 if (!ast_strlen_zero(contact)) {
08249 if (option_debug > 1)
08250 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
08251
08252 c = strchr(contact, '<');
08253 if (c) {
08254
08255 ++c;
08256 len = strcspn(c, ">") + 1;
08257 } else {
08258
08259 c = contact;
08260 len = strlen(contact) + 1;
08261 }
08262 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
08263
08264 ast_copy_string(thishop->hop, c, len);
08265 thishop->next = NULL;
08266
08267 if (tail)
08268 tail->next = thishop;
08269 else
08270 head = thishop;
08271 }
08272 }
08273 }
08274
08275
08276 p->route = head;
08277
08278
08279 if (sip_debug_test_pvt(p))
08280 list_route(p->route);
08281 }
08282
08283 AST_THREADSTORAGE(check_auth_buf, check_auth_buf_init);
08284 #define CHECK_AUTH_BUF_INITLEN 256
08285
08286
08287
08288
08289
08290
08291 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
08292 const char *secret, const char *md5secret, int sipmethod,
08293 char *uri, enum xmittype reliable, int ignore)
08294 {
08295 const char *response = "407 Proxy Authentication Required";
08296 const char *reqheader = "Proxy-Authorization";
08297 const char *respheader = "Proxy-Authenticate";
08298 const char *authtoken;
08299 char a1_hash[256];
08300 char resp_hash[256]="";
08301 char tmp[BUFSIZ * 2];
08302 char *c;
08303 int wrongnonce = FALSE;
08304 int good_response;
08305 const char *usednonce = p->randdata;
08306 struct ast_dynamic_str *buf;
08307
08308
08309 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
08310 struct x {
08311 const char *key;
08312 const char *s;
08313 } *i, keys[] = {
08314 [K_RESP] = { "response=", "" },
08315 [K_URI] = { "uri=", "" },
08316 [K_USER] = { "username=", "" },
08317 [K_NONCE] = { "nonce=", "" },
08318 [K_LAST] = { NULL, NULL}
08319 };
08320
08321
08322 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
08323 return AUTH_SUCCESSFUL;
08324 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
08325
08326
08327
08328 response = "401 Unauthorized";
08329 reqheader = "Authorization";
08330 respheader = "WWW-Authenticate";
08331 }
08332 authtoken = get_header(req, reqheader);
08333 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
08334
08335
08336 if (!reliable) {
08337
08338
08339 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
08340
08341 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08342 }
08343 return AUTH_CHALLENGE_SENT;
08344 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
08345
08346 ast_string_field_build(p, randdata, "%08lx", ast_random());
08347 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
08348
08349 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08350 return AUTH_CHALLENGE_SENT;
08351 }
08352
08353
08354
08355
08356
08357
08358 if (!(buf = ast_dynamic_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
08359 return AUTH_SECRET_FAILED;
08360
08361
08362 ast_copy_string(tmp, authtoken, sizeof(tmp));
08363 c = tmp;
08364
08365 while(c && *(c = ast_skip_blanks(c)) ) {
08366 for (i = keys; i->key != NULL; i++) {
08367 const char *separator = ",";
08368
08369 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
08370 continue;
08371
08372 c += strlen(i->key);
08373 if (*c == '"') {
08374 c++;
08375 separator = "\"";
08376 }
08377 i->s = c;
08378 strsep(&c, separator);
08379 break;
08380 }
08381 if (i->key == NULL)
08382 strsep(&c, " ,");
08383 }
08384
08385
08386 if (strcmp(username, keys[K_USER].s)) {
08387 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
08388 username, keys[K_USER].s);
08389
08390 return AUTH_USERNAME_MISMATCH;
08391 }
08392
08393
08394 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
08395 wrongnonce = TRUE;
08396 usednonce = keys[K_NONCE].s;
08397 }
08398
08399 if (!ast_strlen_zero(md5secret))
08400 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
08401 else {
08402 char a1[256];
08403 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
08404 ast_md5_hash(a1_hash, a1);
08405 }
08406
08407
08408 {
08409 char a2[256];
08410 char a2_hash[256];
08411 char resp[256];
08412
08413 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
08414 S_OR(keys[K_URI].s, uri));
08415 ast_md5_hash(a2_hash, a2);
08416 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
08417 ast_md5_hash(resp_hash, resp);
08418 }
08419
08420 good_response = keys[K_RESP].s &&
08421 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
08422 if (wrongnonce) {
08423 ast_string_field_build(p, randdata, "%08lx", ast_random());
08424 if (good_response) {
08425 if (sipdebug)
08426 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
08427
08428 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
08429 } else {
08430
08431 if (sipdebug)
08432 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
08433 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
08434 }
08435
08436
08437 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08438 return AUTH_CHALLENGE_SENT;
08439 }
08440 if (good_response) {
08441 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
08442 return AUTH_SUCCESSFUL;
08443 }
08444
08445
08446
08447
08448
08449
08450 return AUTH_SECRET_FAILED;
08451 }
08452
08453
08454 static void sip_peer_hold(struct sip_pvt *p, int hold)
08455 {
08456 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
08457
08458 if (!peer)
08459 return;
08460
08461
08462 if (hold)
08463 peer->onHold++;
08464 else
08465 peer->onHold--;
08466
08467
08468 ast_device_state_changed("SIP/%s", peer->name);
08469
08470 return;
08471 }
08472
08473
08474
08475
08476 static int cb_extensionstate(char *context, char* exten, int state, void *data, char *cid_num, char *cid_name)
08477 {
08478 struct sip_pvt *p = data;
08479
08480 ast_mutex_lock(&p->lock);
08481
08482 switch(state) {
08483 case AST_EXTENSION_DEACTIVATED:
08484 case AST_EXTENSION_REMOVED:
08485 if (p->autokillid > -1)
08486 sip_cancel_destroy(p);
08487 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08488 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);
08489 p->stateid = -1;
08490 p->subscribed = NONE;
08491 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
08492 break;
08493 default:
08494 p->laststate = state;
08495 break;
08496 }
08497 if (p->subscribed != NONE)
08498 transmit_state_notify(p, state, 1, FALSE);
08499
08500 if (option_verbose > 1)
08501 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->username);
08502
08503 ast_mutex_unlock(&p->lock);
08504
08505 return 0;
08506 }
08507
08508
08509
08510
08511 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
08512 {
08513
08514
08515 const char *response = "407 Proxy Authentication Required";
08516 const char *reqheader = "Proxy-Authorization";
08517 const char *respheader = "Proxy-Authenticate";
08518 const char *authtoken;
08519 struct ast_dynamic_str *buf;
08520 char *c;
08521
08522
08523 enum keys { K_NONCE, K_LAST };
08524 struct x {
08525 const char *key;
08526 const char *s;
08527 } *i, keys[] = {
08528 [K_NONCE] = { "nonce=", "" },
08529 [K_LAST] = { NULL, NULL}
08530 };
08531
08532 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
08533 response = "401 Unauthorized";
08534 reqheader = "Authorization";
08535 respheader = "WWW-Authenticate";
08536 }
08537 authtoken = get_header(req, reqheader);
08538 if (ast_test_flag(req, SIP_PKT_IGNORE) && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
08539
08540
08541 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
08542
08543 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08544 return;
08545 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
08546
08547 ast_string_field_build(p, randdata, "%08lx", ast_random());
08548 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
08549
08550 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08551 return;
08552 }
08553
08554 if (!(buf = ast_dynamic_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
08555 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
08556 return;
08557 }
08558
08559
08560 if (ast_dynamic_str_thread_set(&buf, 0, &check_auth_buf, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
08561 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
08562 return;
08563 }
08564
08565 c = buf->str;
08566
08567 while (c && *(c = ast_skip_blanks(c))) {
08568 for (i = keys; i->key != NULL; i++) {
08569 const char *separator = ",";
08570
08571 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
08572 continue;
08573 }
08574
08575 c += strlen(i->key);
08576 if (*c == '"') {
08577 c++;
08578 separator = "\"";
08579 }
08580 i->s = c;
08581 strsep(&c, separator);
08582 break;
08583 }
08584 if (i->key == NULL) {
08585 strsep(&c, " ,");
08586 }
08587 }
08588
08589
08590 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
08591 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
08592 ast_string_field_build(p, randdata, "%08lx", ast_random());
08593 }
08594 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
08595
08596
08597 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08598 } else {
08599 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
08600 }
08601 }
08602
08603
08604
08605
08606
08607
08608 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
08609 struct sip_request *req, char *uri)
08610 {
08611 enum check_auth_result res = AUTH_NOT_FOUND;
08612 struct sip_peer *peer;
08613 char tmp[256];
08614 char *name, *c;
08615 char *t;
08616 char *domain;
08617
08618
08619 t = uri;
08620 while(*t && (*t > 32) && (*t != ';'))
08621 t++;
08622 *t = '\0';
08623
08624 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
08625 if (pedanticsipchecking)
08626 ast_uri_decode(tmp);
08627
08628 c = get_in_brackets(tmp);
08629 c = strsep(&c, ";");
08630
08631 if (!strncasecmp(c, "sip:", 4)) {
08632 name = c + 4;
08633 } else {
08634 name = c;
08635 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
08636 }
08637
08638
08639 if ((c = strchr(name, '@'))) {
08640 *c++ = '\0';
08641 domain = c;
08642 if ((c = strchr(domain, ':')))
08643 *c = '\0';
08644 if (!AST_LIST_EMPTY(&domain_list)) {
08645 if (!check_sip_domain(domain, NULL, 0)) {
08646 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
08647 return AUTH_UNKNOWN_DOMAIN;
08648 }
08649 }
08650 }
08651
08652 ast_string_field_set(p, exten, name);
08653 build_contact(p);
08654 peer = find_peer(name, NULL, 1);
08655 if (!(peer && ast_apply_ha(peer->ha, sin))) {
08656
08657 if (peer) {
08658 ASTOBJ_UNREF(peer, sip_destroy_peer);
08659 peer = NULL;
08660 res = AUTH_ACL_FAILED;
08661 } else
08662 res = AUTH_NOT_FOUND;
08663 }
08664 if (peer) {
08665
08666 if (p->rtp) {
08667 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
08668 p->autoframing = peer->autoframing;
08669 }
08670 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
08671 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
08672 res = AUTH_PEER_NOT_DYNAMIC;
08673 } else {
08674 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
08675 transmit_response(p, "100 Trying", req);
08676 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
08677 sip_cancel_destroy(p);
08678
08679
08680
08681 switch (parse_register_contact(p, peer, req)) {
08682 case PARSE_REGISTER_FAILED:
08683 ast_log(LOG_WARNING, "Failed to parse contact info\n");
08684 transmit_response_with_date(p, "400 Bad Request", req);
08685 peer->lastmsgssent = -1;
08686 res = 0;
08687 break;
08688 case PARSE_REGISTER_QUERY:
08689 transmit_response_with_date(p, "200 OK", req);
08690 peer->lastmsgssent = -1;
08691 res = 0;
08692 break;
08693 case PARSE_REGISTER_UPDATE:
08694 update_peer(peer, p->expiry);
08695
08696 transmit_response_with_date(p, "200 OK", req);
08697 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
08698 peer->lastmsgssent = -1;
08699 res = 0;
08700 break;
08701 }
08702 }
08703 }
08704 }
08705 if (!peer && autocreatepeer) {
08706
08707 peer = temp_peer(name);
08708 if (peer) {
08709 ASTOBJ_CONTAINER_LINK(&peerl, peer);
08710 sip_cancel_destroy(p);
08711 switch (parse_register_contact(p, peer, req)) {
08712 case PARSE_REGISTER_FAILED:
08713 ast_log(LOG_WARNING, "Failed to parse contact info\n");
08714 transmit_response_with_date(p, "400 Bad Request", req);
08715 peer->lastmsgssent = -1;
08716 res = 0;
08717 break;
08718 case PARSE_REGISTER_QUERY:
08719 transmit_response_with_date(p, "200 OK", req);
08720 peer->lastmsgssent = -1;
08721 res = 0;
08722 break;
08723 case PARSE_REGISTER_UPDATE:
08724
08725 transmit_response_with_date(p, "200 OK", req);
08726 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
08727 peer->lastmsgssent = -1;
08728 res = 0;
08729 break;
08730 }
08731 }
08732 }
08733 if (!peer && global_alwaysauthreject) {
08734
08735
08736
08737 transmit_response(p, "100 Trying", req);
08738
08739 sched_yield();
08740 }
08741 if (!res) {
08742 ast_device_state_changed("SIP/%s", peer->name);
08743 }
08744 if (res < 0) {
08745 switch (res) {
08746 case AUTH_SECRET_FAILED:
08747
08748 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
08749 break;
08750 case AUTH_USERNAME_MISMATCH:
08751
08752
08753
08754
08755 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
08756 break;
08757 case AUTH_NOT_FOUND:
08758 case AUTH_PEER_NOT_DYNAMIC:
08759 case AUTH_ACL_FAILED:
08760 if (global_alwaysauthreject) {
08761 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
08762 } else {
08763
08764 if (res == AUTH_PEER_NOT_DYNAMIC)
08765 transmit_response(p, "403 Forbidden", &p->initreq);
08766 else
08767 transmit_response(p, "404 Not found", &p->initreq);
08768 }
08769 break;
08770 default:
08771 break;
08772 }
08773 }
08774 if (peer)
08775 ASTOBJ_UNREF(peer, sip_destroy_peer);
08776
08777 return res;
08778 }
08779
08780
08781 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
08782 {
08783 char tmp[256], *c, *a;
08784 struct sip_request *req;
08785
08786 req = oreq;
08787 if (!req)
08788 req = &p->initreq;
08789 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
08790 if (ast_strlen_zero(tmp))
08791 return 0;
08792 c = get_in_brackets(tmp);
08793 if (strncasecmp(c, "sip:", 4)) {
08794 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
08795 return -1;
08796 }
08797 c += 4;
08798 a = c;
08799 strsep(&a, "@;");
08800 if (sip_debug_test_pvt(p))
08801 ast_verbose("RDNIS is %s\n", c);
08802 ast_string_field_set(p, rdnis, c);
08803
08804 return 0;
08805 }
08806
08807
08808
08809
08810 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
08811 {
08812 char tmp[256] = "", *uri, *a;
08813 char tmpf[256] = "", *from;
08814 struct sip_request *req;
08815 char *colon;
08816
08817 req = oreq;
08818 if (!req)
08819 req = &p->initreq;
08820
08821
08822 if (req->rlPart2)
08823 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
08824
08825 if (pedanticsipchecking)
08826 ast_uri_decode(tmp);
08827
08828 uri = get_in_brackets(tmp);
08829
08830 if (strncasecmp(uri, "sip:", 4)) {
08831 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
08832 return -1;
08833 }
08834 uri += 4;
08835
08836
08837 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
08838 if (!ast_strlen_zero(tmpf)) {
08839 if (pedanticsipchecking)
08840 ast_uri_decode(tmpf);
08841 from = get_in_brackets(tmpf);
08842 } else {
08843 from = NULL;
08844 }
08845
08846 if (!ast_strlen_zero(from)) {
08847 if (strncasecmp(from, "sip:", 4)) {
08848 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
08849 return -1;
08850 }
08851 from += 4;
08852 if ((a = strchr(from, '@')))
08853 *a++ = '\0';
08854 else
08855 a = from;
08856 from = strsep(&from, ";");
08857 a = strsep(&a, ";");
08858 ast_string_field_set(p, fromdomain, a);
08859 }
08860
08861
08862
08863
08864 if ((a = strchr(uri, '@'))) {
08865 *a++ = '\0';
08866 } else {
08867 a = uri;
08868 uri = "s";
08869 }
08870 colon = strchr(a, ':');
08871 if (colon)
08872 *colon = '\0';
08873
08874 uri = strsep(&uri, ";");
08875 a = strsep(&a, ";");
08876
08877 ast_string_field_set(p, domain, a);
08878
08879 if (!AST_LIST_EMPTY(&domain_list)) {
08880 char domain_context[AST_MAX_EXTENSION];
08881
08882 domain_context[0] = '\0';
08883 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
08884 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
08885 if (option_debug)
08886 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
08887 return -2;
08888 }
08889 }
08890
08891 if (!ast_strlen_zero(domain_context))
08892 ast_string_field_set(p, context, domain_context);
08893 }
08894
08895
08896 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
08897 ast_string_field_set(p, context, p->subscribecontext);
08898
08899 if (sip_debug_test_pvt(p))
08900 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
08901
08902
08903 if (req->method == SIP_SUBSCRIBE) {
08904 char hint[AST_MAX_EXTENSION];
08905 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
08906 } else {
08907
08908
08909
08910
08911
08912 char *decoded_uri = ast_strdupa(uri);
08913 ast_uri_decode(decoded_uri);
08914 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)) ||
08915 !strcmp(uri, ast_pickup_ext())) {
08916 if (!oreq)
08917 ast_string_field_set(p, exten, uri);
08918 return 0;
08919 }
08920 }
08921
08922
08923 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
08924 ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) ||
08925 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
08926 return 1;
08927 }
08928
08929 return -1;
08930 }
08931
08932
08933
08934
08935
08936
08937 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
08938 {
08939 struct sip_pvt *sip_pvt_ptr;
08940
08941 ast_mutex_lock(&iflock);
08942
08943 if (option_debug > 3 && totag)
08944 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
08945
08946
08947 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
08948 if (!strcmp(sip_pvt_ptr->callid, callid)) {
08949 int match = 1;
08950 char *ourtag = sip_pvt_ptr->tag;
08951
08952
08953 ast_mutex_lock(&sip_pvt_ptr->lock);
08954
08955
08956
08957
08958
08959 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || (!ast_strlen_zero(totag) && strcmp(totag, ourtag))))
08960 match = 0;
08961
08962 if (!match) {
08963 ast_mutex_unlock(&sip_pvt_ptr->lock);
08964 continue;
08965 }
08966
08967 if (option_debug > 3 && totag)
08968 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
08969 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
08970 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
08971
08972
08973 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
08974 ast_mutex_unlock(&sip_pvt_ptr->lock);
08975 usleep(1);
08976 ast_mutex_lock(&sip_pvt_ptr->lock);
08977 }
08978 break;
08979 }
08980 }
08981 ast_mutex_unlock(&iflock);
08982 if (option_debug > 3 && !sip_pvt_ptr)
08983 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
08984 return sip_pvt_ptr;
08985 }
08986
08987
08988
08989 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
08990 {
08991
08992 const char *p_referred_by = NULL;
08993 char *h_refer_to = NULL;
08994 char *h_referred_by = NULL;
08995 char *refer_to;
08996 const char *p_refer_to;
08997 char *referred_by_uri = NULL;
08998 char *ptr;
08999 struct sip_request *req = NULL;
09000 const char *transfer_context = NULL;
09001 struct sip_refer *referdata;
09002
09003
09004 req = outgoing_req;
09005 referdata = transferer->refer;
09006
09007 if (!req)
09008 req = &transferer->initreq;
09009
09010 p_refer_to = get_header(req, "Refer-To");
09011 if (ast_strlen_zero(p_refer_to)) {
09012 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
09013 return -2;
09014 }
09015 h_refer_to = ast_strdupa(p_refer_to);
09016 refer_to = get_in_brackets(h_refer_to);
09017 if (pedanticsipchecking)
09018 ast_uri_decode(refer_to);
09019
09020 if (strncasecmp(refer_to, "sip:", 4)) {
09021 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
09022 return -3;
09023 }
09024 refer_to += 4;
09025
09026
09027 p_referred_by = get_header(req, "Referred-By");
09028 if (!ast_strlen_zero(p_referred_by)) {
09029 char *lessthan;
09030 h_referred_by = ast_strdupa(p_referred_by);
09031 if (pedanticsipchecking)
09032 ast_uri_decode(h_referred_by);
09033
09034
09035 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
09036 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
09037 *(lessthan - 1) = '\0';
09038 }
09039
09040 referred_by_uri = get_in_brackets(h_referred_by);
09041 if(strncasecmp(referred_by_uri, "sip:", 4)) {
09042 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
09043 referred_by_uri = (char *) NULL;
09044 } else {
09045 referred_by_uri += 4;
09046 }
09047 }
09048
09049
09050 if ((ptr = strchr(refer_to, '?'))) {
09051 *ptr++ = '\0';
09052 if (!strncasecmp(ptr, "REPLACES=", 9)) {
09053 char *to = NULL, *from = NULL;
09054
09055
09056 referdata->attendedtransfer = 1;
09057 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
09058 ast_uri_decode(referdata->replaces_callid);
09059 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
09060 *ptr++ = '\0';
09061 }
09062
09063 if (ptr) {
09064
09065 to = strcasestr(ptr, "to-tag=");
09066 from = strcasestr(ptr, "from-tag=");
09067 }
09068
09069
09070 if (to) {
09071 ptr = to + 7;
09072 if ((to = strchr(ptr, '&')))
09073 *to = '\0';
09074 if ((to = strchr(ptr, ';')))
09075 *to = '\0';
09076 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
09077 }
09078
09079 if (from) {
09080 ptr = from + 9;
09081 if ((to = strchr(ptr, '&')))
09082 *to = '\0';
09083 if ((to = strchr(ptr, ';')))
09084 *to = '\0';
09085 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
09086 }
09087
09088 if (option_debug > 1) {
09089 if (!pedanticsipchecking)
09090 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
09091 else
09092 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>" );
09093 }
09094 }
09095 }
09096
09097 if ((ptr = strchr(refer_to, '@'))) {
09098 char *urioption = NULL, *domain;
09099 *ptr++ = '\0';
09100
09101 if ((urioption = strchr(ptr, ';')))
09102 *urioption++ = '\0';
09103
09104 domain = ptr;
09105 if ((ptr = strchr(domain, ':')))
09106 *ptr = '\0';
09107
09108
09109 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
09110 if (urioption)
09111 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
09112 }
09113
09114 if ((ptr = strchr(refer_to, ';')))
09115 *ptr = '\0';
09116 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
09117
09118 if (referred_by_uri) {
09119 if ((ptr = strchr(referred_by_uri, ';')))
09120 *ptr = '\0';
09121 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
09122 } else {
09123 referdata->referred_by[0] = '\0';
09124 }
09125
09126
09127 if (transferer->owner)
09128 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
09129
09130
09131 if (ast_strlen_zero(transfer_context)) {
09132 transfer_context = S_OR(transferer->owner->macrocontext,
09133 S_OR(transferer->context, default_context));
09134 }
09135
09136 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
09137
09138
09139 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
09140 if (sip_debug_test_pvt(transferer)) {
09141 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
09142 }
09143
09144 return 0;
09145 }
09146 if (sip_debug_test_pvt(transferer))
09147 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
09148
09149
09150 return -1;
09151 }
09152
09153
09154
09155 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
09156 {
09157 char tmp[256] = "", *c, *a;
09158 struct sip_request *req = oreq ? oreq : &p->initreq;
09159 struct sip_refer *referdata = NULL;
09160 const char *transfer_context = NULL;
09161
09162 if (!p->refer && !sip_refer_allocate(p))
09163 return -1;
09164
09165 referdata = p->refer;
09166
09167 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
09168 c = get_in_brackets(tmp);
09169
09170 if (pedanticsipchecking)
09171 ast_uri_decode(c);
09172
09173 if (strncasecmp(c, "sip:", 4)) {
09174 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
09175 return -1;
09176 }
09177 c += 4;
09178 if ((a = strchr(c, ';')))
09179 *a = '\0';
09180
09181 if ((a = strchr(c, '@'))) {
09182 *a++ = '\0';
09183 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
09184 }
09185
09186 if (sip_debug_test_pvt(p))
09187 ast_verbose("Looking for %s in %s\n", c, p->context);
09188
09189 if (p->owner)
09190 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
09191
09192
09193 if (ast_strlen_zero(transfer_context)) {
09194 transfer_context = S_OR(p->owner->macrocontext,
09195 S_OR(p->context, default_context));
09196 }
09197 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
09198
09199 if (option_debug)
09200 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
09201 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
09202 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
09203 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
09204 referdata->refer_call = NULL;
09205
09206 ast_string_field_set(p, context, transfer_context);
09207 return 0;
09208 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
09209 return 1;
09210 }
09211
09212 return -1;
09213 }
09214
09215 static void check_via(struct sip_pvt *p, struct sip_request *req)
09216 {
09217 char via[256];
09218 char *c, *pt;
09219 struct hostent *hp;
09220 struct ast_hostent ahp;
09221
09222 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
09223
09224
09225 c = strchr(via, ',');
09226 if (c)
09227 *c = '\0';
09228
09229
09230 c = strstr(via, ";rport");
09231 if (c && (c[6] != '='))
09232 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
09233
09234 c = strchr(via, ';');
09235 if (c)
09236 *c = '\0';
09237
09238 c = strchr(via, ' ');
09239 if (c) {
09240 *c = '\0';
09241 c = ast_skip_blanks(c+1);
09242 if (strcasecmp(via, "SIP/2.0/UDP")) {
09243 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
09244 return;
09245 }
09246 pt = strchr(c, ':');
09247 if (pt)
09248 *pt++ = '\0';
09249 hp = ast_gethostbyname(c, &ahp);
09250 if (!hp) {
09251 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
09252 return;
09253 }
09254 memset(&p->sa, 0, sizeof(p->sa));
09255 p->sa.sin_family = AF_INET;
09256 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09257 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
09258
09259 if (sip_debug_test_pvt(p)) {
09260 const struct sockaddr_in *dst = sip_real_dst(p);
09261 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
09262 }
09263 }
09264 }
09265
09266
09267 static char *get_calleridname(const char *input, char *output, size_t outputsize)
09268 {
09269 const char *end = strchr(input,'<');
09270 const char *tmp = strchr(input,'"');
09271 int bytes = 0;
09272 int maxbytes = outputsize - 1;
09273
09274 if (!end || end == input)
09275 return NULL;
09276
09277 end--;
09278
09279 if (tmp && tmp <= end) {
09280
09281
09282
09283 end = strchr(tmp+1, '"');
09284 if (!end)
09285 return NULL;
09286 bytes = (int) (end - tmp);
09287
09288 if (bytes > maxbytes)
09289 bytes = maxbytes;
09290 ast_copy_string(output, tmp + 1, bytes);
09291 } else {
09292
09293
09294 input = ast_skip_blanks(input);
09295
09296 while(*end && *end < 33 && end > input)
09297 end--;
09298 if (end >= input) {
09299 bytes = (int) (end - input) + 2;
09300
09301 if (bytes > maxbytes)
09302 bytes = maxbytes;
09303 ast_copy_string(output, input, bytes);
09304 } else
09305 return NULL;
09306 }
09307 return output;
09308 }
09309
09310
09311
09312
09313
09314 static int get_rpid_num(const char *input, char *output, int maxlen)
09315 {
09316 char *start;
09317 char *end;
09318
09319 start = strchr(input,':');
09320 if (!start) {
09321 output[0] = '\0';
09322 return 0;
09323 }
09324 start++;
09325
09326
09327 ast_copy_string(output,start,maxlen);
09328 output[maxlen-1] = '\0';
09329
09330 end = strchr(output,'@');
09331 if (end)
09332 *end = '\0';
09333 else
09334 output[0] = '\0';
09335 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
09336 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
09337
09338 return 0;
09339 }
09340
09341
09342
09343
09344
09345
09346
09347 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
09348 int sipmethod, char *uri, enum xmittype reliable,
09349 struct sockaddr_in *sin, struct sip_peer **authpeer)
09350 {
09351 struct sip_user *user = NULL;
09352 struct sip_peer *peer;
09353 char from[256], *c;
09354 char *of;
09355 char rpid_num[50];
09356 const char *rpid;
09357 enum check_auth_result res = AUTH_SUCCESSFUL;
09358 char *t;
09359 char calleridname[50];
09360 int debug=sip_debug_test_addr(sin);
09361 struct ast_variable *tmpvar = NULL, *v = NULL;
09362 char *uri2 = ast_strdupa(uri);
09363
09364
09365 t = uri2;
09366 while (*t && *t > 32 && *t != ';')
09367 t++;
09368 *t = '\0';
09369 ast_copy_string(from, get_header(req, "From"), sizeof(from));
09370 if (pedanticsipchecking)
09371 ast_uri_decode(from);
09372
09373 memset(calleridname, 0, sizeof(calleridname));
09374 get_calleridname(from, calleridname, sizeof(calleridname));
09375 if (calleridname[0])
09376 ast_string_field_set(p, cid_name, calleridname);
09377
09378 rpid = get_header(req, "Remote-Party-ID");
09379 memset(rpid_num, 0, sizeof(rpid_num));
09380 if (!ast_strlen_zero(rpid))
09381 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
09382
09383 of = get_in_brackets(from);
09384 if (ast_strlen_zero(p->exten)) {
09385 t = uri2;
09386 if (!strncasecmp(t, "sip:", 4))
09387 t+= 4;
09388 ast_string_field_set(p, exten, t);
09389 t = strchr(p->exten, '@');
09390 if (t)
09391 *t = '\0';
09392 if (ast_strlen_zero(p->our_contact))
09393 build_contact(p);
09394 }
09395
09396 ast_string_field_set(p, from, of);
09397 if (strncasecmp(of, "sip:", 4)) {
09398 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
09399 } else
09400 of += 4;
09401
09402 if ((c = strchr(of, '@'))) {
09403 char *tmp;
09404 *c = '\0';
09405 if ((c = strchr(of, ':')))
09406 *c = '\0';
09407 tmp = ast_strdupa(of);
09408
09409
09410
09411 tmp = strsep(&tmp, ";");
09412 if (ast_is_shrinkable_phonenumber(tmp))
09413 ast_shrink_phone_number(tmp);
09414 ast_string_field_set(p, cid_num, tmp);
09415 }
09416
09417 if (!authpeer)
09418 user = find_user(of, 1);
09419
09420
09421 if (user && ast_apply_ha(user->ha, sin)) {
09422 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
09423 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09424
09425 for (v = user->chanvars ; v ; v = v->next) {
09426 if ((tmpvar = ast_variable_new(v->name, v->value))) {
09427 tmpvar->next = p->chanvars;
09428 p->chanvars = tmpvar;
09429 }
09430 }
09431 p->prefs = user->prefs;
09432
09433 if (p->rtp) {
09434 ast_rtp_codec_setpref(p->rtp, &p->prefs);
09435 p->autoframing = user->autoframing;
09436 }
09437
09438 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
09439 char *tmp;
09440 if (*calleridname)
09441 ast_string_field_set(p, cid_name, calleridname);
09442 tmp = ast_strdupa(rpid_num);
09443 if (ast_is_shrinkable_phonenumber(tmp))
09444 ast_shrink_phone_number(tmp);
09445 ast_string_field_set(p, cid_num, tmp);
09446 }
09447
09448 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
09449
09450 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
09451 sip_cancel_destroy(p);
09452 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
09453 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09454
09455 if (p->sipoptions)
09456 user->sipoptions = p->sipoptions;
09457
09458
09459 if (user->call_limit)
09460 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
09461 if (!ast_strlen_zero(user->context))
09462 ast_string_field_set(p, context, user->context);
09463 if (!ast_strlen_zero(user->cid_num) && !ast_strlen_zero(p->cid_num)) {
09464 char *tmp = ast_strdupa(user->cid_num);
09465 if (ast_is_shrinkable_phonenumber(tmp))
09466 ast_shrink_phone_number(tmp);
09467 ast_string_field_set(p, cid_num, tmp);
09468 }
09469 if (!ast_strlen_zero(user->cid_name) && !ast_strlen_zero(p->cid_num))
09470 ast_string_field_set(p, cid_name, user->cid_name);
09471 ast_string_field_set(p, username, user->name);
09472 ast_string_field_set(p, peername, user->name);
09473 ast_string_field_set(p, peersecret, user->secret);
09474 ast_string_field_set(p, peermd5secret, user->md5secret);
09475 ast_string_field_set(p, subscribecontext, user->subscribecontext);
09476 ast_string_field_set(p, accountcode, user->accountcode);
09477 ast_string_field_set(p, language, user->language);
09478 ast_string_field_set(p, mohsuggest, user->mohsuggest);
09479 ast_string_field_set(p, mohinterpret, user->mohinterpret);
09480 p->allowtransfer = user->allowtransfer;
09481 p->amaflags = user->amaflags;
09482 p->callgroup = user->callgroup;
09483 p->pickupgroup = user->pickupgroup;
09484 if (user->callingpres)
09485 p->callingpres = user->callingpres;
09486
09487
09488 p->capability = user->capability;
09489 p->jointcapability = user->capability;
09490 if (p->peercapability)
09491 p->jointcapability &= p->peercapability;
09492 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
09493 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
09494 p->noncodeccapability |= AST_RTP_DTMF;
09495 else
09496 p->noncodeccapability &= ~AST_RTP_DTMF;
09497 p->jointnoncodeccapability = p->noncodeccapability;
09498 if (p->t38.peercapability)
09499 p->t38.jointcapability &= p->t38.peercapability;
09500 p->maxcallbitrate = user->maxcallbitrate;
09501
09502 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
09503 ast_rtp_destroy(p->vrtp);
09504 p->vrtp = NULL;
09505 }
09506 }
09507 if (user && debug)
09508 ast_verbose("Found user '%s'\n", user->name);
09509 } else {
09510 if (user) {
09511 if (!authpeer && debug)
09512 ast_verbose("Found user '%s', but fails host access\n", user->name);
09513 ASTOBJ_UNREF(user,sip_destroy_user);
09514 }
09515 user = NULL;
09516 }
09517
09518 if (!user) {
09519
09520 if (sipmethod == SIP_SUBSCRIBE)
09521
09522 peer = find_peer(of, NULL, 1);
09523 else
09524
09525
09526
09527
09528 peer = find_peer(NULL, &p->recv, 1);
09529
09530 if (peer) {
09531
09532 if (p->rtp) {
09533 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
09534 p->autoframing = peer->autoframing;
09535 }
09536 if (debug)
09537 ast_verbose("Found peer '%s'\n", peer->name);
09538
09539
09540 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
09541 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09542
09543
09544 if (p->sipoptions)
09545 peer->sipoptions = p->sipoptions;
09546
09547
09548 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
09549 char *tmp = ast_strdupa(rpid_num);
09550 if (*calleridname)
09551 ast_string_field_set(p, cid_name, calleridname);
09552 if (ast_is_shrinkable_phonenumber(tmp))
09553 ast_shrink_phone_number(tmp);
09554 ast_string_field_set(p, cid_num, tmp);
09555 }
09556 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
09557
09558 ast_string_field_set(p, peersecret, peer->secret);
09559 ast_string_field_set(p, peermd5secret, peer->md5secret);
09560 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
09561 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
09562 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
09563 if (peer->callingpres)
09564 p->callingpres = peer->callingpres;
09565 if (peer->maxms && peer->lastms)
09566 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
09567 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
09568
09569 ast_string_field_free(p, peersecret);
09570 ast_string_field_free(p, peermd5secret);
09571 }
09572 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
09573 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
09574 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09575
09576 if (peer->call_limit)
09577 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
09578 ast_string_field_set(p, peername, peer->name);
09579 ast_string_field_set(p, authname, peer->name);
09580
09581
09582 for (v = peer->chanvars ; v ; v = v->next) {
09583 if ((tmpvar = ast_variable_new(v->name, v->value))) {
09584 tmpvar->next = p->chanvars;
09585 p->chanvars = tmpvar;
09586 }
09587 }
09588 if (authpeer) {
09589 (*authpeer) = ASTOBJ_REF(peer);
09590 }
09591
09592 if (!ast_strlen_zero(peer->username)) {
09593 ast_string_field_set(p, username, peer->username);
09594
09595
09596 ast_string_field_set(p, authname, peer->username);
09597 }
09598 if (!ast_strlen_zero(peer->cid_num) && !ast_strlen_zero(p->cid_num)) {
09599 char *tmp = ast_strdupa(peer->cid_num);
09600 if (ast_is_shrinkable_phonenumber(tmp))
09601 ast_shrink_phone_number(tmp);
09602 ast_string_field_set(p, cid_num, tmp);
09603 }
09604 if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name))
09605 ast_string_field_set(p, cid_name, peer->cid_name);
09606 ast_string_field_set(p, fullcontact, peer->fullcontact);
09607 if (!ast_strlen_zero(peer->context))
09608 ast_string_field_set(p, context, peer->context);
09609 ast_string_field_set(p, peersecret, peer->secret);
09610 ast_string_field_set(p, peermd5secret, peer->md5secret);
09611 ast_string_field_set(p, language, peer->language);
09612 ast_string_field_set(p, accountcode, peer->accountcode);
09613 p->amaflags = peer->amaflags;
09614 p->callgroup = peer->callgroup;
09615 p->pickupgroup = peer->pickupgroup;
09616 p->capability = peer->capability;
09617 p->prefs = peer->prefs;
09618 p->jointcapability = peer->capability;
09619 if (p->peercapability)
09620 p->jointcapability &= p->peercapability;
09621 p->maxcallbitrate = peer->maxcallbitrate;
09622 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
09623 ast_rtp_destroy(p->vrtp);
09624 p->vrtp = NULL;
09625 }
09626 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
09627 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
09628 p->noncodeccapability |= AST_RTP_DTMF;
09629 else
09630 p->noncodeccapability &= ~AST_RTP_DTMF;
09631 p->jointnoncodeccapability = p->noncodeccapability;
09632 if (p->t38.peercapability)
09633 p->t38.jointcapability &= p->t38.peercapability;
09634 }
09635 ASTOBJ_UNREF(peer, sip_destroy_peer);
09636 } else {
09637 if (debug)
09638 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
09639
09640
09641 if (!global_allowguest) {
09642 if (global_alwaysauthreject)
09643 res = AUTH_FAKE_AUTH;
09644 else
09645 res = AUTH_SECRET_FAILED;
09646 } else if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
09647 char *tmp = ast_strdupa(rpid_num);
09648 if (*calleridname)
09649 ast_string_field_set(p, cid_name, calleridname);
09650 if (ast_is_shrinkable_phonenumber(tmp))
09651 ast_shrink_phone_number(tmp);
09652 ast_string_field_set(p, cid_num, tmp);
09653 }
09654 }
09655
09656 }
09657
09658 if (user)
09659 ASTOBJ_UNREF(user, sip_destroy_user);
09660 return res;
09661 }
09662
09663
09664
09665
09666 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
09667 {
09668 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
09669 }
09670
09671
09672 static int get_msg_text(char *buf, int len, struct sip_request *req)
09673 {
09674 int x;
09675 int y;
09676
09677 buf[0] = '\0';
09678 y = len - strlen(buf) - 5;
09679 if (y < 0)
09680 y = 0;
09681 for (x=0;x<req->lines;x++) {
09682 strncat(buf, req->line[x], y);
09683 y -= strlen(req->line[x]) + 1;
09684 if (y < 0)
09685 y = 0;
09686 if (y != 0)
09687 strcat(buf, "\n");
09688 }
09689 return 0;
09690 }
09691
09692
09693
09694
09695
09696 static void receive_message(struct sip_pvt *p, struct sip_request *req)
09697 {
09698 char buf[1024];
09699 struct ast_frame f;
09700 const char *content_type = get_header(req, "Content-Type");
09701
09702 if (strcmp(content_type, "text/plain")) {
09703 transmit_response(p, "415 Unsupported Media Type", req);
09704 if (!p->owner)
09705 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09706 return;
09707 }
09708
09709 if (get_msg_text(buf, sizeof(buf), req)) {
09710 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
09711 transmit_response(p, "202 Accepted", req);
09712 if (!p->owner)
09713 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09714 return;
09715 }
09716
09717 if (p->owner) {
09718 if (sip_debug_test_pvt(p))
09719 ast_verbose("Message received: '%s'\n", buf);
09720 memset(&f, 0, sizeof(f));
09721 f.frametype = AST_FRAME_TEXT;
09722 f.subclass = 0;
09723 f.offset = 0;
09724 f.data = buf;
09725 f.datalen = strlen(buf);
09726 ast_queue_frame(p->owner, &f);
09727 transmit_response(p, "202 Accepted", req);
09728 } else {
09729 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);
09730 transmit_response(p, "405 Method Not Allowed", req);
09731 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09732 }
09733 return;
09734 }
09735
09736
09737 static int sip_show_inuse(int fd, int argc, char *argv[])
09738 {
09739 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
09740 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
09741 char ilimits[40];
09742 char iused[40];
09743 int showall = FALSE;
09744
09745 if (argc < 3)
09746 return RESULT_SHOWUSAGE;
09747
09748 if (argc == 4 && !strcmp(argv[3],"all"))
09749 showall = TRUE;
09750
09751 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
09752 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
09753 ASTOBJ_RDLOCK(iterator);
09754 if (iterator->call_limit)
09755 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
09756 else
09757 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
09758 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
09759 if (showall || iterator->call_limit)
09760 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
09761 ASTOBJ_UNLOCK(iterator);
09762 } while (0) );
09763
09764 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
09765
09766 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
09767 ASTOBJ_RDLOCK(iterator);
09768 if (iterator->call_limit)
09769 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
09770 else
09771 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
09772 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
09773 if (showall || iterator->call_limit)
09774 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
09775 ASTOBJ_UNLOCK(iterator);
09776 } while (0) );
09777
09778 return RESULT_SUCCESS;
09779 #undef FORMAT
09780 #undef FORMAT2
09781 }
09782
09783
09784 static char *transfermode2str(enum transfermodes mode)
09785 {
09786 if (mode == TRANSFER_OPENFORALL)
09787 return "open";
09788 else if (mode == TRANSFER_CLOSED)
09789 return "closed";
09790 return "strict";
09791 }
09792
09793
09794 static char *nat2str(int nat)
09795 {
09796 switch(nat) {
09797 case SIP_NAT_NEVER:
09798 return "No";
09799 case SIP_NAT_ROUTE:
09800 return "Route";
09801 case SIP_NAT_ALWAYS:
09802 return "Always";
09803 case SIP_NAT_RFC3581:
09804 return "RFC3581";
09805 default:
09806 return "Unknown";
09807 }
09808 }
09809
09810
09811
09812
09813 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
09814 {
09815 int res = 0;
09816 if (peer->maxms) {
09817 if (peer->lastms < 0) {
09818 ast_copy_string(status, "UNREACHABLE", statuslen);
09819 } else if (peer->lastms > peer->maxms) {
09820 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
09821 res = 1;
09822 } else if (peer->lastms) {
09823 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
09824 res = 1;
09825 } else {
09826 ast_copy_string(status, "UNKNOWN", statuslen);
09827 }
09828 } else {
09829 ast_copy_string(status, "Unmonitored", statuslen);
09830
09831 res = -1;
09832 }
09833 return res;
09834 }
09835
09836
09837 static int sip_show_users(int fd, int argc, char *argv[])
09838 {
09839 regex_t regexbuf;
09840 int havepattern = FALSE;
09841
09842 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
09843
09844 switch (argc) {
09845 case 5:
09846 if (!strcasecmp(argv[3], "like")) {
09847 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
09848 return RESULT_SHOWUSAGE;
09849 havepattern = TRUE;
09850 } else
09851 return RESULT_SHOWUSAGE;
09852 case 3:
09853 break;
09854 default:
09855 return RESULT_SHOWUSAGE;
09856 }
09857
09858 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
09859 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
09860 ASTOBJ_RDLOCK(iterator);
09861
09862 if (havepattern && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
09863 ASTOBJ_UNLOCK(iterator);
09864 continue;
09865 }
09866
09867 ast_cli(fd, FORMAT, iterator->name,
09868 iterator->secret,
09869 iterator->accountcode,
09870 iterator->context,
09871 iterator->ha ? "Yes" : "No",
09872 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
09873 ASTOBJ_UNLOCK(iterator);
09874 } while (0)
09875 );
09876
09877 if (havepattern)
09878 regfree(®exbuf);
09879
09880 return RESULT_SUCCESS;
09881 #undef FORMAT
09882 }
09883
09884 static char mandescr_show_peers[] =
09885 "Description: Lists SIP peers in text format with details on current status.\n"
09886 "Variables: \n"
09887 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
09888
09889
09890
09891 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
09892 {
09893 const char *id = astman_get_header(m,"ActionID");
09894 const char *a[] = {"sip", "show", "peers"};
09895 char idtext[256] = "";
09896 int total = 0;
09897
09898 if (!ast_strlen_zero(id))
09899 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
09900
09901 astman_send_ack(s, m, "Peer status list will follow");
09902
09903 _sip_show_peers(-1, &total, s, m, 3, a);
09904
09905 astman_append(s,
09906 "Event: PeerlistComplete\r\n"
09907 "ListItems: %d\r\n"
09908 "%s"
09909 "\r\n", total, idtext);
09910 return 0;
09911 }
09912
09913
09914 static int sip_show_peers(int fd, int argc, char *argv[])
09915 {
09916 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
09917 }
09918
09919
09920 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
09921 {
09922 regex_t regexbuf;
09923 int havepattern = FALSE;
09924
09925 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
09926 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
09927
09928 char name[256];
09929 int total_peers = 0;
09930 int peers_mon_online = 0;
09931 int peers_mon_offline = 0;
09932 int peers_unmon_offline = 0;
09933 int peers_unmon_online = 0;
09934 const char *id;
09935 char idtext[256] = "";
09936 int realtimepeers;
09937
09938 realtimepeers = ast_check_realtime("sippeers");
09939
09940 if (s) {
09941 id = astman_get_header(m,"ActionID");
09942 if (!ast_strlen_zero(id))
09943 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
09944 }
09945
09946 switch (argc) {
09947 case 5:
09948 if (!strcasecmp(argv[3], "like")) {
09949 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
09950 return RESULT_SHOWUSAGE;
09951 havepattern = TRUE;
09952 } else
09953 return RESULT_SHOWUSAGE;
09954 case 3:
09955 break;
09956 default:
09957 return RESULT_SHOWUSAGE;
09958 }
09959
09960 if (!s)
09961 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
09962
09963 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
09964 char status[20] = "";
09965 char srch[2000];
09966 char pstatus;
09967
09968 ASTOBJ_RDLOCK(iterator);
09969
09970 if (havepattern && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
09971 ASTOBJ_UNLOCK(iterator);
09972 continue;
09973 }
09974
09975 if (!ast_strlen_zero(iterator->username) && !s)
09976 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
09977 else
09978 ast_copy_string(name, iterator->name, sizeof(name));
09979
09980 pstatus = peer_status(iterator, status, sizeof(status));
09981 if (pstatus == 1)
09982 peers_mon_online++;
09983 else if (pstatus == 0)
09984 peers_mon_offline++;
09985 else {
09986 if (iterator->addr.sin_port == 0)
09987 peers_unmon_offline++;
09988 else
09989 peers_unmon_online++;
09990 }
09991
09992 snprintf(srch, sizeof(srch), FORMAT, name,
09993 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
09994 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ",
09995 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
09996 iterator->ha ? " A " : " ",
09997 ntohs(iterator->addr.sin_port), status,
09998 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
09999
10000 if (!s) {
10001 ast_cli(fd, FORMAT, name,
10002 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
10003 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ",
10004 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
10005 iterator->ha ? " A " : " ",
10006
10007 ntohs(iterator->addr.sin_port), status,
10008 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
10009 } else {
10010
10011 astman_append(s,
10012 "Event: PeerEntry\r\n%s"
10013 "Channeltype: SIP\r\n"
10014 "ObjectName: %s\r\n"
10015 "ChanObjectType: peer\r\n"
10016 "IPaddress: %s\r\n"
10017 "IPport: %d\r\n"
10018 "Dynamic: %s\r\n"
10019 "Natsupport: %s\r\n"
10020 "VideoSupport: %s\r\n"
10021 "ACL: %s\r\n"
10022 "Status: %s\r\n"
10023 "RealtimeDevice: %s\r\n\r\n",
10024 idtext,
10025 iterator->name,
10026 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
10027 ntohs(iterator->addr.sin_port),
10028 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no",
10029 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
10030 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
10031 iterator->ha ? "yes" : "no",
10032 status,
10033 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
10034 }
10035
10036 ASTOBJ_UNLOCK(iterator);
10037
10038 total_peers++;
10039 } while(0) );
10040
10041 if (!s)
10042 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
10043 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
10044
10045 if (havepattern)
10046 regfree(®exbuf);
10047
10048 if (total)
10049 *total = total_peers;
10050
10051
10052 return RESULT_SUCCESS;
10053 #undef FORMAT
10054 #undef FORMAT2
10055 }
10056
10057
10058 static int sip_show_objects(int fd, int argc, char *argv[])
10059 {
10060 char tmp[256];
10061 if (argc != 3)
10062 return RESULT_SHOWUSAGE;
10063 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
10064 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
10065 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
10066 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
10067 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
10068 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), ®l);
10069 return RESULT_SUCCESS;
10070 }
10071
10072 static void print_group(int fd, ast_group_t group, int crlf)
10073 {
10074 char buf[256];
10075 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
10076 }
10077
10078
10079 static const char *dtmfmode2str(int mode)
10080 {
10081 switch (mode) {
10082 case SIP_DTMF_RFC2833:
10083 return "rfc2833";
10084 case SIP_DTMF_INFO:
10085 return "info";
10086 case SIP_DTMF_INBAND:
10087 return "inband";
10088 case SIP_DTMF_AUTO:
10089 return "auto";
10090 }
10091 return "<error>";
10092 }
10093
10094
10095 static const char *insecure2str(int port, int invite)
10096 {
10097 if (port && invite)
10098 return "port,invite";
10099 else if (port)
10100 return "port";
10101 else if (invite)
10102 return "invite";
10103 else
10104 return "no";
10105 }
10106
10107
10108
10109
10110 static void cleanup_stale_contexts(char *new, char *old)
10111 {
10112 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
10113
10114 while ((oldcontext = strsep(&old, "&"))) {
10115 stalecontext = '\0';
10116 ast_copy_string(newlist, new, sizeof(newlist));
10117 stringp = newlist;
10118 while ((newcontext = strsep(&stringp, "&"))) {
10119 if (strcmp(newcontext, oldcontext) == 0) {
10120
10121 stalecontext = '\0';
10122 break;
10123 } else if (strcmp(newcontext, oldcontext)) {
10124 stalecontext = oldcontext;
10125 }
10126
10127 }
10128 if (stalecontext)
10129 ast_context_destroy(ast_context_find(stalecontext), "SIP");
10130 }
10131 }
10132
10133
10134 static int sip_prune_realtime(int fd, int argc, char *argv[])
10135 {
10136 struct sip_peer *peer;
10137 struct sip_user *user;
10138 int pruneuser = FALSE;
10139 int prunepeer = FALSE;
10140 int multi = FALSE;
10141 char *name = NULL;
10142 regex_t regexbuf;
10143
10144 switch (argc) {
10145 case 4:
10146 if (!strcasecmp(argv[3], "user"))
10147 return RESULT_SHOWUSAGE;
10148 if (!strcasecmp(argv[3], "peer"))
10149 return RESULT_SHOWUSAGE;
10150 if (!strcasecmp(argv[3], "like"))
10151 return RESULT_SHOWUSAGE;
10152 if (!strcasecmp(argv[3], "all")) {
10153 multi = TRUE;
10154 pruneuser = prunepeer = TRUE;
10155 } else {
10156 pruneuser = prunepeer = TRUE;
10157 name = argv[3];
10158 }
10159 break;
10160 case 5:
10161 if (!strcasecmp(argv[4], "like"))
10162 return RESULT_SHOWUSAGE;
10163 if (!strcasecmp(argv[3], "all"))
10164 return RESULT_SHOWUSAGE;
10165 if (!strcasecmp(argv[3], "like")) {
10166 multi = TRUE;
10167 name = argv[4];
10168 pruneuser = prunepeer = TRUE;
10169 } else if (!strcasecmp(argv[3], "user")) {
10170 pruneuser = TRUE;
10171 if (!strcasecmp(argv[4], "all"))
10172 multi = TRUE;
10173 else
10174 name = argv[4];
10175 } else if (!strcasecmp(argv[3], "peer")) {
10176 prunepeer = TRUE;
10177 if (!strcasecmp(argv[4], "all"))
10178 multi = TRUE;
10179 else
10180 name = argv[4];
10181 } else
10182 return RESULT_SHOWUSAGE;
10183 break;
10184 case 6:
10185 if (strcasecmp(argv[4], "like"))
10186 return RESULT_SHOWUSAGE;
10187 if (!strcasecmp(argv[3], "user")) {
10188 pruneuser = TRUE;
10189 name = argv[5];
10190 } else if (!strcasecmp(argv[3], "peer")) {
10191 prunepeer = TRUE;
10192 name = argv[5];
10193 } else
10194 return RESULT_SHOWUSAGE;
10195 break;
10196 default:
10197 return RESULT_SHOWUSAGE;
10198 }
10199
10200 if (multi && name) {
10201 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
10202 return RESULT_SHOWUSAGE;
10203 }
10204
10205 if (multi) {
10206 if (prunepeer) {
10207 int pruned = 0;
10208
10209 ASTOBJ_CONTAINER_WRLOCK(&peerl);
10210 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
10211 ASTOBJ_RDLOCK(iterator);
10212 if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
10213 ASTOBJ_UNLOCK(iterator);
10214 continue;
10215 };
10216 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10217 ASTOBJ_MARK(iterator);
10218 pruned++;
10219 }
10220 ASTOBJ_UNLOCK(iterator);
10221 } while (0) );
10222 if (pruned) {
10223 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
10224 ast_cli(fd, "%d peers pruned.\n", pruned);
10225 } else
10226 ast_cli(fd, "No peers found to prune.\n");
10227 ASTOBJ_CONTAINER_UNLOCK(&peerl);
10228 }
10229 if (pruneuser) {
10230 int pruned = 0;
10231
10232 ASTOBJ_CONTAINER_WRLOCK(&userl);
10233 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
10234 ASTOBJ_RDLOCK(iterator);
10235 if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
10236 ASTOBJ_UNLOCK(iterator);
10237 continue;
10238 };
10239 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10240 ASTOBJ_MARK(iterator);
10241 pruned++;
10242 }
10243 ASTOBJ_UNLOCK(iterator);
10244 } while (0) );
10245 if (pruned) {
10246 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
10247 ast_cli(fd, "%d users pruned.\n", pruned);
10248 } else
10249 ast_cli(fd, "No users found to prune.\n");
10250 ASTOBJ_CONTAINER_UNLOCK(&userl);
10251 }
10252 } else {
10253 if (prunepeer) {
10254 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
10255 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10256 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
10257 ASTOBJ_CONTAINER_LINK(&peerl, peer);
10258 } else
10259 ast_cli(fd, "Peer '%s' pruned.\n", name);
10260 ASTOBJ_UNREF(peer, sip_destroy_peer);
10261 } else
10262 ast_cli(fd, "Peer '%s' not found.\n", name);
10263 }
10264 if (pruneuser) {
10265 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
10266 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
10267 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
10268 ASTOBJ_CONTAINER_LINK(&userl, user);
10269 } else
10270 ast_cli(fd, "User '%s' pruned.\n", name);
10271 ASTOBJ_UNREF(user, sip_destroy_user);
10272 } else
10273 ast_cli(fd, "User '%s' not found.\n", name);
10274 }
10275 }
10276
10277 return RESULT_SUCCESS;
10278 }
10279
10280
10281 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
10282 {
10283 int x, codec;
10284
10285 for(x = 0; x < 32 ; x++) {
10286 codec = ast_codec_pref_index(pref, x);
10287 if (!codec)
10288 break;
10289 ast_cli(fd, "%s", ast_getformatname(codec));
10290 ast_cli(fd, ":%d", pref->framing[x]);
10291 if (x < 31 && ast_codec_pref_index(pref, x + 1))
10292 ast_cli(fd, ",");
10293 }
10294 if (!x)
10295 ast_cli(fd, "none");
10296 }
10297
10298
10299 static const char *domain_mode_to_text(const enum domain_mode mode)
10300 {
10301 switch (mode) {
10302 case SIP_DOMAIN_AUTO:
10303 return "[Automatic]";
10304 case SIP_DOMAIN_CONFIG:
10305 return "[Configured]";
10306 }
10307
10308 return "";
10309 }
10310
10311
10312 static int sip_show_domains(int fd, int argc, char *argv[])
10313 {
10314 struct domain *d;
10315 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
10316
10317 if (AST_LIST_EMPTY(&domain_list)) {
10318 ast_cli(fd, "SIP Domain support not enabled.\n\n");
10319 return RESULT_SUCCESS;
10320 } else {
10321 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
10322 AST_LIST_LOCK(&domain_list);
10323 AST_LIST_TRAVERSE(&domain_list, d, list)
10324 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
10325 domain_mode_to_text(d->mode));
10326 AST_LIST_UNLOCK(&domain_list);
10327 ast_cli(fd, "\n");
10328 return RESULT_SUCCESS;
10329 }
10330 }
10331 #undef FORMAT
10332
10333 static char mandescr_show_peer[] =
10334 "Description: Show one SIP peer with details on current status.\n"
10335 "Variables: \n"
10336 " Peer: <name> The peer name you want to check.\n"
10337 " ActionID: <id> Optional action ID for this AMI transaction.\n";
10338
10339
10340 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
10341 {
10342 const char *a[4];
10343 const char *peer;
10344 int ret;
10345
10346 peer = astman_get_header(m,"Peer");
10347 if (ast_strlen_zero(peer)) {
10348 astman_send_error(s, m, "Peer: <name> missing.\n");
10349 return 0;
10350 }
10351 a[0] = "sip";
10352 a[1] = "show";
10353 a[2] = "peer";
10354 a[3] = peer;
10355
10356 ret = _sip_show_peer(1, -1, s, m, 4, a);
10357 astman_append(s, "\r\n\r\n" );
10358 return ret;
10359 }
10360
10361
10362
10363
10364 static int sip_show_peer(int fd, int argc, char *argv[])
10365 {
10366 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
10367 }
10368
10369
10370 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
10371 {
10372 char status[30] = "";
10373 char cbuf[256];
10374 struct sip_peer *peer;
10375 char codec_buf[512];
10376 struct ast_codec_pref *pref;
10377 struct ast_variable *v;
10378 struct sip_auth *auth;
10379 int x = 0, codec = 0, load_realtime;
10380 int realtimepeers;
10381
10382 realtimepeers = ast_check_realtime("sippeers");
10383
10384 if (argc < 4)
10385 return RESULT_SHOWUSAGE;
10386
10387 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10388 peer = find_peer(argv[3], NULL, load_realtime);
10389 if (s) {
10390 if (peer) {
10391 const char *id = astman_get_header(m,"ActionID");
10392
10393 astman_append(s, "Response: Success\r\n");
10394 if (!ast_strlen_zero(id))
10395 astman_append(s, "ActionID: %s\r\n",id);
10396 } else {
10397 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
10398 astman_send_error(s, m, cbuf);
10399 return 0;
10400 }
10401 }
10402 if (peer && type==0 ) {
10403 ast_cli(fd,"\n\n");
10404 ast_cli(fd, " * Name : %s\n", peer->name);
10405 if (realtimepeers) {
10406 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
10407 }
10408 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
10409 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
10410 for (auth = peer->auth; auth; auth = auth->next) {
10411 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
10412 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
10413 }
10414 ast_cli(fd, " Context : %s\n", peer->context);
10415 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
10416 ast_cli(fd, " Language : %s\n", peer->language);
10417 if (!ast_strlen_zero(peer->accountcode))
10418 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10419 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10420 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10421 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10422 if (!ast_strlen_zero(peer->fromuser))
10423 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10424 if (!ast_strlen_zero(peer->fromdomain))
10425 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10426 ast_cli(fd, " Callgroup : ");
10427 print_group(fd, peer->callgroup, 0);
10428 ast_cli(fd, " Pickupgroup : ");
10429 print_group(fd, peer->pickupgroup, 0);
10430 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10431 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10432 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10433 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10434 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10435 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10436 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10437 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10438 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)));
10439 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10440 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10441 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10442 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10443 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10444 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10445 #endif
10446 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10447 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10448 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10449 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10450 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10451 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10452 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10453 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10454
10455
10456 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10457 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10458 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10459 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));
10460 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10461 if (!ast_strlen_zero(global_regcontext))
10462 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10463 ast_cli(fd, " Def. Username: %s\n", peer->username);
10464 ast_cli(fd, " SIP Options : ");
10465 if (peer->sipoptions) {
10466 int lastoption = -1;
10467 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10468 if (sip_options[x].id != lastoption) {
10469 if (peer->sipoptions & sip_options[x].id)
10470 ast_cli(fd, "%s ", sip_options[x].text);
10471 lastoption = x;
10472 }
10473 }
10474 } else
10475 ast_cli(fd, "(none)");
10476
10477 ast_cli(fd, "\n");
10478 ast_cli(fd, " Codecs : ");
10479 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10480 ast_cli(fd, "%s\n", codec_buf);
10481 ast_cli(fd, " Codec Order : (");
10482 print_codec_to_cli(fd, &peer->prefs);
10483 ast_cli(fd, ")\n");
10484
10485 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10486 ast_cli(fd, " Status : ");
10487 peer_status(peer, status, sizeof(status));
10488 ast_cli(fd, "%s\n",status);
10489 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10490 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10491 if (peer->chanvars) {
10492 ast_cli(fd, " Variables :\n");
10493 for (v = peer->chanvars ; v ; v = v->next)
10494 ast_cli(fd, " %s = %s\n", v->name, v->value);
10495 }
10496 ast_cli(fd,"\n");
10497 ASTOBJ_UNREF(peer,sip_destroy_peer);
10498 } else if (peer && type == 1) {
10499 char buf[256];
10500 astman_append(s, "Channeltype: SIP\r\n");
10501 astman_append(s, "ObjectName: %s\r\n", peer->name);
10502 astman_append(s, "ChanObjectType: peer\r\n");
10503 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10504 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10505 astman_append(s, "Context: %s\r\n", peer->context);
10506 astman_append(s, "Language: %s\r\n", peer->language);
10507 if (!ast_strlen_zero(peer->accountcode))
10508 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10509 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10510 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10511 if (!ast_strlen_zero(peer->fromuser))
10512 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10513 if (!ast_strlen_zero(peer->fromdomain))
10514 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10515 astman_append(s, "Callgroup: ");
10516 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10517 astman_append(s, "Pickupgroup: ");
10518 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10519 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10520 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10521 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10522 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
10523 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10524 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10525 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10526 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10527 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)));
10528 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10529 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10530 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10531 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10532 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10533 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10534
10535
10536 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10537 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10538 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10539 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));
10540 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));
10541 astman_append(s, "Default-Username: %s\r\n", peer->username);
10542 if (!ast_strlen_zero(global_regcontext))
10543 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10544 astman_append(s, "Codecs: ");
10545 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10546 astman_append(s, "%s\r\n", codec_buf);
10547 astman_append(s, "CodecOrder: ");
10548 pref = &peer->prefs;
10549 for(x = 0; x < 32 ; x++) {
10550 codec = ast_codec_pref_index(pref,x);
10551 if (!codec)
10552 break;
10553 astman_append(s, "%s", ast_getformatname(codec));
10554 if (x < 31 && ast_codec_pref_index(pref,x+1))
10555 astman_append(s, ",");
10556 }
10557
10558 astman_append(s, "\r\n");
10559 astman_append(s, "Status: ");
10560 peer_status(peer, status, sizeof(status));
10561 astman_append(s, "%s\r\n", status);
10562 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10563 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10564 if (peer->chanvars) {
10565 for (v = peer->chanvars ; v ; v = v->next) {
10566 astman_append(s, "ChanVariable:\n");
10567 astman_append(s, " %s,%s\r\n", v->name, v->value);
10568 }
10569 }
10570
10571 ASTOBJ_UNREF(peer,sip_destroy_peer);
10572
10573 } else {
10574 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10575 ast_cli(fd,"\n");
10576 }
10577
10578 return RESULT_SUCCESS;
10579 }
10580
10581
10582 static int sip_show_user(int fd, int argc, char *argv[])
10583 {
10584 char cbuf[256];
10585 struct sip_user *user;
10586 struct ast_variable *v;
10587 int load_realtime;
10588
10589 if (argc < 4)
10590 return RESULT_SHOWUSAGE;
10591
10592
10593 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10594
10595 user = find_user(argv[3], load_realtime);
10596 if (user) {
10597 ast_cli(fd,"\n\n");
10598 ast_cli(fd, " * Name : %s\n", user->name);
10599 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10600 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10601 ast_cli(fd, " Context : %s\n", user->context);
10602 ast_cli(fd, " Language : %s\n", user->language);
10603 if (!ast_strlen_zero(user->accountcode))
10604 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10605 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10606 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10607 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10608 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10609 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10610 ast_cli(fd, " Callgroup : ");
10611 print_group(fd, user->callgroup, 0);
10612 ast_cli(fd, " Pickupgroup : ");
10613 print_group(fd, user->pickupgroup, 0);
10614 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10615 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10616 ast_cli(fd, " Codec Order : (");
10617 print_codec_to_cli(fd, &user->prefs);
10618 ast_cli(fd, ")\n");
10619
10620 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10621 if (user->chanvars) {
10622 ast_cli(fd, " Variables :\n");
10623 for (v = user->chanvars ; v ; v = v->next)
10624 ast_cli(fd, " %s = %s\n", v->name, v->value);
10625 }
10626 ast_cli(fd,"\n");
10627 ASTOBJ_UNREF(user,sip_destroy_user);
10628 } else {
10629 ast_cli(fd,"User %s not found.\n", argv[3]);
10630 ast_cli(fd,"\n");
10631 }
10632
10633 return RESULT_SUCCESS;
10634 }
10635
10636
10637 static int sip_show_registry(int fd, int argc, char *argv[])
10638 {
10639 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10640 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10641 char host[80];
10642 char tmpdat[256];
10643 struct tm tm;
10644
10645
10646 if (argc != 3)
10647 return RESULT_SHOWUSAGE;
10648 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10649 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
10650 ASTOBJ_RDLOCK(iterator);
10651 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10652 if (iterator->regtime) {
10653 ast_localtime(&iterator->regtime, &tm, NULL);
10654 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10655 } else {
10656 tmpdat[0] = 0;
10657 }
10658 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10659 ASTOBJ_UNLOCK(iterator);
10660 } while(0));
10661 return RESULT_SUCCESS;
10662 #undef FORMAT
10663 #undef FORMAT2
10664 }
10665
10666
10667 static int sip_show_settings(int fd, int argc, char *argv[])
10668 {
10669 int realtimepeers;
10670 int realtimeusers;
10671 char codec_buf[BUFSIZ];
10672
10673 realtimepeers = ast_check_realtime("sippeers");
10674 realtimeusers = ast_check_realtime("sipusers");
10675
10676 if (argc != 3)
10677 return RESULT_SHOWUSAGE;
10678 ast_cli(fd, "\n\nGlobal Settings:\n");
10679 ast_cli(fd, "----------------\n");
10680 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10681 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10682 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10683 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10684 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10685 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10686 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10687 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10688 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10689 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10690 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10691 ast_cli(fd, " Our auth realm %s\n", global_realm);
10692 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10693 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10694 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10695 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10696 ast_cli(fd, " User Agent: %s\n", global_useragent);
10697 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10698 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10699 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10700 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10701 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10702 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10703 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10704 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10705 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10706 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10707 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10708 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10709 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10710 #endif
10711 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10712 if (!realtimepeers && !realtimeusers)
10713 ast_cli(fd, " SIP realtime: Disabled\n" );
10714 else
10715 ast_cli(fd, " SIP realtime: Enabled\n" );
10716
10717 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10718 ast_cli(fd, "---------------------------\n");
10719 ast_cli(fd, " Codecs: ");
10720 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10721 ast_cli(fd, "%s\n", codec_buf);
10722 ast_cli(fd, " Codec Order: ");
10723 print_codec_to_cli(fd, &default_prefs);
10724 ast_cli(fd, "\n");
10725 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10726 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10727 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10728 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10729 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10730 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10731 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10732 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10733 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10734 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10735 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10736 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10737 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10738 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10739 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10740 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10741 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10742 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10743 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10744 ast_cli(fd, "\nDefault Settings:\n");
10745 ast_cli(fd, "-----------------\n");
10746 ast_cli(fd, " Context: %s\n", default_context);
10747 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10748 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10749 ast_cli(fd, " Qualify: %d\n", default_qualify);
10750 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10751 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" );
10752 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10753 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10754 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10755 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10756
10757
10758 if (realtimepeers || realtimeusers) {
10759 ast_cli(fd, "\nRealtime SIP Settings:\n");
10760 ast_cli(fd, "----------------------\n");
10761 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10762 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10763 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10764 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10765 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10766 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10767 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10768 }
10769 ast_cli(fd, "\n----\n");
10770 return RESULT_SUCCESS;
10771 }
10772
10773
10774 static const char *subscription_type2str(enum subscriptiontype subtype)
10775 {
10776 int i;
10777
10778 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10779 if (subscription_types[i].type == subtype) {
10780 return subscription_types[i].text;
10781 }
10782 }
10783 return subscription_types[0].text;
10784 }
10785
10786
10787 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10788 {
10789 int i;
10790
10791 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10792 if (subscription_types[i].type == subtype) {
10793 return &subscription_types[i];
10794 }
10795 }
10796 return &subscription_types[0];
10797 }
10798
10799
10800 static int sip_show_channels(int fd, int argc, char *argv[])
10801 {
10802 return __sip_show_channels(fd, argc, argv, 0);
10803 }
10804
10805
10806 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10807 {
10808 return __sip_show_channels(fd, argc, argv, 1);
10809 }
10810
10811
10812 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10813 {
10814 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10815 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-15.15s %-7.7s %-15.15s\n"
10816 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10817 struct sip_pvt *cur;
10818 int numchans = 0;
10819 char *referstatus = NULL;
10820
10821 if (argc != 3)
10822 return RESULT_SHOWUSAGE;
10823 ast_mutex_lock(&iflock);
10824 cur = iflist;
10825 if (!subscriptions)
10826 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10827 else
10828 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10829 for (; cur; cur = cur->next) {
10830 referstatus = "";
10831 if (cur->refer) {
10832 referstatus = referstatus2str(cur->refer->status);
10833 }
10834 if (cur->subscribed == NONE && !subscriptions) {
10835 char formatbuf[BUFSIZ/2];
10836 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10837 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10838 cur->callid,
10839 cur->ocseq, cur->icseq,
10840 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
10841 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10842 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10843 cur->lastmsg ,
10844 referstatus
10845 );
10846 numchans++;
10847 }
10848 if (cur->subscribed != NONE && subscriptions) {
10849 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10850 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10851 cur->callid,
10852
10853 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10854 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10855 subscription_type2str(cur->subscribed),
10856 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10857 );
10858 numchans++;
10859 }
10860 }
10861 ast_mutex_unlock(&iflock);
10862 if (!subscriptions)
10863 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10864 else
10865 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10866 return RESULT_SUCCESS;
10867 #undef FORMAT
10868 #undef FORMAT2
10869 #undef FORMAT3
10870 }
10871
10872
10873 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10874 {
10875 int which=0;
10876 struct sip_pvt *cur;
10877 char *c = NULL;
10878 int wordlen = strlen(word);
10879
10880 ast_mutex_lock(&iflock);
10881 for (cur = iflist; cur; cur = cur->next) {
10882 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10883 c = ast_strdup(cur->callid);
10884 break;
10885 }
10886 }
10887 ast_mutex_unlock(&iflock);
10888 return c;
10889 }
10890
10891
10892 static char *complete_sip_peer(const char *word, int state, int flags2)
10893 {
10894 char *result = NULL;
10895 int wordlen = strlen(word);
10896 int which = 0;
10897
10898 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10899
10900 if (!strncasecmp(word, iterator->name, wordlen) &&
10901 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
10902 ++which > state)
10903 result = ast_strdup(iterator->name);
10904 } while(0) );
10905 return result;
10906 }
10907
10908
10909 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
10910 {
10911 if (pos == 3)
10912 return complete_sip_peer(word, state, 0);
10913
10914 return NULL;
10915 }
10916
10917
10918 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
10919 {
10920 if (pos == 3)
10921 return complete_sip_peer(word, state, 0);
10922
10923 return NULL;
10924 }
10925
10926
10927 static char *complete_sip_user(const char *word, int state, int flags2)
10928 {
10929 char *result = NULL;
10930 int wordlen = strlen(word);
10931 int which = 0;
10932
10933 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
10934
10935 if (!strncasecmp(word, iterator->name, wordlen)) {
10936 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
10937 continue;
10938 if (++which > state) {
10939 result = ast_strdup(iterator->name);
10940 }
10941 }
10942 } while(0) );
10943 return result;
10944 }
10945
10946
10947 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
10948 {
10949 if (pos == 3)
10950 return complete_sip_user(word, state, 0);
10951
10952 return NULL;
10953 }
10954
10955
10956 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
10957 {
10958 char *c = NULL;
10959
10960 if (pos == 2) {
10961 int which = 0;
10962 char *cat = NULL;
10963 int wordlen = strlen(word);
10964
10965
10966
10967 if (!notify_types)
10968 return NULL;
10969
10970 while ( (cat = ast_category_browse(notify_types, cat)) ) {
10971 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
10972 c = ast_strdup(cat);
10973 break;
10974 }
10975 }
10976 return c;
10977 }
10978
10979 if (pos > 2)
10980 return complete_sip_peer(word, state, 0);
10981
10982 return NULL;
10983 }
10984
10985
10986 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
10987 {
10988 if (pos == 4)
10989 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10990 return NULL;
10991 }
10992
10993
10994 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
10995 {
10996 if (pos == 4)
10997 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10998
10999 return NULL;
11000 }
11001
11002
11003 static int sip_show_channel(int fd, int argc, char *argv[])
11004 {
11005 struct sip_pvt *cur;
11006 size_t len;
11007 int found = 0;
11008
11009 if (argc != 4)
11010 return RESULT_SHOWUSAGE;
11011 len = strlen(argv[3]);
11012 ast_mutex_lock(&iflock);
11013 for (cur = iflist; cur; cur = cur->next) {
11014 if (!strncasecmp(cur->callid, argv[3], len)) {
11015 char formatbuf[BUFSIZ/2];
11016 ast_cli(fd,"\n");
11017 if (cur->subscribed != NONE)
11018 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
11019 else
11020 ast_cli(fd, " * SIP Call\n");
11021 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
11022 ast_cli(fd, " Call-ID: %s\n", cur->callid);
11023 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
11024 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
11025 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
11026 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
11027 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
11028 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
11029 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
11030 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
11031 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
11032 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
11033 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
11034 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)" );
11035 ast_cli(fd, " Our Tag: %s\n", cur->tag);
11036 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
11037 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
11038 if (!ast_strlen_zero(cur->username))
11039 ast_cli(fd, " Username: %s\n", cur->username);
11040 if (!ast_strlen_zero(cur->peername))
11041 ast_cli(fd, " Peername: %s\n", cur->peername);
11042 if (!ast_strlen_zero(cur->uri))
11043 ast_cli(fd, " Original uri: %s\n", cur->uri);
11044 if (!ast_strlen_zero(cur->cid_num))
11045 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
11046 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
11047 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
11048 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
11049 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
11050 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
11051 ast_cli(fd, " SIP Options: ");
11052 if (cur->sipoptions) {
11053 int x;
11054 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
11055 if (cur->sipoptions & sip_options[x].id)
11056 ast_cli(fd, "%s ", sip_options[x].text);
11057 }
11058 } else
11059 ast_cli(fd, "(none)\n");
11060 ast_cli(fd, "\n\n");
11061 found++;
11062 }
11063 }
11064 ast_mutex_unlock(&iflock);
11065 if (!found)
11066 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11067 return RESULT_SUCCESS;
11068 }
11069
11070
11071 static int sip_show_history(int fd, int argc, char *argv[])
11072 {
11073 struct sip_pvt *cur;
11074 size_t len;
11075 int found = 0;
11076
11077 if (argc != 4)
11078 return RESULT_SHOWUSAGE;
11079 if (!recordhistory)
11080 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
11081 len = strlen(argv[3]);
11082 ast_mutex_lock(&iflock);
11083 for (cur = iflist; cur; cur = cur->next) {
11084 if (!strncasecmp(cur->callid, argv[3], len)) {
11085 struct sip_history *hist;
11086 int x = 0;
11087
11088 ast_cli(fd,"\n");
11089 if (cur->subscribed != NONE)
11090 ast_cli(fd, " * Subscription\n");
11091 else
11092 ast_cli(fd, " * SIP Call\n");
11093 if (cur->history)
11094 AST_LIST_TRAVERSE(cur->history, hist, list)
11095 ast_cli(fd, "%d. %s\n", ++x, hist->event);
11096 if (x == 0)
11097 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
11098 found++;
11099 }
11100 }
11101 ast_mutex_unlock(&iflock);
11102 if (!found)
11103 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
11104 return RESULT_SUCCESS;
11105 }
11106
11107
11108 static void sip_dump_history(struct sip_pvt *dialog)
11109 {
11110 int x = 0;
11111 struct sip_history *hist;
11112 static int errmsg = 0;
11113
11114 if (!dialog)
11115 return;
11116
11117 if (!option_debug && !sipdebug) {
11118 if (!errmsg) {
11119 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
11120 errmsg = 1;
11121 }
11122 return;
11123 }
11124
11125 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
11126 if (dialog->subscribed)
11127 ast_log(LOG_DEBUG, " * Subscription\n");
11128 else
11129 ast_log(LOG_DEBUG, " * SIP Call\n");
11130 if (dialog->history)
11131 AST_LIST_TRAVERSE(dialog->history, hist, list)
11132 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
11133 if (!x)
11134 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
11135 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
11136 }
11137
11138
11139
11140
11141 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
11142 {
11143 char buf[1024];
11144 unsigned int event;
11145 const char *c = get_header(req, "Content-Type");
11146
11147
11148 if (!strcasecmp(c, "application/dtmf-relay") ||
11149 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
11150 unsigned int duration = 0;
11151
11152
11153 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
11154 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
11155 transmit_response(p, "200 OK", req);
11156 return;
11157 } else {
11158 ast_copy_string(buf, c, sizeof(buf));
11159 }
11160
11161 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
11162 duration = atoi(c);
11163 if (!duration)
11164 duration = 100;
11165
11166 if (!p->owner) {
11167 transmit_response(p, "481 Call leg/transaction does not exist", req);
11168 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11169 return;
11170 }
11171
11172 if (ast_strlen_zero(buf)) {
11173 transmit_response(p, "200 OK", req);
11174 return;
11175 }
11176
11177 if (buf[0] == '*')
11178 event = 10;
11179 else if (buf[0] == '#')
11180 event = 11;
11181 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
11182 event = 12 + buf[0] - 'A';
11183 else
11184 event = atoi(buf);
11185 if (event == 16) {
11186
11187 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
11188 ast_queue_frame(p->owner, &f);
11189 if (sipdebug)
11190 ast_verbose("* DTMF-relay event received: FLASH\n");
11191 } else {
11192
11193 struct ast_frame f = { AST_FRAME_DTMF, };
11194 if (event < 10) {
11195 f.subclass = '0' + event;
11196 } else if (event < 11) {
11197 f.subclass = '*';
11198 } else if (event < 12) {
11199 f.subclass = '#';
11200 } else if (event < 16) {
11201 f.subclass = 'A' + (event - 12);
11202 }
11203 f.len = duration;
11204 ast_queue_frame(p->owner, &f);
11205 if (sipdebug)
11206 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
11207 }
11208 transmit_response(p, "200 OK", req);
11209 return;
11210 } else if (!strcasecmp(c, "application/media_control+xml")) {
11211
11212 if (p->owner)
11213 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
11214 transmit_response(p, "200 OK", req);
11215 return;
11216 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
11217
11218 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
11219 if (p->owner && p->owner->cdr)
11220 ast_cdr_setuserfield(p->owner, c);
11221 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
11222 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
11223 transmit_response(p, "200 OK", req);
11224 } else {
11225 transmit_response(p, "403 Unauthorized", req);
11226 }
11227 return;
11228 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
11229
11230 transmit_response(p, "200 OK", req);
11231 return;
11232 }
11233
11234
11235
11236
11237 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
11238 transmit_response(p, "415 Unsupported media type", req);
11239 return;
11240 }
11241
11242
11243 static int sip_do_debug_ip(int fd, int argc, char *argv[])
11244 {
11245 struct hostent *hp;
11246 struct ast_hostent ahp;
11247 int port = 0;
11248 char *p, *arg;
11249
11250
11251 if (argc != 5)
11252 return RESULT_SHOWUSAGE;
11253 p = arg = argv[4];
11254 strsep(&p, ":");
11255 if (p)
11256 port = atoi(p);
11257 hp = ast_gethostbyname(arg, &ahp);
11258 if (hp == NULL)
11259 return RESULT_SHOWUSAGE;
11260
11261 debugaddr.sin_family = AF_INET;
11262 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
11263 debugaddr.sin_port = htons(port);
11264 if (port == 0)
11265 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
11266 else
11267 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
11268
11269 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11270
11271 return RESULT_SUCCESS;
11272 }
11273
11274
11275 static int sip_do_debug_peer(int fd, int argc, char *argv[])
11276 {
11277 struct sip_peer *peer;
11278 if (argc != 5)
11279 return RESULT_SHOWUSAGE;
11280 peer = find_peer(argv[4], NULL, 1);
11281 if (peer) {
11282 if (peer->addr.sin_addr.s_addr) {
11283 debugaddr.sin_family = AF_INET;
11284 debugaddr.sin_addr = peer->addr.sin_addr;
11285 debugaddr.sin_port = peer->addr.sin_port;
11286 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
11287 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11288 } else
11289 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
11290 ASTOBJ_UNREF(peer,sip_destroy_peer);
11291 } else
11292 ast_cli(fd, "No such peer '%s'\n", argv[4]);
11293 return RESULT_SUCCESS;
11294 }
11295
11296
11297 static int sip_do_debug(int fd, int argc, char *argv[])
11298 {
11299 int oldsipdebug = sipdebug_console;
11300 if (argc != 3) {
11301 if (argc != 5)
11302 return RESULT_SHOWUSAGE;
11303 else if (strcmp(argv[3], "ip") == 0)
11304 return sip_do_debug_ip(fd, argc, argv);
11305 else if (strcmp(argv[3], "peer") == 0)
11306 return sip_do_debug_peer(fd, argc, argv);
11307 else
11308 return RESULT_SHOWUSAGE;
11309 }
11310 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11311 memset(&debugaddr, 0, sizeof(debugaddr));
11312 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11313 return RESULT_SUCCESS;
11314 }
11315
11316 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
11317 {
11318 int oldsipdebug = sipdebug_console;
11319 char *newargv[6] = { "sip", "set", "debug", NULL };
11320 if (argc != 2) {
11321 if (argc != 4)
11322 return RESULT_SHOWUSAGE;
11323 else if (strcmp(argv[2], "ip") == 0) {
11324 newargv[3] = argv[2];
11325 newargv[4] = argv[3];
11326 return sip_do_debug_ip(fd, argc + 1, newargv);
11327 } else if (strcmp(argv[2], "peer") == 0) {
11328 newargv[3] = argv[2];
11329 newargv[4] = argv[3];
11330 return sip_do_debug_peer(fd, argc + 1, newargv);
11331 } else
11332 return RESULT_SHOWUSAGE;
11333 }
11334 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11335 memset(&debugaddr, 0, sizeof(debugaddr));
11336 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
11337 return RESULT_SUCCESS;
11338 }
11339
11340
11341 static int sip_notify(int fd, int argc, char *argv[])
11342 {
11343 struct ast_variable *varlist;
11344 int i;
11345
11346 if (argc < 4)
11347 return RESULT_SHOWUSAGE;
11348
11349 if (!notify_types) {
11350 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
11351 return RESULT_FAILURE;
11352 }
11353
11354 varlist = ast_variable_browse(notify_types, argv[2]);
11355
11356 if (!varlist) {
11357 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
11358 return RESULT_FAILURE;
11359 }
11360
11361 for (i = 3; i < argc; i++) {
11362 struct sip_pvt *p;
11363 struct sip_request req;
11364 struct ast_variable *var;
11365
11366 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
11367 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
11368 return RESULT_FAILURE;
11369 }
11370
11371 if (create_addr(p, argv[i])) {
11372
11373 sip_destroy(p);
11374 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
11375 continue;
11376 }
11377
11378 initreqprep(&req, p, SIP_NOTIFY);
11379
11380 for (var = varlist; var; var = var->next)
11381 add_header(&req, var->name, ast_unescape_semicolon(var->value));
11382
11383
11384 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
11385 p->ourip = __ourip;
11386 build_via(p);
11387 build_callid_pvt(p);
11388 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
11389 transmit_sip_request(p, &req);
11390 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11391 }
11392
11393 return RESULT_SUCCESS;
11394 }
11395
11396
11397 static int sip_no_debug(int fd, int argc, char *argv[])
11398 {
11399 if (argc != 4)
11400 return RESULT_SHOWUSAGE;
11401 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11402 ast_cli(fd, "SIP Debugging Disabled\n");
11403 return RESULT_SUCCESS;
11404 }
11405
11406 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
11407 {
11408 if (argc != 3)
11409 return RESULT_SHOWUSAGE;
11410 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11411 ast_cli(fd, "SIP Debugging Disabled\n");
11412 return RESULT_SUCCESS;
11413 }
11414
11415
11416 static int sip_do_history(int fd, int argc, char *argv[])
11417 {
11418 if (argc != 2) {
11419 return RESULT_SHOWUSAGE;
11420 }
11421 recordhistory = TRUE;
11422 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
11423 return RESULT_SUCCESS;
11424 }
11425
11426
11427 static int sip_no_history(int fd, int argc, char *argv[])
11428 {
11429 if (argc != 3) {
11430 return RESULT_SHOWUSAGE;
11431 }
11432 recordhistory = FALSE;
11433 ast_cli(fd, "SIP History Recording Disabled\n");
11434 return RESULT_SUCCESS;
11435 }
11436
11437
11438 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11439 {
11440 char digest[1024];
11441 p->authtries++;
11442 memset(digest,0,sizeof(digest));
11443 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11444
11445
11446 if (sip_debug_test_pvt(p) && p->registry)
11447 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11448
11449 return -1;
11450 }
11451 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11452 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11453 if (sip_debug_test_pvt(p) && p->registry)
11454 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11455 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11456 }
11457
11458
11459 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11460 {
11461 char digest[1024];
11462
11463 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11464 return -2;
11465
11466 p->authtries++;
11467 if (option_debug > 1)
11468 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11469 memset(digest, 0, sizeof(digest));
11470 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11471
11472 return -1;
11473 }
11474
11475 p->options->auth = digest;
11476 p->options->authheader = respheader;
11477 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11478 }
11479
11480
11481
11482
11483
11484 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11485 {
11486 char tmp[512];
11487 char *c;
11488 char oldnonce[256];
11489
11490
11491 const struct x {
11492 const char *key;
11493 int field_index;
11494 } *i, keys[] = {
11495 { "realm=", ast_string_field_index(p, realm) },
11496 { "nonce=", ast_string_field_index(p, nonce) },
11497 { "opaque=", ast_string_field_index(p, opaque) },
11498 { "qop=", ast_string_field_index(p, qop) },
11499 { "domain=", ast_string_field_index(p, domain) },
11500 { NULL, 0 },
11501 };
11502
11503 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11504 if (ast_strlen_zero(tmp))
11505 return -1;
11506 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11507 ast_log(LOG_WARNING, "missing Digest.\n");
11508 return -1;
11509 }
11510 c = tmp + strlen("Digest ");
11511 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11512 while (c && *(c = ast_skip_blanks(c))) {
11513 for (i = keys; i->key != NULL; i++) {
11514 char *src, *separator;
11515 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11516 continue;
11517
11518 c += strlen(i->key);
11519 if (*c == '"') {
11520 src = ++c;
11521 separator = "\"";
11522 } else {
11523 src = c;
11524 separator = ",";
11525 }
11526 strsep(&c, separator);
11527 ast_string_field_index_set(p, i->field_index, src);
11528 break;
11529 }
11530 if (i->key == NULL)
11531 strsep(&c, ",");
11532 }
11533
11534 if (strcmp(p->nonce, oldnonce))
11535 p->noncecount = 0;
11536
11537
11538 if (p->registry) {
11539 struct sip_registry *r = p->registry;
11540
11541 if (strcmp(r->nonce, p->nonce)) {
11542 ast_string_field_set(r, realm, p->realm);
11543 ast_string_field_set(r, nonce, p->nonce);
11544 ast_string_field_set(r, domain, p->domain);
11545 ast_string_field_set(r, opaque, p->opaque);
11546 ast_string_field_set(r, qop, p->qop);
11547 r->noncecount = 0;
11548 }
11549 }
11550 return build_reply_digest(p, sipmethod, digest, digest_len);
11551 }
11552
11553
11554
11555
11556
11557
11558 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11559 {
11560 char a1[256];
11561 char a2[256];
11562 char a1_hash[256];
11563 char a2_hash[256];
11564 char resp[256];
11565 char resp_hash[256];
11566 char uri[256];
11567 char cnonce[80];
11568 const char *username;
11569 const char *secret;
11570 const char *md5secret;
11571 struct sip_auth *auth = NULL;
11572
11573 if (!ast_strlen_zero(p->domain))
11574 ast_copy_string(uri, p->domain, sizeof(uri));
11575 else if (!ast_strlen_zero(p->uri))
11576 ast_copy_string(uri, p->uri, sizeof(uri));
11577 else
11578 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11579
11580 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11581
11582
11583 if ((auth = find_realm_authentication(authl, p->realm))) {
11584 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
11585 auth->username, p->peername, p->username);
11586 username = auth->username;
11587 secret = auth->secret;
11588 md5secret = auth->md5secret;
11589 if (sipdebug)
11590 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11591 } else {
11592
11593 username = p->authname;
11594 secret = p->peersecret;
11595 md5secret = p->peermd5secret;
11596 }
11597 if (ast_strlen_zero(username))
11598 return -1;
11599
11600
11601 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11602 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11603 if (!ast_strlen_zero(md5secret))
11604 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11605 else
11606 ast_md5_hash(a1_hash,a1);
11607 ast_md5_hash(a2_hash,a2);
11608
11609 p->noncecount++;
11610 if (!ast_strlen_zero(p->qop))
11611 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11612 else
11613 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11614 ast_md5_hash(resp_hash, resp);
11615
11616 if (!ast_strlen_zero(p->qop))
11617 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\", qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, p->opaque, cnonce, p->noncecount);
11618 else
11619 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"", username, p->realm, uri, p->nonce, resp_hash, p->opaque);
11620
11621 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11622
11623 return 0;
11624 }
11625
11626 static char show_domains_usage[] =
11627 "Usage: sip show domains\n"
11628 " Lists all configured SIP local domains.\n"
11629 " Asterisk only responds to SIP messages to local domains.\n";
11630
11631 static char notify_usage[] =
11632 "Usage: sip notify <type> <peer> [<peer>...]\n"
11633 " Send a NOTIFY message to a SIP peer or peers\n"
11634 " Message types are defined in sip_notify.conf\n";
11635
11636 static char show_users_usage[] =
11637 "Usage: sip show users [like <pattern>]\n"
11638 " Lists all known SIP users.\n"
11639 " Optional regular expression pattern is used to filter the user list.\n";
11640
11641 static char show_user_usage[] =
11642 "Usage: sip show user <name> [load]\n"
11643 " Shows all details on one SIP user and the current status.\n"
11644 " Option \"load\" forces lookup of peer in realtime storage.\n";
11645
11646 static char show_inuse_usage[] =
11647 "Usage: sip show inuse [all]\n"
11648 " List all SIP users and peers usage counters and limits.\n"
11649 " Add option \"all\" to show all devices, not only those with a limit.\n";
11650
11651 static char show_channels_usage[] =
11652 "Usage: sip show channels\n"
11653 " Lists all currently active SIP channels.\n";
11654
11655 static char show_channel_usage[] =
11656 "Usage: sip show channel <channel>\n"
11657 " Provides detailed status on a given SIP channel.\n";
11658
11659 static char show_history_usage[] =
11660 "Usage: sip show history <channel>\n"
11661 " Provides detailed dialog history on a given SIP channel.\n";
11662
11663 static char show_peers_usage[] =
11664 "Usage: sip show peers [like <pattern>]\n"
11665 " Lists all known SIP peers.\n"
11666 " Optional regular expression pattern is used to filter the peer list.\n";
11667
11668 static char show_peer_usage[] =
11669 "Usage: sip show peer <name> [load]\n"
11670 " Shows all details on one SIP peer and the current status.\n"
11671 " Option \"load\" forces lookup of peer in realtime storage.\n";
11672
11673 static char prune_realtime_usage[] =
11674 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11675 " Prunes object(s) from the cache.\n"
11676 " Optional regular expression pattern is used to filter the objects.\n";
11677
11678 static char show_reg_usage[] =
11679 "Usage: sip show registry\n"
11680 " Lists all registration requests and status.\n";
11681
11682 static char debug_usage[] =
11683 "Usage: sip set debug\n"
11684 " Enables dumping of SIP packets for debugging purposes\n\n"
11685 " sip set debug ip <host[:PORT]>\n"
11686 " Enables dumping of SIP packets to and from host.\n\n"
11687 " sip set debug peer <peername>\n"
11688 " Enables dumping of SIP packets to and from host.\n"
11689 " Require peer to be registered.\n";
11690
11691 static char no_debug_usage[] =
11692 "Usage: sip set debug off\n"
11693 " Disables dumping of SIP packets for debugging purposes\n";
11694
11695 static char no_history_usage[] =
11696 "Usage: sip history off\n"
11697 " Disables recording of SIP dialog history for debugging purposes\n";
11698
11699 static char history_usage[] =
11700 "Usage: sip history\n"
11701 " Enables recording of SIP dialog history for debugging purposes.\n"
11702 "Use 'sip show history' to view the history of a call number.\n";
11703
11704 static char sip_reload_usage[] =
11705 "Usage: sip reload\n"
11706 " Reloads SIP configuration from sip.conf\n";
11707
11708 static char show_subscriptions_usage[] =
11709 "Usage: sip show subscriptions\n"
11710 " Lists active SIP subscriptions for extension states\n";
11711
11712 static char show_objects_usage[] =
11713 "Usage: sip show objects\n"
11714 " Lists status of known SIP objects\n";
11715
11716 static char show_settings_usage[] =
11717 "Usage: sip show settings\n"
11718 " Provides detailed list of the configuration of the SIP channel.\n";
11719
11720
11721 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11722 {
11723 struct sip_pvt *p;
11724 const char *content = NULL;
11725 AST_DECLARE_APP_ARGS(args,
11726 AST_APP_ARG(header);
11727 AST_APP_ARG(number);
11728 );
11729 int i, number, start = 0;
11730
11731 if (ast_strlen_zero(data)) {
11732 ast_log(LOG_WARNING, "This function requires a header name.\n");
11733 return -1;
11734 }
11735
11736 ast_channel_lock(chan);
11737 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11738 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11739 ast_channel_unlock(chan);
11740 return -1;
11741 }
11742
11743 AST_STANDARD_APP_ARGS(args, data);
11744 if (!args.number) {
11745 number = 1;
11746 } else {
11747 sscanf(args.number, "%d", &number);
11748 if (number < 1)
11749 number = 1;
11750 }
11751
11752 p = chan->tech_pvt;
11753
11754
11755 if (!p) {
11756 ast_channel_unlock(chan);
11757 return -1;
11758 }
11759
11760 for (i = 0; i < number; i++)
11761 content = __get_header(&p->initreq, args.header, &start);
11762
11763 if (ast_strlen_zero(content)) {
11764 ast_channel_unlock(chan);
11765 return -1;
11766 }
11767
11768 ast_copy_string(buf, content, len);
11769 ast_channel_unlock(chan);
11770
11771 return 0;
11772 }
11773
11774 static struct ast_custom_function sip_header_function = {
11775 .name = "SIP_HEADER",
11776 .synopsis = "Gets the specified SIP header",
11777 .syntax = "SIP_HEADER(<name>[,<number>])",
11778 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11779 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11780 "that name to retrieve. Headers start at offset 1.\n",
11781 .read = func_header_read,
11782 };
11783
11784
11785 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11786 {
11787 if (ast_strlen_zero(data)) {
11788 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11789 return -1;
11790 }
11791 if (check_sip_domain(data, NULL, 0))
11792 ast_copy_string(buf, data, len);
11793 else
11794 buf[0] = '\0';
11795 return 0;
11796 }
11797
11798 static struct ast_custom_function checksipdomain_function = {
11799 .name = "CHECKSIPDOMAIN",
11800 .synopsis = "Checks if domain is a local domain",
11801 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11802 .read = func_check_sipdomain,
11803 .desc = "This function checks if the domain in the argument is configured\n"
11804 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11805 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11806 "Check the domain= configuration in sip.conf\n",
11807 };
11808
11809
11810 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11811 {
11812 struct sip_peer *peer;
11813 char *colname;
11814
11815 if ((colname = strchr(data, ':')))
11816 *colname++ = '\0';
11817 else if ((colname = strchr(data, '|')))
11818 *colname++ = '\0';
11819 else
11820 colname = "ip";
11821
11822 if (!(peer = find_peer(data, NULL, 1)))
11823 return -1;
11824
11825 if (!strcasecmp(colname, "ip")) {
11826 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11827 } else if (!strcasecmp(colname, "status")) {
11828 peer_status(peer, buf, len);
11829 } else if (!strcasecmp(colname, "language")) {
11830 ast_copy_string(buf, peer->language, len);
11831 } else if (!strcasecmp(colname, "regexten")) {
11832 ast_copy_string(buf, peer->regexten, len);
11833 } else if (!strcasecmp(colname, "limit")) {
11834 snprintf(buf, len, "%d", peer->call_limit);
11835 } else if (!strcasecmp(colname, "curcalls")) {
11836 snprintf(buf, len, "%d", peer->inUse);
11837 } else if (!strcasecmp(colname, "accountcode")) {
11838 ast_copy_string(buf, peer->accountcode, len);
11839 } else if (!strcasecmp(colname, "useragent")) {
11840 ast_copy_string(buf, peer->useragent, len);
11841 } else if (!strcasecmp(colname, "mailbox")) {
11842 ast_copy_string(buf, peer->mailbox, len);
11843 } else if (!strcasecmp(colname, "context")) {
11844 ast_copy_string(buf, peer->context, len);
11845 } else if (!strcasecmp(colname, "expire")) {
11846 snprintf(buf, len, "%d", peer->expire);
11847 } else if (!strcasecmp(colname, "dynamic")) {
11848 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11849 } else if (!strcasecmp(colname, "callerid_name")) {
11850 ast_copy_string(buf, peer->cid_name, len);
11851 } else if (!strcasecmp(colname, "callerid_num")) {
11852 ast_copy_string(buf, peer->cid_num, len);
11853 } else if (!strcasecmp(colname, "codecs")) {
11854 ast_getformatname_multiple(buf, len -1, peer->capability);
11855 } else if (!strncasecmp(colname, "codec[", 6)) {
11856 char *codecnum;
11857 int index = 0, codec = 0;
11858
11859 codecnum = colname + 6;
11860 codecnum = strsep(&codecnum, "]");
11861 index = atoi(codecnum);
11862 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11863 ast_copy_string(buf, ast_getformatname(codec), len);
11864 }
11865 }
11866
11867 ASTOBJ_UNREF(peer, sip_destroy_peer);
11868
11869 return 0;
11870 }
11871
11872
11873 struct ast_custom_function sippeer_function = {
11874 .name = "SIPPEER",
11875 .synopsis = "Gets SIP peer information",
11876 .syntax = "SIPPEER(<peername>[|item])",
11877 .read = function_sippeer,
11878 .desc = "Valid items are:\n"
11879 "- ip (default) The IP address.\n"
11880 "- mailbox The configured mailbox.\n"
11881 "- context The configured context.\n"
11882 "- expire The epoch time of the next expire.\n"
11883 "- dynamic Is it dynamic? (yes/no).\n"
11884 "- callerid_name The configured Caller ID name.\n"
11885 "- callerid_num The configured Caller ID number.\n"
11886 "- codecs The configured codecs.\n"
11887 "- status Status (if qualify=yes).\n"
11888 "- regexten Registration extension\n"
11889 "- limit Call limit (call-limit)\n"
11890 "- curcalls Current amount of calls \n"
11891 " Only available if call-limit is set\n"
11892 "- language Default language for peer\n"
11893 "- accountcode Account code for this peer\n"
11894 "- useragent Current user agent id for peer\n"
11895 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11896 "\n"
11897 };
11898
11899
11900 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11901 {
11902 struct sip_pvt *p;
11903
11904 *buf = 0;
11905
11906 if (!data) {
11907 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
11908 return -1;
11909 }
11910
11911 ast_channel_lock(chan);
11912 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11913 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11914 ast_channel_unlock(chan);
11915 return -1;
11916 }
11917
11918 p = chan->tech_pvt;
11919
11920
11921 if (!p) {
11922 ast_channel_unlock(chan);
11923 return -1;
11924 }
11925
11926 if (!strcasecmp(data, "peerip")) {
11927 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
11928 } else if (!strcasecmp(data, "recvip")) {
11929 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
11930 } else if (!strcasecmp(data, "from")) {
11931 ast_copy_string(buf, p->from, len);
11932 } else if (!strcasecmp(data, "uri")) {
11933 ast_copy_string(buf, p->uri, len);
11934 } else if (!strcasecmp(data, "useragent")) {
11935 ast_copy_string(buf, p->useragent, len);
11936 } else if (!strcasecmp(data, "peername")) {
11937 ast_copy_string(buf, p->peername, len);
11938 } else if (!strcasecmp(data, "t38passthrough")) {
11939 if (p->t38.state == T38_DISABLED)
11940 ast_copy_string(buf, "0", sizeof("0"));
11941 else
11942 ast_copy_string(buf, "1", sizeof("1"));
11943 } else {
11944 ast_channel_unlock(chan);
11945 return -1;
11946 }
11947 ast_channel_unlock(chan);
11948
11949 return 0;
11950 }
11951
11952
11953 static struct ast_custom_function sipchaninfo_function = {
11954 .name = "SIPCHANINFO",
11955 .synopsis = "Gets the specified SIP parameter from the current channel",
11956 .syntax = "SIPCHANINFO(item)",
11957 .read = function_sipchaninfo_read,
11958 .desc = "Valid items are:\n"
11959 "- peerip The IP address of the peer.\n"
11960 "- recvip The source IP address of the peer.\n"
11961 "- from The URI from the From: header.\n"
11962 "- uri The URI from the Contact: header.\n"
11963 "- useragent The useragent.\n"
11964 "- peername The name of the peer.\n"
11965 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
11966 };
11967
11968
11969 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
11970 {
11971 char tmp[BUFSIZ];
11972 char *s, *e, *uri, *t;
11973 char *domain;
11974
11975 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
11976 if ((t = strchr(tmp, ',')))
11977 *t = '\0';
11978 s = get_in_brackets(tmp);
11979 uri = ast_strdupa(s);
11980 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
11981 if (!strncasecmp(s, "sip:", 4))
11982 s += 4;
11983 e = strchr(s, ';');
11984 if (e)
11985 *e = '\0';
11986 if (option_debug)
11987 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
11988 if (p->owner)
11989 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
11990 } else {
11991 e = strchr(tmp, '@');
11992 if (e) {
11993 *e++ = '\0';
11994 domain = e;
11995 } else {
11996
11997 domain = tmp;
11998 }
11999 e = strchr(s, ';');
12000 if (e)
12001 *e = '\0';
12002 e = strchr(domain, ';');
12003 if (e)
12004 *e = '\0';
12005
12006 if (!strncasecmp(s, "sip:", 4))
12007 s += 4;
12008 if (option_debug > 1)
12009 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
12010 if (p->owner) {
12011 pbx_builtin_setvar_helper(p->owner, "SIPREDIRECTURI", uri);
12012 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
12013 ast_string_field_set(p->owner, call_forward, s);
12014 }
12015 }
12016 }
12017
12018
12019 static void check_pendings(struct sip_pvt *p)
12020 {
12021 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
12022
12023 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
12024 transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
12025
12026
12027 else {
12028
12029
12030 if (p->pendinginvite)
12031 return;
12032
12033
12034 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
12035 }
12036 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
12037 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12038 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
12039
12040 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
12041 if (option_debug)
12042 ast_log(LOG_DEBUG, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
12043 } else {
12044 if (option_debug)
12045 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
12046
12047 transmit_reinvite_with_sdp(p);
12048 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
12049 }
12050 }
12051 }
12052
12053
12054
12055
12056
12057 static int sip_reinvite_retry(const void *data)
12058 {
12059 struct sip_pvt *p = (struct sip_pvt *) data;
12060
12061 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12062 p->waitid = -1;
12063 return 0;
12064 }
12065
12066
12067
12068 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12069 {
12070 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
12071 int res = 0;
12072 int xmitres = 0;
12073 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
12074 struct ast_channel *bridgepeer = NULL;
12075
12076 if (option_debug > 3) {
12077 if (reinvite)
12078 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
12079 else
12080 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
12081 }
12082
12083 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
12084 if (option_debug)
12085 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
12086 return;
12087 }
12088
12089
12090 if (p->initid > -1) {
12091
12092 ast_sched_del(sched, p->initid);
12093 p->initid = -1;
12094 }
12095
12096
12097
12098
12099 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
12100 resp = 183;
12101
12102
12103 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
12104 p->invitestate = INV_PROCEEDING;
12105
12106
12107 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
12108 p->invitestate = INV_COMPLETED;
12109
12110
12111 switch (resp) {
12112 case 100:
12113 case 101:
12114 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12115 sip_cancel_destroy(p);
12116 check_pendings(p);
12117 break;
12118
12119 case 180:
12120 case 182:
12121 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12122 sip_cancel_destroy(p);
12123 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12124 ast_queue_control(p->owner, AST_CONTROL_RINGING);
12125 if (p->owner->_state != AST_STATE_UP) {
12126 ast_setstate(p->owner, AST_STATE_RINGING);
12127 }
12128 }
12129 if (find_sdp(req)) {
12130 p->invitestate = INV_EARLY_MEDIA;
12131 res = process_sdp(p, req);
12132 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12133
12134 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12135 }
12136 }
12137 check_pendings(p);
12138 break;
12139
12140 case 183:
12141 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12142 sip_cancel_destroy(p);
12143
12144 if (find_sdp(req)) {
12145 p->invitestate = INV_EARLY_MEDIA;
12146 res = process_sdp(p, req);
12147 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12148
12149 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12150 }
12151 }
12152 check_pendings(p);
12153 break;
12154
12155 case 200:
12156 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12157 sip_cancel_destroy(p);
12158 p->authtries = 0;
12159 if (find_sdp(req)) {
12160 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
12161 if (!reinvite)
12162
12163
12164 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12165 }
12166
12167
12168
12169
12170 if (outgoing) {
12171 update_call_counter(p, DEC_CALL_RINGING);
12172 parse_ok_contact(p, req);
12173 if(set_address_from_contact(p)) {
12174
12175
12176
12177
12178
12179
12180
12181 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12182 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12183 }
12184
12185
12186 build_route(p, req, 1);
12187 }
12188
12189 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) {
12190 struct sip_pvt *bridgepvt = NULL;
12191
12192 if (!bridgepeer->tech) {
12193 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
12194 break;
12195 }
12196 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
12197 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
12198 if (bridgepvt->udptl) {
12199 if (p->t38.state == T38_PEER_REINVITE) {
12200 sip_handle_t38_reinvite(bridgepeer, p, 0);
12201 ast_rtp_set_rtptimers_onhold(p->rtp);
12202 if (p->vrtp)
12203 ast_rtp_set_rtptimers_onhold(p->vrtp);
12204 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
12205 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
12206
12207
12208 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12209 }
12210 } else {
12211 if (option_debug > 1)
12212 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
12213 ast_mutex_lock(&bridgepvt->lock);
12214 bridgepvt->t38.state = T38_DISABLED;
12215 ast_mutex_unlock(&bridgepvt->lock);
12216 if (option_debug)
12217 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
12218 p->t38.state = T38_DISABLED;
12219 if (option_debug > 1)
12220 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12221 }
12222 } else {
12223
12224 if (option_debug > 1)
12225 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
12226 p->t38.state = T38_DISABLED;
12227 if (option_debug > 1)
12228 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12229 }
12230 }
12231 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
12232
12233 p->t38.state = T38_ENABLED;
12234 if (option_debug)
12235 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12236 }
12237
12238 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
12239 if (!reinvite) {
12240 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
12241 } else {
12242 ast_queue_frame(p->owner, &ast_null_frame);
12243 }
12244 } else {
12245
12246
12247
12248 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12249 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12250 }
12251
12252 p->invitestate = INV_TERMINATED;
12253 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
12254 check_pendings(p);
12255 break;
12256 case 407:
12257 case 401:
12258
12259 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12260 if (p->options)
12261 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
12262
12263
12264 ast_string_field_free(p, theirtag);
12265 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12266 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
12267 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
12268 if (p->authtries < MAX_AUTHTRIES)
12269 p->invitestate = INV_CALLING;
12270 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
12271 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
12272 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12273 sip_alreadygone(p);
12274 if (p->owner)
12275 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12276 }
12277 }
12278 break;
12279
12280 case 403:
12281
12282 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12283 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
12284 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
12285 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12286 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12287 sip_alreadygone(p);
12288 break;
12289
12290 case 404:
12291 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12292 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12293 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12294 sip_alreadygone(p);
12295 break;
12296
12297 case 408:
12298 case 481:
12299
12300 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
12301 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12302 if (p->owner)
12303 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12304 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12305 break;
12306 case 487:
12307
12308
12309
12310 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12311 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12312 ast_queue_hangup(p->owner);
12313 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
12314 } else if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
12315 update_call_counter(p, DEC_CALL_LIMIT);
12316 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
12317 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12318 sip_alreadygone(p);
12319 }
12320 break;
12321 case 488:
12322 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12323 if (reinvite && p->udptl) {
12324
12325
12326
12327
12328
12329 p->t38.state = T38_DISABLED;
12330
12331 ast_rtp_set_rtptimers_onhold(p->rtp);
12332 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
12333
12334
12335
12336
12337
12338 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12339 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12340 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12341 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
12342
12343
12344
12345 p->t38.state = T38_DISABLED;
12346
12347 ast_rtp_set_rtptimers_onhold(p->rtp);
12348 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
12349
12350
12351 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12352 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12353 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12354 sip_alreadygone(p);
12355 } else {
12356
12357 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
12358 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12359 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12360 }
12361 break;
12362 case 491:
12363
12364
12365
12366 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12367 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE)) {
12368 if (p->owner->_state != AST_STATE_UP) {
12369 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12370 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12371 } else {
12372
12373
12374
12375 int wait = 3 + ast_random() % 5;
12376 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, p);
12377 if (option_debug > 2)
12378 ast_log(LOG_DEBUG, "Reinvite race. Waiting %d secs before retry\n", wait);
12379 }
12380 }
12381 break;
12382
12383 case 501:
12384 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12385 if (p->owner)
12386 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12387 break;
12388 }
12389 if (xmitres == XMIT_ERROR)
12390 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
12391 }
12392
12393
12394
12395
12396 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
12397 {
12398 char *auth = "Proxy-Authenticate";
12399 char *auth2 = "Proxy-Authorization";
12400
12401
12402 if (!p->refer)
12403 return;
12404
12405 switch (resp) {
12406 case 202:
12407
12408
12409 p->refer->status = REFER_ACCEPTED;
12410
12411 if (option_debug > 2)
12412 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
12413
12414 break;
12415
12416 case 401:
12417 case 407:
12418 if (ast_strlen_zero(p->authname)) {
12419 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
12420 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12421 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12422 }
12423 if (resp == 401) {
12424 auth = "WWW-Authenticate";
12425 auth2 = "Authorization";
12426 }
12427 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
12428 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
12429 p->refer->status = REFER_NOAUTH;
12430 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12431 }
12432 break;
12433 case 481:
12434
12435
12436
12437
12438 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
12439 if (p->owner)
12440 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12441 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12442 break;
12443
12444 case 500:
12445 case 501:
12446
12447
12448 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
12449 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12450 p->refer->status = REFER_FAILED;
12451 break;
12452 case 603:
12453 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
12454 p->refer->status = REFER_FAILED;
12455 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12456 break;
12457 }
12458 }
12459
12460
12461 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12462 {
12463 int expires, expires_ms;
12464 struct sip_registry *r;
12465 r=p->registry;
12466
12467 switch (resp) {
12468 case 401:
12469 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
12470 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
12471 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12472 }
12473 break;
12474 case 403:
12475 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
12476 if (global_regattempts_max)
12477 p->registry->regattempts = global_regattempts_max+1;
12478 ast_sched_del(sched, r->timeout);
12479 r->timeout = -1;
12480 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12481 break;
12482 case 404:
12483 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
12484 if (global_regattempts_max)
12485 p->registry->regattempts = global_regattempts_max+1;
12486 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12487 r->call = NULL;
12488 ast_sched_del(sched, r->timeout);
12489 r->timeout = -1;
12490 break;
12491 case 407:
12492 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12493 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12494 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12495 }
12496 break;
12497 case 408:
12498 if (global_regattempts_max)
12499 p->registry->regattempts = global_regattempts_max+1;
12500 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12501 r->call = NULL;
12502 ast_sched_del(sched, r->timeout);
12503 r->timeout = -1;
12504 break;
12505 case 479:
12506 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12507 if (global_regattempts_max)
12508 p->registry->regattempts = global_regattempts_max+1;
12509 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12510 r->call = NULL;
12511 ast_sched_del(sched, r->timeout);
12512 r->timeout = -1;
12513 break;
12514 case 200:
12515 if (!r) {
12516 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12517 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12518 return 0;
12519 }
12520
12521 r->regstate = REG_STATE_REGISTERED;
12522 r->regtime = time(NULL);
12523 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12524 r->regattempts = 0;
12525 if (option_debug)
12526 ast_log(LOG_DEBUG, "Registration successful\n");
12527 if (r->timeout > -1) {
12528 if (option_debug)
12529 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12530 ast_sched_del(sched, r->timeout);
12531 }
12532 r->timeout=-1;
12533 r->call = NULL;
12534 p->registry = NULL;
12535
12536 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12537
12538
12539
12540
12541 if (r->expire > -1)
12542 ast_sched_del(sched, r->expire);
12543
12544
12545 expires = 0;
12546
12547
12548 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12549 const char *contact = NULL;
12550 const char *tmptmp = NULL;
12551 int start = 0;
12552 for(;;) {
12553 contact = __get_header(req, "Contact", &start);
12554
12555 if(!ast_strlen_zero(contact)) {
12556 if( (tmptmp=strstr(contact, p->our_contact))) {
12557 contact=tmptmp;
12558 break;
12559 }
12560 } else
12561 break;
12562 }
12563 tmptmp = strcasestr(contact, "expires=");
12564 if (tmptmp) {
12565 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12566 expires = 0;
12567 }
12568
12569 }
12570 if (!expires)
12571 expires=atoi(get_header(req, "expires"));
12572 if (!expires)
12573 expires=default_expiry;
12574
12575 expires_ms = expires * 1000;
12576 if (expires <= EXPIRY_GUARD_LIMIT)
12577 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12578 else
12579 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12580 if (sipdebug)
12581 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12582
12583 r->refresh= (int) expires_ms / 1000;
12584
12585
12586 if (r->expire > -1)
12587 ast_sched_del(sched, r->expire);
12588 r->expire = ast_sched_add(sched, expires_ms, sip_reregister, r);
12589 ASTOBJ_UNREF(r, sip_registry_destroy);
12590 }
12591 return 1;
12592 }
12593
12594
12595 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12596 {
12597 struct sip_peer *peer = p->relatedpeer;
12598 int statechanged, is_reachable, was_reachable;
12599 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12600
12601
12602
12603
12604
12605
12606 if (pingtime < 1)
12607 pingtime = 1;
12608
12609
12610
12611
12612
12613 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12614 is_reachable = pingtime <= peer->maxms;
12615 statechanged = peer->lastms == 0
12616 || was_reachable != is_reachable;
12617
12618 peer->lastms = pingtime;
12619 peer->call = NULL;
12620 if (statechanged) {
12621 const char *s = is_reachable ? "Reachable" : "Lagged";
12622
12623 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12624 peer->name, s, pingtime, peer->maxms);
12625 ast_device_state_changed("SIP/%s", peer->name);
12626 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12627 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12628 peer->name, s, pingtime);
12629 }
12630
12631 if (peer->pokeexpire > -1)
12632 ast_sched_del(sched, peer->pokeexpire);
12633 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12634
12635
12636 peer->pokeexpire = ast_sched_add(sched,
12637 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12638 sip_poke_peer_s, peer);
12639 }
12640
12641
12642 static void stop_media_flows(struct sip_pvt *p)
12643 {
12644
12645 if (p->rtp)
12646 ast_rtp_stop(p->rtp);
12647 if (p->vrtp)
12648 ast_rtp_stop(p->vrtp);
12649 if (p->udptl)
12650 ast_udptl_stop(p->udptl);
12651 }
12652
12653
12654
12655 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12656 {
12657 struct ast_channel *owner;
12658 int sipmethod;
12659 int res = 1;
12660 const char *c = get_header(req, "Cseq");
12661 const char *msg = strchr(c, ' ');
12662
12663 if (!msg)
12664 msg = "";
12665 else
12666 msg++;
12667 sipmethod = find_sip_method(msg);
12668
12669 owner = p->owner;
12670 if (owner)
12671 owner->hangupcause = hangup_sip2cause(resp);
12672
12673
12674 if ((resp >= 100) && (resp <= 199))
12675 __sip_semi_ack(p, seqno, 0, sipmethod);
12676 else
12677 __sip_ack(p, seqno, 0, sipmethod);
12678
12679
12680 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12681 char tag[128];
12682
12683 gettag(req, "To", tag, sizeof(tag));
12684 ast_string_field_set(p, theirtag, tag);
12685 }
12686 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12687
12688
12689
12690 if (resp != 100)
12691 handle_response_peerpoke(p, resp, req);
12692 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12693 switch(resp) {
12694 case 100:
12695 case 101:
12696 if (sipmethod == SIP_INVITE)
12697 handle_response_invite(p, resp, rest, req, seqno);
12698 break;
12699 case 183:
12700 if (sipmethod == SIP_INVITE)
12701 handle_response_invite(p, resp, rest, req, seqno);
12702 break;
12703 case 180:
12704 if (sipmethod == SIP_INVITE)
12705 handle_response_invite(p, resp, rest, req, seqno);
12706 break;
12707 case 182:
12708 if (sipmethod == SIP_INVITE)
12709 handle_response_invite(p, resp, rest, req, seqno);
12710 break;
12711 case 200:
12712 p->authtries = 0;
12713 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
12714
12715
12716
12717 } else if (sipmethod == SIP_INVITE) {
12718 handle_response_invite(p, resp, rest, req, seqno);
12719 } else if (sipmethod == SIP_NOTIFY) {
12720
12721 if (p->owner) {
12722 if (!p->refer) {
12723 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12724 ast_queue_hangup(p->owner);
12725 } else if (option_debug > 3)
12726 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12727 } else {
12728 if (p->subscribed == NONE)
12729 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12730 }
12731 } else if (sipmethod == SIP_REGISTER)
12732 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12733 else if (sipmethod == SIP_BYE)
12734 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12735 break;
12736 case 202:
12737 if (sipmethod == SIP_REFER)
12738 handle_response_refer(p, resp, rest, req, seqno);
12739 break;
12740 case 401:
12741 if (sipmethod == SIP_INVITE)
12742 handle_response_invite(p, resp, rest, req, seqno);
12743 else if (sipmethod == SIP_REFER)
12744 handle_response_refer(p, resp, rest, req, seqno);
12745 else if (p->registry && sipmethod == SIP_REGISTER)
12746 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12747 else if (sipmethod == SIP_BYE) {
12748 if (ast_strlen_zero(p->authname)) {
12749 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12750 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12751 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12752 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", sipmethod, 0)) {
12753 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12754 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12755
12756
12757 }
12758 } else {
12759 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12760 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12761 }
12762 break;
12763 case 403:
12764 if (sipmethod == SIP_INVITE)
12765 handle_response_invite(p, resp, rest, req, seqno);
12766 else if (p->registry && sipmethod == SIP_REGISTER)
12767 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12768 else {
12769 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12770 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12771 }
12772 break;
12773 case 404:
12774 if (p->registry && sipmethod == SIP_REGISTER)
12775 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12776 else if (sipmethod == SIP_INVITE)
12777 handle_response_invite(p, resp, rest, req, seqno);
12778 else if (owner)
12779 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12780 break;
12781 case 407:
12782 if (sipmethod == SIP_INVITE)
12783 handle_response_invite(p, resp, rest, req, seqno);
12784 else if (sipmethod == SIP_REFER)
12785 handle_response_refer(p, resp, rest, req, seqno);
12786 else if (p->registry && sipmethod == SIP_REGISTER)
12787 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12788 else if (sipmethod == SIP_BYE) {
12789 if (ast_strlen_zero(p->authname)) {
12790 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12791 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12792 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12793 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12794 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12795 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12796 }
12797 } else
12798 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12799
12800 break;
12801 case 408:
12802 if (sipmethod == SIP_INVITE)
12803 handle_response_invite(p, resp, rest, req, seqno);
12804 else if (sipmethod == SIP_REGISTER)
12805 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12806 else if (sipmethod == SIP_BYE) {
12807 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12808 if (option_debug)
12809 ast_log(LOG_DEBUG, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
12810 } else {
12811 if (owner)
12812 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12813 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12814 }
12815 break;
12816 case 481:
12817 if (sipmethod == SIP_INVITE) {
12818 handle_response_invite(p, resp, rest, req, seqno);
12819 } else if (sipmethod == SIP_REFER) {
12820 handle_response_refer(p, resp, rest, req, seqno);
12821 } else if (sipmethod == SIP_BYE) {
12822
12823
12824 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12825 } else if (sipmethod == SIP_CANCEL) {
12826
12827
12828 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12829 } else {
12830 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12831
12832 }
12833 break;
12834 case 487:
12835 if (sipmethod == SIP_INVITE)
12836 handle_response_invite(p, resp, rest, req, seqno);
12837 break;
12838 case 488:
12839 if (sipmethod == SIP_INVITE)
12840 handle_response_invite(p, resp, rest, req, seqno);
12841 break;
12842 case 491:
12843 if (sipmethod == SIP_INVITE)
12844 handle_response_invite(p, resp, rest, req, seqno);
12845 else {
12846 if (option_debug)
12847 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
12848 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12849 }
12850 break;
12851 case 501:
12852 if (sipmethod == SIP_INVITE)
12853 handle_response_invite(p, resp, rest, req, seqno);
12854 else if (sipmethod == SIP_REFER)
12855 handle_response_refer(p, resp, rest, req, seqno);
12856 else
12857 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
12858 break;
12859 case 603:
12860 if (sipmethod == SIP_REFER) {
12861 handle_response_refer(p, resp, rest, req, seqno);
12862 break;
12863 }
12864
12865 default:
12866 if ((resp >= 300) && (resp < 700)) {
12867
12868 if ((option_verbose > 2) && (resp != 487))
12869 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
12870
12871 if (sipmethod == SIP_INVITE)
12872 stop_media_flows(p);
12873
12874
12875 switch(resp) {
12876 case 300:
12877 case 301:
12878 case 302:
12879 case 305:
12880 parse_moved_contact(p, req);
12881
12882 case 486:
12883 case 600:
12884 case 603:
12885 if (p->owner)
12886 ast_queue_control(p->owner, AST_CONTROL_BUSY);
12887 break;
12888 case 482:
12889
12890
12891
12892
12893 if (option_debug)
12894 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
12895 if (p->owner)
12896 ast_string_field_build(p->owner, call_forward,
12897 "Local/%s@%s", p->username, p->context);
12898
12899 case 480:
12900 case 404:
12901 case 410:
12902 case 400:
12903 case 500:
12904 if (sipmethod == SIP_REFER) {
12905 handle_response_refer(p, resp, rest, req, seqno);
12906 break;
12907 }
12908
12909 case 503:
12910 case 504:
12911 if (owner)
12912 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12913 break;
12914 default:
12915
12916 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
12917 ast_queue_hangup(p->owner);
12918 break;
12919 }
12920
12921 if (sipmethod == SIP_INVITE)
12922 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12923 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
12924 sip_alreadygone(p);
12925 if (!p->owner)
12926 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12927 } else if ((resp >= 100) && (resp < 200)) {
12928 if (sipmethod == SIP_INVITE) {
12929 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12930 sip_cancel_destroy(p);
12931 if (find_sdp(req))
12932 process_sdp(p, req);
12933 if (p->owner) {
12934
12935 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12936 }
12937 }
12938 } else
12939 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));
12940 }
12941 } else {
12942
12943
12944 if (ast_test_flag(req, SIP_PKT_DEBUG))
12945 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
12946
12947 if (sipmethod == SIP_INVITE && resp == 200) {
12948
12949
12950 char tag[128];
12951
12952 gettag(req, "To", tag, sizeof(tag));
12953 ast_string_field_set(p, theirtag, tag);
12954 }
12955
12956 switch(resp) {
12957 case 200:
12958 if (sipmethod == SIP_INVITE) {
12959 handle_response_invite(p, resp, rest, req, seqno);
12960 } else if (sipmethod == SIP_CANCEL) {
12961 if (option_debug)
12962 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
12963
12964
12965 } else if (sipmethod == SIP_NOTIFY) {
12966
12967 if (p->owner) {
12968 if (p->refer) {
12969 if (option_debug)
12970 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
12971 } else
12972 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
12973
12974 } else {
12975 if (!p->subscribed && !p->refer)
12976 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12977 }
12978 } else if (sipmethod == SIP_BYE)
12979 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12980 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
12981
12982
12983 ;
12984 else if (sipmethod == SIP_BYE)
12985
12986 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12987 break;
12988 case 202:
12989 if (sipmethod == SIP_REFER)
12990 handle_response_refer(p, resp, rest, req, seqno);
12991 break;
12992 case 401:
12993 case 407:
12994 if (sipmethod == SIP_REFER)
12995 handle_response_refer(p, resp, rest, req, seqno);
12996 else if (sipmethod == SIP_INVITE)
12997 handle_response_invite(p, resp, rest, req, seqno);
12998 else if (sipmethod == SIP_BYE) {
12999 char *auth, *auth2;
13000
13001 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
13002 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
13003 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
13004 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
13005 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13006 }
13007 }
13008 break;
13009 case 481:
13010 if (sipmethod == SIP_INVITE) {
13011
13012 handle_response_invite(p, resp, rest, req, seqno);
13013 } else if (sipmethod == SIP_BYE) {
13014 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13015 } else if (sipdebug) {
13016 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
13017 }
13018 break;
13019 case 501:
13020 if (sipmethod == SIP_INVITE)
13021 handle_response_invite(p, resp, rest, req, seqno);
13022 else if (sipmethod == SIP_REFER)
13023 handle_response_refer(p, resp, rest, req, seqno);
13024 break;
13025 case 603:
13026 if (sipmethod == SIP_REFER) {
13027 handle_response_refer(p, resp, rest, req, seqno);
13028 break;
13029 }
13030
13031 default:
13032 if ((resp >= 100) && (resp < 200)) {
13033 if (sipmethod == SIP_INVITE) {
13034 if (!ast_test_flag(req, SIP_PKT_IGNORE))
13035 sip_cancel_destroy(p);
13036 }
13037 }
13038 if ((resp >= 300) && (resp < 700)) {
13039 if ((option_verbose > 2) && (resp != 487))
13040 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));
13041 switch(resp) {
13042 case 488:
13043 case 603:
13044 case 500:
13045 case 503:
13046 case 504:
13047
13048 if (sipmethod == SIP_INVITE) {
13049 sip_cancel_destroy(p);
13050 }
13051 break;
13052 }
13053 }
13054 break;
13055 }
13056 }
13057 }
13058
13059
13060
13061
13062
13063
13064
13065 static void *sip_park_thread(void *stuff)
13066 {
13067 struct ast_channel *transferee, *transferer;
13068 struct sip_dual *d;
13069 struct sip_request req;
13070 int ext;
13071 int res;
13072
13073 d = stuff;
13074 transferee = d->chan1;
13075 transferer = d->chan2;
13076 copy_request(&req, &d->req);
13077 free(d);
13078
13079 if (!transferee || !transferer) {
13080 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
13081 return NULL;
13082 }
13083 if (option_debug > 3)
13084 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
13085
13086 ast_channel_lock(transferee);
13087 if (ast_do_masquerade(transferee)) {
13088 ast_log(LOG_WARNING, "Masquerade failed.\n");
13089 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
13090 ast_channel_unlock(transferee);
13091 return NULL;
13092 }
13093 ast_channel_unlock(transferee);
13094
13095 res = ast_park_call(transferee, transferer, 0, &ext);
13096
13097
13098 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
13099 if (!res) {
13100 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
13101 } else {
13102
13103 sprintf(buf, "Call parked on extension '%d'", ext);
13104 transmit_message_with_text(transferer->tech_pvt, buf);
13105 }
13106 #endif
13107
13108
13109
13110 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
13111 if (!res) {
13112
13113 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
13114 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
13115 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13116 ast_hangup(transferer);
13117 if (option_debug)
13118 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
13119 } else {
13120 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
13121 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
13122 if (option_debug)
13123 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
13124
13125 }
13126 return NULL;
13127 }
13128
13129
13130
13131
13132 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
13133 {
13134 struct sip_dual *d;
13135 struct ast_channel *transferee, *transferer;
13136
13137 pthread_t th;
13138
13139 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
13140 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
13141 if ((!transferer) || (!transferee)) {
13142 if (transferee) {
13143 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13144 ast_hangup(transferee);
13145 }
13146 if (transferer) {
13147 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13148 ast_hangup(transferer);
13149 }
13150 return -1;
13151 }
13152
13153
13154 transferee->readformat = chan1->readformat;
13155 transferee->writeformat = chan1->writeformat;
13156
13157
13158 ast_channel_masquerade(transferee, chan1);
13159
13160
13161 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
13162 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
13163 transferee->priority = chan1->priority;
13164
13165
13166
13167
13168
13169 transferer->readformat = chan2->readformat;
13170 transferer->writeformat = chan2->writeformat;
13171
13172
13173
13174
13175 while (ast_channel_trylock(chan2)) {
13176 struct sip_pvt *pvt = chan2->tech_pvt;
13177 ast_mutex_unlock(&pvt->lock);
13178 usleep(1);
13179 ast_mutex_lock(&pvt->lock);
13180 }
13181 ast_channel_masquerade(transferer, chan2);
13182 ast_channel_unlock(chan2);
13183
13184
13185 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
13186 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
13187 transferer->priority = chan2->priority;
13188
13189 ast_channel_lock(transferer);
13190 if (ast_do_masquerade(transferer)) {
13191 ast_log(LOG_WARNING, "Masquerade failed :(\n");
13192 ast_channel_unlock(transferer);
13193 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13194 ast_hangup(transferer);
13195 return -1;
13196 }
13197 ast_channel_unlock(transferer);
13198 if (!transferer || !transferee) {
13199 if (!transferer) {
13200 if (option_debug)
13201 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
13202 }
13203 if (!transferee) {
13204 if (option_debug)
13205 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
13206 }
13207 return -1;
13208 }
13209 if ((d = ast_calloc(1, sizeof(*d)))) {
13210 pthread_attr_t attr;
13211
13212 pthread_attr_init(&attr);
13213 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13214
13215
13216 copy_request(&d->req, req);
13217 d->chan1 = transferee;
13218 d->chan2 = transferer;
13219 d->seqno = seqno;
13220 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
13221
13222 free(d);
13223
13224 pthread_attr_destroy(&attr);
13225 return 0;
13226 }
13227 pthread_attr_destroy(&attr);
13228 }
13229 return -1;
13230 }
13231
13232
13233
13234
13235 static void ast_quiet_chan(struct ast_channel *chan)
13236 {
13237 if (chan && chan->_state == AST_STATE_UP) {
13238 if (chan->generatordata)
13239 ast_deactivate_generator(chan);
13240 }
13241 }
13242
13243
13244
13245 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
13246 {
13247 int res = 0;
13248 struct ast_channel *peera = NULL,
13249 *peerb = NULL,
13250 *peerc = NULL,
13251 *peerd = NULL;
13252
13253
13254
13255
13256 if (option_debug > 3) {
13257 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
13258 if (transferer->chan1)
13259 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
13260 else
13261 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
13262 if (target->chan1)
13263 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
13264 else
13265 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
13266 if (transferer->chan2)
13267 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
13268 else
13269 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
13270 if (target->chan2)
13271 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)");
13272 else
13273 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
13274 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
13275 }
13276 if (transferer->chan2) {
13277 peera = transferer->chan1;
13278 peerb = target->chan1;
13279 peerc = transferer->chan2;
13280 peerd = target->chan2;
13281 if (option_debug > 2)
13282 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
13283 } else if (target->chan2) {
13284 peera = target->chan1;
13285 peerb = transferer->chan1;
13286 peerc = target->chan2;
13287 peerd = transferer->chan2;
13288 if (option_debug > 2)
13289 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
13290 }
13291
13292 if (peera && peerb && peerc && (peerb != peerc)) {
13293 ast_quiet_chan(peera);
13294 ast_quiet_chan(peerb);
13295 ast_quiet_chan(peerc);
13296 if (peerd)
13297 ast_quiet_chan(peerd);
13298
13299
13300 if (peera->cdr && peerb->cdr)
13301 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
13302 else if (peera->cdr)
13303 peerb->cdr = peera->cdr;
13304 peera->cdr = NULL;
13305
13306 if (peerb->cdr && peerc->cdr)
13307 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
13308 else if (peerc->cdr)
13309 peerb->cdr = peerc->cdr;
13310 peerc->cdr = NULL;
13311
13312 if (option_debug > 3)
13313 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
13314 if (ast_channel_masquerade(peerb, peerc)) {
13315 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
13316 res = -1;
13317 } else
13318 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
13319 return res;
13320 } else {
13321 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
13322 if (transferer->chan1)
13323 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
13324 if (target->chan1)
13325 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
13326 return -2;
13327 }
13328 return 0;
13329 }
13330
13331
13332
13333
13334
13335
13336 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
13337 {
13338 const char *thetag;
13339
13340 if (!tagbuf)
13341 return NULL;
13342 tagbuf[0] = '\0';
13343 thetag = get_header(req, header);
13344 thetag = strcasestr(thetag, ";tag=");
13345 if (thetag) {
13346 thetag += 5;
13347 ast_copy_string(tagbuf, thetag, tagbufsize);
13348 return strsep(&tagbuf, ";");
13349 }
13350 return NULL;
13351 }
13352
13353
13354 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
13355 {
13356
13357
13358 int res = 0;
13359 const char *event = get_header(req, "Event");
13360 char *eventid = NULL;
13361 char *sep;
13362
13363 if( (sep = strchr(event, ';')) ) {
13364 *sep++ = '\0';
13365 eventid = sep;
13366 }
13367
13368 if (option_debug > 1 && sipdebug)
13369 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
13370
13371 if (strcmp(event, "refer")) {
13372
13373
13374 transmit_response(p, "489 Bad event", req);
13375 res = -1;
13376 } else {
13377
13378
13379
13380
13381
13382 char buf[1024];
13383 char *cmd, *code;
13384 int respcode;
13385 int success = TRUE;
13386
13387
13388
13389
13390
13391
13392
13393
13394 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
13395
13396 transmit_response(p, "400 Bad request", req);
13397 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13398 return -1;
13399 }
13400
13401
13402 if (get_msg_text(buf, sizeof(buf), req)) {
13403 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
13404 transmit_response(p, "400 Bad request", req);
13405 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13406 return -1;
13407 }
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429 if (option_debug > 2)
13430 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
13431 cmd = ast_skip_blanks(buf);
13432 code = cmd;
13433
13434 while(*code && (*code > 32)) {
13435 code++;
13436 }
13437 *code++ = '\0';
13438 code = ast_skip_blanks(code);
13439 sep = code;
13440 sep++;
13441 while(*sep && (*sep > 32)) {
13442 sep++;
13443 }
13444 *sep++ = '\0';
13445 respcode = atoi(code);
13446 switch (respcode) {
13447 case 100:
13448 case 101:
13449
13450 break;
13451 case 183:
13452
13453 break;
13454 case 200:
13455
13456 break;
13457 case 301:
13458 case 302:
13459
13460 success = FALSE;
13461 break;
13462 case 503:
13463
13464 success = FALSE;
13465 break;
13466 case 603:
13467
13468 success = FALSE;
13469 break;
13470 }
13471 if (!success) {
13472 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
13473 }
13474
13475
13476 transmit_response(p, "200 OK", req);
13477 };
13478
13479 if (!p->lastinvite)
13480 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13481
13482 return res;
13483 }
13484
13485
13486 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
13487 {
13488 int res;
13489
13490 res = get_destination(p, req);
13491 build_contact(p);
13492
13493
13494
13495 if (ast_strlen_zero(p->context))
13496 ast_string_field_set(p, context, default_context);
13497
13498 if (ast_shutting_down())
13499 transmit_response_with_allow(p, "503 Unavailable", req, 0);
13500 else if (res < 0)
13501 transmit_response_with_allow(p, "404 Not Found", req, 0);
13502 else
13503 transmit_response_with_allow(p, "200 OK", req, 0);
13504
13505
13506
13507 if (!p->lastinvite)
13508 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13509
13510 return res;
13511 }
13512
13513
13514
13515 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
13516 {
13517 struct ast_frame *f;
13518 int earlyreplace = 0;
13519 int oneleggedreplace = 0;
13520 struct ast_channel *c = p->owner;
13521 struct ast_channel *replacecall = p->refer->refer_call->owner;
13522 struct ast_channel *targetcall;
13523
13524
13525 if (replacecall->_state == AST_STATE_RING)
13526 earlyreplace = 1;
13527
13528
13529 if (!(targetcall = ast_bridged_channel(replacecall))) {
13530
13531 if (!earlyreplace) {
13532 if (option_debug > 1)
13533 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
13534 oneleggedreplace = 1;
13535 }
13536 }
13537 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
13538 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
13539
13540 if (option_debug > 3) {
13541 if (targetcall)
13542 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);
13543 else
13544 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
13545 }
13546
13547 if (ignore) {
13548 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
13549
13550
13551
13552 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13553
13554 ast_channel_unlock(c);
13555 ast_mutex_unlock(&p->refer->refer_call->lock);
13556 return 1;
13557 }
13558 if (!c) {
13559
13560 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13561 transmit_response_reliable(p, "503 Service Unavailable", req);
13562 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13563 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13564 ast_mutex_unlock(&p->refer->refer_call->lock);
13565 return 1;
13566 }
13567 append_history(p, "Xfer", "INVITE/Replace received");
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579 transmit_response(p, "100 Trying", req);
13580 ast_setstate(c, AST_STATE_RING);
13581
13582
13583
13584
13585
13586 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13587
13588 ast_setstate(c, AST_STATE_UP);
13589
13590
13591 ast_quiet_chan(replacecall);
13592 ast_quiet_chan(targetcall);
13593 if (option_debug > 3)
13594 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13595
13596 if (!oneleggedreplace)
13597 ast_channel_unlock(c);
13598
13599
13600 ast_mutex_unlock(&p->refer->refer_call->lock);
13601
13602
13603 if (! earlyreplace && ! oneleggedreplace )
13604 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
13605
13606
13607 if(ast_channel_masquerade(replacecall, c))
13608 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13609 else if (option_debug > 3)
13610 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13611
13612
13613
13614
13615
13616 ast_channel_unlock(c);
13617
13618 if (earlyreplace || oneleggedreplace ) {
13619
13620 if ((f = ast_read(replacecall))) {
13621 ast_frfree(f);
13622 f = NULL;
13623 if (option_debug > 3)
13624 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13625 } else {
13626 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13627 }
13628 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13629 if (!oneleggedreplace)
13630 ast_channel_unlock(replacecall);
13631 } else {
13632 if ((f = ast_read(replacecall))) {
13633
13634 ast_frfree(f);
13635 f = NULL;
13636 if (option_debug > 2)
13637 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13638 } else {
13639 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13640 }
13641 ast_channel_unlock(replacecall);
13642 }
13643 ast_mutex_unlock(&p->refer->refer_call->lock);
13644
13645 ast_setstate(c, AST_STATE_DOWN);
13646 if (option_debug > 3) {
13647 struct ast_channel *test;
13648 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13649 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13650 if (replacecall)
13651 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13652 if (p->owner) {
13653 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13654 test = ast_bridged_channel(p->owner);
13655 if (test)
13656 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13657 else
13658 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13659 } else
13660 ast_log(LOG_DEBUG, " -- No channel yet \n");
13661 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13662 }
13663
13664 ast_channel_unlock(p->owner);
13665 if (!oneleggedreplace)
13666 ast_mutex_unlock(&p->lock);
13667
13668
13669 c->tech_pvt = NULL;
13670 ast_hangup(c);
13671 return 0;
13672 }
13673
13674
13675
13676
13677
13678
13679
13680
13681 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)
13682 {
13683 int res = 1;
13684 int gotdest;
13685 const char *p_replaces;
13686 char *replace_id = NULL;
13687 const char *required;
13688 unsigned int required_profile = 0;
13689 struct ast_channel *c = NULL;
13690 int reinvite = 0;
13691
13692
13693 if (!p->sipoptions) {
13694 const char *supported = get_header(req, "Supported");
13695 if (!ast_strlen_zero(supported))
13696 parse_sip_options(p, supported);
13697 }
13698
13699
13700 required = get_header(req, "Require");
13701 if (!ast_strlen_zero(required)) {
13702 required_profile = parse_sip_options(NULL, required);
13703 if (required_profile && required_profile != SIP_OPT_REPLACES) {
13704
13705 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
13706 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
13707 p->invitestate = INV_COMPLETED;
13708 if (!p->lastinvite)
13709 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13710 return -1;
13711 }
13712 }
13713
13714
13715 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
13716
13717
13718
13719
13720
13721 transmit_response(p, "482 Loop Detected", req);
13722 p->invitestate = INV_COMPLETED;
13723 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13724 return 0;
13725 }
13726
13727 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
13728
13729 transmit_response(p, "491 Request Pending", req);
13730 if (option_debug)
13731 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
13732
13733 return 0;
13734 }
13735
13736 p_replaces = get_header(req, "Replaces");
13737 if (!ast_strlen_zero(p_replaces)) {
13738
13739 char *ptr;
13740 char *fromtag = NULL;
13741 char *totag = NULL;
13742 char *start, *to;
13743 int error = 0;
13744
13745 if (p->owner) {
13746 if (option_debug > 2)
13747 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
13748 transmit_response(p, "400 Bad request", req);
13749
13750 return -1;
13751 }
13752
13753 if (sipdebug && option_debug > 2)
13754 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
13755
13756 replace_id = ast_strdupa(p_replaces);
13757 ast_uri_decode(replace_id);
13758
13759 if (!p->refer && !sip_refer_allocate(p)) {
13760 transmit_response(p, "500 Server Internal Error", req);
13761 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
13762 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13763 p->invitestate = INV_COMPLETED;
13764 return -1;
13765 }
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776 replace_id = ast_skip_blanks(replace_id);
13777
13778 start = replace_id;
13779 while ( (ptr = strsep(&start, ";")) ) {
13780 ptr = ast_skip_blanks(ptr);
13781 if ( (to = strcasestr(ptr, "to-tag=") ) )
13782 totag = to + 7;
13783 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
13784 fromtag = to + 9;
13785 fromtag = strsep(&fromtag, "&");
13786 }
13787 }
13788
13789 if (sipdebug && option_debug > 3)
13790 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>");
13791
13792
13793
13794
13795
13796 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
13797 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
13798 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
13799 error = 1;
13800 }
13801
13802
13803
13804
13805
13806
13807
13808 if (p->refer->refer_call == p) {
13809 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
13810 p->refer->refer_call = NULL;
13811 transmit_response(p, "400 Bad request", req);
13812 error = 1;
13813 }
13814
13815 if (!error && !p->refer->refer_call->owner) {
13816
13817 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
13818
13819 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
13820 error = 1;
13821 }
13822
13823 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 ) {
13824 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
13825 transmit_response(p, "603 Declined (Replaces)", req);
13826 error = 1;
13827 }
13828
13829 if (error) {
13830 append_history(p, "Xfer", "INVITE/Replace Failed.");
13831 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13832 ast_mutex_unlock(&p->lock);
13833 if (p->refer->refer_call) {
13834 ast_mutex_unlock(&p->refer->refer_call->lock);
13835 ast_channel_unlock(p->refer->refer_call->owner);
13836 }
13837 p->invitestate = INV_COMPLETED;
13838 return -1;
13839 }
13840 }
13841
13842
13843
13844
13845
13846 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13847 int newcall = (p->initreq.headers ? TRUE : FALSE);
13848
13849 sip_cancel_destroy(p);
13850
13851 p->pendinginvite = seqno;
13852 check_via(p, req);
13853
13854 copy_request(&p->initreq, req);
13855 if (!p->owner) {
13856 if (debug)
13857 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
13858 if (newcall)
13859 append_history(p, "Invite", "New call: %s", p->callid);
13860 parse_ok_contact(p, req);
13861 } else {
13862 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
13863
13864 if (find_sdp(req)) {
13865 if (process_sdp(p, req)) {
13866 transmit_response(p, "488 Not acceptable here", req);
13867 if (!p->lastinvite)
13868 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13869 return -1;
13870 }
13871 } else {
13872 p->jointcapability = p->capability;
13873 if (option_debug > 2)
13874 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
13875
13876
13877
13878 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
13879 change_hold_state(p, req, FALSE, 0);
13880 }
13881 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
13882 append_history(p, "ReInv", "Re-invite received");
13883 }
13884 } else if (debug)
13885 ast_verbose("Ignoring this INVITE request\n");
13886
13887
13888 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
13889
13890
13891 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
13892 if (res == AUTH_CHALLENGE_SENT) {
13893 p->invitestate = INV_COMPLETED;
13894 return 0;
13895 }
13896 if (res < 0) {
13897 if (res == AUTH_FAKE_AUTH) {
13898 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
13899 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
13900 } else {
13901 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
13902 transmit_response_reliable(p, "403 Forbidden", req);
13903 }
13904 p->invitestate = INV_COMPLETED;
13905 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13906 ast_string_field_free(p, theirtag);
13907 return 0;
13908 }
13909
13910
13911 if (find_sdp(req)) {
13912 if (process_sdp(p, req)) {
13913
13914 transmit_response_reliable(p, "488 Not acceptable here", req);
13915 p->invitestate = INV_COMPLETED;
13916 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13917 if (option_debug)
13918 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
13919 return -1;
13920 }
13921 } else {
13922 p->jointcapability = p->capability;
13923 if (option_debug > 1)
13924 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
13925 }
13926
13927
13928
13929 if (p->owner)
13930 ast_queue_frame(p->owner, &ast_null_frame);
13931
13932
13933
13934 if (ast_strlen_zero(p->context))
13935 ast_string_field_set(p, context, default_context);
13936
13937
13938
13939 if (option_debug)
13940 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
13941 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
13942 if (res < 0) {
13943 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
13944 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
13945 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13946 p->invitestate = INV_COMPLETED;
13947 }
13948 return 0;
13949 }
13950 gotdest = get_destination(p, NULL);
13951 get_rdnis(p, NULL);
13952 extract_uri(p, req);
13953 build_contact(p);
13954
13955 if (p->rtp) {
13956 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
13957 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
13958 }
13959
13960 if (!replace_id && gotdest) {
13961 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
13962 transmit_response_reliable(p, "484 Address Incomplete", req);
13963 else {
13964 transmit_response_reliable(p, "404 Not Found", req);
13965 ast_log(LOG_NOTICE, "Call from '%s' to extension"
13966 " '%s' rejected because extension not found.\n",
13967 S_OR(p->username, p->peername), p->exten);
13968 }
13969 p->invitestate = INV_COMPLETED;
13970 update_call_counter(p, DEC_CALL_LIMIT);
13971 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13972 return 0;
13973 } else {
13974
13975
13976 if (ast_strlen_zero(p->exten))
13977 ast_string_field_set(p, exten, "s");
13978
13979
13980 make_our_tag(p->tag, sizeof(p->tag));
13981
13982 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
13983 *recount = 1;
13984
13985
13986 build_route(p, req, 0);
13987
13988 if (c) {
13989
13990 ast_channel_lock(c);
13991 }
13992 }
13993 } else {
13994 if (option_debug > 1 && sipdebug) {
13995 if (!ast_test_flag(req, SIP_PKT_IGNORE))
13996 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
13997 else
13998 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
13999 }
14000 reinvite = 1;
14001 c = p->owner;
14002 }
14003
14004 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14005 p->lastinvite = seqno;
14006
14007 if (replace_id) {
14008
14009 if (sipdebug && option_debug > 3)
14010 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
14011 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
14012 }
14013
14014
14015 if (c) {
14016 switch(c->_state) {
14017 case AST_STATE_DOWN:
14018 if (option_debug > 1)
14019 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
14020 transmit_response(p, "100 Trying", req);
14021 p->invitestate = INV_PROCEEDING;
14022 ast_setstate(c, AST_STATE_RING);
14023 if (strcmp(p->exten, ast_pickup_ext())) {
14024 enum ast_pbx_result res;
14025
14026 res = ast_pbx_start(c);
14027
14028 switch(res) {
14029 case AST_PBX_FAILED:
14030 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
14031 p->invitestate = INV_COMPLETED;
14032 if (ast_test_flag(req, SIP_PKT_IGNORE))
14033 transmit_response(p, "503 Unavailable", req);
14034 else
14035 transmit_response_reliable(p, "503 Unavailable", req);
14036 break;
14037 case AST_PBX_CALL_LIMIT:
14038 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
14039 p->invitestate = INV_COMPLETED;
14040 if (ast_test_flag(req, SIP_PKT_IGNORE))
14041 transmit_response(p, "480 Temporarily Unavailable", req);
14042 else
14043 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
14044 break;
14045 case AST_PBX_SUCCESS:
14046
14047 break;
14048 }
14049
14050 if (res) {
14051
14052
14053 ast_mutex_unlock(&c->lock);
14054 ast_mutex_unlock(&p->lock);
14055 ast_hangup(c);
14056 ast_mutex_lock(&p->lock);
14057 c = NULL;
14058 }
14059 } else {
14060 ast_channel_unlock(c);
14061 *nounlock = 1;
14062 if (ast_pickup_call(c)) {
14063 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
14064 if (ast_test_flag(req, SIP_PKT_IGNORE))
14065 transmit_response(p, "503 Unavailable", req);
14066 else
14067 transmit_response_reliable(p, "503 Unavailable", req);
14068 sip_alreadygone(p);
14069
14070 ast_mutex_unlock(&p->lock);
14071 c->hangupcause = AST_CAUSE_CALL_REJECTED;
14072 } else {
14073 ast_mutex_unlock(&p->lock);
14074 ast_setstate(c, AST_STATE_DOWN);
14075 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14076 }
14077 p->invitestate = INV_COMPLETED;
14078 ast_hangup(c);
14079 ast_mutex_lock(&p->lock);
14080 c = NULL;
14081 }
14082 break;
14083 case AST_STATE_RING:
14084 transmit_response(p, "100 Trying", req);
14085 p->invitestate = INV_PROCEEDING;
14086 break;
14087 case AST_STATE_RINGING:
14088 transmit_response(p, "180 Ringing", req);
14089 p->invitestate = INV_PROCEEDING;
14090 break;
14091 case AST_STATE_UP:
14092 if (option_debug > 1)
14093 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
14094
14095 transmit_response(p, "100 Trying", req);
14096
14097 if (p->t38.state == T38_PEER_REINVITE) {
14098 struct ast_channel *bridgepeer = NULL;
14099 struct sip_pvt *bridgepvt = NULL;
14100
14101 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14102
14103
14104 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
14105 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14106 if (bridgepvt->t38.state == T38_DISABLED) {
14107 if (bridgepvt->udptl) {
14108
14109 sip_handle_t38_reinvite(bridgepeer, p, 1);
14110 } else {
14111 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
14112 ast_mutex_lock(&bridgepvt->lock);
14113 bridgepvt->t38.state = T38_DISABLED;
14114 ast_mutex_unlock(&bridgepvt->lock);
14115 if (option_debug > 1)
14116 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
14117 if (ast_test_flag(req, SIP_PKT_IGNORE))
14118 transmit_response(p, "488 Not acceptable here", req);
14119 else
14120 transmit_response_reliable(p, "488 Not acceptable here", req);
14121
14122 }
14123 } else {
14124
14125 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14126 p->t38.state = T38_ENABLED;
14127 if (option_debug)
14128 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14129 }
14130 } else {
14131
14132 if (ast_test_flag(req, SIP_PKT_IGNORE))
14133 transmit_response(p, "488 Not acceptable here", req);
14134 else
14135 transmit_response_reliable(p, "488 Not acceptable here", req);
14136 p->t38.state = T38_DISABLED;
14137 if (option_debug > 1)
14138 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14139
14140 if (!p->lastinvite)
14141 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14142 }
14143 } else {
14144
14145 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
14146 p->t38.state = T38_ENABLED;
14147 if (option_debug)
14148 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
14149 }
14150 } else if (p->t38.state == T38_DISABLED) {
14151 int sendok = TRUE;
14152
14153
14154
14155 struct ast_channel *bridgepeer = NULL;
14156 struct sip_pvt *bridgepvt = NULL;
14157 if ((bridgepeer = ast_bridged_channel(p->owner))) {
14158 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
14159 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
14160
14161 if (bridgepvt->t38.state == T38_ENABLED) {
14162 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
14163
14164 if (ast_test_flag(req, SIP_PKT_IGNORE))
14165 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
14166 else
14167 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
14168 sendok = FALSE;
14169 }
14170
14171 }
14172 }
14173
14174 if (sendok)
14175
14176 transmit_response_with_sdp(p, "200 OK", req, (reinvite || ast_test_flag(req, SIP_PKT_IGNORE)) ? XMIT_UNRELIABLE : XMIT_CRITICAL);
14177 }
14178 p->invitestate = INV_TERMINATED;
14179 break;
14180 default:
14181 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
14182 transmit_response(p, "100 Trying", req);
14183 break;
14184 }
14185 } else {
14186 if (p && (p->autokillid == -1)) {
14187 const char *msg;
14188
14189 if (!p->jointcapability)
14190 msg = "488 Not Acceptable Here (codec error)";
14191 else {
14192 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
14193 msg = "503 Unavailable";
14194 }
14195 if (ast_test_flag(req, SIP_PKT_IGNORE))
14196 transmit_response(p, msg, req);
14197 else
14198 transmit_response_reliable(p, msg, req);
14199 p->invitestate = INV_COMPLETED;
14200 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14201 }
14202 }
14203 return res;
14204 }
14205
14206
14207
14208 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
14209 {
14210 struct sip_dual target;
14211
14212 int res = 0;
14213 struct sip_pvt *targetcall_pvt;
14214
14215
14216 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
14217 transferer->refer->replaces_callid_fromtag))) {
14218 if (transferer->refer->localtransfer) {
14219
14220 transmit_response(transferer, "202 Accepted", req);
14221
14222
14223 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
14224 append_history(transferer, "Xfer", "Refer failed");
14225 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14226 transferer->refer->status = REFER_FAILED;
14227 return -1;
14228 }
14229
14230 if (option_debug > 2)
14231 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
14232 return 0;
14233 }
14234
14235
14236 transmit_response(transferer, "202 Accepted", req);
14237 append_history(transferer, "Xfer", "Refer accepted");
14238 if (!targetcall_pvt->owner) {
14239 if (option_debug > 3)
14240 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
14241
14242 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
14243 append_history(transferer, "Xfer", "Refer failed");
14244 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
14245 transferer->refer->status = REFER_FAILED;
14246 ast_mutex_unlock(&targetcall_pvt->lock);
14247 ast_channel_unlock(current->chan1);
14248 return -1;
14249 }
14250
14251
14252 target.chan1 = targetcall_pvt->owner;
14253 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
14254
14255 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
14256
14257 if (option_debug > 3) {
14258 if (target.chan2)
14259 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
14260 else if (target.chan1->_state != AST_STATE_RING)
14261 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
14262 else
14263 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
14264 }
14265 }
14266
14267
14268 if (option_debug > 3 && sipdebug) {
14269 if (current->chan2)
14270 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
14271 else
14272 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
14273 }
14274
14275 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14276
14277
14278 res = attempt_transfer(current, &target);
14279 ast_mutex_unlock(&targetcall_pvt->lock);
14280 if (res) {
14281
14282 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
14283 append_history(transferer, "Xfer", "Refer failed");
14284 transferer->refer->status = REFER_FAILED;
14285 if (targetcall_pvt->owner)
14286 ast_channel_unlock(targetcall_pvt->owner);
14287
14288 if (res != -2)
14289 ast_hangup(transferer->owner);
14290 else
14291 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14292 } else {
14293
14294
14295
14296 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
14297 append_history(transferer, "Xfer", "Refer succeeded");
14298 transferer->refer->status = REFER_200OK;
14299 if (targetcall_pvt->owner) {
14300 if (option_debug)
14301 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
14302 ast_channel_unlock(targetcall_pvt->owner);
14303 }
14304 }
14305 return 1;
14306 }
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
14373 {
14374 struct sip_dual current;
14375
14376
14377 int res = 0;
14378
14379 if (ast_test_flag(req, SIP_PKT_DEBUG))
14380 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");
14381
14382 if (!p->owner) {
14383
14384
14385 if (option_debug > 2)
14386 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
14387 transmit_response(p, "603 Declined (No dialog)", req);
14388 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14389 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
14390 sip_alreadygone(p);
14391 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14392 }
14393 return 0;
14394 }
14395
14396
14397
14398 if (p->allowtransfer == TRANSFER_CLOSED ) {
14399
14400 transmit_response(p, "603 Declined (policy)", req);
14401 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
14402
14403 return 0;
14404 }
14405
14406 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
14407
14408 transmit_response(p, "491 Request pending", req);
14409 append_history(p, "Xfer", "Refer failed. Request pending.");
14410 return 0;
14411 }
14412
14413
14414 if (!p->refer && !sip_refer_allocate(p)) {
14415 transmit_response(p, "500 Internal Server Error", req);
14416 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
14417 return -3;
14418 }
14419
14420 res = get_refer_info(p, req);
14421
14422 p->refer->status = REFER_SENT;
14423
14424 if (res != 0) {
14425 switch (res) {
14426 case -2:
14427 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
14428 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
14429 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14430 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
14431 break;
14432 case -3:
14433 transmit_response(p, "603 Declined (Non sip: uri)", req);
14434 append_history(p, "Xfer", "Refer failed. Non SIP uri");
14435 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14436 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
14437 break;
14438 default:
14439
14440 transmit_response(p, "202 Accepted", req);
14441 append_history(p, "Xfer", "Refer failed. Bad extension.");
14442 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
14443 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14444 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
14445 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
14446 break;
14447 }
14448 return 0;
14449 }
14450 if (ast_strlen_zero(p->context))
14451 ast_string_field_set(p, context, default_context);
14452
14453
14454 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14455 p->refer->localtransfer = 1;
14456 if (sipdebug && option_debug > 2)
14457 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
14458 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
14459
14460 p->refer->localtransfer = 1;
14461 } else if (sipdebug && option_debug > 2)
14462 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
14463
14464
14465
14466 if (ignore)
14467 return res;
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 current.chan1 = p->owner;
14496
14497
14498 current.chan2 = ast_bridged_channel(current.chan1);
14499
14500 if (sipdebug && option_debug > 2)
14501 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>");
14502
14503 if (!current.chan2 && !p->refer->attendedtransfer) {
14504
14505
14506
14507 if (sipdebug && option_debug > 2)
14508 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
14509 p->refer->status = REFER_FAILED;
14510 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
14511 transmit_response(p, "603 Declined", req);
14512 return -1;
14513 }
14514
14515 if (current.chan2) {
14516 if (sipdebug && option_debug > 3)
14517 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
14518
14519 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
14520 }
14521
14522 ast_set_flag(&p->flags[0], SIP_GOTREFER);
14523
14524
14525 if (p->refer->attendedtransfer) {
14526 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
14527 return res;
14528
14529 if (sipdebug && option_debug > 3)
14530 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14531
14532 }
14533
14534
14535
14536 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
14537
14538 *nounlock = 1;
14539 ast_channel_unlock(current.chan1);
14540 copy_request(¤t.req, req);
14541 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14542 p->refer->status = REFER_200OK;
14543 append_history(p, "Xfer", "REFER to call parking.");
14544 if (sipdebug && option_debug > 3)
14545 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
14546 sip_park(current.chan2, current.chan1, req, seqno);
14547 return res;
14548 }
14549
14550
14551 transmit_response(p, "202 Accepted", req);
14552
14553 if (current.chan1 && current.chan2) {
14554 if (option_debug > 2)
14555 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
14556 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
14557 }
14558 if (current.chan2) {
14559 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
14560 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
14561 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
14562
14563 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
14564
14565 if (p->refer->referred_by)
14566 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
14567 }
14568
14569 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
14570 char tempheader[BUFSIZ];
14571 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
14572 p->refer->replaces_callid_totag ? ";to-tag=" : "",
14573 p->refer->replaces_callid_totag,
14574 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
14575 p->refer->replaces_callid_fromtag);
14576 if (current.chan2)
14577 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
14578 }
14579
14580
14581 *nounlock = 1;
14582 ast_channel_unlock(current.chan1);
14583
14584
14585
14586
14587 if (!p->refer->attendedtransfer)
14588 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
14589
14590
14591
14592
14593
14594 if (!current.chan2) {
14595
14596
14597
14598
14599
14600
14601
14602 p->refer->status = REFER_FAILED;
14603 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
14604 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14605 append_history(p, "Xfer", "Refer failed (only bridged calls).");
14606 return -1;
14607 }
14608 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14609
14610
14611
14612 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
14613
14614 if (!res) {
14615
14616 if (option_debug > 2)
14617 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14618 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
14619 if (p->refer->localtransfer)
14620 p->refer->status = REFER_200OK;
14621 if (p->owner)
14622 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14623 append_history(p, "Xfer", "Refer succeeded.");
14624 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14625
14626
14627 res = 0;
14628 } else {
14629 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14630 if (option_debug > 2)
14631 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14632 append_history(p, "Xfer", "Refer failed.");
14633
14634 p->refer->status = REFER_FAILED;
14635 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
14636 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14637 res = -1;
14638 }
14639 return res;
14640 }
14641
14642
14643 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
14644 {
14645
14646 check_via(p, req);
14647 sip_alreadygone(p);
14648
14649
14650
14651
14652
14653
14654 if (p->invitestate == INV_TERMINATED)
14655 __sip_pretend_ack(p);
14656 else
14657 p->invitestate = INV_CANCELLED;
14658
14659 if (p->owner && p->owner->_state == AST_STATE_UP) {
14660
14661 transmit_response(p, "200 OK", req);
14662 if (option_debug)
14663 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
14664 return 0;
14665 }
14666
14667 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
14668 update_call_counter(p, DEC_CALL_LIMIT);
14669
14670 stop_media_flows(p);
14671
14672 if (p->owner)
14673 ast_queue_hangup(p->owner);
14674 else
14675 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14676 if (p->initreq.len > 0) {
14677 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14678 transmit_response(p, "200 OK", req);
14679 return 1;
14680 } else {
14681 transmit_response(p, "481 Call Leg Does Not Exist", req);
14682 return 0;
14683 }
14684 }
14685
14686 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen)
14687 {
14688 struct ast_rtp_quality qos;
14689 struct sip_pvt *p = chan->tech_pvt;
14690 char *all = "", *parse = ast_strdupa(preparse);
14691 AST_DECLARE_APP_ARGS(args,
14692 AST_APP_ARG(param);
14693 AST_APP_ARG(type);
14694 AST_APP_ARG(field);
14695 );
14696 AST_STANDARD_APP_ARGS(args, parse);
14697
14698
14699 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
14700 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
14701 return 0;
14702 }
14703
14704 if (strcasecmp(args.param, "rtpqos"))
14705 return 0;
14706
14707
14708 if (ast_strlen_zero(args.type))
14709 args.type = "audio";
14710 if (ast_strlen_zero(args.field))
14711 args.field = "all";
14712
14713 memset(buf, 0, buflen);
14714 memset(&qos, 0, sizeof(qos));
14715
14716 if (strcasecmp(args.type, "AUDIO") == 0) {
14717 all = ast_rtp_get_quality(p->rtp, &qos);
14718 } else if (strcasecmp(args.type, "VIDEO") == 0) {
14719 all = ast_rtp_get_quality(p->vrtp, &qos);
14720 }
14721
14722 if (strcasecmp(args.field, "local_ssrc") == 0)
14723 snprintf(buf, buflen, "%u", qos.local_ssrc);
14724 else if (strcasecmp(args.field, "local_lostpackets") == 0)
14725 snprintf(buf, buflen, "%u", qos.local_lostpackets);
14726 else if (strcasecmp(args.field, "local_jitter") == 0)
14727 snprintf(buf, buflen, "%.0lf", qos.local_jitter * 1000.0);
14728 else if (strcasecmp(args.field, "local_count") == 0)
14729 snprintf(buf, buflen, "%u", qos.local_count);
14730 else if (strcasecmp(args.field, "remote_ssrc") == 0)
14731 snprintf(buf, buflen, "%u", qos.remote_ssrc);
14732 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
14733 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
14734 else if (strcasecmp(args.field, "remote_jitter") == 0)
14735 snprintf(buf, buflen, "%.0lf", qos.remote_jitter * 1000.0);
14736 else if (strcasecmp(args.field, "remote_count") == 0)
14737 snprintf(buf, buflen, "%u", qos.remote_count);
14738 else if (strcasecmp(args.field, "rtt") == 0)
14739 snprintf(buf, buflen, "%.0lf", qos.rtt * 1000.0);
14740 else if (strcasecmp(args.field, "all") == 0)
14741 ast_copy_string(buf, all, buflen);
14742 else {
14743 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
14744 return -1;
14745 }
14746 return 0;
14747 }
14748
14749
14750 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
14751 {
14752 struct ast_channel *c=NULL;
14753 int res;
14754 struct ast_channel *bridged_to;
14755
14756
14757 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
14758 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14759
14760 p->invitestate = INV_TERMINATED;
14761
14762 copy_request(&p->initreq, req);
14763 check_via(p, req);
14764 sip_alreadygone(p);
14765
14766
14767 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
14768 char *audioqos, *videoqos;
14769 if (p->rtp) {
14770 audioqos = ast_rtp_get_quality(p->rtp, NULL);
14771 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14772 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
14773 if (p->owner)
14774 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
14775 }
14776 if (p->vrtp) {
14777 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
14778 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14779 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
14780 if (p->owner)
14781 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
14782 }
14783 }
14784
14785 stop_media_flows(p);
14786
14787 if (!ast_strlen_zero(get_header(req, "Also"))) {
14788 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14789 ast_inet_ntoa(p->recv.sin_addr));
14790 if (ast_strlen_zero(p->context))
14791 ast_string_field_set(p, context, default_context);
14792 res = get_also_info(p, req);
14793 if (!res) {
14794 c = p->owner;
14795 if (c) {
14796 bridged_to = ast_bridged_channel(c);
14797 if (bridged_to) {
14798
14799 ast_queue_control(c, AST_CONTROL_UNHOLD);
14800 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
14801 } else
14802 ast_queue_hangup(p->owner);
14803 }
14804 } else {
14805 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
14806 if (p->owner)
14807 ast_queue_hangup(p->owner);
14808 }
14809 } else if (p->owner) {
14810 ast_queue_hangup(p->owner);
14811 if (option_debug > 2)
14812 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
14813 } else {
14814 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14815 if (option_debug > 2)
14816 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
14817 }
14818 transmit_response(p, "200 OK", req);
14819
14820 return 1;
14821 }
14822
14823
14824 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
14825 {
14826 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14827 if (ast_test_flag(req, SIP_PKT_DEBUG))
14828 ast_verbose("Receiving message!\n");
14829 receive_message(p, req);
14830 } else
14831 transmit_response(p, "202 Accepted", req);
14832 return 1;
14833 }
14834
14835
14836 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
14837 {
14838 int gotdest;
14839 int res = 0;
14840 int firststate = AST_EXTENSION_REMOVED;
14841 struct sip_peer *authpeer = NULL;
14842 const char *eventheader = get_header(req, "Event");
14843 const char *accept = get_header(req, "Accept");
14844 int resubscribe = (p->subscribed != NONE);
14845 char *temp, *event;
14846
14847 if (p->initreq.headers) {
14848
14849 if (p->initreq.method != SIP_SUBSCRIBE) {
14850
14851
14852 transmit_response(p, "403 Forbidden (within dialog)", req);
14853
14854 if (option_debug)
14855 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);
14856 return 0;
14857 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
14858 if (option_debug) {
14859 if (resubscribe)
14860 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
14861 else
14862 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
14863 }
14864 }
14865 }
14866
14867
14868
14869
14870 if (!global_allowsubscribe) {
14871 transmit_response(p, "403 Forbidden (policy)", req);
14872 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14873 return 0;
14874 }
14875
14876 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) {
14877
14878 if (ast_test_flag(req, SIP_PKT_DEBUG))
14879 ast_verbose("Creating new subscription\n");
14880
14881 copy_request(&p->initreq, req);
14882 check_via(p, req);
14883 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
14884 ast_verbose("Ignoring this SUBSCRIBE request\n");
14885
14886
14887 if (ast_strlen_zero(eventheader)) {
14888 transmit_response(p, "489 Bad Event", req);
14889 if (option_debug > 1)
14890 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
14891 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14892 return 0;
14893 }
14894
14895 if ( (strchr(eventheader, ';'))) {
14896 event = ast_strdupa(eventheader);
14897 temp = strchr(event, ';');
14898 *temp = '\0';
14899
14900 } else
14901 event = (char *) eventheader;
14902
14903
14904 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
14905
14906 if (res == AUTH_CHALLENGE_SENT) {
14907 if (authpeer)
14908 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14909 return 0;
14910 }
14911 if (res < 0) {
14912 if (res == AUTH_FAKE_AUTH) {
14913 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
14914 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
14915 } else {
14916 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
14917 transmit_response_reliable(p, "403 Forbidden", req);
14918 }
14919 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14920 if (authpeer)
14921 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14922 return 0;
14923 }
14924
14925
14926 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
14927 transmit_response(p, "403 Forbidden (policy)", req);
14928 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14929 if (authpeer)
14930 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14931 return 0;
14932 }
14933
14934
14935 gotdest = get_destination(p, NULL);
14936
14937
14938 parse_ok_contact(p, req);
14939
14940 build_contact(p);
14941 if (gotdest) {
14942 transmit_response(p, "404 Not Found", req);
14943 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14944 if (authpeer)
14945 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14946 return 0;
14947 }
14948
14949
14950 if (ast_strlen_zero(p->tag))
14951 make_our_tag(p->tag, sizeof(p->tag));
14952
14953 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
14954 if (authpeer)
14955 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14956
14957
14958
14959
14960
14961 if (strstr(p->useragent, "Polycom")) {
14962 p->subscribed = XPIDF_XML;
14963 } else if (strstr(accept, "application/pidf+xml")) {
14964 p->subscribed = PIDF_XML;
14965 } else if (strstr(accept, "application/dialog-info+xml")) {
14966 p->subscribed = DIALOG_INFO_XML;
14967
14968 } else if (strstr(accept, "application/cpim-pidf+xml")) {
14969 p->subscribed = CPIM_PIDF_XML;
14970 } else if (strstr(accept, "application/xpidf+xml")) {
14971 p->subscribed = XPIDF_XML;
14972 } else if (ast_strlen_zero(accept)) {
14973 if (p->subscribed == NONE) {
14974 transmit_response(p, "489 Bad Event", req);
14975
14976 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
14977 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
14978 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14979 return 0;
14980 }
14981
14982
14983 } else {
14984
14985 char mybuf[200];
14986 snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
14987 transmit_response(p, mybuf, req);
14988
14989 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
14990 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
14991 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14992 return 0;
14993 }
14994 } else if (!strcmp(event, "message-summary")) {
14995 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
14996
14997 transmit_response(p, "406 Not Acceptable", req);
14998 if (option_debug > 1)
14999 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
15000 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15001 if (authpeer)
15002 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15003 return 0;
15004 }
15005
15006
15007
15008
15009
15010 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
15011 transmit_response(p, "404 Not found (no mailbox)", req);
15012 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15013 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
15014 if (authpeer)
15015 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15016 return 0;
15017 }
15018
15019 p->subscribed = MWI_NOTIFICATION;
15020 if (authpeer->mwipvt && authpeer->mwipvt != p)
15021
15022 sip_destroy(authpeer->mwipvt);
15023 authpeer->mwipvt = p;
15024 p->relatedpeer = authpeer;
15025 } else {
15026 transmit_response(p, "489 Bad Event", req);
15027 if (option_debug > 1)
15028 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
15029 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15030 if (authpeer)
15031 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
15032 return 0;
15033 }
15034
15035 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
15036 if (p->stateid > -1)
15037 ast_extension_state_del(p->stateid, cb_extensionstate);
15038 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
15039 }
15040
15041 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
15042 p->lastinvite = seqno;
15043 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
15044 p->expiry = atoi(get_header(req, "Expires"));
15045
15046
15047 if (p->expiry > max_expiry)
15048 p->expiry = max_expiry;
15049 if (p->expiry < min_expiry && p->expiry > 0)
15050 p->expiry = min_expiry;
15051
15052 if (sipdebug || option_debug > 1) {
15053 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
15054 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
15055 else
15056 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
15057 }
15058 if (p->autokillid > -1)
15059 sip_cancel_destroy(p);
15060 if (p->expiry > 0)
15061 sip_scheddestroy(p, (p->expiry + 10) * 1000);
15062
15063 if (p->subscribed == MWI_NOTIFICATION) {
15064 transmit_response(p, "200 OK", req);
15065 if (p->relatedpeer) {
15066 ASTOBJ_WRLOCK(p->relatedpeer);
15067 sip_send_mwi_to_peer(p->relatedpeer);
15068 ASTOBJ_UNLOCK(p->relatedpeer);
15069 }
15070 } else {
15071 struct sip_pvt *p_old;
15072
15073 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
15074
15075 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));
15076 transmit_response(p, "404 Not found", req);
15077 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15078 return 0;
15079 }
15080
15081 transmit_response(p, "200 OK", req);
15082 transmit_state_notify(p, firststate, 1, FALSE);
15083 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
15084
15085 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
15086
15087
15088
15089
15090
15091
15092 ast_mutex_lock(&iflock);
15093 for (p_old = iflist; p_old; p_old = p_old->next) {
15094 if (p_old == p)
15095 continue;
15096 if (p_old->initreq.method != SIP_SUBSCRIBE)
15097 continue;
15098 if (p_old->subscribed == NONE)
15099 continue;
15100 ast_mutex_lock(&p_old->lock);
15101 if (!strcmp(p_old->username, p->username)) {
15102 if (!strcmp(p_old->exten, p->exten) &&
15103 !strcmp(p_old->context, p->context)) {
15104 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
15105 ast_mutex_unlock(&p_old->lock);
15106 break;
15107 }
15108 }
15109 ast_mutex_unlock(&p_old->lock);
15110 }
15111 ast_mutex_unlock(&iflock);
15112 }
15113 if (!p->expiry)
15114 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15115 }
15116 return 1;
15117 }
15118
15119
15120 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
15121 {
15122 enum check_auth_result res;
15123
15124
15125 if (ast_test_flag(req, SIP_PKT_DEBUG))
15126 ast_verbose("Using latest REGISTER request as basis request\n");
15127 copy_request(&p->initreq, req);
15128 check_via(p, req);
15129 if ((res = register_verify(p, sin, req, e)) < 0) {
15130 const char *reason;
15131
15132 switch (res) {
15133 case AUTH_SECRET_FAILED:
15134 reason = "Wrong password";
15135 break;
15136 case AUTH_USERNAME_MISMATCH:
15137 reason = "Username/auth name mismatch";
15138 break;
15139 case AUTH_NOT_FOUND:
15140 reason = "No matching peer found";
15141 break;
15142 case AUTH_UNKNOWN_DOMAIN:
15143 reason = "Not a local domain";
15144 break;
15145 case AUTH_PEER_NOT_DYNAMIC:
15146 reason = "Peer is not supposed to register";
15147 break;
15148 case AUTH_ACL_FAILED:
15149 reason = "Device does not match ACL";
15150 break;
15151 default:
15152 reason = "Unknown failure";
15153 break;
15154 }
15155 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
15156 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
15157 reason);
15158 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
15159 } else
15160 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
15161
15162 if (res < 1) {
15163
15164
15165 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15166 }
15167 return res;
15168 }
15169
15170
15171
15172
15173 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
15174 {
15175
15176
15177 const char *cmd;
15178 const char *cseq;
15179 const char *useragent;
15180 int seqno;
15181 int len;
15182 int ignore = FALSE;
15183 int respid;
15184 int res = 0;
15185 int debug = sip_debug_test_pvt(p);
15186 char *e;
15187 int error = 0;
15188
15189
15190 cseq = get_header(req, "Cseq");
15191 cmd = req->header[0];
15192
15193
15194 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
15195 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
15196 error = 1;
15197 }
15198 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
15199 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
15200 error = 1;
15201 }
15202 if (error) {
15203 if (!p->initreq.headers)
15204 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15205 return -1;
15206 }
15207
15208
15209 cmd = req->rlPart1;
15210 e = req->rlPart2;
15211
15212
15213 useragent = get_header(req, "User-Agent");
15214 if (!ast_strlen_zero(useragent))
15215 ast_string_field_set(p, useragent, useragent);
15216
15217
15218 if (req->method == SIP_RESPONSE) {
15219
15220 if (!p->initreq.headers) {
15221 if (option_debug)
15222 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
15223 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15224 return 0;
15225 } else if (p->ocseq && (p->ocseq < seqno) && (seqno != p->lastnoninvite)) {
15226 if (option_debug)
15227 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
15228 return -1;
15229 } else if (p->ocseq && (p->ocseq != seqno) && (seqno != p->lastnoninvite)) {
15230
15231
15232 ignore = TRUE;
15233 ast_set_flag(req, SIP_PKT_IGNORE);
15234 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
15235 append_history(p, "Ignore", "Ignoring this retransmit\n");
15236 } else if (e) {
15237 e = ast_skip_blanks(e);
15238 if (sscanf(e, "%d %n", &respid, &len) != 1) {
15239 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
15240 } else {
15241 if (respid <= 0) {
15242 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
15243 return 0;
15244 }
15245
15246 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
15247 extract_uri(p, req);
15248 handle_response(p, respid, e + len, req, ignore, seqno);
15249 }
15250 }
15251 return 0;
15252 }
15253
15254
15255
15256
15257
15258 p->method = req->method;
15259 if (option_debug > 3)
15260 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
15261
15262 if (p->icseq && (p->icseq > seqno)) {
15263 if (option_debug)
15264 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
15265 if (req->method != SIP_ACK)
15266 transmit_response(p, "503 Server error", req);
15267 return -1;
15268 } else if (p->icseq &&
15269 p->icseq == seqno &&
15270 req->method != SIP_ACK &&
15271 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
15272
15273
15274
15275 ignore = 2;
15276 ast_set_flag(req, SIP_PKT_IGNORE);
15277 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
15278 if (option_debug > 2)
15279 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
15280 }
15281
15282 if (seqno >= p->icseq)
15283
15284
15285
15286 p->icseq = seqno;
15287
15288
15289 if (ast_strlen_zero(p->theirtag)) {
15290 char tag[128];
15291
15292 gettag(req, "From", tag, sizeof(tag));
15293 ast_string_field_set(p, theirtag, tag);
15294 }
15295 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
15296
15297 if (pedanticsipchecking) {
15298
15299
15300
15301
15302 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
15303
15304 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
15305 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
15306
15307 } else if (req->method != SIP_ACK) {
15308 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
15309 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15310 }
15311 return res;
15312 }
15313 }
15314
15315 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
15316 transmit_response(p, "400 Bad request", req);
15317 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15318 return -1;
15319 }
15320
15321
15322 switch (p->method) {
15323 case SIP_OPTIONS:
15324 res = handle_request_options(p, req);
15325 break;
15326 case SIP_INVITE:
15327 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
15328 break;
15329 case SIP_REFER:
15330 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
15331 break;
15332 case SIP_CANCEL:
15333 res = handle_request_cancel(p, req);
15334 break;
15335 case SIP_BYE:
15336 res = handle_request_bye(p, req);
15337 break;
15338 case SIP_MESSAGE:
15339 res = handle_request_message(p, req);
15340 break;
15341 case SIP_SUBSCRIBE:
15342 res = handle_request_subscribe(p, req, sin, seqno, e);
15343 break;
15344 case SIP_REGISTER:
15345 res = handle_request_register(p, req, sin, e);
15346 break;
15347 case SIP_INFO:
15348 if (ast_test_flag(req, SIP_PKT_DEBUG))
15349 ast_verbose("Receiving INFO!\n");
15350 if (!ignore)
15351 handle_request_info(p, req);
15352 else
15353 transmit_response(p, "200 OK", req);
15354 break;
15355 case SIP_NOTIFY:
15356 res = handle_request_notify(p, req, sin, seqno, e);
15357 break;
15358 case SIP_ACK:
15359
15360 if (seqno == p->pendinginvite) {
15361 p->invitestate = INV_TERMINATED;
15362 p->pendinginvite = 0;
15363 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
15364 if (find_sdp(req)) {
15365 if (process_sdp(p, req))
15366 return -1;
15367 }
15368 check_pendings(p);
15369 }
15370
15371 if (!p->lastinvite && ast_strlen_zero(p->randdata))
15372 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15373 break;
15374 default:
15375 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
15376 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
15377 cmd, ast_inet_ntoa(p->sa.sin_addr));
15378
15379 if (!p->initreq.headers)
15380 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
15381 break;
15382 }
15383 return res;
15384 }
15385
15386
15387
15388
15389
15390
15391 static int sipsock_read(int *id, int fd, short events, void *ignore)
15392 {
15393 struct sip_request req;
15394 struct sockaddr_in sin = { 0, };
15395 struct sip_pvt *p;
15396 int res;
15397 socklen_t len = sizeof(sin);
15398 int nounlock;
15399 int recount = 0;
15400 int lockretry;
15401
15402 memset(&req, 0, sizeof(req));
15403 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
15404 if (res < 0) {
15405 #if !defined(__FreeBSD__)
15406 if (errno == EAGAIN)
15407 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
15408 else
15409 #endif
15410 if (errno != ECONNREFUSED)
15411 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
15412 return 1;
15413 }
15414 if (option_debug && res == sizeof(req.data)) {
15415 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
15416 req.data[sizeof(req.data) - 1] = '\0';
15417 } else
15418 req.data[res] = '\0';
15419 req.len = res;
15420 if(sip_debug_test_addr(&sin))
15421 ast_set_flag(&req, SIP_PKT_DEBUG);
15422 if (pedanticsipchecking)
15423 req.len = lws2sws(req.data, req.len);
15424 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15425 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
15426
15427 parse_request(&req);
15428 req.method = find_sip_method(req.rlPart1);
15429
15430 if (ast_test_flag(&req, SIP_PKT_DEBUG))
15431 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
15432
15433 if (req.headers < 2)
15434 return 1;
15435
15436
15437 for (lockretry = 100; lockretry > 0; lockretry--) {
15438 ast_mutex_lock(&netlock);
15439
15440
15441 p = find_call(&req, &sin, req.method);
15442 if (p == NULL) {
15443 if (option_debug)
15444 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
15445 ast_mutex_unlock(&netlock);
15446 return 1;
15447 }
15448
15449
15450 if (!p->owner || !ast_channel_trylock(p->owner))
15451 break;
15452 if (option_debug)
15453 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
15454 ast_mutex_unlock(&p->lock);
15455 ast_mutex_unlock(&netlock);
15456
15457 usleep(1);
15458 }
15459 p->recv = sin;
15460
15461 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
15462 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
15463
15464 if (!lockretry) {
15465 if (p->owner)
15466 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
15467 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
15468 if (req.method != SIP_ACK)
15469 transmit_response(p, "503 Server error", &req);
15470
15471 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
15472 return 1;
15473 }
15474 nounlock = 0;
15475 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
15476
15477 if (option_debug)
15478 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
15479 }
15480
15481 if (p->owner && !nounlock)
15482 ast_channel_unlock(p->owner);
15483 ast_mutex_unlock(&p->lock);
15484 ast_mutex_unlock(&netlock);
15485 if (recount)
15486 ast_update_use_count();
15487
15488 return 1;
15489 }
15490
15491
15492 static int sip_send_mwi_to_peer(struct sip_peer *peer)
15493 {
15494
15495 struct sip_pvt *p;
15496 int newmsgs, oldmsgs;
15497
15498
15499 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
15500 return 0;
15501
15502
15503 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
15504
15505 peer->lastmsgcheck = time(NULL);
15506
15507
15508 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
15509 return 0;
15510 }
15511
15512
15513 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
15514
15515 if (peer->mwipvt) {
15516
15517 p = peer->mwipvt;
15518 } else {
15519
15520 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
15521 return -1;
15522 if (create_addr_from_peer(p, peer)) {
15523
15524 sip_destroy(p);
15525 return 0;
15526 }
15527
15528 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15529 p->ourip = __ourip;
15530 build_via(p);
15531 build_callid_pvt(p);
15532
15533 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15534 }
15535
15536 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15537 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
15538 return 0;
15539 }
15540
15541
15542 static int does_peer_need_mwi(struct sip_peer *peer)
15543 {
15544 time_t t = time(NULL);
15545
15546 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
15547 !peer->mwipvt) {
15548 peer->lastmsgcheck = t;
15549 return FALSE;
15550 }
15551
15552 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
15553 return TRUE;
15554
15555 return FALSE;
15556 }
15557
15558
15559
15560
15561
15562
15563 static void *do_monitor(void *data)
15564 {
15565 int res;
15566 struct sip_pvt *sip;
15567 struct sip_peer *peer = NULL;
15568 time_t t;
15569 int fastrestart = FALSE;
15570 int lastpeernum = -1;
15571 int curpeernum;
15572 int reloading;
15573
15574
15575 if (sipsock > -1)
15576 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15577
15578
15579 for(;;) {
15580
15581 ast_mutex_lock(&sip_reload_lock);
15582 reloading = sip_reloading;
15583 sip_reloading = FALSE;
15584 ast_mutex_unlock(&sip_reload_lock);
15585 if (reloading) {
15586 if (option_verbose > 0)
15587 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
15588 sip_do_reload(sip_reloadreason);
15589
15590
15591 if (sipsock > -1) {
15592 if (sipsock_read_id)
15593 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
15594 else
15595 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15596 }
15597 }
15598
15599 ast_mutex_lock(&iflock);
15600 restartsearch:
15601 t = time(NULL);
15602
15603
15604
15605
15606 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
15607
15608
15609
15610
15611
15612 if (ast_mutex_trylock(&sip->lock))
15613 continue;
15614
15615
15616 if (sip->rtp && sip->owner &&
15617 (sip->owner->_state == AST_STATE_UP) &&
15618 !sip->redirip.sin_addr.s_addr &&
15619 sip->t38.state != T38_ENABLED) {
15620 if (sip->lastrtptx &&
15621 ast_rtp_get_rtpkeepalive(sip->rtp) &&
15622 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
15623
15624 sip->lastrtptx = time(NULL);
15625 ast_rtp_sendcng(sip->rtp, 0);
15626 }
15627 if (sip->lastrtprx &&
15628 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
15629 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
15630
15631 struct sockaddr_in sin;
15632 ast_rtp_get_peer(sip->rtp, &sin);
15633 if (sin.sin_addr.s_addr ||
15634 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
15635 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
15636
15637 if (ast_rtp_get_rtptimeout(sip->rtp)) {
15638 while (sip->owner && ast_channel_trylock(sip->owner)) {
15639 ast_mutex_unlock(&sip->lock);
15640 usleep(1);
15641 ast_mutex_lock(&sip->lock);
15642 }
15643 if (sip->owner) {
15644 ast_log(LOG_NOTICE,
15645 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
15646 sip->owner->name,
15647 (long) (t - sip->lastrtprx));
15648
15649 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
15650 ast_channel_unlock(sip->owner);
15651
15652
15653
15654
15655 ast_rtp_set_rtptimeout(sip->rtp, 0);
15656 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
15657 if (sip->vrtp) {
15658 ast_rtp_set_rtptimeout(sip->vrtp, 0);
15659 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
15660 }
15661 }
15662 }
15663 }
15664 }
15665 }
15666
15667 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
15668 !sip->owner) {
15669 ast_mutex_unlock(&sip->lock);
15670 __sip_destroy(sip, 1);
15671 goto restartsearch;
15672 }
15673 ast_mutex_unlock(&sip->lock);
15674 }
15675 ast_mutex_unlock(&iflock);
15676
15677 pthread_testcancel();
15678
15679 res = ast_sched_wait(sched);
15680 if ((res < 0) || (res > 1000))
15681 res = 1000;
15682
15683 if (fastrestart)
15684 res = 1;
15685 res = ast_io_wait(io, res);
15686 if (option_debug && res > 20)
15687 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
15688 ast_mutex_lock(&monlock);
15689 if (res >= 0) {
15690 res = ast_sched_runq(sched);
15691 if (option_debug && res >= 20)
15692 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
15693 }
15694
15695
15696 t = time(NULL);
15697 fastrestart = FALSE;
15698 curpeernum = 0;
15699 peer = NULL;
15700
15701 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
15702 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
15703 fastrestart = TRUE;
15704 lastpeernum = curpeernum;
15705 peer = ASTOBJ_REF(iterator);
15706 };
15707 curpeernum++;
15708 } while (0)
15709 );
15710
15711 if (peer) {
15712 ASTOBJ_WRLOCK(peer);
15713 sip_send_mwi_to_peer(peer);
15714 ASTOBJ_UNLOCK(peer);
15715 ASTOBJ_UNREF(peer,sip_destroy_peer);
15716 } else {
15717
15718 lastpeernum = -1;
15719 }
15720 ast_mutex_unlock(&monlock);
15721 }
15722
15723 return NULL;
15724
15725 }
15726
15727
15728 static int restart_monitor(void)
15729 {
15730
15731 if (monitor_thread == AST_PTHREADT_STOP)
15732 return 0;
15733 ast_mutex_lock(&monlock);
15734 if (monitor_thread == pthread_self()) {
15735 ast_mutex_unlock(&monlock);
15736 ast_log(LOG_WARNING, "Cannot kill myself\n");
15737 return -1;
15738 }
15739 if (monitor_thread != AST_PTHREADT_NULL) {
15740
15741 pthread_kill(monitor_thread, SIGURG);
15742 } else {
15743
15744 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
15745 ast_mutex_unlock(&monlock);
15746 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
15747 return -1;
15748 }
15749 }
15750 ast_mutex_unlock(&monlock);
15751 return 0;
15752 }
15753
15754
15755 static int sip_poke_noanswer(const void *data)
15756 {
15757 struct sip_peer *peer = (struct sip_peer *)data;
15758
15759 peer->pokeexpire = -1;
15760 if (peer->lastms > -1) {
15761 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
15762 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
15763 }
15764 if (peer->call)
15765 sip_destroy(peer->call);
15766 peer->call = NULL;
15767 peer->lastms = -1;
15768 ast_device_state_changed("SIP/%s", peer->name);
15769
15770 if (peer->pokeexpire > -1)
15771 ast_sched_del(sched, peer->pokeexpire);
15772 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
15773 return 0;
15774 }
15775
15776
15777
15778
15779 static int sip_poke_peer(struct sip_peer *peer)
15780 {
15781 struct sip_pvt *p;
15782 int xmitres = 0;
15783
15784 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
15785
15786
15787 if (peer->pokeexpire > -1)
15788 ast_sched_del(sched, peer->pokeexpire);
15789 peer->lastms = 0;
15790 peer->pokeexpire = -1;
15791 peer->call = NULL;
15792 return 0;
15793 }
15794 if (peer->call) {
15795 if (sipdebug)
15796 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
15797 sip_destroy(peer->call);
15798 }
15799 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
15800 return -1;
15801
15802 p->sa = peer->addr;
15803 p->recv = peer->addr;
15804 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15805 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15806
15807
15808 if (!ast_strlen_zero(peer->fullcontact))
15809 ast_string_field_set(p, fullcontact, peer->fullcontact);
15810
15811 if (!ast_strlen_zero(peer->tohost))
15812 ast_string_field_set(p, tohost, peer->tohost);
15813 else
15814 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
15815
15816
15817 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15818 p->ourip = __ourip;
15819 build_via(p);
15820 build_callid_pvt(p);
15821
15822 if (peer->pokeexpire > -1)
15823 ast_sched_del(sched, peer->pokeexpire);
15824 p->relatedpeer = peer;
15825 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15826 #ifdef VOCAL_DATA_HACK
15827 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
15828 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
15829 #else
15830 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
15831 #endif
15832 gettimeofday(&peer->ps, NULL);
15833 if (xmitres == XMIT_ERROR)
15834 sip_poke_noanswer(peer);
15835 else {
15836 if (peer->pokeexpire > -1)
15837 ast_sched_del(sched, peer->pokeexpire);
15838 peer->pokeexpire = ast_sched_add(sched, peer->maxms * 2, sip_poke_noanswer, peer);
15839 }
15840
15841 return 0;
15842 }
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877 static int sip_devicestate(void *data)
15878 {
15879 char *host;
15880 char *tmp;
15881
15882 struct hostent *hp;
15883 struct ast_hostent ahp;
15884 struct sip_peer *p;
15885
15886 int res = AST_DEVICE_INVALID;
15887
15888
15889 host = ast_strdupa(data ? data : "");
15890 if ((tmp = strchr(host, '@')))
15891 host = tmp + 1;
15892
15893 if (option_debug > 2)
15894 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
15895
15896 if ((p = find_peer(host, NULL, 1))) {
15897 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909 if (p->onHold)
15910
15911 res = AST_DEVICE_ONHOLD;
15912 else if (p->inRinging) {
15913 if (p->inRinging == p->inUse)
15914 res = AST_DEVICE_RINGING;
15915 else
15916 res = AST_DEVICE_RINGINUSE;
15917 } else if (p->call_limit && (p->inUse == p->call_limit))
15918
15919 res = AST_DEVICE_BUSY;
15920 else if (p->call_limit && p->inUse)
15921
15922 res = AST_DEVICE_INUSE;
15923 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
15924
15925 res = AST_DEVICE_UNAVAILABLE;
15926 else
15927 res = AST_DEVICE_NOT_INUSE;
15928 } else {
15929
15930 res = AST_DEVICE_UNAVAILABLE;
15931 }
15932 ASTOBJ_UNREF(p,sip_destroy_peer);
15933 } else {
15934 char *port = strchr(host, ':');
15935 if (port)
15936 *port = '\0';
15937 hp = ast_gethostbyname(host, &ahp);
15938 if (hp)
15939 res = AST_DEVICE_UNKNOWN;
15940 }
15941
15942 return res;
15943 }
15944
15945
15946
15947 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
15948 {
15949 int oldformat;
15950 struct sip_pvt *p;
15951 struct ast_channel *tmpc = NULL;
15952 char *ext, *host;
15953 char tmp[256];
15954 char *dest = data;
15955
15956 oldformat = format;
15957 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
15958 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));
15959 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
15960 return NULL;
15961 }
15962 if (option_debug)
15963 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
15964
15965 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
15966 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
15967 *cause = AST_CAUSE_SWITCH_CONGESTION;
15968 return NULL;
15969 }
15970
15971 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
15972
15973 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
15974 sip_destroy(p);
15975 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
15976 *cause = AST_CAUSE_SWITCH_CONGESTION;
15977 return NULL;
15978 }
15979
15980 ast_copy_string(tmp, dest, sizeof(tmp));
15981 host = strchr(tmp, '@');
15982 if (host) {
15983 *host++ = '\0';
15984 ext = tmp;
15985 } else {
15986 ext = strchr(tmp, '/');
15987 if (ext)
15988 *ext++ = '\0';
15989 host = tmp;
15990 }
15991
15992 if (create_addr(p, host)) {
15993 *cause = AST_CAUSE_UNREGISTERED;
15994 if (option_debug > 2)
15995 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
15996 sip_destroy(p);
15997 return NULL;
15998 }
15999 if (ast_strlen_zero(p->peername) && ext)
16000 ast_string_field_set(p, peername, ext);
16001
16002 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
16003 p->ourip = __ourip;
16004 build_via(p);
16005 build_callid_pvt(p);
16006
16007
16008
16009
16010
16011 if (ext) {
16012 ast_string_field_set(p, username, ext);
16013 ast_string_field_free(p, fullcontact);
16014 }
16015 #if 0
16016 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
16017 #endif
16018 p->prefcodec = oldformat;
16019 ast_mutex_lock(&p->lock);
16020 tmpc = sip_new(p, AST_STATE_DOWN, host);
16021 ast_mutex_unlock(&p->lock);
16022 if (!tmpc)
16023 sip_destroy(p);
16024 ast_update_use_count();
16025 restart_monitor();
16026 return tmpc;
16027 }
16028
16029
16030
16031
16032
16033
16034
16035 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno)
16036 {
16037 static int dep_insecure_very = 0;
16038 static int dep_insecure_yes = 0;
16039
16040 if (ast_strlen_zero(value))
16041 return;
16042
16043 if (!strcasecmp(value, "very")) {
16044 ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16045 if(!dep_insecure_very) {
16046 if(lineno != -1)
16047 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", lineno);
16048 else
16049 ast_log(LOG_WARNING, "insecure=very is deprecated; use insecure=port,invite instead\n");
16050 dep_insecure_very = 1;
16051 }
16052 }
16053 else if (ast_true(value)) {
16054 ast_set_flag(flags, SIP_INSECURE_PORT);
16055 if(!dep_insecure_yes) {
16056 if(lineno != -1)
16057 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", value, lineno);
16058 else
16059 ast_log(LOG_WARNING, "insecure=%s is deprecated; use insecure=port instead\n", value);
16060 dep_insecure_yes = 1;
16061 }
16062 }
16063 else if (!ast_false(value)) {
16064 char buf[64];
16065 char *word, *next;
16066 ast_copy_string(buf, value, sizeof(buf));
16067 next = buf;
16068 while ((word = strsep(&next, ","))) {
16069 if (!strcasecmp(word, "port"))
16070 ast_set_flag(flags, SIP_INSECURE_PORT);
16071 else if (!strcasecmp(word, "invite"))
16072 ast_set_flag(flags, SIP_INSECURE_INVITE);
16073 else
16074 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
16075 }
16076 }
16077 }
16078
16079
16080
16081
16082
16083
16084
16085
16086 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
16087 {
16088 int res = 1;
16089
16090 if (!strcasecmp(v->name, "trustrpid")) {
16091 ast_set_flag(&mask[0], SIP_TRUSTRPID);
16092 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
16093 } else if (!strcasecmp(v->name, "sendrpid")) {
16094 ast_set_flag(&mask[0], SIP_SENDRPID);
16095 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
16096 } else if (!strcasecmp(v->name, "g726nonstandard")) {
16097 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
16098 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
16099 } else if (!strcasecmp(v->name, "useclientcode")) {
16100 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
16101 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
16102 } else if (!strcasecmp(v->name, "dtmfmode")) {
16103 ast_set_flag(&mask[0], SIP_DTMF);
16104 ast_clear_flag(&flags[0], SIP_DTMF);
16105 if (!strcasecmp(v->value, "inband"))
16106 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
16107 else if (!strcasecmp(v->value, "rfc2833"))
16108 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16109 else if (!strcasecmp(v->value, "info"))
16110 ast_set_flag(&flags[0], SIP_DTMF_INFO);
16111 else if (!strcasecmp(v->value, "auto"))
16112 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
16113 else {
16114 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
16115 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
16116 }
16117 } else if (!strcasecmp(v->name, "nat")) {
16118 ast_set_flag(&mask[0], SIP_NAT);
16119 ast_clear_flag(&flags[0], SIP_NAT);
16120 if (!strcasecmp(v->value, "never"))
16121 ast_set_flag(&flags[0], SIP_NAT_NEVER);
16122 else if (!strcasecmp(v->value, "route"))
16123 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
16124 else if (ast_true(v->value))
16125 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
16126 else
16127 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
16128 } else if (!strcasecmp(v->name, "canreinvite")) {
16129 ast_set_flag(&mask[0], SIP_REINVITE);
16130 ast_clear_flag(&flags[0], SIP_REINVITE);
16131 if(ast_true(v->value)) {
16132 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
16133 } else if (!ast_false(v->value)) {
16134 char buf[64];
16135 char *word, *next = buf;
16136
16137 ast_copy_string(buf, v->value, sizeof(buf));
16138 while ((word = strsep(&next, ","))) {
16139 if(!strcasecmp(word, "update")) {
16140 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
16141 } else if(!strcasecmp(word, "nonat")) {
16142 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
16143 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
16144 } else {
16145 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
16146 }
16147 }
16148 }
16149 } else if (!strcasecmp(v->name, "insecure")) {
16150 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16151 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
16152 set_insecure_flags(flags, v->value, v->lineno);
16153 } else if (!strcasecmp(v->name, "progressinband")) {
16154 ast_set_flag(&mask[0], SIP_PROG_INBAND);
16155 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
16156 if (ast_true(v->value))
16157 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
16158 else if (strcasecmp(v->value, "never"))
16159 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
16160 } else if (!strcasecmp(v->name, "promiscredir")) {
16161 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
16162 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
16163 } else if (!strcasecmp(v->name, "videosupport")) {
16164 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
16165 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
16166 } else if (!strcasecmp(v->name, "allowoverlap")) {
16167 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
16168 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
16169 } else if (!strcasecmp(v->name, "allowsubscribe")) {
16170 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16171 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
16172 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
16173 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
16174 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
16175 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
16176 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
16177 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
16178 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
16179 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
16180 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
16181 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
16182 #endif
16183 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
16184 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
16185 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
16186 } else if (!strcasecmp(v->name, "buggymwi")) {
16187 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
16188 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
16189 } else
16190 res = 0;
16191
16192 return res;
16193 }
16194
16195
16196 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
16197 {
16198 struct domain *d;
16199
16200 if (ast_strlen_zero(domain)) {
16201 ast_log(LOG_WARNING, "Zero length domain.\n");
16202 return 1;
16203 }
16204
16205 if (!(d = ast_calloc(1, sizeof(*d))))
16206 return 0;
16207
16208 ast_copy_string(d->domain, domain, sizeof(d->domain));
16209
16210 if (!ast_strlen_zero(context))
16211 ast_copy_string(d->context, context, sizeof(d->context));
16212
16213 d->mode = mode;
16214
16215 AST_LIST_LOCK(&domain_list);
16216 AST_LIST_INSERT_TAIL(&domain_list, d, list);
16217 AST_LIST_UNLOCK(&domain_list);
16218
16219 if (sipdebug)
16220 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
16221
16222 return 1;
16223 }
16224
16225
16226 static int check_sip_domain(const char *domain, char *context, size_t len)
16227 {
16228 struct domain *d;
16229 int result = 0;
16230
16231 AST_LIST_LOCK(&domain_list);
16232 AST_LIST_TRAVERSE(&domain_list, d, list) {
16233 if (strcasecmp(d->domain, domain))
16234 continue;
16235
16236 if (len && !ast_strlen_zero(d->context))
16237 ast_copy_string(context, d->context, len);
16238
16239 result = 1;
16240 break;
16241 }
16242 AST_LIST_UNLOCK(&domain_list);
16243
16244 return result;
16245 }
16246
16247
16248 static void clear_sip_domains(void)
16249 {
16250 struct domain *d;
16251
16252 AST_LIST_LOCK(&domain_list);
16253 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
16254 free(d);
16255 AST_LIST_UNLOCK(&domain_list);
16256 }
16257
16258
16259
16260 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
16261 {
16262 char authcopy[256];
16263 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
16264 char *stringp;
16265 struct sip_auth *a, *b, *auth;
16266
16267 if (ast_strlen_zero(configuration))
16268 return authlist;
16269
16270 if (option_debug)
16271 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
16272
16273 ast_copy_string(authcopy, configuration, sizeof(authcopy));
16274 stringp = authcopy;
16275
16276 username = stringp;
16277 realm = strrchr(stringp, '@');
16278 if (realm)
16279 *realm++ = '\0';
16280 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
16281 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
16282 return authlist;
16283 }
16284 stringp = username;
16285 username = strsep(&stringp, ":");
16286 if (username) {
16287 secret = strsep(&stringp, ":");
16288 if (!secret) {
16289 stringp = username;
16290 md5secret = strsep(&stringp,"#");
16291 }
16292 }
16293 if (!(auth = ast_calloc(1, sizeof(*auth))))
16294 return authlist;
16295
16296 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
16297 ast_copy_string(auth->username, username, sizeof(auth->username));
16298 if (secret)
16299 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
16300 if (md5secret)
16301 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
16302
16303
16304 for (b = NULL, a = authlist; a ; b = a, a = a->next)
16305 ;
16306 if (b)
16307 b->next = auth;
16308 else
16309 authlist = auth;
16310
16311 if (option_verbose > 2)
16312 ast_verbose("Added authentication for realm %s\n", realm);
16313
16314 return authlist;
16315
16316 }
16317
16318
16319 static int clear_realm_authentication(struct sip_auth *authlist)
16320 {
16321 struct sip_auth *a = authlist;
16322 struct sip_auth *b;
16323
16324 while (a) {
16325 b = a;
16326 a = a->next;
16327 free(b);
16328 }
16329
16330 return 1;
16331 }
16332
16333
16334 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
16335 {
16336 struct sip_auth *a;
16337
16338 for (a = authlist; a; a = a->next) {
16339 if (!strcasecmp(a->realm, realm))
16340 break;
16341 }
16342
16343 return a;
16344 }
16345
16346
16347 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime)
16348 {
16349 struct sip_user *user;
16350 int format;
16351 struct ast_ha *oldha = NULL;
16352 char *varname = NULL, *varval = NULL;
16353 struct ast_variable *tmpvar = NULL;
16354 struct ast_flags userflags[2] = {{(0)}};
16355 struct ast_flags mask[2] = {{(0)}};
16356
16357
16358 if (!(user = ast_calloc(1, sizeof(*user))))
16359 return NULL;
16360
16361 suserobjs++;
16362 ASTOBJ_INIT(user);
16363 ast_copy_string(user->name, name, sizeof(user->name));
16364 oldha = user->ha;
16365 user->ha = NULL;
16366 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16367 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16368 user->capability = global_capability;
16369 user->allowtransfer = global_allowtransfer;
16370 user->maxcallbitrate = default_maxcallbitrate;
16371 user->autoframing = global_autoframing;
16372 user->prefs = default_prefs;
16373
16374 strcpy(user->context, default_context);
16375 strcpy(user->language, default_language);
16376 strcpy(user->mohinterpret, default_mohinterpret);
16377 strcpy(user->mohsuggest, default_mohsuggest);
16378 for (; v; v = v->next) {
16379 if (handle_common_options(&userflags[0], &mask[0], v))
16380 continue;
16381
16382 if (!strcasecmp(v->name, "context")) {
16383 ast_copy_string(user->context, v->value, sizeof(user->context));
16384 } else if (!strcasecmp(v->name, "subscribecontext")) {
16385 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
16386 } else if (!strcasecmp(v->name, "setvar")) {
16387 varname = ast_strdupa(v->value);
16388 if ((varval = strchr(varname,'='))) {
16389 *varval++ = '\0';
16390 if ((tmpvar = ast_variable_new(varname, varval))) {
16391 tmpvar->next = user->chanvars;
16392 user->chanvars = tmpvar;
16393 }
16394 }
16395 } else if (!strcasecmp(v->name, "permit") ||
16396 !strcasecmp(v->name, "deny")) {
16397 user->ha = ast_append_ha(v->name, v->value, user->ha);
16398 } else if (!strcasecmp(v->name, "allowtransfer")) {
16399 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16400 } else if (!strcasecmp(v->name, "secret")) {
16401 ast_copy_string(user->secret, v->value, sizeof(user->secret));
16402 } else if (!strcasecmp(v->name, "md5secret")) {
16403 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
16404 } else if (!strcasecmp(v->name, "callerid")) {
16405 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
16406 } else if (!strcasecmp(v->name, "fullname")) {
16407 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
16408 } else if (!strcasecmp(v->name, "cid_number")) {
16409 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
16410 } else if (!strcasecmp(v->name, "callgroup")) {
16411 user->callgroup = ast_get_group(v->value);
16412 } else if (!strcasecmp(v->name, "pickupgroup")) {
16413 user->pickupgroup = ast_get_group(v->value);
16414 } else if (!strcasecmp(v->name, "language")) {
16415 ast_copy_string(user->language, v->value, sizeof(user->language));
16416 } else if (!strcasecmp(v->name, "mohinterpret")
16417 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16418 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
16419 } else if (!strcasecmp(v->name, "mohsuggest")) {
16420 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
16421 } else if (!strcasecmp(v->name, "accountcode")) {
16422 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
16423 } else if (!strcasecmp(v->name, "call-limit")) {
16424 user->call_limit = atoi(v->value);
16425 if (user->call_limit < 0)
16426 user->call_limit = 0;
16427 } else if (!strcasecmp(v->name, "amaflags")) {
16428 format = ast_cdr_amaflags2int(v->value);
16429 if (format < 0) {
16430 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
16431 } else {
16432 user->amaflags = format;
16433 }
16434 } else if (!strcasecmp(v->name, "allow")) {
16435 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
16436 } else if (!strcasecmp(v->name, "disallow")) {
16437 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
16438 } else if (!strcasecmp(v->name, "autoframing")) {
16439 user->autoframing = ast_true(v->value);
16440 } else if (!strcasecmp(v->name, "callingpres")) {
16441 user->callingpres = ast_parse_caller_presentation(v->value);
16442 if (user->callingpres == -1)
16443 user->callingpres = atoi(v->value);
16444 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16445 user->maxcallbitrate = atoi(v->value);
16446 if (user->maxcallbitrate < 0)
16447 user->maxcallbitrate = default_maxcallbitrate;
16448 }
16449
16450
16451
16452 }
16453 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
16454 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
16455 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16456 global_allowsubscribe = TRUE;
16457 ast_free_ha(oldha);
16458 return user;
16459 }
16460
16461
16462 static void set_peer_defaults(struct sip_peer *peer)
16463 {
16464 if (peer->expire == 0) {
16465
16466
16467
16468 peer->expire = -1;
16469 peer->pokeexpire = -1;
16470 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16471 }
16472 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
16473 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16474 strcpy(peer->context, default_context);
16475 strcpy(peer->subscribecontext, default_subscribecontext);
16476 strcpy(peer->language, default_language);
16477 strcpy(peer->mohinterpret, default_mohinterpret);
16478 strcpy(peer->mohsuggest, default_mohsuggest);
16479 peer->addr.sin_family = AF_INET;
16480 peer->defaddr.sin_family = AF_INET;
16481 peer->capability = global_capability;
16482 peer->maxcallbitrate = default_maxcallbitrate;
16483 peer->rtptimeout = global_rtptimeout;
16484 peer->rtpholdtimeout = global_rtpholdtimeout;
16485 peer->rtpkeepalive = global_rtpkeepalive;
16486 peer->allowtransfer = global_allowtransfer;
16487 peer->autoframing = global_autoframing;
16488 strcpy(peer->vmexten, default_vmexten);
16489 peer->secret[0] = '\0';
16490 peer->md5secret[0] = '\0';
16491 peer->cid_num[0] = '\0';
16492 peer->cid_name[0] = '\0';
16493 peer->fromdomain[0] = '\0';
16494 peer->fromuser[0] = '\0';
16495 peer->regexten[0] = '\0';
16496 peer->mailbox[0] = '\0';
16497 peer->callgroup = 0;
16498 peer->pickupgroup = 0;
16499 peer->maxms = default_qualify;
16500 peer->prefs = default_prefs;
16501 }
16502
16503
16504 static struct sip_peer *temp_peer(const char *name)
16505 {
16506 struct sip_peer *peer;
16507
16508 if (!(peer = ast_calloc(1, sizeof(*peer))))
16509 return NULL;
16510
16511 apeerobjs++;
16512 ASTOBJ_INIT(peer);
16513 set_peer_defaults(peer);
16514
16515 ast_copy_string(peer->name, name, sizeof(peer->name));
16516
16517 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
16518 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16519 peer->prefs = default_prefs;
16520 reg_source_db(peer);
16521
16522 return peer;
16523 }
16524
16525
16526 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
16527 {
16528 struct sip_peer *peer = NULL;
16529 struct ast_ha *oldha = NULL;
16530 int obproxyfound=0;
16531 int found=0;
16532 int firstpass=1;
16533 int format=0;
16534 time_t regseconds = 0;
16535 char *varname = NULL, *varval = NULL;
16536 struct ast_variable *tmpvar = NULL;
16537 struct ast_flags peerflags[2] = {{(0)}};
16538 struct ast_flags mask[2] = {{(0)}};
16539
16540
16541 if (!realtime)
16542
16543
16544
16545
16546
16547 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
16548
16549 if (peer) {
16550
16551 found = 1;
16552 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
16553 firstpass = 0;
16554 } else {
16555 if (!(peer = ast_calloc(1, sizeof(*peer))))
16556 return NULL;
16557
16558 if (realtime)
16559 rpeerobjs++;
16560 else
16561 speerobjs++;
16562 ASTOBJ_INIT(peer);
16563 }
16564
16565 if (firstpass) {
16566 peer->lastmsgssent = -1;
16567 oldha = peer->ha;
16568 peer->ha = NULL;
16569 set_peer_defaults(peer);
16570 }
16571 if (!found && name)
16572 ast_copy_string(peer->name, name, sizeof(peer->name));
16573
16574
16575 if (peer->chanvars) {
16576 ast_variables_destroy(peer->chanvars);
16577 peer->chanvars = NULL;
16578
16579 }
16580
16581
16582 clear_realm_authentication(peer->auth);
16583 peer->auth = NULL;
16584
16585 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16586 if (handle_common_options(&peerflags[0], &mask[0], v))
16587 continue;
16588 if (realtime && !strcasecmp(v->name, "regseconds")) {
16589 ast_get_time_t(v->value, ®seconds, 0, NULL);
16590 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
16591 inet_aton(v->value, &(peer->addr.sin_addr));
16592 } else if (realtime && !strcasecmp(v->name, "name"))
16593 ast_copy_string(peer->name, v->value, sizeof(peer->name));
16594 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
16595 ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
16596 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
16597 } else if (!strcasecmp(v->name, "secret"))
16598 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
16599 else if (!strcasecmp(v->name, "md5secret"))
16600 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
16601 else if (!strcasecmp(v->name, "auth"))
16602 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
16603 else if (!strcasecmp(v->name, "callerid")) {
16604 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
16605 } else if (!strcasecmp(v->name, "fullname")) {
16606 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
16607 } else if (!strcasecmp(v->name, "cid_number")) {
16608 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
16609 } else if (!strcasecmp(v->name, "context")) {
16610 ast_copy_string(peer->context, v->value, sizeof(peer->context));
16611 } else if (!strcasecmp(v->name, "subscribecontext")) {
16612 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
16613 } else if (!strcasecmp(v->name, "fromdomain")) {
16614 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
16615 } else if (!strcasecmp(v->name, "usereqphone")) {
16616 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
16617 } else if (!strcasecmp(v->name, "fromuser")) {
16618 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
16619 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
16620 if (!strcasecmp(v->value, "dynamic")) {
16621 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
16622 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
16623 } else {
16624
16625 if (!found || !ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
16626
16627
16628 memset(&peer->addr.sin_addr, 0, 4);
16629 if (peer->addr.sin_port) {
16630
16631 peer->defaddr.sin_port = peer->addr.sin_port;
16632 peer->addr.sin_port = 0;
16633 }
16634 }
16635 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16636 }
16637 } else {
16638
16639 if (peer->expire > -1)
16640 ast_sched_del(sched, peer->expire);
16641 peer->expire = -1;
16642 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16643 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
16644 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
16645 ASTOBJ_UNREF(peer, sip_destroy_peer);
16646 return NULL;
16647 }
16648 }
16649 if (!strcasecmp(v->name, "outboundproxy"))
16650 obproxyfound=1;
16651 else {
16652 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
16653 if (!peer->addr.sin_port)
16654 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16655 }
16656 }
16657 } else if (!strcasecmp(v->name, "defaultip")) {
16658 if (ast_get_ip(&peer->defaddr, v->value)) {
16659 ASTOBJ_UNREF(peer, sip_destroy_peer);
16660 return NULL;
16661 }
16662 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
16663 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
16664 } else if (!strcasecmp(v->name, "port")) {
16665 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
16666 peer->defaddr.sin_port = htons(atoi(v->value));
16667 else
16668 peer->addr.sin_port = htons(atoi(v->value));
16669 } else if (!strcasecmp(v->name, "callingpres")) {
16670 peer->callingpres = ast_parse_caller_presentation(v->value);
16671 if (peer->callingpres == -1)
16672 peer->callingpres = atoi(v->value);
16673 } else if (!strcasecmp(v->name, "username")) {
16674 ast_copy_string(peer->username, v->value, sizeof(peer->username));
16675 } else if (!strcasecmp(v->name, "language")) {
16676 ast_copy_string(peer->language, v->value, sizeof(peer->language));
16677 } else if (!strcasecmp(v->name, "regexten")) {
16678 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
16679 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
16680 peer->call_limit = atoi(v->value);
16681 if (peer->call_limit < 0)
16682 peer->call_limit = 0;
16683 } else if (!strcasecmp(v->name, "amaflags")) {
16684 format = ast_cdr_amaflags2int(v->value);
16685 if (format < 0) {
16686 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
16687 } else {
16688 peer->amaflags = format;
16689 }
16690 } else if (!strcasecmp(v->name, "accountcode")) {
16691 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
16692 } else if (!strcasecmp(v->name, "mohinterpret")
16693 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16694 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
16695 } else if (!strcasecmp(v->name, "mohsuggest")) {
16696 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
16697 } else if (!strcasecmp(v->name, "mailbox")) {
16698 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
16699 } else if (!strcasecmp(v->name, "subscribemwi")) {
16700 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
16701 } else if (!strcasecmp(v->name, "vmexten")) {
16702 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
16703 } else if (!strcasecmp(v->name, "callgroup")) {
16704 peer->callgroup = ast_get_group(v->value);
16705 } else if (!strcasecmp(v->name, "allowtransfer")) {
16706 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16707 } else if (!strcasecmp(v->name, "pickupgroup")) {
16708 peer->pickupgroup = ast_get_group(v->value);
16709 } else if (!strcasecmp(v->name, "allow")) {
16710 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
16711 } else if (!strcasecmp(v->name, "disallow")) {
16712 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
16713 } else if (!strcasecmp(v->name, "autoframing")) {
16714 peer->autoframing = ast_true(v->value);
16715 } else if (!strcasecmp(v->name, "rtptimeout")) {
16716 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
16717 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16718 peer->rtptimeout = global_rtptimeout;
16719 }
16720 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16721 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
16722 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16723 peer->rtpholdtimeout = global_rtpholdtimeout;
16724 }
16725 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16726 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
16727 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16728 peer->rtpkeepalive = global_rtpkeepalive;
16729 }
16730 } else if (!strcasecmp(v->name, "setvar")) {
16731
16732 varname = ast_strdupa(v->value);
16733 if ((varval = strchr(varname, '='))) {
16734 *varval++ = '\0';
16735 if ((tmpvar = ast_variable_new(varname, varval))) {
16736 tmpvar->next = peer->chanvars;
16737 peer->chanvars = tmpvar;
16738 }
16739 }
16740 } else if (!strcasecmp(v->name, "qualify")) {
16741 if (!strcasecmp(v->value, "no")) {
16742 peer->maxms = 0;
16743 } else if (!strcasecmp(v->value, "yes")) {
16744 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
16745 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
16746 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);
16747 peer->maxms = 0;
16748 }
16749 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16750 peer->maxcallbitrate = atoi(v->value);
16751 if (peer->maxcallbitrate < 0)
16752 peer->maxcallbitrate = default_maxcallbitrate;
16753 }
16754 }
16755 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
16756 time_t nowtime = time(NULL);
16757
16758 if ((nowtime - regseconds) > 0) {
16759 destroy_association(peer);
16760 memset(&peer->addr, 0, sizeof(peer->addr));
16761 if (option_debug)
16762 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
16763 }
16764 }
16765 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
16766 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
16767 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16768 global_allowsubscribe = TRUE;
16769 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
16770 reg_source_db(peer);
16771 ASTOBJ_UNMARK(peer);
16772 ast_free_ha(oldha);
16773 return peer;
16774 }
16775
16776
16777
16778
16779
16780
16781
16782 static int reload_config(enum channelreloadreason reason)
16783 {
16784 struct ast_config *cfg, *ucfg;
16785 struct ast_variable *v;
16786 struct sip_peer *peer;
16787 struct sip_user *user;
16788 struct ast_hostent ahp;
16789 char *cat, *stringp, *context, *oldregcontext;
16790 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
16791 struct hostent *hp;
16792 int format;
16793 struct ast_flags dummy[2];
16794 int auto_sip_domains = FALSE;
16795 struct sockaddr_in old_bindaddr = bindaddr;
16796 int registry_count = 0, peer_count = 0, user_count = 0;
16797 unsigned int temp_tos = 0;
16798 struct ast_flags debugflag = {0};
16799
16800 cfg = ast_config_load(config);
16801
16802
16803 if (!cfg) {
16804 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
16805 return -1;
16806 }
16807
16808 if (option_debug > 3)
16809 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
16810
16811 clear_realm_authentication(authl);
16812 clear_sip_domains();
16813 authl = NULL;
16814
16815
16816
16817 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
16818 ASTOBJ_RDLOCK(iterator);
16819 if (iterator->call) {
16820 if (option_debug > 2)
16821 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
16822
16823 sip_destroy(iterator->call);
16824 }
16825 ASTOBJ_UNLOCK(iterator);
16826
16827 } while(0));
16828
16829
16830 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
16831 if (option_debug > 3)
16832 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
16833 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
16834 if (option_debug > 3)
16835 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
16836 ASTOBJ_CONTAINER_MARKALL(&peerl);
16837
16838
16839 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
16840 oldregcontext = oldcontexts;
16841
16842
16843
16844 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
16845 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
16846 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
16847 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
16848
16849
16850 memset(&bindaddr, 0, sizeof(bindaddr));
16851 ast_free_ha(localaddr);
16852 memset(&localaddr, 0, sizeof(localaddr));
16853 memset(&externip, 0, sizeof(externip));
16854 memset(&default_prefs, 0 , sizeof(default_prefs));
16855 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
16856 outboundproxyip.sin_family = AF_INET;
16857 ourport = STANDARD_SIP_PORT;
16858 srvlookup = DEFAULT_SRVLOOKUP;
16859 global_tos_sip = DEFAULT_TOS_SIP;
16860 global_tos_audio = DEFAULT_TOS_AUDIO;
16861 global_tos_video = DEFAULT_TOS_VIDEO;
16862 externhost[0] = '\0';
16863 externexpire = 0;
16864 externrefresh = 10;
16865 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
16866
16867
16868 allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
16869 global_regcontext[0] = '\0';
16870 expiry = DEFAULT_EXPIRY;
16871 global_notifyringing = DEFAULT_NOTIFYRINGING;
16872 global_limitonpeers = FALSE;
16873 global_directrtpsetup = FALSE;
16874 global_notifyhold = FALSE;
16875 global_alwaysauthreject = 0;
16876 global_allowsubscribe = FALSE;
16877 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
16878 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
16879 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
16880 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
16881 else
16882 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
16883 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
16884 compactheaders = DEFAULT_COMPACTHEADERS;
16885 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
16886 global_regattempts_max = 0;
16887 pedanticsipchecking = DEFAULT_PEDANTIC;
16888 global_mwitime = DEFAULT_MWITIME;
16889 autocreatepeer = DEFAULT_AUTOCREATEPEER;
16890 global_autoframing = 0;
16891 global_allowguest = DEFAULT_ALLOWGUEST;
16892 global_rtptimeout = 0;
16893 global_rtpholdtimeout = 0;
16894 global_rtpkeepalive = 0;
16895 global_allowtransfer = TRANSFER_OPENFORALL;
16896 global_rtautoclear = 120;
16897 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16898 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
16899 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
16900
16901
16902 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
16903 default_subscribecontext[0] = '\0';
16904 default_language[0] = '\0';
16905 default_fromdomain[0] = '\0';
16906 default_qualify = DEFAULT_QUALIFY;
16907 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
16908 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
16909 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
16910 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
16911 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
16912 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
16913 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);
16914
16915
16916 dumphistory = FALSE;
16917 recordhistory = FALSE;
16918 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
16919
16920
16921 global_relaxdtmf = FALSE;
16922 global_callevents = FALSE;
16923 global_t1min = DEFAULT_T1MIN;
16924
16925 global_matchexterniplocally = FALSE;
16926
16927
16928 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
16929
16930 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
16931
16932
16933 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
16934 if (handle_common_options(&global_flags[0], &dummy[0], v))
16935 continue;
16936
16937 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
16938 continue;
16939
16940
16941 if (!strcasecmp(v->name, "context")) {
16942 ast_copy_string(default_context, v->value, sizeof(default_context));
16943 } else if (!strcasecmp(v->name, "subscribecontext")) {
16944 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
16945 } else if (!strcasecmp(v->name, "allowguest")) {
16946 global_allowguest = ast_true(v->value) ? 1 : 0;
16947 } else if (!strcasecmp(v->name, "realm")) {
16948 ast_copy_string(global_realm, v->value, sizeof(global_realm));
16949 } else if (!strcasecmp(v->name, "useragent")) {
16950 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
16951 if (option_debug)
16952 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
16953 } else if (!strcasecmp(v->name, "allowtransfer")) {
16954 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16955 } else if (!strcasecmp(v->name, "rtcachefriends")) {
16956 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
16957 } else if (!strcasecmp(v->name, "rtsavesysname")) {
16958 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
16959 } else if (!strcasecmp(v->name, "rtupdate")) {
16960 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
16961 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
16962 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
16963 } else if (!strcasecmp(v->name, "t1min")) {
16964 global_t1min = atoi(v->value);
16965 } else if (!strcasecmp(v->name, "rtautoclear")) {
16966 int i = atoi(v->value);
16967 if (i > 0)
16968 global_rtautoclear = i;
16969 else
16970 i = 0;
16971 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
16972 } else if (!strcasecmp(v->name, "usereqphone")) {
16973 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
16974 } else if (!strcasecmp(v->name, "relaxdtmf")) {
16975 global_relaxdtmf = ast_true(v->value);
16976 } else if (!strcasecmp(v->name, "checkmwi")) {
16977 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
16978 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
16979 global_mwitime = DEFAULT_MWITIME;
16980 }
16981 } else if (!strcasecmp(v->name, "vmexten")) {
16982 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
16983 } else if (!strcasecmp(v->name, "rtptimeout")) {
16984 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
16985 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16986 global_rtptimeout = 0;
16987 }
16988 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16989 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
16990 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16991 global_rtpholdtimeout = 0;
16992 }
16993 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16994 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
16995 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16996 global_rtpkeepalive = 0;
16997 }
16998 } else if (!strcasecmp(v->name, "compactheaders")) {
16999 compactheaders = ast_true(v->value);
17000 } else if (!strcasecmp(v->name, "notifymimetype")) {
17001 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
17002 } else if (!strncasecmp(v->name, "limitonpeer", 11)) {
17003 global_limitonpeers = ast_true(v->value);
17004 } else if (!strcasecmp(v->name, "directrtpsetup")) {
17005 global_directrtpsetup = ast_true(v->value);
17006 } else if (!strcasecmp(v->name, "notifyringing")) {
17007 global_notifyringing = ast_true(v->value);
17008 } else if (!strcasecmp(v->name, "notifyhold")) {
17009 global_notifyhold = ast_true(v->value);
17010 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
17011 global_alwaysauthreject = ast_true(v->value);
17012 } else if (!strcasecmp(v->name, "mohinterpret")
17013 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
17014 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
17015 } else if (!strcasecmp(v->name, "mohsuggest")) {
17016 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
17017 } else if (!strcasecmp(v->name, "language")) {
17018 ast_copy_string(default_language, v->value, sizeof(default_language));
17019 } else if (!strcasecmp(v->name, "regcontext")) {
17020 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
17021 stringp = newcontexts;
17022
17023 cleanup_stale_contexts(stringp, oldregcontext);
17024
17025 while ((context = strsep(&stringp, "&"))) {
17026 if (!ast_context_find(context))
17027 ast_context_create(NULL, context,"SIP");
17028 }
17029 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
17030 } else if (!strcasecmp(v->name, "callerid")) {
17031 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
17032 } else if (!strcasecmp(v->name, "fromdomain")) {
17033 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
17034 } else if (!strcasecmp(v->name, "outboundproxy")) {
17035 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
17036 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
17037 } else if (!strcasecmp(v->name, "outboundproxyport")) {
17038
17039 sscanf(v->value, "%d", &format);
17040 outboundproxyip.sin_port = htons(format);
17041 } else if (!strcasecmp(v->name, "autocreatepeer")) {
17042 autocreatepeer = ast_true(v->value);
17043 } else if (!strcasecmp(v->name, "srvlookup")) {
17044 srvlookup = ast_true(v->value);
17045 } else if (!strcasecmp(v->name, "pedantic")) {
17046 pedanticsipchecking = ast_true(v->value);
17047 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
17048 max_expiry = atoi(v->value);
17049 if (max_expiry < 1)
17050 max_expiry = DEFAULT_MAX_EXPIRY;
17051 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
17052 min_expiry = atoi(v->value);
17053 if (min_expiry < 1)
17054 min_expiry = DEFAULT_MIN_EXPIRY;
17055 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
17056 default_expiry = atoi(v->value);
17057 if (default_expiry < 1)
17058 default_expiry = DEFAULT_DEFAULT_EXPIRY;
17059 } else if (!strcasecmp(v->name, "sipdebug")) {
17060 if (ast_true(v->value))
17061 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
17062 } else if (!strcasecmp(v->name, "dumphistory")) {
17063 dumphistory = ast_true(v->value);
17064 } else if (!strcasecmp(v->name, "recordhistory")) {
17065 recordhistory = ast_true(v->value);
17066 } else if (!strcasecmp(v->name, "registertimeout")) {
17067 global_reg_timeout = atoi(v->value);
17068 if (global_reg_timeout < 1)
17069 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
17070 } else if (!strcasecmp(v->name, "registerattempts")) {
17071 global_regattempts_max = atoi(v->value);
17072 } else if (!strcasecmp(v->name, "bindaddr")) {
17073 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
17074 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
17075 } else {
17076 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
17077 }
17078 } else if (!strcasecmp(v->name, "localnet")) {
17079 struct ast_ha *na;
17080 if (!(na = ast_append_ha("d", v->value, localaddr)))
17081 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
17082 else
17083 localaddr = na;
17084 } else if (!strcasecmp(v->name, "localmask")) {
17085 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
17086 } else if (!strcasecmp(v->name, "externip")) {
17087 if (!(hp = ast_gethostbyname(v->value, &ahp)))
17088 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
17089 else
17090 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17091 externexpire = 0;
17092 } else if (!strcasecmp(v->name, "externhost")) {
17093 ast_copy_string(externhost, v->value, sizeof(externhost));
17094 if (!(hp = ast_gethostbyname(externhost, &ahp)))
17095 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
17096 else
17097 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
17098 externexpire = time(NULL);
17099 } else if (!strcasecmp(v->name, "externrefresh")) {
17100 if (sscanf(v->value, "%d", &externrefresh) != 1) {
17101 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
17102 externrefresh = 10;
17103 }
17104 } else if (!strcasecmp(v->name, "allow")) {
17105 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
17106 } else if (!strcasecmp(v->name, "disallow")) {
17107 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
17108 } else if (!strcasecmp(v->name, "autoframing")) {
17109 global_autoframing = ast_true(v->value);
17110 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
17111 allow_external_domains = ast_true(v->value);
17112 } else if (!strcasecmp(v->name, "autodomain")) {
17113 auto_sip_domains = ast_true(v->value);
17114 } else if (!strcasecmp(v->name, "domain")) {
17115 char *domain = ast_strdupa(v->value);
17116 char *context = strchr(domain, ',');
17117
17118 if (context)
17119 *context++ = '\0';
17120
17121 if (option_debug && ast_strlen_zero(context))
17122 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
17123 if (ast_strlen_zero(domain))
17124 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
17125 else
17126 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
17127 } else if (!strcasecmp(v->name, "register")) {
17128 if (sip_register(v->value, v->lineno) == 0)
17129 registry_count++;
17130 } else if (!strcasecmp(v->name, "tos")) {
17131 if (!ast_str2tos(v->value, &temp_tos)) {
17132 global_tos_sip = temp_tos;
17133 global_tos_audio = temp_tos;
17134 global_tos_video = temp_tos;
17135 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
17136 } else
17137 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
17138 } else if (!strcasecmp(v->name, "tos_sip")) {
17139 if (ast_str2tos(v->value, &global_tos_sip))
17140 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
17141 } else if (!strcasecmp(v->name, "tos_audio")) {
17142 if (ast_str2tos(v->value, &global_tos_audio))
17143 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
17144 } else if (!strcasecmp(v->name, "tos_video")) {
17145 if (ast_str2tos(v->value, &global_tos_video))
17146 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
17147 } else if (!strcasecmp(v->name, "bindport")) {
17148 if (sscanf(v->value, "%d", &ourport) == 1) {
17149 bindaddr.sin_port = htons(ourport);
17150 } else {
17151 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
17152 }
17153 } else if (!strcasecmp(v->name, "qualify")) {
17154 if (!strcasecmp(v->value, "no")) {
17155 default_qualify = 0;
17156 } else if (!strcasecmp(v->value, "yes")) {
17157 default_qualify = DEFAULT_MAXMS;
17158 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
17159 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
17160 default_qualify = 0;
17161 }
17162 } else if (!strcasecmp(v->name, "callevents")) {
17163 global_callevents = ast_true(v->value);
17164 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
17165 default_maxcallbitrate = atoi(v->value);
17166 if (default_maxcallbitrate < 0)
17167 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
17168 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
17169 global_matchexterniplocally = ast_true(v->value);
17170 }
17171 }
17172
17173 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
17174 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
17175 allow_external_domains = 1;
17176 }
17177
17178
17179 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
17180
17181 if (!strcasecmp(v->name, "auth"))
17182 authl = add_realm_authentication(authl, v->value, v->lineno);
17183 }
17184
17185 ucfg = ast_config_load("users.conf");
17186 if (ucfg) {
17187 struct ast_variable *gen;
17188 int genhassip, genregistersip;
17189 const char *hassip, *registersip;
17190
17191 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
17192 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
17193 gen = ast_variable_browse(ucfg, "general");
17194 cat = ast_category_browse(ucfg, NULL);
17195 while (cat) {
17196 if (strcasecmp(cat, "general")) {
17197 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
17198 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
17199 if (ast_true(hassip) || (!hassip && genhassip)) {
17200 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
17201 if (peer) {
17202 ast_device_state_changed("SIP/%s", peer->name);
17203 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17204 ASTOBJ_UNREF(peer, sip_destroy_peer);
17205 peer_count++;
17206 }
17207 }
17208 if (ast_true(registersip) || (!registersip && genregistersip)) {
17209 char tmp[256];
17210 const char *host = ast_variable_retrieve(ucfg, cat, "host");
17211 const char *username = ast_variable_retrieve(ucfg, cat, "username");
17212 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
17213 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
17214 if (!host)
17215 host = ast_variable_retrieve(ucfg, "general", "host");
17216 if (!username)
17217 username = ast_variable_retrieve(ucfg, "general", "username");
17218 if (!secret)
17219 secret = ast_variable_retrieve(ucfg, "general", "secret");
17220 if (!contact)
17221 contact = "s";
17222 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
17223 if (!ast_strlen_zero(secret))
17224 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
17225 else
17226 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
17227 if (sip_register(tmp, 0) == 0)
17228 registry_count++;
17229 }
17230 }
17231 }
17232 cat = ast_category_browse(ucfg, cat);
17233 }
17234 ast_config_destroy(ucfg);
17235 }
17236
17237
17238
17239 cat = NULL;
17240 while ( (cat = ast_category_browse(cfg, cat)) ) {
17241 const char *utype;
17242 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
17243 continue;
17244 utype = ast_variable_retrieve(cfg, cat, "type");
17245 if (!utype) {
17246 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
17247 continue;
17248 } else {
17249 int is_user = 0, is_peer = 0;
17250 if (!strcasecmp(utype, "user"))
17251 is_user = 1;
17252 else if (!strcasecmp(utype, "friend"))
17253 is_user = is_peer = 1;
17254 else if (!strcasecmp(utype, "peer"))
17255 is_peer = 1;
17256 else {
17257 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
17258 continue;
17259 }
17260 if (is_user) {
17261 user = build_user(cat, ast_variable_browse(cfg, cat), 0);
17262 if (user) {
17263 ASTOBJ_CONTAINER_LINK(&userl,user);
17264 ASTOBJ_UNREF(user, sip_destroy_user);
17265 user_count++;
17266 }
17267 }
17268 if (is_peer) {
17269 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
17270 if (peer) {
17271 ASTOBJ_CONTAINER_LINK(&peerl,peer);
17272 ASTOBJ_UNREF(peer, sip_destroy_peer);
17273 peer_count++;
17274 }
17275 }
17276 }
17277 }
17278 if (ast_find_ourip(&__ourip, bindaddr)) {
17279 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
17280 ast_config_destroy(cfg);
17281 return 0;
17282 }
17283 if (!ntohs(bindaddr.sin_port))
17284 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
17285 bindaddr.sin_family = AF_INET;
17286 ast_mutex_lock(&netlock);
17287 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
17288 close(sipsock);
17289 sipsock = -1;
17290 }
17291 if (sipsock < 0) {
17292 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
17293 if (sipsock < 0) {
17294 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
17295 ast_config_destroy(cfg);
17296 return -1;
17297 } else {
17298
17299 const int reuseFlag = 1;
17300
17301 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
17302 (const char*)&reuseFlag,
17303 sizeof reuseFlag);
17304
17305 ast_enable_packet_fragmentation(sipsock);
17306
17307 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
17308 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
17309 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
17310 strerror(errno));
17311 close(sipsock);
17312 sipsock = -1;
17313 } else {
17314 if (option_verbose > 1) {
17315 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
17316 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
17317 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
17318 }
17319 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
17320 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
17321 }
17322 }
17323 }
17324 ast_mutex_unlock(&netlock);
17325
17326
17327
17328
17329
17330 if (auto_sip_domains) {
17331 char temp[MAXHOSTNAMELEN];
17332
17333
17334 if (bindaddr.sin_addr.s_addr)
17335 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
17336 else
17337 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
17338
17339
17340 if (externip.sin_addr.s_addr)
17341 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
17342
17343
17344 if (!ast_strlen_zero(externhost))
17345 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
17346
17347
17348 if (!gethostname(temp, sizeof(temp)))
17349 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
17350 }
17351
17352
17353 ast_config_destroy(cfg);
17354
17355
17356 if (notify_types)
17357 ast_config_destroy(notify_types);
17358 notify_types = ast_config_load(notify_config);
17359
17360
17361 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);
17362
17363 return 0;
17364 }
17365
17366 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
17367 {
17368 struct sip_pvt *p;
17369 struct ast_udptl *udptl = NULL;
17370
17371 p = chan->tech_pvt;
17372 if (!p)
17373 return NULL;
17374
17375 ast_mutex_lock(&p->lock);
17376 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17377 udptl = p->udptl;
17378 ast_mutex_unlock(&p->lock);
17379 return udptl;
17380 }
17381
17382 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
17383 {
17384 struct sip_pvt *p;
17385
17386 p = chan->tech_pvt;
17387 if (!p)
17388 return -1;
17389 ast_mutex_lock(&p->lock);
17390 if (udptl)
17391 ast_udptl_get_peer(udptl, &p->udptlredirip);
17392 else
17393 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17394 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17395 if (!p->pendinginvite) {
17396 if (option_debug > 2) {
17397 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);
17398 }
17399 transmit_reinvite_with_t38_sdp(p);
17400 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17401 if (option_debug > 2) {
17402 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);
17403 }
17404 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17405 }
17406 }
17407
17408 p->lastrtprx = p->lastrtptx = time(NULL);
17409 ast_mutex_unlock(&p->lock);
17410 return 0;
17411 }
17412
17413
17414
17415
17416
17417
17418 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
17419 {
17420 struct sip_pvt *p;
17421 int flag = 0;
17422
17423 p = chan->tech_pvt;
17424 if (!p || !pvt->udptl)
17425 return -1;
17426
17427
17428 ast_mutex_lock(&p->lock);
17429
17430
17431
17432 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
17433
17434 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17435 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
17436 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
17437
17438 if (reinvite) {
17439
17440
17441
17442
17443
17444 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17445 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17446 flag =1;
17447 } else {
17448 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17449 }
17450 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17451 if (!p->pendinginvite) {
17452 if (option_debug > 2) {
17453 if (flag)
17454 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));
17455 else
17456 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));
17457 }
17458 transmit_reinvite_with_t38_sdp(p);
17459 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17460 if (option_debug > 2) {
17461 if (flag)
17462 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));
17463 else
17464 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));
17465 }
17466 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17467 }
17468 }
17469
17470 p->lastrtprx = p->lastrtptx = time(NULL);
17471 ast_mutex_unlock(&p->lock);
17472 return 0;
17473 } else {
17474 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
17475 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
17476 flag = 1;
17477 } else {
17478 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
17479 }
17480 if (option_debug > 2) {
17481 if (flag)
17482 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));
17483 else
17484 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));
17485 }
17486 pvt->t38.state = T38_ENABLED;
17487 p->t38.state = T38_ENABLED;
17488 if (option_debug > 1) {
17489 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
17490 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
17491 }
17492 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
17493 p->lastrtprx = p->lastrtptx = time(NULL);
17494 ast_mutex_unlock(&p->lock);
17495 return 0;
17496 }
17497 }
17498
17499
17500
17501 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17502 {
17503 struct sip_pvt *p = NULL;
17504 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17505
17506 if (!(p = chan->tech_pvt))
17507 return AST_RTP_GET_FAILED;
17508
17509 ast_mutex_lock(&p->lock);
17510 if (!(p->rtp)) {
17511 ast_mutex_unlock(&p->lock);
17512 return AST_RTP_GET_FAILED;
17513 }
17514
17515 *rtp = p->rtp;
17516
17517 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
17518 res = AST_RTP_TRY_PARTIAL;
17519 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17520 res = AST_RTP_TRY_NATIVE;
17521 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
17522 res = AST_RTP_GET_FAILED;
17523
17524 ast_mutex_unlock(&p->lock);
17525
17526 return res;
17527 }
17528
17529
17530 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
17531 {
17532 struct sip_pvt *p = NULL;
17533 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
17534
17535 if (!(p = chan->tech_pvt))
17536 return AST_RTP_GET_FAILED;
17537
17538 ast_mutex_lock(&p->lock);
17539 if (!(p->vrtp)) {
17540 ast_mutex_unlock(&p->lock);
17541 return AST_RTP_GET_FAILED;
17542 }
17543
17544 *rtp = p->vrtp;
17545
17546 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
17547 res = AST_RTP_TRY_NATIVE;
17548
17549 ast_mutex_unlock(&p->lock);
17550
17551 return res;
17552 }
17553
17554
17555 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
17556 {
17557 struct sip_pvt *p;
17558 int changed = 0;
17559
17560 p = chan->tech_pvt;
17561 if (!p)
17562 return -1;
17563
17564
17565 if (chan->_state != AST_STATE_UP && !global_directrtpsetup)
17566 return 0;
17567
17568 ast_mutex_lock(&p->lock);
17569 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
17570
17571 ast_mutex_unlock(&p->lock);
17572 return 0;
17573 }
17574
17575
17576
17577
17578 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
17579 ast_mutex_unlock(&p->lock);
17580 return 0;
17581 }
17582
17583 if (rtp) {
17584 changed |= ast_rtp_get_peer(rtp, &p->redirip);
17585 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
17586 memset(&p->redirip, 0, sizeof(p->redirip));
17587 changed = 1;
17588 }
17589 if (vrtp) {
17590 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
17591 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
17592 memset(&p->vredirip, 0, sizeof(p->vredirip));
17593 changed = 1;
17594 }
17595 if (codecs) {
17596 if ((p->redircodecs != codecs)) {
17597 p->redircodecs = codecs;
17598 changed = 1;
17599 }
17600 if ((p->capability & codecs) != p->capability) {
17601 p->jointcapability &= codecs;
17602 p->capability &= codecs;
17603 changed = 1;
17604 }
17605 }
17606 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
17607 if (chan->_state != AST_STATE_UP) {
17608 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
17609 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
17610 if (option_debug)
17611 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));
17612 } else if (!p->pendinginvite) {
17613 if (option_debug > 2) {
17614 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));
17615 }
17616 transmit_reinvite_with_sdp(p);
17617 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17618 if (option_debug > 2) {
17619 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));
17620 }
17621
17622 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17623 }
17624 }
17625
17626 p->lastrtprx = p->lastrtptx = time(NULL);
17627 ast_mutex_unlock(&p->lock);
17628 return 0;
17629 }
17630
17631 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
17632 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
17633 static char *app_dtmfmode = "SIPDtmfMode";
17634
17635 static char *app_sipaddheader = "SIPAddHeader";
17636 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
17637
17638 static char *descrip_sipaddheader = ""
17639 " SIPAddHeader(Header: Content)\n"
17640 "Adds a header to a SIP call placed with DIAL.\n"
17641 "Remember to user the X-header if you are adding non-standard SIP\n"
17642 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
17643 "Adding the wrong headers may jeopardize the SIP dialog.\n"
17644 "Always returns 0\n";
17645
17646
17647
17648 static int sip_dtmfmode(struct ast_channel *chan, void *data)
17649 {
17650 struct sip_pvt *p;
17651 char *mode;
17652 if (data)
17653 mode = (char *)data;
17654 else {
17655 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
17656 return 0;
17657 }
17658 ast_channel_lock(chan);
17659 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
17660 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
17661 ast_channel_unlock(chan);
17662 return 0;
17663 }
17664 p = chan->tech_pvt;
17665 if (!p) {
17666 ast_channel_unlock(chan);
17667 return 0;
17668 }
17669 ast_mutex_lock(&p->lock);
17670 if (!strcasecmp(mode,"info")) {
17671 ast_clear_flag(&p->flags[0], SIP_DTMF);
17672 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
17673 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17674 } else if (!strcasecmp(mode,"rfc2833")) {
17675 ast_clear_flag(&p->flags[0], SIP_DTMF);
17676 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
17677 p->jointnoncodeccapability |= AST_RTP_DTMF;
17678 } else if (!strcasecmp(mode,"inband")) {
17679 ast_clear_flag(&p->flags[0], SIP_DTMF);
17680 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
17681 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17682 } else
17683 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
17684 if (p->rtp)
17685 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
17686 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
17687 if (!p->vad) {
17688 p->vad = ast_dsp_new();
17689 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
17690 }
17691 } else {
17692 if (p->vad) {
17693 ast_dsp_free(p->vad);
17694 p->vad = NULL;
17695 }
17696 }
17697 ast_mutex_unlock(&p->lock);
17698 ast_channel_unlock(chan);
17699 return 0;
17700 }
17701
17702
17703 static int sip_addheader(struct ast_channel *chan, void *data)
17704 {
17705 int no = 0;
17706 int ok = FALSE;
17707 char varbuf[30];
17708 char *inbuf = (char *) data;
17709
17710 if (ast_strlen_zero(inbuf)) {
17711 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
17712 return 0;
17713 }
17714 ast_channel_lock(chan);
17715
17716
17717 while (!ok && no <= 50) {
17718 no++;
17719 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
17720
17721
17722 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
17723 ok = TRUE;
17724 }
17725 if (ok) {
17726 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
17727 if (sipdebug)
17728 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
17729 } else {
17730 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
17731 }
17732 ast_channel_unlock(chan);
17733 return 0;
17734 }
17735
17736
17737
17738
17739
17740
17741
17742 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
17743 {
17744 char *cdest;
17745 char *extension, *host, *port;
17746 char tmp[80];
17747
17748 cdest = ast_strdupa(dest);
17749
17750 extension = strsep(&cdest, "@");
17751 host = strsep(&cdest, ":");
17752 port = strsep(&cdest, ":");
17753 if (ast_strlen_zero(extension)) {
17754 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
17755 return 0;
17756 }
17757
17758
17759 if (!host) {
17760 char *localtmp;
17761 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
17762 if (ast_strlen_zero(tmp)) {
17763 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
17764 return 0;
17765 }
17766 if ((localtmp = strcasestr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
17767 char lhost[80], lport[80];
17768 memset(lhost, 0, sizeof(lhost));
17769 memset(lport, 0, sizeof(lport));
17770 localtmp++;
17771
17772 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
17773 if (ast_strlen_zero(lhost)) {
17774 ast_log(LOG_ERROR, "Can't find the host address\n");
17775 return 0;
17776 }
17777 host = ast_strdupa(lhost);
17778 if (!ast_strlen_zero(lport)) {
17779 port = ast_strdupa(lport);
17780 }
17781 }
17782 }
17783
17784 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
17785 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
17786
17787 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17788 sip_alreadygone(p);
17789 return 0;
17790 }
17791
17792
17793 static int sip_get_codec(struct ast_channel *chan)
17794 {
17795 struct sip_pvt *p = chan->tech_pvt;
17796 return p->peercapability ? p->peercapability : p->capability;
17797 }
17798
17799
17800
17801
17802
17803 static void sip_poke_all_peers(void)
17804 {
17805 int ms = 0;
17806
17807 if (!speerobjs)
17808 return;
17809
17810 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
17811 ASTOBJ_WRLOCK(iterator);
17812 if (iterator->pokeexpire > -1)
17813 ast_sched_del(sched, iterator->pokeexpire);
17814 ms += 100;
17815 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, iterator);
17816 ASTOBJ_UNLOCK(iterator);
17817 } while (0)
17818 );
17819 }
17820
17821
17822 static void sip_send_all_registers(void)
17823 {
17824 int ms;
17825 int regspacing;
17826 if (!regobjs)
17827 return;
17828 regspacing = default_expiry * 1000/regobjs;
17829 if (regspacing > 100)
17830 regspacing = 100;
17831 ms = regspacing;
17832 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
17833 ASTOBJ_WRLOCK(iterator);
17834 if (iterator->expire > -1)
17835 ast_sched_del(sched, iterator->expire);
17836 ms += regspacing;
17837 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
17838 ASTOBJ_UNLOCK(iterator);
17839 } while (0)
17840 );
17841 }
17842
17843
17844 static int sip_do_reload(enum channelreloadreason reason)
17845 {
17846 reload_config(reason);
17847
17848
17849 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
17850 if (option_debug > 3)
17851 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
17852
17853
17854 sip_poke_all_peers();
17855
17856
17857 sip_send_all_registers();
17858
17859 if (option_debug > 3)
17860 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
17861
17862 return 0;
17863 }
17864
17865
17866 static int sip_reload(int fd, int argc, char *argv[])
17867 {
17868 ast_mutex_lock(&sip_reload_lock);
17869 if (sip_reloading)
17870 ast_verbose("Previous SIP reload not yet done\n");
17871 else {
17872 sip_reloading = TRUE;
17873 if (fd)
17874 sip_reloadreason = CHANNEL_CLI_RELOAD;
17875 else
17876 sip_reloadreason = CHANNEL_MODULE_RELOAD;
17877 }
17878 ast_mutex_unlock(&sip_reload_lock);
17879 restart_monitor();
17880
17881 return 0;
17882 }
17883
17884
17885 static int reload(void)
17886 {
17887 return sip_reload(0, 0, NULL);
17888 }
17889
17890 static struct ast_cli_entry cli_sip_debug_deprecated =
17891 { { "sip", "debug", NULL },
17892 sip_do_debug_deprecated, "Enable SIP debugging",
17893 debug_usage };
17894
17895 static struct ast_cli_entry cli_sip_no_debug_deprecated =
17896 { { "sip", "no", "debug", NULL },
17897 sip_no_debug_deprecated, "Disable SIP debugging",
17898 debug_usage };
17899
17900 static struct ast_cli_entry cli_sip[] = {
17901 { { "sip", "show", "channels", NULL },
17902 sip_show_channels, "List active SIP channels",
17903 show_channels_usage },
17904
17905 { { "sip", "show", "domains", NULL },
17906 sip_show_domains, "List our local SIP domains.",
17907 show_domains_usage },
17908
17909 { { "sip", "show", "inuse", NULL },
17910 sip_show_inuse, "List all inuse/limits",
17911 show_inuse_usage },
17912
17913 { { "sip", "show", "objects", NULL },
17914 sip_show_objects, "List all SIP object allocations",
17915 show_objects_usage },
17916
17917 { { "sip", "show", "peers", NULL },
17918 sip_show_peers, "List defined SIP peers",
17919 show_peers_usage },
17920
17921 { { "sip", "show", "registry", NULL },
17922 sip_show_registry, "List SIP registration status",
17923 show_reg_usage },
17924
17925 { { "sip", "show", "settings", NULL },
17926 sip_show_settings, "Show SIP global settings",
17927 show_settings_usage },
17928
17929 { { "sip", "show", "subscriptions", NULL },
17930 sip_show_subscriptions, "List active SIP subscriptions",
17931 show_subscriptions_usage },
17932
17933 { { "sip", "show", "users", NULL },
17934 sip_show_users, "List defined SIP users",
17935 show_users_usage },
17936
17937 { { "sip", "notify", NULL },
17938 sip_notify, "Send a notify packet to a SIP peer",
17939 notify_usage, complete_sipnotify },
17940
17941 { { "sip", "show", "channel", NULL },
17942 sip_show_channel, "Show detailed SIP channel info",
17943 show_channel_usage, complete_sipch },
17944
17945 { { "sip", "show", "history", NULL },
17946 sip_show_history, "Show SIP dialog history",
17947 show_history_usage, complete_sipch },
17948
17949 { { "sip", "show", "peer", NULL },
17950 sip_show_peer, "Show details on specific SIP peer",
17951 show_peer_usage, complete_sip_show_peer },
17952
17953 { { "sip", "show", "user", NULL },
17954 sip_show_user, "Show details on specific SIP user",
17955 show_user_usage, complete_sip_show_user },
17956
17957 { { "sip", "prune", "realtime", NULL },
17958 sip_prune_realtime, "Prune cached Realtime object(s)",
17959 prune_realtime_usage },
17960
17961 { { "sip", "prune", "realtime", "peer", NULL },
17962 sip_prune_realtime, "Prune cached Realtime peer(s)",
17963 prune_realtime_usage, complete_sip_prune_realtime_peer },
17964
17965 { { "sip", "prune", "realtime", "user", NULL },
17966 sip_prune_realtime, "Prune cached Realtime user(s)",
17967 prune_realtime_usage, complete_sip_prune_realtime_user },
17968
17969 { { "sip", "set", "debug", NULL },
17970 sip_do_debug, "Enable SIP debugging",
17971 debug_usage, NULL, &cli_sip_debug_deprecated },
17972
17973 { { "sip", "set", "debug", "ip", NULL },
17974 sip_do_debug, "Enable SIP debugging on IP",
17975 debug_usage },
17976
17977 { { "sip", "set", "debug", "peer", NULL },
17978 sip_do_debug, "Enable SIP debugging on Peername",
17979 debug_usage, complete_sip_debug_peer },
17980
17981 { { "sip", "set", "debug", "off", NULL },
17982 sip_no_debug, "Disable SIP debugging",
17983 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
17984
17985 { { "sip", "history", NULL },
17986 sip_do_history, "Enable SIP history",
17987 history_usage },
17988
17989 { { "sip", "history", "off", NULL },
17990 sip_no_history, "Disable SIP history",
17991 no_history_usage },
17992
17993 { { "sip", "reload", NULL },
17994 sip_reload, "Reload SIP configuration",
17995 sip_reload_usage },
17996 };
17997
17998
17999 static int load_module(void)
18000 {
18001 ASTOBJ_CONTAINER_INIT(&userl);
18002 ASTOBJ_CONTAINER_INIT(&peerl);
18003 ASTOBJ_CONTAINER_INIT(®l);
18004
18005 if (!(sched = sched_context_create())) {
18006 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
18007 return AST_MODULE_LOAD_FAILURE;
18008 }
18009
18010 if (!(io = io_context_create())) {
18011 ast_log(LOG_ERROR, "Unable to create I/O context\n");
18012 sched_context_destroy(sched);
18013 return AST_MODULE_LOAD_FAILURE;
18014 }
18015
18016 sip_reloadreason = CHANNEL_MODULE_LOAD;
18017
18018 if(reload_config(sip_reloadreason))
18019 return AST_MODULE_LOAD_DECLINE;
18020
18021
18022 if (ast_channel_register(&sip_tech)) {
18023 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
18024 io_context_destroy(io);
18025 sched_context_destroy(sched);
18026 return AST_MODULE_LOAD_FAILURE;
18027 }
18028
18029
18030 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
18031
18032
18033 ast_rtp_proto_register(&sip_rtp);
18034
18035
18036 ast_udptl_proto_register(&sip_udptl);
18037
18038
18039 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
18040 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
18041
18042
18043 ast_custom_function_register(&sip_header_function);
18044 ast_custom_function_register(&sippeer_function);
18045 ast_custom_function_register(&sipchaninfo_function);
18046 ast_custom_function_register(&checksipdomain_function);
18047
18048
18049 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
18050 "List SIP peers (text format)", mandescr_show_peers);
18051 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
18052 "Show SIP peer (text format)", mandescr_show_peer);
18053
18054 sip_poke_all_peers();
18055 sip_send_all_registers();
18056
18057
18058 restart_monitor();
18059
18060 return AST_MODULE_LOAD_SUCCESS;
18061 }
18062
18063
18064 static int unload_module(void)
18065 {
18066 struct sip_pvt *p, *pl;
18067
18068
18069 ast_channel_unregister(&sip_tech);
18070
18071
18072 ast_custom_function_unregister(&sipchaninfo_function);
18073 ast_custom_function_unregister(&sippeer_function);
18074 ast_custom_function_unregister(&sip_header_function);
18075 ast_custom_function_unregister(&checksipdomain_function);
18076
18077
18078 ast_unregister_application(app_dtmfmode);
18079 ast_unregister_application(app_sipaddheader);
18080
18081
18082 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
18083
18084
18085 ast_rtp_proto_unregister(&sip_rtp);
18086
18087
18088 ast_udptl_proto_unregister(&sip_udptl);
18089
18090
18091 ast_manager_unregister("SIPpeers");
18092 ast_manager_unregister("SIPshowpeer");
18093
18094 ast_mutex_lock(&iflock);
18095
18096 for (p = iflist; p ; p = p->next) {
18097 if (p->owner)
18098 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
18099 }
18100 ast_mutex_unlock(&iflock);
18101
18102 ast_mutex_lock(&monlock);
18103 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
18104 pthread_cancel(monitor_thread);
18105 pthread_kill(monitor_thread, SIGURG);
18106 pthread_join(monitor_thread, NULL);
18107 }
18108 monitor_thread = AST_PTHREADT_STOP;
18109 ast_mutex_unlock(&monlock);
18110
18111 ast_mutex_lock(&iflock);
18112
18113 p = iflist;
18114 while (p) {
18115 pl = p;
18116 p = p->next;
18117 __sip_destroy(pl, TRUE);
18118 }
18119 iflist = NULL;
18120 ast_mutex_unlock(&iflock);
18121
18122
18123 ast_free_ha(localaddr);
18124
18125 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
18126 ASTOBJ_CONTAINER_DESTROY(&userl);
18127 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
18128 ASTOBJ_CONTAINER_DESTROY(&peerl);
18129 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
18130 ASTOBJ_CONTAINER_DESTROY(®l);
18131
18132 clear_realm_authentication(authl);
18133 clear_sip_domains();
18134 close(sipsock);
18135 sched_context_destroy(sched);
18136
18137 return 0;
18138 }
18139
18140 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
18141 .load = load_module,
18142 .unload = unload_module,
18143 .reload = reload,
18144 );