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 #include "asterisk.h"
00092
00093 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00094
00095 #include <stdio.h>
00096 #include <ctype.h>
00097 #include <string.h>
00098 #include <unistd.h>
00099 #include <sys/socket.h>
00100 #include <sys/ioctl.h>
00101 #include <net/if.h>
00102 #include <errno.h>
00103 #include <stdlib.h>
00104 #include <fcntl.h>
00105 #include <netdb.h>
00106 #include <signal.h>
00107 #include <sys/signal.h>
00108 #include <netinet/in.h>
00109 #include <netinet/in_systm.h>
00110 #include <arpa/inet.h>
00111 #include <netinet/ip.h>
00112 #include <regex.h>
00113
00114 #include "asterisk/lock.h"
00115 #include "asterisk/channel.h"
00116 #include "asterisk/config.h"
00117 #include "asterisk/logger.h"
00118 #include "asterisk/module.h"
00119 #include "asterisk/pbx.h"
00120 #include "asterisk/options.h"
00121 #include "asterisk/sched.h"
00122 #include "asterisk/io.h"
00123 #include "asterisk/rtp.h"
00124 #include "asterisk/udptl.h"
00125 #include "asterisk/acl.h"
00126 #include "asterisk/manager.h"
00127 #include "asterisk/callerid.h"
00128 #include "asterisk/cli.h"
00129 #include "asterisk/app.h"
00130 #include "asterisk/musiconhold.h"
00131 #include "asterisk/dsp.h"
00132 #include "asterisk/features.h"
00133 #include "asterisk/srv.h"
00134 #include "asterisk/astdb.h"
00135 #include "asterisk/causes.h"
00136 #include "asterisk/utils.h"
00137 #include "asterisk/file.h"
00138 #include "asterisk/astobj.h"
00139 #include "asterisk/devicestate.h"
00140 #include "asterisk/linkedlists.h"
00141 #include "asterisk/stringfields.h"
00142 #include "asterisk/monitor.h"
00143 #include "asterisk/localtime.h"
00144 #include "asterisk/abstract_jb.h"
00145 #include "asterisk/compiler.h"
00146 #include "asterisk/threadstorage.h"
00147 #include "asterisk/translate.h"
00148
00149 #ifndef FALSE
00150 #define FALSE 0
00151 #endif
00152
00153 #ifndef TRUE
00154 #define TRUE 1
00155 #endif
00156
00157 #define VIDEO_CODEC_MASK 0x1fc0000
00158 #ifndef IPTOS_MINCOST
00159 #define IPTOS_MINCOST 0x02
00160 #endif
00161
00162
00163
00164 #define DEFAULT_DEFAULT_EXPIRY 120
00165 #define DEFAULT_MIN_EXPIRY 60
00166 #define DEFAULT_MAX_EXPIRY 3600
00167 #define DEFAULT_REGISTRATION_TIMEOUT 20
00168 #define DEFAULT_MAX_FORWARDS "70"
00169
00170
00171
00172 #define EXPIRY_GUARD_SECS 15
00173 #define EXPIRY_GUARD_LIMIT 30
00174
00175 #define EXPIRY_GUARD_MIN 500
00176
00177
00178
00179 #define EXPIRY_GUARD_PCT 0.20
00180
00181 #define DEFAULT_EXPIRY 900
00182
00183 static int min_expiry = DEFAULT_MIN_EXPIRY;
00184 static int max_expiry = DEFAULT_MAX_EXPIRY;
00185 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00186 static int expiry = DEFAULT_EXPIRY;
00187
00188 #ifndef MAX
00189 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00190 #endif
00191
00192 #define CALLERID_UNKNOWN "Unknown"
00193
00194 #define DEFAULT_MAXMS 2000
00195 #define DEFAULT_FREQ_OK 60 * 1000
00196 #define DEFAULT_FREQ_NOTOK 10 * 1000
00197
00198 #define DEFAULT_RETRANS 1000
00199 #define MAX_RETRANS 6
00200 #define SIP_TRANS_TIMEOUT 32000
00201
00202
00203 #define DEFAULT_TRANS_TIMEOUT -1
00204 #define MAX_AUTHTRIES 3
00205
00206 #define SIP_MAX_HEADERS 64
00207 #define SIP_MAX_LINES 64
00208 #define SIP_MAX_PACKET 4096
00209
00210 #define INITIAL_CSEQ 101
00211
00212
00213 static struct ast_jb_conf default_jbconf =
00214 {
00215 .flags = 0,
00216 .max_size = -1,
00217 .resync_threshold = -1,
00218 .impl = ""
00219 };
00220 static struct ast_jb_conf global_jbconf;
00221
00222 static const char config[] = "sip.conf";
00223 static const char notify_config[] = "sip_notify.conf";
00224
00225 #define RTP 1
00226 #define NO_RTP 0
00227
00228
00229
00230
00231 enum transfermodes {
00232 TRANSFER_OPENFORALL,
00233 TRANSFER_CLOSED,
00234 };
00235
00236
00237 enum sip_result {
00238 AST_SUCCESS = 0,
00239 AST_FAILURE = -1,
00240 };
00241
00242
00243
00244
00245 enum invitestates {
00246 INV_NONE = 0,
00247 INV_CALLING = 1,
00248 INV_PROCEEDING = 2,
00249 INV_EARLY_MEDIA = 3,
00250 INV_COMPLETED = 4,
00251 INV_CONFIRMED = 5,
00252 INV_TERMINATED = 6,
00253
00254 INV_CANCELLED = 7,
00255 };
00256
00257
00258
00259
00260
00261
00262
00263
00264
00265 enum xmittype {
00266 XMIT_CRITICAL = 2,
00267
00268 XMIT_RELIABLE = 1,
00269 XMIT_UNRELIABLE = 0,
00270 };
00271
00272 enum parse_register_result {
00273 PARSE_REGISTER_FAILED,
00274 PARSE_REGISTER_UPDATE,
00275 PARSE_REGISTER_QUERY,
00276 };
00277
00278 enum subscriptiontype {
00279 NONE = 0,
00280 XPIDF_XML,
00281 DIALOG_INFO_XML,
00282 CPIM_PIDF_XML,
00283 PIDF_XML,
00284 MWI_NOTIFICATION
00285 };
00286
00287 static const struct cfsubscription_types {
00288 enum subscriptiontype type;
00289 const char * const event;
00290 const char * const mediatype;
00291 const char * const text;
00292 } subscription_types[] = {
00293 { NONE, "-", "unknown", "unknown" },
00294
00295 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00296 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00297 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00298 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00299 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00300 };
00301
00302
00303 enum sipmethod {
00304 SIP_UNKNOWN,
00305 SIP_RESPONSE,
00306 SIP_REGISTER,
00307 SIP_OPTIONS,
00308 SIP_NOTIFY,
00309 SIP_INVITE,
00310 SIP_ACK,
00311 SIP_PRACK,
00312 SIP_BYE,
00313 SIP_REFER,
00314 SIP_SUBSCRIBE,
00315 SIP_MESSAGE,
00316 SIP_UPDATE,
00317 SIP_INFO,
00318 SIP_CANCEL,
00319 SIP_PUBLISH,
00320 SIP_PING,
00321 };
00322
00323
00324
00325
00326
00327
00328 enum sip_auth_type {
00329 PROXY_AUTH,
00330 WWW_AUTH,
00331 };
00332
00333
00334 enum check_auth_result {
00335 AUTH_SUCCESSFUL = 0,
00336 AUTH_CHALLENGE_SENT = 1,
00337 AUTH_SECRET_FAILED = -1,
00338 AUTH_USERNAME_MISMATCH = -2,
00339 AUTH_NOT_FOUND = -3,
00340 AUTH_FAKE_AUTH = -4,
00341 AUTH_UNKNOWN_DOMAIN = -5,
00342 };
00343
00344
00345 enum sipregistrystate {
00346 REG_STATE_UNREGISTERED = 0,
00347 REG_STATE_REGSENT,
00348 REG_STATE_AUTHSENT,
00349 REG_STATE_REGISTERED,
00350 REG_STATE_REJECTED,
00351 REG_STATE_TIMEOUT,
00352 REG_STATE_NOAUTH,
00353 REG_STATE_FAILED,
00354 };
00355
00356 #define CAN_NOT_CREATE_DIALOG 0
00357 #define CAN_CREATE_DIALOG 1
00358 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
00359
00360
00361 static const struct cfsip_methods {
00362 enum sipmethod id;
00363 int need_rtp;
00364 char * const text;
00365 int can_create;
00366 } sip_methods[] = {
00367 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
00368 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00369 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00370 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00371 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00372 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00373 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00374 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00375 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00376 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00377 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
00378 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00379 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00380 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00381 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00382 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00383 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00384 };
00385
00386
00387
00388
00389
00390
00391
00392
00393
00394
00395
00396 #define SUPPORTED 1
00397 #define NOT_SUPPORTED 0
00398
00399 #define SIP_OPT_REPLACES (1 << 0)
00400 #define SIP_OPT_100REL (1 << 1)
00401 #define SIP_OPT_TIMER (1 << 2)
00402 #define SIP_OPT_EARLY_SESSION (1 << 3)
00403 #define SIP_OPT_JOIN (1 << 4)
00404 #define SIP_OPT_PATH (1 << 5)
00405 #define SIP_OPT_PREF (1 << 6)
00406 #define SIP_OPT_PRECONDITION (1 << 7)
00407 #define SIP_OPT_PRIVACY (1 << 8)
00408 #define SIP_OPT_SDP_ANAT (1 << 9)
00409 #define SIP_OPT_SEC_AGREE (1 << 10)
00410 #define SIP_OPT_EVENTLIST (1 << 11)
00411 #define SIP_OPT_GRUU (1 << 12)
00412 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00413 #define SIP_OPT_NOREFERSUB (1 << 14)
00414 #define SIP_OPT_HISTINFO (1 << 15)
00415 #define SIP_OPT_RESPRIORITY (1 << 16)
00416
00417
00418
00419 static const struct cfsip_options {
00420 int id;
00421 int supported;
00422 char * const text;
00423 } sip_options[] = {
00424
00425 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
00426
00427 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
00428
00429 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
00430
00431 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
00432
00433 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
00434
00435 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
00436
00437 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
00438
00439 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
00440
00441 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00442
00443 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
00444
00445 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
00446
00447 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00448
00449 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00450
00451 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
00452
00453 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00454
00455 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
00456
00457 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
00458
00459 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
00460 };
00461
00462
00463
00464 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
00465
00466
00467 #define SUPPORTED_EXTENSIONS "replaces"
00468
00469
00470 #define STANDARD_SIP_PORT 5060
00471
00472
00473
00474
00475
00476
00477
00478
00479
00480
00481
00482
00483 #define DEFAULT_CONTEXT "default"
00484 #define DEFAULT_MOHINTERPRET "default"
00485 #define DEFAULT_MOHSUGGEST ""
00486 #define DEFAULT_VMEXTEN "asterisk"
00487 #define DEFAULT_CALLERID "asterisk"
00488 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
00489 #define DEFAULT_MWITIME 10
00490 #define DEFAULT_ALLOWGUEST TRUE
00491 #define DEFAULT_SRVLOOKUP FALSE
00492 #define DEFAULT_COMPACTHEADERS FALSE
00493 #define DEFAULT_TOS_SIP 0
00494 #define DEFAULT_TOS_AUDIO 0
00495 #define DEFAULT_TOS_VIDEO 0
00496 #define DEFAULT_ALLOW_EXT_DOM TRUE
00497 #define DEFAULT_REALM "asterisk"
00498 #define DEFAULT_NOTIFYRINGING TRUE
00499 #define DEFAULT_PEDANTIC FALSE
00500 #define DEFAULT_AUTOCREATEPEER FALSE
00501 #define DEFAULT_QUALIFY FALSE
00502 #define DEFAULT_T1MIN 100
00503 #define DEFAULT_MAX_CALL_BITRATE (384)
00504 #ifndef DEFAULT_USERAGENT
00505 #define DEFAULT_USERAGENT "Asterisk PBX"
00506 #endif
00507
00508
00509
00510
00511 static char default_context[AST_MAX_CONTEXT];
00512 static char default_subscribecontext[AST_MAX_CONTEXT];
00513 static char default_language[MAX_LANGUAGE];
00514 static char default_callerid[AST_MAX_EXTENSION];
00515 static char default_fromdomain[AST_MAX_EXTENSION];
00516 static char default_notifymime[AST_MAX_EXTENSION];
00517 static int default_qualify;
00518 static char default_vmexten[AST_MAX_EXTENSION];
00519 static char default_mohinterpret[MAX_MUSICCLASS];
00520 static char default_mohsuggest[MAX_MUSICCLASS];
00521
00522 static int default_maxcallbitrate;
00523 static struct ast_codec_pref default_prefs;
00524
00525
00526 static int global_directrtpsetup;
00527 static int global_limitonpeers;
00528 static int global_rtautoclear;
00529 static int global_notifyringing;
00530 static int global_notifyhold;
00531 static int global_alwaysauthreject;
00532 static int srvlookup;
00533 static int pedanticsipchecking;
00534 static int autocreatepeer;
00535 static int global_relaxdtmf;
00536 static int global_rtptimeout;
00537 static int global_rtpholdtimeout;
00538 static int global_rtpkeepalive;
00539 static int global_reg_timeout;
00540 static int global_regattempts_max;
00541 static int global_allowguest;
00542 static int global_allowsubscribe;
00543
00544 static int global_mwitime;
00545 static unsigned int global_tos_sip;
00546 static unsigned int global_tos_audio;
00547 static unsigned int global_tos_video;
00548 static int compactheaders;
00549 static int recordhistory;
00550 static int dumphistory;
00551 static char global_realm[MAXHOSTNAMELEN];
00552 static char global_regcontext[AST_MAX_CONTEXT];
00553 static char global_useragent[AST_MAX_EXTENSION];
00554 static int allow_external_domains;
00555 static int global_callevents;
00556 static int global_t1min;
00557 static int global_autoframing;
00558 static enum transfermodes global_allowtransfer;
00559
00560 static int global_matchexterniplocally;
00561
00562
00563 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00564
00565
00566 static int suserobjs = 0;
00567 static int ruserobjs = 0;
00568 static int speerobjs = 0;
00569 static int rpeerobjs = 0;
00570 static int apeerobjs = 0;
00571 static int regobjs = 0;
00572
00573 static struct ast_flags global_flags[2] = {{0}};
00574
00575
00576 AST_MUTEX_DEFINE_STATIC(iflock);
00577
00578
00579
00580 AST_MUTEX_DEFINE_STATIC(netlock);
00581
00582 AST_MUTEX_DEFINE_STATIC(monlock);
00583
00584 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00585
00586
00587
00588 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00589
00590 static int sip_reloading = FALSE;
00591 static enum channelreloadreason sip_reloadreason;
00592
00593 static struct sched_context *sched;
00594 static struct io_context *io;
00595 static int *sipsock_read_id;
00596
00597 #define DEC_CALL_LIMIT 0
00598 #define INC_CALL_LIMIT 1
00599 #define DEC_CALL_RINGING 2
00600 #define INC_CALL_RINGING 3
00601
00602
00603 struct sip_request {
00604 char *rlPart1;
00605 char *rlPart2;
00606 int len;
00607 int headers;
00608 int method;
00609 int lines;
00610 unsigned int flags;
00611 char *header[SIP_MAX_HEADERS];
00612 char *line[SIP_MAX_LINES];
00613 char data[SIP_MAX_PACKET];
00614 unsigned int sdp_start;
00615 unsigned int sdp_end;
00616 };
00617
00618
00619
00620
00621
00622
00623
00624
00625
00626
00627
00628
00629
00630
00631
00632
00633
00634
00635
00636
00637
00638 struct sip_dual {
00639 struct ast_channel *chan1;
00640 struct ast_channel *chan2;
00641 struct sip_request req;
00642 int seqno;
00643 };
00644
00645 struct sip_pkt;
00646
00647
00648 struct sip_invite_param {
00649 const char *distinctive_ring;
00650 int addsipheaders;
00651 const char *uri_options;
00652 const char *vxml_url;
00653 char *auth;
00654 char *authheader;
00655 enum sip_auth_type auth_type;
00656 const char *replaces;
00657 int transfer;
00658 };
00659
00660
00661 struct sip_route {
00662 struct sip_route *next;
00663 char hop[0];
00664 };
00665
00666
00667 enum domain_mode {
00668 SIP_DOMAIN_AUTO,
00669 SIP_DOMAIN_CONFIG,
00670 };
00671
00672
00673
00674
00675
00676 struct domain {
00677 char domain[MAXHOSTNAMELEN];
00678 char context[AST_MAX_EXTENSION];
00679 enum domain_mode mode;
00680 AST_LIST_ENTRY(domain) list;
00681 };
00682
00683 static AST_LIST_HEAD_STATIC(domain_list, domain);
00684
00685
00686
00687 struct sip_history {
00688 AST_LIST_ENTRY(sip_history) list;
00689 char event[0];
00690 };
00691
00692 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00693
00694
00695 struct sip_auth {
00696 char realm[AST_MAX_EXTENSION];
00697 char username[256];
00698 char secret[256];
00699 char md5secret[256];
00700 struct sip_auth *next;
00701 };
00702
00703
00704 #define SIP_ALREADYGONE (1 << 0)
00705 #define SIP_NEEDDESTROY (1 << 1)
00706 #define SIP_NOVIDEO (1 << 2)
00707 #define SIP_RINGING (1 << 3)
00708 #define SIP_PROGRESS_SENT (1 << 4)
00709 #define SIP_NEEDREINVITE (1 << 5)
00710 #define SIP_PENDINGBYE (1 << 6)
00711 #define SIP_GOTREFER (1 << 7)
00712 #define SIP_PROMISCREDIR (1 << 8)
00713 #define SIP_TRUSTRPID (1 << 9)
00714 #define SIP_USEREQPHONE (1 << 10)
00715 #define SIP_REALTIME (1 << 11)
00716 #define SIP_USECLIENTCODE (1 << 12)
00717 #define SIP_OUTGOING (1 << 13)
00718 #define SIP_FREE_BIT (1 << 14)
00719 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15)
00720 #define SIP_DTMF (3 << 16)
00721 #define SIP_DTMF_RFC2833 (0 << 16)
00722 #define SIP_DTMF_INBAND (1 << 16)
00723 #define SIP_DTMF_INFO (2 << 16)
00724 #define SIP_DTMF_AUTO (3 << 16)
00725
00726 #define SIP_NAT (3 << 18)
00727 #define SIP_NAT_NEVER (0 << 18)
00728 #define SIP_NAT_RFC3581 (1 << 18)
00729 #define SIP_NAT_ROUTE (2 << 18)
00730 #define SIP_NAT_ALWAYS (3 << 18)
00731
00732 #define SIP_REINVITE (7 << 20)
00733 #define SIP_CAN_REINVITE (1 << 20)
00734 #define SIP_CAN_REINVITE_NAT (2 << 20)
00735 #define SIP_REINVITE_UPDATE (4 << 20)
00736
00737 #define SIP_INSECURE_PORT (1 << 23)
00738 #define SIP_INSECURE_INVITE (1 << 24)
00739
00740 #define SIP_PROG_INBAND (3 << 25)
00741 #define SIP_PROG_INBAND_NEVER (0 << 25)
00742 #define SIP_PROG_INBAND_NO (1 << 25)
00743 #define SIP_PROG_INBAND_YES (2 << 25)
00744 #define SIP_NO_HISTORY (1 << 27)
00745 #define SIP_CALL_LIMIT (1 << 28)
00746 #define SIP_SENDRPID (1 << 29)
00747 #define SIP_INC_COUNT (1 << 30)
00748 #define SIP_G726_NONSTANDARD (1 << 31)
00749
00750 #define SIP_FLAGS_TO_COPY \
00751 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
00752 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
00753 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
00754
00755
00756
00757 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
00758 #define SIP_PAGE2_RTUPDATE (1 << 1)
00759 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
00760 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
00761 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
00762
00763 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
00764 #define SIP_PAGE2_DEBUG (3 << 11)
00765 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
00766 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
00767 #define SIP_PAGE2_DYNAMIC (1 << 13)
00768 #define SIP_PAGE2_SELFDESTRUCT (1 << 14)
00769 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
00770 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)
00771 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17)
00772 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18)
00773 #define SIP_PAGE2_INC_RINGING (1 << 19)
00774 #define SIP_PAGE2_T38SUPPORT (7 << 20)
00775 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20)
00776 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20)
00777 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20)
00778 #define SIP_PAGE2_CALL_ONHOLD (3 << 23)
00779 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23)
00780 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23)
00781 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)
00782 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
00783 #define SIP_PAGE2_BUGGY_MWI (1 << 26)
00784 #define SIP_PAGE2_OUTGOING_CALL (1 << 27)
00785
00786 #define SIP_PAGE2_FLAGS_TO_COPY \
00787 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
00788 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI)
00789
00790
00791 #define SIP_PKT_DEBUG (1 << 0)
00792 #define SIP_PKT_WITH_TOTAG (1 << 1)
00793 #define SIP_PKT_IGNORE (1 << 2)
00794 #define SIP_PKT_IGNORE_RESP (1 << 3)
00795 #define SIP_PKT_IGNORE_REQ (1 << 4)
00796
00797
00798 #define T38FAX_FILL_BIT_REMOVAL (1 << 0)
00799 #define T38FAX_TRANSCODING_MMR (1 << 1)
00800 #define T38FAX_TRANSCODING_JBIG (1 << 2)
00801
00802 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
00803 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3)
00804
00805 #define T38FAX_UDP_EC_NONE (0 << 4)
00806 #define T38FAX_UDP_EC_FEC (1 << 4)
00807 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4)
00808
00809 #define T38FAX_VERSION (3 << 6)
00810 #define T38FAX_VERSION_0 (0 << 6)
00811 #define T38FAX_VERSION_1 (1 << 6)
00812
00813 #define T38FAX_RATE_2400 (1 << 8)
00814 #define T38FAX_RATE_4800 (1 << 9)
00815 #define T38FAX_RATE_7200 (1 << 10)
00816 #define T38FAX_RATE_9600 (1 << 11)
00817 #define T38FAX_RATE_12000 (1 << 12)
00818 #define T38FAX_RATE_14400 (1 << 13)
00819
00820
00821 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
00822
00823 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
00824 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
00825 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
00826
00827
00828 enum t38state {
00829 T38_DISABLED = 0,
00830 T38_LOCAL_DIRECT,
00831 T38_LOCAL_REINVITE,
00832 T38_PEER_DIRECT,
00833 T38_PEER_REINVITE,
00834 T38_ENABLED
00835 };
00836
00837
00838 struct t38properties {
00839 struct ast_flags t38support;
00840 int capability;
00841 int peercapability;
00842 int jointcapability;
00843 enum t38state state;
00844 };
00845
00846
00847 enum referstatus {
00848 REFER_IDLE,
00849 REFER_SENT,
00850 REFER_RECEIVED,
00851 REFER_CONFIRMED,
00852 REFER_ACCEPTED,
00853 REFER_RINGING,
00854 REFER_200OK,
00855 REFER_FAILED,
00856 REFER_NOAUTH
00857 };
00858
00859 static const struct c_referstatusstring {
00860 enum referstatus status;
00861 char *text;
00862 } referstatusstrings[] = {
00863 { REFER_IDLE, "<none>" },
00864 { REFER_SENT, "Request sent" },
00865 { REFER_RECEIVED, "Request received" },
00866 { REFER_ACCEPTED, "Accepted" },
00867 { REFER_RINGING, "Target ringing" },
00868 { REFER_200OK, "Done" },
00869 { REFER_FAILED, "Failed" },
00870 { REFER_NOAUTH, "Failed - auth failure" }
00871 } ;
00872
00873
00874
00875 struct sip_refer {
00876 char refer_to[AST_MAX_EXTENSION];
00877 char refer_to_domain[AST_MAX_EXTENSION];
00878 char refer_to_urioption[AST_MAX_EXTENSION];
00879 char refer_to_context[AST_MAX_EXTENSION];
00880 char referred_by[AST_MAX_EXTENSION];
00881 char referred_by_name[AST_MAX_EXTENSION];
00882 char refer_contact[AST_MAX_EXTENSION];
00883 char replaces_callid[BUFSIZ];
00884 char replaces_callid_totag[BUFSIZ/2];
00885 char replaces_callid_fromtag[BUFSIZ/2];
00886 struct sip_pvt *refer_call;
00887 int attendedtransfer;
00888 int localtransfer;
00889 enum referstatus status;
00890 };
00891
00892
00893 static struct sip_pvt {
00894 ast_mutex_t lock;
00895 int method;
00896 enum invitestates invitestate;
00897 AST_DECLARE_STRING_FIELDS(
00898 AST_STRING_FIELD(callid);
00899 AST_STRING_FIELD(randdata);
00900 AST_STRING_FIELD(accountcode);
00901 AST_STRING_FIELD(realm);
00902 AST_STRING_FIELD(nonce);
00903 AST_STRING_FIELD(opaque);
00904 AST_STRING_FIELD(qop);
00905 AST_STRING_FIELD(domain);
00906 AST_STRING_FIELD(from);
00907 AST_STRING_FIELD(useragent);
00908 AST_STRING_FIELD(exten);
00909 AST_STRING_FIELD(context);
00910 AST_STRING_FIELD(subscribecontext);
00911 AST_STRING_FIELD(subscribeuri);
00912 AST_STRING_FIELD(fromdomain);
00913 AST_STRING_FIELD(fromuser);
00914 AST_STRING_FIELD(fromname);
00915 AST_STRING_FIELD(tohost);
00916 AST_STRING_FIELD(language);
00917 AST_STRING_FIELD(mohinterpret);
00918 AST_STRING_FIELD(mohsuggest);
00919 AST_STRING_FIELD(rdnis);
00920 AST_STRING_FIELD(theirtag);
00921 AST_STRING_FIELD(username);
00922 AST_STRING_FIELD(peername);
00923 AST_STRING_FIELD(authname);
00924 AST_STRING_FIELD(uri);
00925 AST_STRING_FIELD(okcontacturi);
00926 AST_STRING_FIELD(peersecret);
00927 AST_STRING_FIELD(peermd5secret);
00928 AST_STRING_FIELD(cid_num);
00929 AST_STRING_FIELD(cid_name);
00930 AST_STRING_FIELD(via);
00931 AST_STRING_FIELD(fullcontact);
00932 AST_STRING_FIELD(our_contact);
00933 AST_STRING_FIELD(rpid);
00934 AST_STRING_FIELD(rpid_from);
00935 );
00936 unsigned int ocseq;
00937 unsigned int icseq;
00938 ast_group_t callgroup;
00939 ast_group_t pickupgroup;
00940 int lastinvite;
00941 struct ast_flags flags[2];
00942 int timer_t1;
00943 unsigned int sipoptions;
00944 struct ast_codec_pref prefs;
00945 int capability;
00946 int jointcapability;
00947 int peercapability;
00948 int prefcodec;
00949 int noncodeccapability;
00950 int jointnoncodeccapability;
00951 int redircodecs;
00952 int maxcallbitrate;
00953 struct t38properties t38;
00954 struct sockaddr_in udptlredirip;
00955 struct ast_udptl *udptl;
00956 int callingpres;
00957 int authtries;
00958 int expiry;
00959 long branch;
00960 char tag[11];
00961 int sessionid;
00962 int sessionversion;
00963 struct sockaddr_in sa;
00964 struct sockaddr_in redirip;
00965 struct sockaddr_in vredirip;
00966 time_t lastrtprx;
00967 time_t lastrtptx;
00968 int rtptimeout;
00969 struct sockaddr_in recv;
00970 struct in_addr ourip;
00971 struct ast_channel *owner;
00972 struct sip_route *route;
00973 int route_persistant;
00974 struct sip_auth *peerauth;
00975 int noncecount;
00976 char lastmsg[256];
00977 int amaflags;
00978 int pendinginvite;
00979 struct sip_request initreq;
00980
00981
00982 int maxtime;
00983 int initid;
00984 int autokillid;
00985 enum transfermodes allowtransfer;
00986 struct sip_refer *refer;
00987 enum subscriptiontype subscribed;
00988 int stateid;
00989 int laststate;
00990 int dialogver;
00991
00992 struct ast_dsp *vad;
00993
00994 struct sip_peer *relatedpeer;
00995
00996 struct sip_registry *registry;
00997 struct ast_rtp *rtp;
00998 struct ast_rtp *vrtp;
00999 struct sip_pkt *packets;
01000 struct sip_history_head *history;
01001 struct ast_variable *chanvars;
01002 struct sip_pvt *next;
01003 struct sip_invite_param *options;
01004 int autoframing;
01005 } *iflist = NULL;
01006
01007 #define FLAG_RESPONSE (1 << 0)
01008 #define FLAG_FATAL (1 << 1)
01009
01010
01011 struct sip_pkt {
01012 struct sip_pkt *next;
01013 int retrans;
01014 int method;
01015 int seqno;
01016 unsigned int flags;
01017 struct sip_pvt *owner;
01018 int retransid;
01019 int timer_a;
01020 int timer_t1;
01021 int packetlen;
01022 char data[0];
01023 };
01024
01025
01026 struct sip_user {
01027
01028 ASTOBJ_COMPONENTS(struct sip_user);
01029 char secret[80];
01030 char md5secret[80];
01031 char context[AST_MAX_CONTEXT];
01032 char subscribecontext[AST_MAX_CONTEXT];
01033 char cid_num[80];
01034 char cid_name[80];
01035 char accountcode[AST_MAX_ACCOUNT_CODE];
01036 char language[MAX_LANGUAGE];
01037 char mohinterpret[MAX_MUSICCLASS];
01038 char mohsuggest[MAX_MUSICCLASS];
01039 char useragent[256];
01040 struct ast_codec_pref prefs;
01041 ast_group_t callgroup;
01042 ast_group_t pickupgroup;
01043 unsigned int sipoptions;
01044 struct ast_flags flags[2];
01045 int amaflags;
01046 int callingpres;
01047 int capability;
01048 int inUse;
01049 int call_limit;
01050 enum transfermodes allowtransfer;
01051 struct ast_ha *ha;
01052 struct ast_variable *chanvars;
01053 int maxcallbitrate;
01054 int autoframing;
01055 };
01056
01057
01058
01059 struct sip_peer {
01060 ASTOBJ_COMPONENTS(struct sip_peer);
01061
01062 char secret[80];
01063 char md5secret[80];
01064 struct sip_auth *auth;
01065 char context[AST_MAX_CONTEXT];
01066 char subscribecontext[AST_MAX_CONTEXT];
01067 char username[80];
01068 char accountcode[AST_MAX_ACCOUNT_CODE];
01069 int amaflags;
01070 char tohost[MAXHOSTNAMELEN];
01071 char regexten[AST_MAX_EXTENSION];
01072 char fromuser[80];
01073 char fromdomain[MAXHOSTNAMELEN];
01074 char fullcontact[256];
01075 char cid_num[80];
01076 char cid_name[80];
01077 int callingpres;
01078 int inUse;
01079 int inRinging;
01080 int onHold;
01081 int call_limit;
01082 enum transfermodes allowtransfer;
01083 char vmexten[AST_MAX_EXTENSION];
01084 char mailbox[AST_MAX_EXTENSION];
01085 char language[MAX_LANGUAGE];
01086 char mohinterpret[MAX_MUSICCLASS];
01087 char mohsuggest[MAX_MUSICCLASS];
01088 char useragent[256];
01089 struct ast_codec_pref prefs;
01090 int lastmsgssent;
01091 time_t lastmsgcheck;
01092 unsigned int sipoptions;
01093 struct ast_flags flags[2];
01094 int expire;
01095 int capability;
01096 int rtptimeout;
01097 int rtpholdtimeout;
01098 int rtpkeepalive;
01099 ast_group_t callgroup;
01100 ast_group_t pickupgroup;
01101 struct sockaddr_in addr;
01102 int maxcallbitrate;
01103
01104
01105 struct sip_pvt *call;
01106 int pokeexpire;
01107 int lastms;
01108 int maxms;
01109 struct timeval ps;
01110
01111 struct sockaddr_in defaddr;
01112 struct ast_ha *ha;
01113 struct ast_variable *chanvars;
01114 struct sip_pvt *mwipvt;
01115 int lastmsg;
01116 int autoframing;
01117 };
01118
01119
01120
01121
01122 struct sip_registry {
01123 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01124 AST_DECLARE_STRING_FIELDS(
01125 AST_STRING_FIELD(callid);
01126 AST_STRING_FIELD(realm);
01127 AST_STRING_FIELD(nonce);
01128 AST_STRING_FIELD(opaque);
01129 AST_STRING_FIELD(qop);
01130 AST_STRING_FIELD(domain);
01131 AST_STRING_FIELD(username);
01132 AST_STRING_FIELD(authuser);
01133 AST_STRING_FIELD(hostname);
01134 AST_STRING_FIELD(secret);
01135 AST_STRING_FIELD(md5secret);
01136 AST_STRING_FIELD(contact);
01137 AST_STRING_FIELD(random);
01138 );
01139 int portno;
01140 int expire;
01141 int regattempts;
01142 int timeout;
01143 int refresh;
01144 struct sip_pvt *call;
01145 enum sipregistrystate regstate;
01146 time_t regtime;
01147 int callid_valid;
01148 unsigned int ocseq;
01149 struct sockaddr_in us;
01150 int noncecount;
01151 char lastmsg[256];
01152 };
01153
01154
01155
01156
01157 static struct ast_user_list {
01158 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
01159 } userl;
01160
01161
01162 static struct ast_peer_list {
01163 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
01164 } peerl;
01165
01166
01167 static struct ast_register_list {
01168 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01169 int recheck;
01170 } regl;
01171
01172 static void temp_pvt_cleanup(void *);
01173
01174
01175 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01176
01177
01178 static struct sip_auth *authl = NULL;
01179
01180
01181
01182 static int sipsock = -1;
01183 static struct sockaddr_in bindaddr = { 0, };
01184 static struct sockaddr_in externip;
01185 static char externhost[MAXHOSTNAMELEN];
01186 static time_t externexpire = 0;
01187 static int externrefresh = 10;
01188 static struct ast_ha *localaddr;
01189 static struct in_addr __ourip;
01190 static struct sockaddr_in outboundproxyip;
01191 static int ourport;
01192 static struct sockaddr_in debugaddr;
01193
01194 static struct ast_config *notify_types;
01195
01196
01197
01198
01199
01200
01201 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
01202 static int sip_devicestate(void *data);
01203 static int sip_sendtext(struct ast_channel *ast, const char *text);
01204 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01205 static int sip_hangup(struct ast_channel *ast);
01206 static int sip_answer(struct ast_channel *ast);
01207 static struct ast_frame *sip_read(struct ast_channel *ast);
01208 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01209 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01210 static int sip_transfer(struct ast_channel *ast, const char *dest);
01211 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01212 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01213 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01214
01215
01216 static int sipsock_read(int *id, int fd, short events, void *ignore);
01217 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
01218 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
01219 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01220 static int retrans_pkt(void *data);
01221 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
01222 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);
01223 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01224 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01225 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01226 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01227 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01228 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);
01229 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01230 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
01231 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01232 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01233 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
01234 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
01235 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01236 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01237 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01238 static int transmit_refer(struct sip_pvt *p, const char *dest);
01239 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
01240 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01241 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01242 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01243 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01244 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01245 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01246 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
01247 static int sip_send_mwi_to_peer(struct sip_peer *peer);
01248 static int does_peer_need_mwi(struct sip_peer *peer);
01249
01250
01251 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
01252 int useglobal_nat, const int intended_method);
01253 static int __sip_autodestruct(void *data);
01254 static void sip_scheddestroy(struct sip_pvt *p, int ms);
01255 static void sip_cancel_destroy(struct sip_pvt *p);
01256 static void sip_destroy(struct sip_pvt *p);
01257 static void __sip_destroy(struct sip_pvt *p, int lockowner);
01258 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01259 static void __sip_pretend_ack(struct sip_pvt *p);
01260 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01261 static int auto_congest(void *nothing);
01262 static int update_call_counter(struct sip_pvt *fup, int event);
01263 static int hangup_sip2cause(int cause);
01264 static const char *hangup_cause2sip(int cause);
01265 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
01266 static void free_old_route(struct sip_route *route);
01267 static void list_route(struct sip_route *route);
01268 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01269 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
01270 struct sip_request *req, char *uri);
01271 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01272 static void check_pendings(struct sip_pvt *p);
01273 static void *sip_park_thread(void *stuff);
01274 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
01275 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01276
01277
01278 static void try_suggested_sip_codec(struct sip_pvt *p);
01279 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01280 static const char *get_sdp(struct sip_request *req, const char *name);
01281 static int find_sdp(struct sip_request *req);
01282 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
01283 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
01284 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
01285 int debug, int *min_packet_size);
01286 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
01287 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
01288 int debug);
01289 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
01290
01291
01292 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01293 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01294 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01295 const char *secret, const char *md5secret, int sipmethod,
01296 char *uri, enum xmittype reliable, int ignore);
01297 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01298 int sipmethod, char *uri, enum xmittype reliable,
01299 struct sockaddr_in *sin, struct sip_peer **authpeer);
01300 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
01301
01302
01303 static int check_sip_domain(const char *domain, char *context, size_t len);
01304 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01305 static void clear_sip_domains(void);
01306
01307
01308 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
01309 static int clear_realm_authentication(struct sip_auth *authlist);
01310 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
01311
01312
01313 static int sip_do_reload(enum channelreloadreason reason);
01314 static int reload_config(enum channelreloadreason reason);
01315 static int expire_register(void *data);
01316 static void *do_monitor(void *data);
01317 static int restart_monitor(void);
01318 static int sip_send_mwi_to_peer(struct sip_peer *peer);
01319 static void sip_destroy(struct sip_pvt *p);
01320 static int sip_addrcmp(char *name, struct sockaddr_in *sin);
01321 static int sip_refer_allocate(struct sip_pvt *p);
01322 static void ast_quiet_chan(struct ast_channel *chan);
01323 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01324
01325
01326 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01327 static int sip_devicestate(void *data);
01328 static int sip_poke_noanswer(void *data);
01329 static int sip_poke_peer(struct sip_peer *peer);
01330 static void sip_poke_all_peers(void);
01331 static void sip_peer_hold(struct sip_pvt *p, int hold);
01332
01333
01334 static const char *sip_nat_mode(const struct sip_pvt *p);
01335 static int sip_show_inuse(int fd, int argc, char *argv[]);
01336 static char *transfermode2str(enum transfermodes mode) attribute_const;
01337 static char *nat2str(int nat) attribute_const;
01338 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01339 static int sip_show_users(int fd, int argc, char *argv[]);
01340 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01341 static int sip_show_peers(int fd, int argc, char *argv[]);
01342 static int sip_show_objects(int fd, int argc, char *argv[]);
01343 static void print_group(int fd, ast_group_t group, int crlf);
01344 static const char *dtmfmode2str(int mode) attribute_const;
01345 static const char *insecure2str(int port, int invite) attribute_const;
01346 static void cleanup_stale_contexts(char *new, char *old);
01347 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01348 static const char *domain_mode_to_text(const enum domain_mode mode);
01349 static int sip_show_domains(int fd, int argc, char *argv[]);
01350 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01351 static int sip_show_peer(int fd, int argc, char *argv[]);
01352 static int sip_show_user(int fd, int argc, char *argv[]);
01353 static int sip_show_registry(int fd, int argc, char *argv[]);
01354 static int sip_show_settings(int fd, int argc, char *argv[]);
01355 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01356 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01357 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
01358 static int sip_show_channels(int fd, int argc, char *argv[]);
01359 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
01360 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
01361 static char *complete_sipch(const char *line, const char *word, int pos, int state);
01362 static char *complete_sip_peer(const char *word, int state, int flags2);
01363 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01364 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
01365 static char *complete_sip_user(const char *word, int state, int flags2);
01366 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
01367 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01368 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
01369 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
01370 static int sip_show_channel(int fd, int argc, char *argv[]);
01371 static int sip_show_history(int fd, int argc, char *argv[]);
01372 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
01373 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
01374 static int sip_do_debug(int fd, int argc, char *argv[]);
01375 static int sip_no_debug(int fd, int argc, char *argv[]);
01376 static int sip_notify(int fd, int argc, char *argv[]);
01377 static int sip_do_history(int fd, int argc, char *argv[]);
01378 static int sip_no_history(int fd, int argc, char *argv[]);
01379 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
01380 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01381 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01382 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
01383 static int sip_dtmfmode(struct ast_channel *chan, void *data);
01384 static int sip_addheader(struct ast_channel *chan, void *data);
01385 static int sip_do_reload(enum channelreloadreason reason);
01386 static int sip_reload(int fd, int argc, char *argv[]);
01387 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen);
01388
01389
01390
01391
01392
01393 static void sip_dump_history(struct sip_pvt *dialog);
01394 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
01395 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01396 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01397 static void sip_dump_history(struct sip_pvt *dialog);
01398
01399
01400 static struct sip_peer *temp_peer(const char *name);
01401 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
01402 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
01403 static int update_call_counter(struct sip_pvt *fup, int event);
01404 static void sip_destroy_peer(struct sip_peer *peer);
01405 static void sip_destroy_user(struct sip_user *user);
01406 static int sip_poke_peer(struct sip_peer *peer);
01407 static int sip_poke_peer_s(void *data);
01408 static void set_peer_defaults(struct sip_peer *peer);
01409 static struct sip_peer *temp_peer(const char *name);
01410 static void register_peer_exten(struct sip_peer *peer, int onoff);
01411 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
01412 static struct sip_user *find_user(const char *name, int realtime);
01413 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01414 static int expire_register(void *data);
01415 static void reg_source_db(struct sip_peer *peer);
01416 static void destroy_association(struct sip_peer *peer);
01417 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01418
01419
01420 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
01421 static struct sip_user *realtime_user(const char *username);
01422 static void update_peer(struct sip_peer *p, int expiry);
01423 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
01424 static int sip_prune_realtime(int fd, int argc, char *argv[]);
01425
01426
01427 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
01428 static void sip_registry_destroy(struct sip_registry *reg);
01429 static int sip_register(char *value, int lineno);
01430 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
01431 static int sip_reregister(void *data);
01432 static int __sip_do_register(struct sip_registry *r);
01433 static int sip_reg_timeout(void *data);
01434 static void sip_send_all_registers(void);
01435
01436
01437 static void append_date(struct sip_request *req);
01438 static int determine_firstline_parts(struct sip_request *req);
01439 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01440 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01441 static int find_sip_method(const char *msg);
01442 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
01443 static void parse_request(struct sip_request *req);
01444 static const char *get_header(const struct sip_request *req, const char *name);
01445 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
01446 static int method_match(enum sipmethod id, const char *name);
01447 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01448 static char *get_in_brackets(char *tmp);
01449 static const char *find_alias(const char *name, const char *_default);
01450 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01451 static int lws2sws(char *msgbuf, int len);
01452 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01453 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01454 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01455 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01456 static int set_address_from_contact(struct sip_pvt *pvt);
01457 static void check_via(struct sip_pvt *p, struct sip_request *req);
01458 static char *get_calleridname(const char *input, char *output, size_t outputsize);
01459 static int get_rpid_num(const char *input, char *output, int maxlen);
01460 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
01461 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
01462 static int get_msg_text(char *buf, int len, struct sip_request *req);
01463 static void free_old_route(struct sip_route *route);
01464 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01465
01466
01467 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01468 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01469 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
01470 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
01471 static int init_resp(struct sip_request *resp, const char *msg);
01472 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01473 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
01474 static void build_via(struct sip_pvt *p);
01475 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01476 static int create_addr(struct sip_pvt *dialog, const char *opeer);
01477 static char *generate_random_string(char *buf, size_t size);
01478 static void build_callid_pvt(struct sip_pvt *pvt);
01479 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
01480 static void make_our_tag(char *tagbuf, size_t len);
01481 static int add_header(struct sip_request *req, const char *var, const char *value);
01482 static int add_header_contentLength(struct sip_request *req, int len);
01483 static int add_line(struct sip_request *req, const char *line);
01484 static int add_text(struct sip_request *req, const char *text);
01485 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
01486 static int add_vidupdate(struct sip_request *req);
01487 static void add_route(struct sip_request *req, struct sip_route *route);
01488 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01489 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01490 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01491 static void set_destination(struct sip_pvt *p, char *uri);
01492 static void append_date(struct sip_request *req);
01493 static void build_contact(struct sip_pvt *p);
01494 static void build_rpid(struct sip_pvt *p);
01495
01496
01497 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
01498 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);
01499 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
01500 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01501 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
01502 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01503 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01504 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
01505 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01506 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
01507 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
01508 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
01509 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
01510
01511
01512 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
01513 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
01514 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
01515 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
01516
01517
01518 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
01519 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
01520 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
01521 static int sip_get_codec(struct ast_channel *chan);
01522 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
01523
01524
01525 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
01526 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01527 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
01528 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01529 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01530
01531
01532 static const struct ast_channel_tech sip_tech = {
01533 .type = "SIP",
01534 .description = "Session Initiation Protocol (SIP)",
01535 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
01536 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01537 .requester = sip_request_call,
01538 .devicestate = sip_devicestate,
01539 .call = sip_call,
01540 .hangup = sip_hangup,
01541 .answer = sip_answer,
01542 .read = sip_read,
01543 .write = sip_write,
01544 .write_video = sip_write,
01545 .indicate = sip_indicate,
01546 .transfer = sip_transfer,
01547 .fixup = sip_fixup,
01548 .send_digit_begin = sip_senddigit_begin,
01549 .send_digit_end = sip_senddigit_end,
01550 .bridge = ast_rtp_bridge,
01551 .send_text = sip_sendtext,
01552 .func_channel_read = acf_channel_read,
01553 };
01554
01555
01556
01557
01558 static const struct ast_channel_tech sip_tech_info = {
01559 .type = "SIP",
01560 .description = "Session Initiation Protocol (SIP)",
01561 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
01562 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01563 .requester = sip_request_call,
01564 .devicestate = sip_devicestate,
01565 .call = sip_call,
01566 .hangup = sip_hangup,
01567 .answer = sip_answer,
01568 .read = sip_read,
01569 .write = sip_write,
01570 .write_video = sip_write,
01571 .indicate = sip_indicate,
01572 .transfer = sip_transfer,
01573 .fixup = sip_fixup,
01574 .send_digit_end = sip_senddigit_end,
01575 .bridge = ast_rtp_bridge,
01576 .send_text = sip_sendtext,
01577 };
01578
01579
01580
01581 #define UNLINK(element, head, prev) do { \
01582 if (prev) \
01583 (prev)->next = (element)->next; \
01584 else \
01585 (head) = (element)->next; \
01586 } while (0)
01587
01588
01589 static struct ast_rtp_protocol sip_rtp = {
01590 type: "SIP",
01591 get_rtp_info: sip_get_rtp_peer,
01592 get_vrtp_info: sip_get_vrtp_peer,
01593 set_rtp_peer: sip_set_rtp_peer,
01594 get_codec: sip_get_codec,
01595 };
01596
01597
01598 static struct ast_udptl_protocol sip_udptl = {
01599 type: "SIP",
01600 get_udptl_info: sip_get_udptl_peer,
01601 set_udptl_peer: sip_set_udptl_peer,
01602 };
01603
01604
01605 static char *referstatus2str(enum referstatus rstatus)
01606 {
01607 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
01608 int x;
01609
01610 for (x = 0; x < i; x++) {
01611 if (referstatusstrings[x].status == rstatus)
01612 return (char *) referstatusstrings[x].text;
01613 }
01614 return "";
01615 }
01616
01617
01618
01619
01620 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
01621 {
01622 if (p->initreq.headers && option_debug) {
01623 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
01624 }
01625
01626 copy_request(&p->initreq, req);
01627 parse_request(&p->initreq);
01628 if (ast_test_flag(req, SIP_PKT_DEBUG))
01629 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
01630 }
01631
01632 static void sip_alreadygone(struct sip_pvt *dialog)
01633 {
01634 if (option_debug > 2)
01635 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
01636 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
01637 }
01638
01639
01640
01641
01642
01643
01644
01645
01646 static int method_match(enum sipmethod id, const char *name)
01647 {
01648 int len = strlen(sip_methods[id].text);
01649 int l_name = name ? strlen(name) : 0;
01650
01651 return (l_name >= len && name[len] < 33 &&
01652 !strncasecmp(sip_methods[id].text, name, len));
01653 }
01654
01655
01656 static int find_sip_method(const char *msg)
01657 {
01658 int i, res = 0;
01659
01660 if (ast_strlen_zero(msg))
01661 return 0;
01662 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
01663 if (method_match(i, msg))
01664 res = sip_methods[i].id;
01665 }
01666 return res;
01667 }
01668
01669
01670 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
01671 {
01672 char *next, *sep;
01673 char *temp;
01674 unsigned int profile = 0;
01675 int i, found;
01676
01677 if (ast_strlen_zero(supported) )
01678 return 0;
01679 temp = ast_strdupa(supported);
01680
01681 if (option_debug > 2 && sipdebug)
01682 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
01683
01684 for (next = temp; next; next = sep) {
01685 found = FALSE;
01686 if ( (sep = strchr(next, ',')) != NULL)
01687 *sep++ = '\0';
01688 next = ast_skip_blanks(next);
01689 if (option_debug > 2 && sipdebug)
01690 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
01691 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
01692 if (!strcasecmp(next, sip_options[i].text)) {
01693 profile |= sip_options[i].id;
01694 found = TRUE;
01695 if (option_debug > 2 && sipdebug)
01696 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
01697 break;
01698 }
01699 }
01700 if (!found && option_debug > 2 && sipdebug) {
01701 if (!strncasecmp(next, "x-", 2))
01702 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
01703 else
01704 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
01705 }
01706 }
01707
01708 if (pvt)
01709 pvt->sipoptions = profile;
01710 return profile;
01711 }
01712
01713
01714 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
01715 {
01716 if (!sipdebug)
01717 return 0;
01718 if (debugaddr.sin_addr.s_addr) {
01719 if (((ntohs(debugaddr.sin_port) != 0)
01720 && (debugaddr.sin_port != addr->sin_port))
01721 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
01722 return 0;
01723 }
01724 return 1;
01725 }
01726
01727
01728 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
01729 {
01730 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
01731 }
01732
01733
01734 static const char *sip_nat_mode(const struct sip_pvt *p)
01735 {
01736 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
01737 }
01738
01739
01740 static inline int sip_debug_test_pvt(struct sip_pvt *p)
01741 {
01742 if (!sipdebug)
01743 return 0;
01744 return sip_debug_test_addr(sip_real_dst(p));
01745 }
01746
01747
01748 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
01749 {
01750 int res;
01751 const struct sockaddr_in *dst = sip_real_dst(p);
01752 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
01753
01754 if (res != len)
01755 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));
01756 return res;
01757 }
01758
01759
01760
01761 static void build_via(struct sip_pvt *p)
01762 {
01763
01764 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
01765
01766
01767 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
01768 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
01769 }
01770
01771
01772
01773
01774
01775
01776
01777 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
01778 {
01779 struct sockaddr_in theirs, ours;
01780
01781
01782 ast_ouraddrfor(them, us);
01783 theirs.sin_addr = *them;
01784 ours.sin_addr = *us;
01785
01786 if (localaddr && externip.sin_addr.s_addr &&
01787 (ast_apply_ha(localaddr, &theirs)) &&
01788 (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
01789 if (externexpire && time(NULL) >= externexpire) {
01790 struct ast_hostent ahp;
01791 struct hostent *hp;
01792
01793 externexpire = time(NULL) + externrefresh;
01794 if ((hp = ast_gethostbyname(externhost, &ahp))) {
01795 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
01796 } else
01797 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
01798 }
01799 *us = externip.sin_addr;
01800 if (option_debug) {
01801 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
01802 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
01803 }
01804 } else if (bindaddr.sin_addr.s_addr)
01805 *us = bindaddr.sin_addr;
01806 return AST_SUCCESS;
01807 }
01808
01809
01810
01811 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
01812
01813 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
01814 __attribute__ ((format (printf, 2, 3)));
01815
01816
01817 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
01818 {
01819 char buf[80], *c = buf;
01820 struct sip_history *hist;
01821 int l;
01822
01823 vsnprintf(buf, sizeof(buf), fmt, ap);
01824 strsep(&c, "\r\n");
01825 l = strlen(buf) + 1;
01826 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
01827 return;
01828 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
01829 free(hist);
01830 return;
01831 }
01832 memcpy(hist->event, buf, l);
01833 AST_LIST_INSERT_TAIL(p->history, hist, list);
01834 }
01835
01836
01837 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
01838 {
01839 va_list ap;
01840
01841 if (!p)
01842 return;
01843 va_start(ap, fmt);
01844 append_history_va(p, fmt, ap);
01845 va_end(ap);
01846
01847 return;
01848 }
01849
01850
01851 static int retrans_pkt(void *data)
01852 {
01853 struct sip_pkt *pkt = data, *prev, *cur = NULL;
01854 int reschedule = DEFAULT_RETRANS;
01855
01856
01857 ast_mutex_lock(&pkt->owner->lock);
01858
01859 if (pkt->retrans < MAX_RETRANS) {
01860 pkt->retrans++;
01861 if (!pkt->timer_t1) {
01862 if (sipdebug && option_debug > 3)
01863 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);
01864 } else {
01865 int siptimer_a;
01866
01867 if (sipdebug && option_debug > 3)
01868 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
01869 if (!pkt->timer_a)
01870 pkt->timer_a = 2 ;
01871 else
01872 pkt->timer_a = 2 * pkt->timer_a;
01873
01874
01875 siptimer_a = pkt->timer_t1 * pkt->timer_a;
01876 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
01877 siptimer_a = 4000;
01878
01879
01880 reschedule = siptimer_a;
01881 if (option_debug > 3)
01882 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);
01883 }
01884
01885 if (sip_debug_test_pvt(pkt->owner)) {
01886 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
01887 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
01888 pkt->retrans, sip_nat_mode(pkt->owner),
01889 ast_inet_ntoa(dst->sin_addr),
01890 ntohs(dst->sin_port), pkt->data);
01891 }
01892
01893 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
01894 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
01895 ast_mutex_unlock(&pkt->owner->lock);
01896 return reschedule;
01897 }
01898
01899 if (pkt->owner && pkt->method != SIP_OPTIONS) {
01900 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug)
01901 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");
01902 } else {
01903 if ((pkt->method == SIP_OPTIONS) && sipdebug)
01904 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
01905 }
01906 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
01907
01908 pkt->retransid = -1;
01909
01910 if (ast_test_flag(pkt, FLAG_FATAL)) {
01911 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
01912 ast_mutex_unlock(&pkt->owner->lock);
01913 usleep(1);
01914 ast_mutex_lock(&pkt->owner->lock);
01915 }
01916 if (pkt->owner->owner) {
01917 sip_alreadygone(pkt->owner);
01918 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
01919 ast_queue_hangup(pkt->owner->owner);
01920 ast_channel_unlock(pkt->owner->owner);
01921 } else {
01922
01923
01924
01925 if (pkt->method != SIP_OPTIONS)
01926 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
01927 }
01928 }
01929
01930 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
01931 if (cur == pkt)
01932 break;
01933 }
01934 if (cur) {
01935 if (prev)
01936 prev->next = cur->next;
01937 else
01938 pkt->owner->packets = cur->next;
01939 ast_mutex_unlock(&pkt->owner->lock);
01940 free(cur);
01941 pkt = NULL;
01942 } else
01943 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
01944 if (pkt)
01945 ast_mutex_unlock(&pkt->owner->lock);
01946 return 0;
01947 }
01948
01949
01950
01951
01952 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
01953 {
01954 struct sip_pkt *pkt;
01955 int siptimer_a = DEFAULT_RETRANS;
01956
01957 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
01958 return AST_FAILURE;
01959 memcpy(pkt->data, data, len);
01960 pkt->method = sipmethod;
01961 pkt->packetlen = len;
01962 pkt->next = p->packets;
01963 pkt->owner = p;
01964 pkt->seqno = seqno;
01965 if (resp)
01966 ast_set_flag(pkt, FLAG_RESPONSE);
01967 pkt->data[len] = '\0';
01968 pkt->timer_t1 = p->timer_t1;
01969 if (fatal)
01970 ast_set_flag(pkt, FLAG_FATAL);
01971 if (pkt->timer_t1)
01972 siptimer_a = pkt->timer_t1 * 2;
01973
01974
01975 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
01976 if (option_debug > 3 && sipdebug)
01977 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
01978 pkt->next = p->packets;
01979 p->packets = pkt;
01980
01981 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
01982 if (sipmethod == SIP_INVITE) {
01983
01984 p->pendinginvite = seqno;
01985 }
01986 return AST_SUCCESS;
01987 }
01988
01989
01990 static int __sip_autodestruct(void *data)
01991 {
01992 struct sip_pvt *p = data;
01993
01994
01995 if (p->subscribed) {
01996 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
01997 p->subscribed = NONE;
01998 append_history(p, "Subscribestatus", "timeout");
01999 if (option_debug > 2)
02000 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
02001 return 10000;
02002 }
02003
02004
02005 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
02006 ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);
02007
02008
02009 p->autokillid = -1;
02010
02011 if (option_debug)
02012 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
02013 append_history(p, "AutoDestroy", "%s", p->callid);
02014 if (p->owner) {
02015 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
02016 ast_queue_hangup(p->owner);
02017 } else if (p->refer) {
02018 if (option_debug > 2)
02019 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
02020 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
02021 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
02022 } else
02023 sip_destroy(p);
02024 return 0;
02025 }
02026
02027
02028 static void sip_scheddestroy(struct sip_pvt *p, int ms)
02029 {
02030 if (ms < 0) {
02031 if (p->timer_t1 == 0)
02032 p->timer_t1 = 500;
02033 ms = p->timer_t1 * 64;
02034 }
02035 if (sip_debug_test_pvt(p))
02036 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
02037 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
02038 append_history(p, "SchedDestroy", "%d ms", ms);
02039
02040 if (p->autokillid > -1)
02041 ast_sched_del(sched, p->autokillid);
02042 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
02043 }
02044
02045
02046 static void sip_cancel_destroy(struct sip_pvt *p)
02047 {
02048 if (p->autokillid > -1) {
02049 ast_sched_del(sched, p->autokillid);
02050 append_history(p, "CancelDestroy", "");
02051 p->autokillid = -1;
02052 }
02053 }
02054
02055
02056 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
02057 {
02058 struct sip_pkt *cur, *prev = NULL;
02059
02060
02061 char *msg;
02062 int res = FALSE;
02063
02064 msg = sip_methods[sipmethod].text;
02065
02066 ast_mutex_lock(&p->lock);
02067 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
02068 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
02069 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
02070 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
02071 if (!resp && (seqno == p->pendinginvite)) {
02072 if (option_debug)
02073 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
02074 p->pendinginvite = 0;
02075 }
02076
02077 res = TRUE;
02078 UNLINK(cur, p->packets, prev);
02079 if (cur->retransid > -1) {
02080 if (sipdebug && option_debug > 3)
02081 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
02082 ast_sched_del(sched, cur->retransid);
02083 cur->retransid = -1;
02084 }
02085 free(cur);
02086 break;
02087 }
02088 }
02089 ast_mutex_unlock(&p->lock);
02090 if (option_debug)
02091 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
02092 }
02093
02094
02095
02096 static void __sip_pretend_ack(struct sip_pvt *p)
02097 {
02098 struct sip_pkt *cur = NULL;
02099
02100 while (p->packets) {
02101 int method;
02102 if (cur == p->packets) {
02103 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
02104 return;
02105 }
02106 cur = p->packets;
02107 method = (cur->method) ? cur->method : find_sip_method(cur->data);
02108 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
02109 }
02110 }
02111
02112
02113 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
02114 {
02115 struct sip_pkt *cur;
02116 int res = -1;
02117
02118 for (cur = p->packets; cur; cur = cur->next) {
02119 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
02120 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
02121
02122 if (cur->retransid > -1) {
02123 if (option_debug > 3 && sipdebug)
02124 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
02125 ast_sched_del(sched, cur->retransid);
02126 cur->retransid = -1;
02127 }
02128 res = 0;
02129 break;
02130 }
02131 }
02132 if (option_debug)
02133 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");
02134 return res;
02135 }
02136
02137
02138
02139 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
02140 {
02141 memset(dst, 0, sizeof(*dst));
02142 memcpy(dst->data, src->data, sizeof(dst->data));
02143 dst->len = src->len;
02144 parse_request(dst);
02145 }
02146
02147
02148 static void add_blank(struct sip_request *req)
02149 {
02150 if (!req->lines) {
02151
02152 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
02153 req->len += strlen(req->data + req->len);
02154 }
02155 }
02156
02157
02158 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
02159 {
02160 int res;
02161
02162 add_blank(req);
02163 if (sip_debug_test_pvt(p)) {
02164 const struct sockaddr_in *dst = sip_real_dst(p);
02165
02166 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
02167 reliable ? "Reliably " : "", sip_nat_mode(p),
02168 ast_inet_ntoa(dst->sin_addr),
02169 ntohs(dst->sin_port), req->data);
02170 }
02171 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
02172 struct sip_request tmp;
02173 parse_copy(&tmp, req);
02174 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
02175 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
02176 }
02177 res = (reliable) ?
02178 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
02179 __sip_xmit(p, req->data, req->len);
02180 if (res > 0)
02181 return 0;
02182 return res;
02183 }
02184
02185
02186 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
02187 {
02188 int res;
02189
02190 add_blank(req);
02191 if (sip_debug_test_pvt(p)) {
02192 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
02193 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);
02194 else
02195 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);
02196 }
02197 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
02198 struct sip_request tmp;
02199 parse_copy(&tmp, req);
02200 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
02201 }
02202 res = (reliable) ?
02203 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
02204 __sip_xmit(p, req->data, req->len);
02205 return res;
02206 }
02207
02208
02209
02210
02211
02212 static const char *find_closing_quote(const char *start, const char *lim)
02213 {
02214 char last_char = '\0';
02215 const char *s;
02216 for (s = start; *s && s != lim; last_char = *s++) {
02217 if (*s == '"' && last_char != '\\')
02218 break;
02219 }
02220 return s;
02221 }
02222
02223
02224
02225
02226
02227
02228
02229
02230
02231
02232
02233
02234 static char *get_in_brackets(char *tmp)
02235 {
02236 const char *parse = tmp;
02237 char *first_bracket;
02238
02239
02240
02241
02242
02243 while ( (first_bracket = strchr(parse, '<')) ) {
02244 char *first_quote = strchr(parse, '"');
02245
02246 if (!first_quote || first_quote > first_bracket)
02247 break;
02248
02249 parse = find_closing_quote(first_quote + 1, NULL);
02250 if (!*parse) {
02251
02252 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
02253 break;
02254 }
02255 parse++;
02256 }
02257 if (first_bracket) {
02258 char *second_bracket = strchr(first_bracket + 1, '>');
02259 if (second_bracket) {
02260 *second_bracket = '\0';
02261 tmp = first_bracket + 1;
02262 } else {
02263 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
02264 }
02265 }
02266 return tmp;
02267 }
02268
02269
02270
02271 static int sip_sendtext(struct ast_channel *ast, const char *text)
02272 {
02273 struct sip_pvt *p = ast->tech_pvt;
02274 int debug = sip_debug_test_pvt(p);
02275
02276 if (debug)
02277 ast_verbose("Sending text %s on %s\n", text, ast->name);
02278 if (!p)
02279 return -1;
02280 if (ast_strlen_zero(text))
02281 return 0;
02282 if (debug)
02283 ast_verbose("Really sending text %s on %s\n", text, ast->name);
02284 transmit_message_with_text(p, text);
02285 return 0;
02286 }
02287
02288
02289
02290
02291
02292
02293 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
02294 {
02295 char port[10];
02296 char ipaddr[INET_ADDRSTRLEN];
02297 char regseconds[20];
02298
02299 char *sysname = ast_config_AST_SYSTEM_NAME;
02300 char *syslabel = NULL;
02301
02302 time_t nowtime = time(NULL) + expirey;
02303 const char *fc = fullcontact ? "fullcontact" : NULL;
02304
02305 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
02306 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
02307 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
02308
02309 if (ast_strlen_zero(sysname))
02310 sysname = NULL;
02311 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
02312 syslabel = "regserver";
02313
02314 if (fc)
02315 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
02316 "port", port, "regseconds", regseconds,
02317 "username", username, fc, fullcontact, syslabel, sysname, NULL);
02318 else
02319 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
02320 "port", port, "regseconds", regseconds,
02321 "username", username, syslabel, sysname, NULL);
02322 }
02323
02324
02325 static void register_peer_exten(struct sip_peer *peer, int onoff)
02326 {
02327 char multi[256];
02328 char *stringp, *ext, *context;
02329
02330
02331
02332
02333
02334 if (ast_strlen_zero(global_regcontext))
02335 return;
02336
02337 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
02338 stringp = multi;
02339 while ((ext = strsep(&stringp, "&"))) {
02340 if ((context = strchr(ext, '@'))) {
02341 *context++ = '\0';
02342 if (!ast_context_find(context)) {
02343 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
02344 continue;
02345 }
02346 } else {
02347 context = global_regcontext;
02348 }
02349 if (onoff)
02350 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
02351 ast_strdup(peer->name), ast_free, "SIP");
02352 else
02353 ast_context_remove_extension(context, ext, 1, NULL);
02354 }
02355 }
02356
02357
02358 static void sip_destroy_peer(struct sip_peer *peer)
02359 {
02360 if (option_debug > 2)
02361 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
02362
02363
02364 if (peer->call)
02365 sip_destroy(peer->call);
02366
02367 if (peer->mwipvt)
02368 sip_destroy(peer->mwipvt);
02369
02370 if (peer->chanvars) {
02371 ast_variables_destroy(peer->chanvars);
02372 peer->chanvars = NULL;
02373 }
02374 if (peer->expire > -1)
02375 ast_sched_del(sched, peer->expire);
02376
02377 if (peer->pokeexpire > -1)
02378 ast_sched_del(sched, peer->pokeexpire);
02379 register_peer_exten(peer, FALSE);
02380 ast_free_ha(peer->ha);
02381 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
02382 apeerobjs--;
02383 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
02384 rpeerobjs--;
02385 else
02386 speerobjs--;
02387 clear_realm_authentication(peer->auth);
02388 peer->auth = NULL;
02389 free(peer);
02390 }
02391
02392
02393 static void update_peer(struct sip_peer *p, int expiry)
02394 {
02395 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
02396 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
02397 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
02398 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
02399 }
02400 }
02401
02402
02403
02404
02405
02406
02407
02408 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
02409 {
02410 struct sip_peer *peer;
02411 struct ast_variable *var = NULL;
02412 struct ast_variable *tmp;
02413 char ipaddr[INET_ADDRSTRLEN];
02414
02415
02416 if (newpeername)
02417 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
02418 else if (sin) {
02419 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
02420 var = ast_load_realtime("sippeers", "host", ipaddr, NULL);
02421 if (!var)
02422 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL);
02423 }
02424
02425 if (!var)
02426 return NULL;
02427
02428 for (tmp = var; tmp; tmp = tmp->next) {
02429
02430 if (!strcasecmp(tmp->name, "type") &&
02431 !strcasecmp(tmp->value, "user")) {
02432 ast_variables_destroy(var);
02433 return NULL;
02434 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
02435 newpeername = tmp->value;
02436 }
02437 }
02438
02439 if (!newpeername) {
02440 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
02441 ast_variables_destroy(var);
02442 return NULL;
02443 }
02444
02445
02446 peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
02447 if (!peer) {
02448 ast_variables_destroy(var);
02449 return NULL;
02450 }
02451
02452 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
02453
02454 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
02455 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
02456 if (peer->expire > -1) {
02457 ast_sched_del(sched, peer->expire);
02458 }
02459 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
02460 }
02461 ASTOBJ_CONTAINER_LINK(&peerl,peer);
02462 } else {
02463 ast_set_flag(&peer->flags[0], SIP_REALTIME);
02464 }
02465 ast_variables_destroy(var);
02466
02467 return peer;
02468 }
02469
02470
02471 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
02472 {
02473
02474 struct sip_peer *p = (struct sip_peer *) name;
02475 return !(!inaddrcmp(&p->addr, sin) ||
02476 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
02477 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
02478 }
02479
02480
02481
02482
02483 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
02484 {
02485 struct sip_peer *p = NULL;
02486
02487 if (peer)
02488 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
02489 else
02490 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
02491
02492 if (!p && realtime)
02493 p = realtime_peer(peer, sin);
02494
02495 return p;
02496 }
02497
02498
02499 static void sip_destroy_user(struct sip_user *user)
02500 {
02501 if (option_debug > 2)
02502 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
02503 ast_free_ha(user->ha);
02504 if (user->chanvars) {
02505 ast_variables_destroy(user->chanvars);
02506 user->chanvars = NULL;
02507 }
02508 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
02509 ruserobjs--;
02510 else
02511 suserobjs--;
02512 free(user);
02513 }
02514
02515
02516
02517
02518 static struct sip_user *realtime_user(const char *username)
02519 {
02520 struct ast_variable *var;
02521 struct ast_variable *tmp;
02522 struct sip_user *user = NULL;
02523
02524 var = ast_load_realtime("sipusers", "name", username, NULL);
02525
02526 if (!var)
02527 return NULL;
02528
02529 for (tmp = var; tmp; tmp = tmp->next) {
02530 if (!strcasecmp(tmp->name, "type") &&
02531 !strcasecmp(tmp->value, "peer")) {
02532 ast_variables_destroy(var);
02533 return NULL;
02534 }
02535 }
02536
02537 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
02538
02539 if (!user) {
02540 ast_variables_destroy(var);
02541 return NULL;
02542 }
02543
02544 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
02545 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
02546 suserobjs++;
02547 ASTOBJ_CONTAINER_LINK(&userl,user);
02548 } else {
02549
02550 suserobjs--;
02551 ruserobjs++;
02552 ast_set_flag(&user->flags[0], SIP_REALTIME);
02553 }
02554 ast_variables_destroy(var);
02555 return user;
02556 }
02557
02558
02559
02560
02561
02562 static struct sip_user *find_user(const char *name, int realtime)
02563 {
02564 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
02565 if (!u && realtime)
02566 u = realtime_user(name);
02567 return u;
02568 }
02569
02570
02571 static void do_setnat(struct sip_pvt *p, int natflags)
02572 {
02573 const char *mode = natflags ? "On" : "Off";
02574
02575 if (p->rtp) {
02576 if (option_debug)
02577 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
02578 ast_rtp_setnat(p->rtp, natflags);
02579 }
02580 if (p->vrtp) {
02581 if (option_debug)
02582 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
02583 ast_rtp_setnat(p->vrtp, natflags);
02584 }
02585 if (p->udptl) {
02586 if (option_debug)
02587 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
02588 ast_udptl_setnat(p->udptl, natflags);
02589 }
02590 }
02591
02592
02593
02594
02595 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
02596 {
02597 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
02598 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
02599 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
02600 dialog->recv = dialog->sa;
02601 } else
02602 return -1;
02603
02604 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
02605 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
02606 dialog->capability = peer->capability;
02607 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
02608 ast_rtp_destroy(dialog->vrtp);
02609 dialog->vrtp = NULL;
02610 }
02611 dialog->prefs = peer->prefs;
02612 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
02613 dialog->t38.capability = global_t38_capability;
02614 if (dialog->udptl) {
02615 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
02616 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
02617 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
02618 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
02619 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
02620 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
02621 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
02622 if (option_debug > 1)
02623 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
02624 }
02625 dialog->t38.jointcapability = dialog->t38.capability;
02626 } else if (dialog->udptl) {
02627 ast_udptl_destroy(dialog->udptl);
02628 dialog->udptl = NULL;
02629 }
02630 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
02631
02632 if (dialog->rtp) {
02633 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
02634 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
02635 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
02636 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
02637 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
02638
02639 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
02640 dialog->autoframing = peer->autoframing;
02641 }
02642 if (dialog->vrtp) {
02643 ast_rtp_setdtmf(dialog->vrtp, 0);
02644 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
02645 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
02646 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
02647 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
02648 }
02649
02650 ast_string_field_set(dialog, peername, peer->username);
02651 ast_string_field_set(dialog, authname, peer->username);
02652 ast_string_field_set(dialog, username, peer->username);
02653 ast_string_field_set(dialog, peersecret, peer->secret);
02654 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
02655 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
02656 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
02657 ast_string_field_set(dialog, tohost, peer->tohost);
02658 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
02659 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
02660 char *tmpcall;
02661 char *c;
02662 tmpcall = ast_strdupa(dialog->callid);
02663 c = strchr(tmpcall, '@');
02664 if (c) {
02665 *c = '\0';
02666 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
02667 }
02668 }
02669 if (ast_strlen_zero(dialog->tohost))
02670 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
02671 if (!ast_strlen_zero(peer->fromdomain))
02672 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
02673 if (!ast_strlen_zero(peer->fromuser))
02674 ast_string_field_set(dialog, fromuser, peer->fromuser);
02675 dialog->maxtime = peer->maxms;
02676 dialog->callgroup = peer->callgroup;
02677 dialog->pickupgroup = peer->pickupgroup;
02678 dialog->allowtransfer = peer->allowtransfer;
02679
02680
02681 if (peer->maxms && peer->lastms)
02682 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
02683 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
02684 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
02685 dialog->noncodeccapability |= AST_RTP_DTMF;
02686 else
02687 dialog->noncodeccapability &= ~AST_RTP_DTMF;
02688 ast_string_field_set(dialog, context, peer->context);
02689 dialog->rtptimeout = peer->rtptimeout;
02690 if (peer->call_limit)
02691 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
02692 dialog->maxcallbitrate = peer->maxcallbitrate;
02693
02694 return 0;
02695 }
02696
02697
02698
02699
02700 static int create_addr(struct sip_pvt *dialog, const char *opeer)
02701 {
02702 struct hostent *hp;
02703 struct ast_hostent ahp;
02704 struct sip_peer *p;
02705 char *port;
02706 int portno;
02707 char host[MAXHOSTNAMELEN], *hostn;
02708 char peer[256];
02709
02710 ast_copy_string(peer, opeer, sizeof(peer));
02711 port = strchr(peer, ':');
02712 if (port)
02713 *port++ = '\0';
02714 dialog->sa.sin_family = AF_INET;
02715 dialog->timer_t1 = 500;
02716 p = find_peer(peer, NULL, 1);
02717
02718 if (p) {
02719 int res = create_addr_from_peer(dialog, p);
02720 ASTOBJ_UNREF(p, sip_destroy_peer);
02721 return res;
02722 }
02723 hostn = peer;
02724 portno = port ? atoi(port) : STANDARD_SIP_PORT;
02725 if (srvlookup) {
02726 char service[MAXHOSTNAMELEN];
02727 int tportno;
02728 int ret;
02729
02730 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
02731 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
02732 if (ret > 0) {
02733 hostn = host;
02734 portno = tportno;
02735 }
02736 }
02737 hp = ast_gethostbyname(hostn, &ahp);
02738 if (!hp) {
02739 ast_log(LOG_WARNING, "No such host: %s\n", peer);
02740 return -1;
02741 }
02742 ast_string_field_set(dialog, tohost, peer);
02743 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
02744 dialog->sa.sin_port = htons(portno);
02745 dialog->recv = dialog->sa;
02746 return 0;
02747 }
02748
02749
02750 static int auto_congest(void *nothing)
02751 {
02752 struct sip_pvt *p = nothing;
02753
02754 ast_mutex_lock(&p->lock);
02755 p->initid = -1;
02756 if (p->owner) {
02757
02758 if (!ast_channel_trylock(p->owner)) {
02759 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
02760 append_history(p, "Cong", "Auto-congesting (timer)");
02761 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
02762 ast_channel_unlock(p->owner);
02763 }
02764 }
02765 ast_mutex_unlock(&p->lock);
02766 return 0;
02767 }
02768
02769
02770
02771
02772 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
02773 {
02774 int res;
02775 struct sip_pvt *p;
02776 struct varshead *headp;
02777 struct ast_var_t *current;
02778 const char *referer = NULL;
02779
02780 p = ast->tech_pvt;
02781 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
02782 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
02783 return -1;
02784 }
02785
02786
02787 headp=&ast->varshead;
02788 AST_LIST_TRAVERSE(headp,current,entries) {
02789
02790 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
02791 p->options->vxml_url = ast_var_value(current);
02792 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
02793 p->options->uri_options = ast_var_value(current);
02794 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
02795
02796 p->options->distinctive_ring = ast_var_value(current);
02797 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
02798
02799 p->options->addsipheaders = 1;
02800 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
02801
02802 p->options->transfer = 1;
02803 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
02804
02805 referer = ast_var_value(current);
02806 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
02807
02808 p->options->replaces = ast_var_value(current);
02809 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
02810 p->t38.state = T38_LOCAL_DIRECT;
02811 if (option_debug)
02812 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
02813 }
02814
02815 }
02816
02817 res = 0;
02818 ast_set_flag(&p->flags[0], SIP_OUTGOING);
02819
02820 if (p->options->transfer) {
02821 char buf[BUFSIZ/2];
02822
02823 if (referer) {
02824 if (sipdebug && option_debug > 2)
02825 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
02826 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
02827 } else
02828 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
02829 ast_string_field_set(p, cid_name, buf);
02830 }
02831 if (option_debug)
02832 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
02833
02834 res = update_call_counter(p, INC_CALL_RINGING);
02835 if ( res != -1 ) {
02836 p->callingpres = ast->cid.cid_pres;
02837 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
02838 p->jointnoncodeccapability = p->noncodeccapability;
02839
02840
02841 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
02842 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
02843 res = -1;
02844 } else {
02845 p->t38.jointcapability = p->t38.capability;
02846 if (option_debug > 1)
02847 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
02848 transmit_invite(p, SIP_INVITE, 1, 2);
02849 p->invitestate = INV_CALLING;
02850
02851
02852 p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, auto_congest, p);
02853 }
02854 }
02855 return res;
02856 }
02857
02858
02859
02860 static void sip_registry_destroy(struct sip_registry *reg)
02861 {
02862
02863 if (option_debug > 2)
02864 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
02865
02866 if (reg->call) {
02867
02868
02869 reg->call->registry = NULL;
02870 if (option_debug > 2)
02871 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
02872 sip_destroy(reg->call);
02873 }
02874 if (reg->expire > -1)
02875 ast_sched_del(sched, reg->expire);
02876 if (reg->timeout > -1)
02877 ast_sched_del(sched, reg->timeout);
02878 ast_string_field_free_pools(reg);
02879 regobjs--;
02880 free(reg);
02881
02882 }
02883
02884
02885 static void __sip_destroy(struct sip_pvt *p, int lockowner)
02886 {
02887 struct sip_pvt *cur, *prev = NULL;
02888 struct sip_pkt *cp;
02889
02890 if (sip_debug_test_pvt(p) || option_debug > 2)
02891 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
02892
02893 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT)) {
02894 update_call_counter(p, DEC_CALL_LIMIT);
02895 if (option_debug > 1)
02896 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
02897 }
02898
02899
02900 if (p->relatedpeer && p->relatedpeer->mwipvt)
02901 p->relatedpeer->mwipvt = NULL;
02902
02903 if (dumphistory)
02904 sip_dump_history(p);
02905
02906 if (p->options)
02907 free(p->options);
02908
02909 if (p->stateid > -1)
02910 ast_extension_state_del(p->stateid, NULL);
02911 if (p->initid > -1)
02912 ast_sched_del(sched, p->initid);
02913 if (p->autokillid > -1)
02914 ast_sched_del(sched, p->autokillid);
02915
02916 if (p->rtp)
02917 ast_rtp_destroy(p->rtp);
02918 if (p->vrtp)
02919 ast_rtp_destroy(p->vrtp);
02920 if (p->udptl)
02921 ast_udptl_destroy(p->udptl);
02922 if (p->refer)
02923 free(p->refer);
02924 if (p->route) {
02925 free_old_route(p->route);
02926 p->route = NULL;
02927 }
02928 if (p->registry) {
02929 if (p->registry->call == p)
02930 p->registry->call = NULL;
02931 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
02932 }
02933
02934
02935 if (p->owner) {
02936 if (lockowner)
02937 ast_channel_lock(p->owner);
02938 if (option_debug)
02939 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
02940 p->owner->tech_pvt = NULL;
02941 if (lockowner)
02942 ast_channel_unlock(p->owner);
02943 }
02944
02945 if (p->history) {
02946 struct sip_history *hist;
02947 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
02948 free(hist);
02949 free(p->history);
02950 p->history = NULL;
02951 }
02952
02953 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
02954 if (cur == p) {
02955 UNLINK(cur, iflist, prev);
02956 break;
02957 }
02958 }
02959 if (!cur) {
02960 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
02961 return;
02962 }
02963
02964
02965 while((cp = p->packets)) {
02966 p->packets = p->packets->next;
02967 if (cp->retransid > -1)
02968 ast_sched_del(sched, cp->retransid);
02969 free(cp);
02970 }
02971 if (p->chanvars) {
02972 ast_variables_destroy(p->chanvars);
02973 p->chanvars = NULL;
02974 }
02975 ast_mutex_destroy(&p->lock);
02976
02977 ast_string_field_free_pools(p);
02978
02979 free(p);
02980 }
02981
02982
02983
02984
02985
02986
02987
02988
02989
02990
02991
02992
02993
02994
02995
02996 static int update_call_counter(struct sip_pvt *fup, int event)
02997 {
02998 char name[256];
02999 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
03000 int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
03001 struct sip_user *u = NULL;
03002 struct sip_peer *p = NULL;
03003
03004 if (option_debug > 2)
03005 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
03006
03007
03008 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
03009 return 0;
03010
03011 ast_copy_string(name, fup->username, sizeof(name));
03012
03013
03014 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
03015 inuse = &u->inUse;
03016 call_limit = &u->call_limit;
03017 inringing = NULL;
03018 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) {
03019 inuse = &p->inUse;
03020 call_limit = &p->call_limit;
03021 inringing = &p->inRinging;
03022 ast_copy_string(name, fup->peername, sizeof(name));
03023 }
03024 if (!p && !u) {
03025 if (option_debug > 1)
03026 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
03027 return 0;
03028 }
03029
03030 switch(event) {
03031
03032 case DEC_CALL_LIMIT:
03033 if ( *inuse > 0 ) {
03034 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
03035 (*inuse)--;
03036 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
03037 }
03038 } else {
03039 *inuse = 0;
03040 }
03041 if (inringing) {
03042 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03043 if (*inringing > 0)
03044 (*inringing)--;
03045 else
03046 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
03047 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03048 }
03049 }
03050 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold)
03051 sip_peer_hold(fup, 0);
03052 if (option_debug > 1 || sipdebug) {
03053 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
03054 }
03055 break;
03056
03057 case INC_CALL_RINGING:
03058 case INC_CALL_LIMIT:
03059 if (*call_limit > 0 ) {
03060 if (*inuse >= *call_limit) {
03061 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);
03062 if (u)
03063 ASTOBJ_UNREF(u, sip_destroy_user);
03064 else
03065 ASTOBJ_UNREF(p, sip_destroy_peer);
03066 return -1;
03067 }
03068 }
03069 if (inringing && (event == INC_CALL_RINGING)) {
03070 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03071 (*inringing)++;
03072 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03073 }
03074 }
03075
03076 (*inuse)++;
03077 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
03078 if (option_debug > 1 || sipdebug) {
03079 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
03080 }
03081 break;
03082
03083 case DEC_CALL_RINGING:
03084 if (inringing) {
03085 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
03086 if (*inringing > 0)
03087 (*inringing)--;
03088 else
03089 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
03090 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
03091 }
03092 }
03093 break;
03094
03095 default:
03096 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
03097 }
03098 if (p) {
03099 ast_device_state_changed("SIP/%s", p->name);
03100 ASTOBJ_UNREF(p, sip_destroy_peer);
03101 } else
03102 ASTOBJ_UNREF(u, sip_destroy_user);
03103 return 0;
03104 }
03105
03106
03107 static void sip_destroy(struct sip_pvt *p)
03108 {
03109 ast_mutex_lock(&iflock);
03110 if (option_debug > 2)
03111 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
03112 __sip_destroy(p, 1);
03113 ast_mutex_unlock(&iflock);
03114 }
03115
03116
03117 static int hangup_sip2cause(int cause)
03118 {
03119
03120
03121 switch(cause) {
03122 case 401:
03123 return AST_CAUSE_CALL_REJECTED;
03124 case 403:
03125 return AST_CAUSE_CALL_REJECTED;
03126 case 404:
03127 return AST_CAUSE_UNALLOCATED;
03128 case 405:
03129 return AST_CAUSE_INTERWORKING;
03130 case 407:
03131 return AST_CAUSE_CALL_REJECTED;
03132 case 408:
03133 return AST_CAUSE_NO_USER_RESPONSE;
03134 case 409:
03135 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
03136 case 410:
03137 return AST_CAUSE_UNALLOCATED;
03138 case 411:
03139 return AST_CAUSE_INTERWORKING;
03140 case 413:
03141 return AST_CAUSE_INTERWORKING;
03142 case 414:
03143 return AST_CAUSE_INTERWORKING;
03144 case 415:
03145 return AST_CAUSE_INTERWORKING;
03146 case 420:
03147 return AST_CAUSE_NO_ROUTE_DESTINATION;
03148 case 480:
03149 return AST_CAUSE_NO_ANSWER;
03150 case 481:
03151 return AST_CAUSE_INTERWORKING;
03152 case 482:
03153 return AST_CAUSE_INTERWORKING;
03154 case 483:
03155 return AST_CAUSE_NO_ANSWER;
03156 case 484:
03157 return AST_CAUSE_INVALID_NUMBER_FORMAT;
03158 case 485:
03159 return AST_CAUSE_UNALLOCATED;
03160 case 486:
03161 return AST_CAUSE_BUSY;
03162 case 487:
03163 return AST_CAUSE_INTERWORKING;
03164 case 488:
03165 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
03166 case 491:
03167 return AST_CAUSE_INTERWORKING;
03168 case 493:
03169 return AST_CAUSE_INTERWORKING;
03170 case 500:
03171 return AST_CAUSE_FAILURE;
03172 case 501:
03173 return AST_CAUSE_FACILITY_REJECTED;
03174 case 502:
03175 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03176 case 503:
03177 return AST_CAUSE_CONGESTION;
03178 case 504:
03179 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
03180 case 505:
03181 return AST_CAUSE_INTERWORKING;
03182 case 600:
03183 return AST_CAUSE_USER_BUSY;
03184 case 603:
03185 return AST_CAUSE_CALL_REJECTED;
03186 case 604:
03187 return AST_CAUSE_UNALLOCATED;
03188 case 606:
03189 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
03190 default:
03191 return AST_CAUSE_NORMAL;
03192 }
03193
03194 return 0;
03195 }
03196
03197
03198
03199
03200
03201
03202
03203
03204
03205
03206
03207
03208
03209
03210
03211
03212
03213
03214
03215
03216
03217
03218
03219
03220
03221
03222
03223
03224
03225
03226
03227
03228
03229 static const char *hangup_cause2sip(int cause)
03230 {
03231 switch (cause) {
03232 case AST_CAUSE_UNALLOCATED:
03233 case AST_CAUSE_NO_ROUTE_DESTINATION:
03234 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
03235 return "404 Not Found";
03236 case AST_CAUSE_CONGESTION:
03237 case AST_CAUSE_SWITCH_CONGESTION:
03238 return "503 Service Unavailable";
03239 case AST_CAUSE_NO_USER_RESPONSE:
03240 return "408 Request Timeout";
03241 case AST_CAUSE_NO_ANSWER:
03242 return "480 Temporarily unavailable";
03243 case AST_CAUSE_CALL_REJECTED:
03244 return "403 Forbidden";
03245 case AST_CAUSE_NUMBER_CHANGED:
03246 return "410 Gone";
03247 case AST_CAUSE_NORMAL_UNSPECIFIED:
03248 return "480 Temporarily unavailable";
03249 case AST_CAUSE_INVALID_NUMBER_FORMAT:
03250 return "484 Address incomplete";
03251 case AST_CAUSE_USER_BUSY:
03252 return "486 Busy here";
03253 case AST_CAUSE_FAILURE:
03254 return "500 Server internal failure";
03255 case AST_CAUSE_FACILITY_REJECTED:
03256 return "501 Not Implemented";
03257 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
03258 return "503 Service Unavailable";
03259
03260 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
03261 return "502 Bad Gateway";
03262 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
03263 return "488 Not Acceptable Here";
03264
03265 case AST_CAUSE_NOTDEFINED:
03266 default:
03267 if (option_debug)
03268 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
03269 return NULL;
03270 }
03271
03272
03273 return 0;
03274 }
03275
03276
03277
03278
03279 static int sip_hangup(struct ast_channel *ast)
03280 {
03281 struct sip_pvt *p = ast->tech_pvt;
03282 int needcancel = FALSE;
03283 int needdestroy = 0;
03284 struct ast_channel *oldowner = ast;
03285
03286 if (!p) {
03287 if (option_debug)
03288 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
03289 return 0;
03290 }
03291
03292 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
03293 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT)) {
03294 if (option_debug && sipdebug)
03295 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
03296 update_call_counter(p, DEC_CALL_LIMIT);
03297 }
03298 if (option_debug >3)
03299 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
03300 if (p->autokillid > -1)
03301 sip_cancel_destroy(p);
03302 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03303 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
03304 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
03305 p->owner->tech_pvt = NULL;
03306 p->owner = NULL;
03307 return 0;
03308 }
03309 if (option_debug) {
03310 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
03311 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
03312 else {
03313 if (option_debug)
03314 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
03315 }
03316 }
03317 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
03318 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
03319
03320 ast_mutex_lock(&p->lock);
03321 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT)) {
03322 if (option_debug && sipdebug)
03323 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
03324 update_call_counter(p, DEC_CALL_LIMIT);
03325 }
03326
03327
03328 if (p->owner != ast) {
03329 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
03330 ast_mutex_unlock(&p->lock);
03331 return 0;
03332 }
03333
03334 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING || (p->invitestate < INV_COMPLETED && ast->_state != AST_STATE_UP)) {
03335 needcancel = TRUE;
03336 if (option_debug > 3)
03337 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
03338 }
03339
03340
03341 if (p->vad)
03342 ast_dsp_free(p->vad);
03343
03344 p->owner = NULL;
03345 ast->tech_pvt = NULL;
03346
03347 ast_module_unref(ast_module_info->self);
03348
03349
03350
03351
03352
03353
03354
03355 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
03356 needdestroy = 1;
03357 else if (p->invitestate != INV_CALLING)
03358 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03359
03360
03361 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
03362 if (needcancel) {
03363 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03364
03365 __sip_pretend_ack(p);
03366
03367
03368 if (p->invitestate == INV_CALLING) {
03369
03370 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
03371
03372 } else {
03373
03374 transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
03375
03376
03377 needdestroy = 0;
03378 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03379 }
03380 if ( p->initid != -1 ) {
03381
03382
03383 update_call_counter(p, INC_CALL_LIMIT);
03384 }
03385 } else {
03386 const char *res;
03387 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
03388 transmit_response_reliable(p, res, &p->initreq);
03389 else
03390 transmit_response_reliable(p, "603 Declined", &p->initreq);
03391 }
03392 } else {
03393 if (!p->pendinginvite) {
03394 char *audioqos = "";
03395 char *videoqos = "";
03396 if (p->rtp)
03397 audioqos = ast_rtp_get_quality(p->rtp, NULL);
03398 if (p->vrtp)
03399 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
03400
03401 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03402
03403
03404 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
03405 if (p->rtp)
03406 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
03407 if (p->vrtp)
03408 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
03409 }
03410 if (p->rtp && oldowner)
03411 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
03412 if (p->vrtp && oldowner)
03413 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
03414 } else {
03415
03416
03417 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
03418 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
03419 sip_cancel_destroy(p);
03420 }
03421 }
03422 }
03423 if (needdestroy)
03424 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
03425 ast_mutex_unlock(&p->lock);
03426 return 0;
03427 }
03428
03429
03430 static void try_suggested_sip_codec(struct sip_pvt *p)
03431 {
03432 int fmt;
03433 const char *codec;
03434
03435 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
03436 if (!codec)
03437 return;
03438
03439 fmt = ast_getformatbyname(codec);
03440 if (fmt) {
03441 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
03442 if (p->jointcapability & fmt) {
03443 p->jointcapability &= fmt;
03444 p->capability &= fmt;
03445 } else
03446 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
03447 } else
03448 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
03449 return;
03450 }
03451
03452
03453
03454 static int sip_answer(struct ast_channel *ast)
03455 {
03456 int res = 0;
03457 struct sip_pvt *p = ast->tech_pvt;
03458
03459 ast_mutex_lock(&p->lock);
03460 if (ast->_state != AST_STATE_UP) {
03461 try_suggested_sip_codec(p);
03462
03463 ast_setstate(ast, AST_STATE_UP);
03464 if (option_debug)
03465 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
03466 if (p->t38.state == T38_PEER_DIRECT) {
03467 p->t38.state = T38_ENABLED;
03468 if (option_debug > 1)
03469 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
03470 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
03471 } else
03472 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
03473 }
03474 ast_mutex_unlock(&p->lock);
03475 return res;
03476 }
03477
03478
03479 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
03480 {
03481 struct sip_pvt *p = ast->tech_pvt;
03482 int res = 0;
03483
03484 switch (frame->frametype) {
03485 case AST_FRAME_VOICE:
03486 if (!(frame->subclass & ast->nativeformats)) {
03487 char s1[512], s2[512], s3[512];
03488 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
03489 frame->subclass,
03490 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
03491 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
03492 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
03493 ast->readformat,
03494 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
03495 ast->writeformat);
03496 ast_frame_dump(ast->name, frame, "<<");
03497 ast_backtrace();
03498 return 0;
03499 }
03500 if (p) {
03501 ast_mutex_lock(&p->lock);
03502 if (p->rtp) {
03503
03504 if ((ast->_state != AST_STATE_UP) &&
03505 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03506 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03507 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03508 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03509 }
03510 p->lastrtptx = time(NULL);
03511 res = ast_rtp_write(p->rtp, frame);
03512 }
03513 ast_mutex_unlock(&p->lock);
03514 }
03515 break;
03516 case AST_FRAME_VIDEO:
03517 if (p) {
03518 ast_mutex_lock(&p->lock);
03519 if (p->vrtp) {
03520
03521 if ((ast->_state != AST_STATE_UP) &&
03522 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03523 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03524 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03525 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03526 }
03527 p->lastrtptx = time(NULL);
03528 res = ast_rtp_write(p->vrtp, frame);
03529 }
03530 ast_mutex_unlock(&p->lock);
03531 }
03532 break;
03533 case AST_FRAME_IMAGE:
03534 return 0;
03535 break;
03536 case AST_FRAME_MODEM:
03537 if (p) {
03538 ast_mutex_lock(&p->lock);
03539
03540
03541
03542
03543 if (p->udptl && ast->_state == AST_STATE_UP)
03544 res = ast_udptl_write(p->udptl, frame);
03545 ast_mutex_unlock(&p->lock);
03546 }
03547 break;
03548 default:
03549 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
03550 return 0;
03551 }
03552
03553 return res;
03554 }
03555
03556
03557
03558 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
03559 {
03560 int ret = -1;
03561 struct sip_pvt *p;
03562
03563 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
03564 ast_log(LOG_DEBUG, "New channel is zombie\n");
03565 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
03566 ast_log(LOG_DEBUG, "Old channel is zombie\n");
03567
03568 if (!newchan || !newchan->tech_pvt) {
03569 if (!newchan)
03570 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
03571 else
03572 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
03573 return -1;
03574 }
03575 p = newchan->tech_pvt;
03576
03577 if (!p) {
03578 ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
03579 return -1;
03580 }
03581
03582 ast_mutex_lock(&p->lock);
03583 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
03584 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
03585 if (p->owner != oldchan)
03586 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
03587 else {
03588 p->owner = newchan;
03589 ret = 0;
03590 }
03591 if (option_debug > 2)
03592 ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
03593
03594 ast_mutex_unlock(&p->lock);
03595 return ret;
03596 }
03597
03598 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
03599 {
03600 struct sip_pvt *p = ast->tech_pvt;
03601 int res = 0;
03602
03603 ast_mutex_lock(&p->lock);
03604 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
03605 case SIP_DTMF_INBAND:
03606 res = -1;
03607 break;
03608 case SIP_DTMF_RFC2833:
03609 if (p->rtp)
03610 ast_rtp_senddigit_begin(p->rtp, digit);
03611 break;
03612 default:
03613 break;
03614 }
03615 ast_mutex_unlock(&p->lock);
03616
03617 return res;
03618 }
03619
03620
03621
03622 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
03623 {
03624 struct sip_pvt *p = ast->tech_pvt;
03625 int res = 0;
03626
03627 ast_mutex_lock(&p->lock);
03628 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
03629 case SIP_DTMF_INFO:
03630 transmit_info_with_digit(p, digit, duration);
03631 break;
03632 case SIP_DTMF_RFC2833:
03633 if (p->rtp)
03634 ast_rtp_senddigit_end(p->rtp, digit);
03635 break;
03636 case SIP_DTMF_INBAND:
03637 res = -1;
03638 break;
03639 }
03640 ast_mutex_unlock(&p->lock);
03641
03642 return res;
03643 }
03644
03645
03646 static int sip_transfer(struct ast_channel *ast, const char *dest)
03647 {
03648 struct sip_pvt *p = ast->tech_pvt;
03649 int res;
03650
03651 if (dest == NULL)
03652 dest = "";
03653 ast_mutex_lock(&p->lock);
03654 if (ast->_state == AST_STATE_RING)
03655 res = sip_sipredirect(p, dest);
03656 else
03657 res = transmit_refer(p, dest);
03658 ast_mutex_unlock(&p->lock);
03659 return res;
03660 }
03661
03662
03663
03664
03665
03666
03667 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
03668 {
03669 struct sip_pvt *p = ast->tech_pvt;
03670 int res = 0;
03671
03672 ast_mutex_lock(&p->lock);
03673 switch(condition) {
03674 case AST_CONTROL_RINGING:
03675 if (ast->_state == AST_STATE_RING) {
03676 p->invitestate = INV_EARLY_MEDIA;
03677 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
03678 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
03679
03680 transmit_response(p, "180 Ringing", &p->initreq);
03681 ast_set_flag(&p->flags[0], SIP_RINGING);
03682 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
03683 break;
03684 } else {
03685
03686 }
03687 }
03688 res = -1;
03689 break;
03690 case AST_CONTROL_BUSY:
03691 if (ast->_state != AST_STATE_UP) {
03692 transmit_response(p, "486 Busy Here", &p->initreq);
03693 p->invitestate = INV_COMPLETED;
03694 sip_alreadygone(p);
03695 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
03696 break;
03697 }
03698 res = -1;
03699 break;
03700 case AST_CONTROL_CONGESTION:
03701 if (ast->_state != AST_STATE_UP) {
03702 transmit_response(p, "503 Service Unavailable", &p->initreq);
03703 p->invitestate = INV_COMPLETED;
03704 sip_alreadygone(p);
03705 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
03706 break;
03707 }
03708 res = -1;
03709 break;
03710 case AST_CONTROL_PROCEEDING:
03711 if ((ast->_state != AST_STATE_UP) &&
03712 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03713 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03714 transmit_response(p, "100 Trying", &p->initreq);
03715 p->invitestate = INV_PROCEEDING;
03716 break;
03717 }
03718 res = -1;
03719 break;
03720 case AST_CONTROL_PROGRESS:
03721 if ((ast->_state != AST_STATE_UP) &&
03722 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
03723 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
03724 p->invitestate = INV_EARLY_MEDIA;
03725 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
03726 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
03727 break;
03728 }
03729 res = -1;
03730 break;
03731 case AST_CONTROL_HOLD:
03732 ast_moh_start(ast, data, p->mohinterpret);
03733 break;
03734 case AST_CONTROL_UNHOLD:
03735 ast_moh_stop(ast);
03736 break;
03737 case AST_CONTROL_VIDUPDATE:
03738 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
03739 transmit_info_with_vidupdate(p);
03740
03741 } else
03742 res = -1;
03743 break;
03744 case -1:
03745 res = -1;
03746 break;
03747 default:
03748 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
03749 res = -1;
03750 break;
03751 }
03752 ast_mutex_unlock(&p->lock);
03753 return res;
03754 }
03755
03756
03757
03758
03759
03760
03761
03762
03763 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
03764 {
03765 struct ast_channel *tmp;
03766 struct ast_variable *v = NULL;
03767 int fmt;
03768 int what;
03769 int needvideo = 0;
03770 {
03771 const char *my_name;
03772
03773 if (title)
03774 my_name = title;
03775 else if ( (my_name = strchr(i->fromdomain,':')) )
03776 my_name++;
03777 else
03778 my_name = i->fromdomain;
03779
03780 ast_mutex_unlock(&i->lock);
03781
03782 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);
03783
03784 }
03785 if (!tmp) {
03786 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
03787 return NULL;
03788 }
03789 ast_mutex_lock(&i->lock);
03790
03791 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO)
03792 tmp->tech = &sip_tech_info;
03793 else
03794 tmp->tech = &sip_tech;
03795
03796
03797
03798 if (i->jointcapability)
03799 what = i->jointcapability;
03800 else if (i->capability)
03801 what = i->capability;
03802 else
03803 what = global_capability;
03804
03805
03806 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
03807 if (option_debug > 2) {
03808 char buf[BUFSIZ];
03809 ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, tmp->nativeformats));
03810 ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->jointcapability));
03811 ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->capability));
03812 ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, ast_codec_choose(&i->prefs, what, 1)));
03813 if (i->prefcodec)
03814 ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->prefcodec));
03815 }
03816
03817
03818 fmt = ast_best_codec(tmp->nativeformats);
03819
03820
03821
03822
03823
03824 if (i->vrtp) {
03825 if (i->prefcodec)
03826 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
03827 else
03828 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
03829 }
03830
03831 if (option_debug > 2) {
03832 if (needvideo)
03833 ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
03834 else
03835 ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
03836 }
03837
03838
03839
03840 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
03841 i->vad = ast_dsp_new();
03842 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
03843 if (global_relaxdtmf)
03844 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
03845 }
03846 if (i->rtp) {
03847 tmp->fds[0] = ast_rtp_fd(i->rtp);
03848 tmp->fds[1] = ast_rtcp_fd(i->rtp);
03849 }
03850 if (needvideo && i->vrtp) {
03851 tmp->fds[2] = ast_rtp_fd(i->vrtp);
03852 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
03853 }
03854 if (i->udptl) {
03855 tmp->fds[5] = ast_udptl_fd(i->udptl);
03856 }
03857 if (state == AST_STATE_RING)
03858 tmp->rings = 1;
03859 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
03860 tmp->writeformat = fmt;
03861 tmp->rawwriteformat = fmt;
03862 tmp->readformat = fmt;
03863 tmp->rawreadformat = fmt;
03864 tmp->tech_pvt = i;
03865
03866 tmp->callgroup = i->callgroup;
03867 tmp->pickupgroup = i->pickupgroup;
03868 tmp->cid.cid_pres = i->callingpres;
03869 if (!ast_strlen_zero(i->accountcode))
03870 ast_string_field_set(tmp, accountcode, i->accountcode);
03871 if (i->amaflags)
03872 tmp->amaflags = i->amaflags;
03873 if (!ast_strlen_zero(i->language))
03874 ast_string_field_set(tmp, language, i->language);
03875 i->owner = tmp;
03876 ast_module_ref(ast_module_info->self);
03877 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
03878 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
03879
03880
03881
03882
03883 tmp->cid.cid_num = ast_strdup(i->cid_num);
03884 tmp->cid.cid_ani = ast_strdup(i->cid_num);
03885 tmp->cid.cid_name = ast_strdup(i->cid_name);
03886 if (!ast_strlen_zero(i->rdnis))
03887 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
03888
03889 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
03890 tmp->cid.cid_dnid = ast_strdup(i->exten);
03891
03892 tmp->priority = 1;
03893 if (!ast_strlen_zero(i->uri))
03894 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
03895 if (!ast_strlen_zero(i->domain))
03896 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
03897 if (!ast_strlen_zero(i->useragent))
03898 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
03899 if (!ast_strlen_zero(i->callid))
03900 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
03901 if (i->rtp)
03902 ast_jb_configure(tmp, &global_jbconf);
03903 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
03904 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
03905 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
03906 ast_hangup(tmp);
03907 tmp = NULL;
03908 }
03909
03910 for (v = i->chanvars ; v ; v = v->next)
03911 pbx_builtin_setvar_helper(tmp,v->name,v->value);
03912
03913 if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
03914 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
03915
03916 return tmp;
03917 }
03918
03919
03920 static char *get_body_by_line(const char *line, const char *name, int nameLen)
03921 {
03922 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
03923 return ast_skip_blanks(line + nameLen + 1);
03924
03925 return "";
03926 }
03927
03928
03929
03930
03931
03932 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
03933 {
03934 int len = strlen(name);
03935
03936 while (*start < req->sdp_end) {
03937 const char *r = get_body_by_line(req->line[(*start)++], name, len);
03938 if (r[0] != '\0')
03939 return r;
03940 }
03941
03942 return "";
03943 }
03944
03945
03946 static const char *get_sdp(struct sip_request *req, const char *name)
03947 {
03948 int dummy = 0;
03949
03950 return get_sdp_iterate(&dummy, req, name);
03951 }
03952
03953
03954 static char *get_body(struct sip_request *req, char *name)
03955 {
03956 int x;
03957 int len = strlen(name);
03958 char *r;
03959
03960 for (x = 0; x < req->lines; x++) {
03961 r = get_body_by_line(req->line[x], name, len);
03962 if (r[0] != '\0')
03963 return r;
03964 }
03965
03966 return "";
03967 }
03968
03969
03970 static const char *find_alias(const char *name, const char *_default)
03971 {
03972
03973 static const struct cfalias {
03974 char * const fullname;
03975 char * const shortname;
03976 } aliases[] = {
03977 { "Content-Type", "c" },
03978 { "Content-Encoding", "e" },
03979 { "From", "f" },
03980 { "Call-ID", "i" },
03981 { "Contact", "m" },
03982 { "Content-Length", "l" },
03983 { "Subject", "s" },
03984 { "To", "t" },
03985 { "Supported", "k" },
03986 { "Refer-To", "r" },
03987 { "Referred-By", "b" },
03988 { "Allow-Events", "u" },
03989 { "Event", "o" },
03990 { "Via", "v" },
03991 { "Accept-Contact", "a" },
03992 { "Reject-Contact", "j" },
03993 { "Request-Disposition", "d" },
03994 { "Session-Expires", "x" },
03995 { "Identity", "y" },
03996 { "Identity-Info", "n" },
03997 };
03998 int x;
03999
04000 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
04001 if (!strcasecmp(aliases[x].fullname, name))
04002 return aliases[x].shortname;
04003
04004 return _default;
04005 }
04006
04007 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
04008 {
04009 int pass;
04010
04011
04012
04013
04014
04015
04016
04017
04018
04019
04020 for (pass = 0; name && pass < 2;pass++) {
04021 int x, len = strlen(name);
04022 for (x=*start; x<req->headers; x++) {
04023 if (!strncasecmp(req->header[x], name, len)) {
04024 char *r = req->header[x] + len;
04025 if (pedanticsipchecking)
04026 r = ast_skip_blanks(r);
04027
04028 if (*r == ':') {
04029 *start = x+1;
04030 return ast_skip_blanks(r+1);
04031 }
04032 }
04033 }
04034 if (pass == 0)
04035 name = find_alias(name, NULL);
04036 }
04037
04038
04039 return "";
04040 }
04041
04042
04043 static const char *get_header(const struct sip_request *req, const char *name)
04044 {
04045 int start = 0;
04046 return __get_header(req, name, &start);
04047 }
04048
04049
04050 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
04051 {
04052
04053 struct ast_frame *f;
04054
04055 if (!p->rtp) {
04056
04057 return &ast_null_frame;
04058 }
04059
04060 switch(ast->fdno) {
04061 case 0:
04062 f = ast_rtp_read(p->rtp);
04063 break;
04064 case 1:
04065 f = ast_rtcp_read(p->rtp);
04066 break;
04067 case 2:
04068 f = ast_rtp_read(p->vrtp);
04069 break;
04070 case 3:
04071 f = ast_rtcp_read(p->vrtp);
04072 break;
04073 case 5:
04074 f = ast_udptl_read(p->udptl);
04075 break;
04076 default:
04077 f = &ast_null_frame;
04078 }
04079
04080 if (f && (f->frametype == AST_FRAME_DTMF) &&
04081 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
04082 return &ast_null_frame;
04083
04084
04085 if (!p->owner || f->frametype != AST_FRAME_VOICE)
04086 return f;
04087
04088 if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
04089 if (!(f->subclass & p->jointcapability)) {
04090 if (option_debug) {
04091 ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
04092 ast_getformatname(f->subclass), p->owner->name);
04093 }
04094 return &ast_null_frame;
04095 }
04096 if (option_debug)
04097 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
04098 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
04099 ast_set_read_format(p->owner, p->owner->readformat);
04100 ast_set_write_format(p->owner, p->owner->writeformat);
04101 }
04102
04103 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
04104 f = ast_dsp_process(p->owner, p->vad, f);
04105 if (f && f->frametype == AST_FRAME_DTMF) {
04106 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
04107 if (option_debug)
04108 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
04109 *faxdetect = 1;
04110 } else if (option_debug) {
04111 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
04112 }
04113 }
04114 }
04115
04116 return f;
04117 }
04118
04119
04120 static struct ast_frame *sip_read(struct ast_channel *ast)
04121 {
04122 struct ast_frame *fr;
04123 struct sip_pvt *p;
04124
04125 if( ast == NULL )
04126 return NULL;
04127
04128 p = ast->tech_pvt;
04129 int faxdetected = FALSE;
04130
04131 if( p == NULL )
04132 return NULL;
04133
04134 ast_mutex_lock(&p->lock);
04135 fr = sip_rtp_read(ast, p, &faxdetected);
04136 p->lastrtprx = time(NULL);
04137
04138
04139
04140 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
04141 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
04142 if (!p->pendinginvite) {
04143 if (option_debug > 2)
04144 ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
04145 p->t38.state = T38_LOCAL_REINVITE;
04146 transmit_reinvite_with_t38_sdp(p);
04147 if (option_debug > 1)
04148 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
04149 }
04150 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04151 if (option_debug > 2)
04152 ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
04153 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04154 }
04155 }
04156
04157 ast_mutex_unlock(&p->lock);
04158 return fr;
04159 }
04160
04161
04162
04163 static char *generate_random_string(char *buf, size_t size)
04164 {
04165 long val[4];
04166 int x;
04167
04168 for (x=0; x<4; x++)
04169 val[x] = ast_random();
04170 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
04171
04172 return buf;
04173 }
04174
04175
04176 static void build_callid_pvt(struct sip_pvt *pvt)
04177 {
04178 char buf[33];
04179
04180 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip));
04181
04182 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
04183
04184 }
04185
04186
04187 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
04188 {
04189 char buf[33];
04190
04191 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
04192
04193 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
04194 }
04195
04196
04197 static void make_our_tag(char *tagbuf, size_t len)
04198 {
04199 snprintf(tagbuf, len, "as%08lx", ast_random());
04200 }
04201
04202
04203 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
04204 int useglobal_nat, const int intended_method)
04205 {
04206 struct sip_pvt *p;
04207
04208 if (!(p = ast_calloc(1, sizeof(*p))))
04209 return NULL;
04210
04211 if (ast_string_field_init(p, 512)) {
04212 free(p);
04213 return NULL;
04214 }
04215
04216 ast_mutex_init(&p->lock);
04217
04218 p->method = intended_method;
04219 p->initid = -1;
04220 p->autokillid = -1;
04221 p->subscribed = NONE;
04222 p->stateid = -1;
04223 p->prefs = default_prefs;
04224
04225 if (intended_method != SIP_OPTIONS)
04226 p->timer_t1 = 500;
04227
04228 if (sin) {
04229 p->sa = *sin;
04230 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
04231 p->ourip = __ourip;
04232 } else
04233 p->ourip = __ourip;
04234
04235
04236 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
04237 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04238
04239 ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);
04240
04241 p->branch = ast_random();
04242 make_our_tag(p->tag, sizeof(p->tag));
04243 p->ocseq = INITIAL_CSEQ;
04244
04245 if (sip_methods[intended_method].need_rtp) {
04246 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
04247
04248 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
04249 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
04250 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
04251 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
04252 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
04253 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
04254 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
04255 ast_mutex_destroy(&p->lock);
04256 if (p->chanvars) {
04257 ast_variables_destroy(p->chanvars);
04258 p->chanvars = NULL;
04259 }
04260 free(p);
04261 return NULL;
04262 }
04263 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04264 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04265 ast_rtp_settos(p->rtp, global_tos_audio);
04266 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
04267 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
04268 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
04269 if (p->vrtp) {
04270 ast_rtp_settos(p->vrtp, global_tos_video);
04271 ast_rtp_setdtmf(p->vrtp, 0);
04272 ast_rtp_setdtmfcompensate(p->vrtp, 0);
04273 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
04274 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
04275 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
04276 }
04277 if (p->udptl)
04278 ast_udptl_settos(p->udptl, global_tos_audio);
04279 p->maxcallbitrate = default_maxcallbitrate;
04280 }
04281
04282 if (useglobal_nat && sin) {
04283
04284 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
04285 p->recv = *sin;
04286 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04287 }
04288
04289 if (p->method != SIP_REGISTER)
04290 ast_string_field_set(p, fromdomain, default_fromdomain);
04291 build_via(p);
04292 if (!callid)
04293 build_callid_pvt(p);
04294 else
04295 ast_string_field_set(p, callid, callid);
04296
04297 ast_string_field_set(p, mohinterpret, default_mohinterpret);
04298 ast_string_field_set(p, mohsuggest, default_mohsuggest);
04299 p->capability = global_capability;
04300 p->allowtransfer = global_allowtransfer;
04301 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
04302 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
04303 p->noncodeccapability |= AST_RTP_DTMF;
04304 if (p->udptl) {
04305 p->t38.capability = global_t38_capability;
04306 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
04307 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
04308 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
04309 p->t38.capability |= T38FAX_UDP_EC_FEC;
04310 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
04311 p->t38.capability |= T38FAX_UDP_EC_NONE;
04312 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
04313 p->t38.jointcapability = p->t38.capability;
04314 }
04315 ast_string_field_set(p, context, default_context);
04316
04317
04318 ast_mutex_lock(&iflock);
04319 p->next = iflist;
04320 iflist = p;
04321 ast_mutex_unlock(&iflock);
04322 if (option_debug)
04323 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");
04324 return p;
04325 }
04326
04327
04328
04329 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
04330 {
04331 struct sip_pvt *p = NULL;
04332 char *tag = "";
04333 char totag[128];
04334 char fromtag[128];
04335 const char *callid = get_header(req, "Call-ID");
04336 const char *from = get_header(req, "From");
04337 const char *to = get_header(req, "To");
04338 const char *cseq = get_header(req, "Cseq");
04339
04340
04341
04342 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
04343 ast_strlen_zero(from) || ast_strlen_zero(cseq))
04344 return NULL;
04345
04346 if (pedanticsipchecking) {
04347
04348
04349
04350
04351
04352
04353 if (gettag(req, "To", totag, sizeof(totag)))
04354 ast_set_flag(req, SIP_PKT_WITH_TOTAG);
04355 gettag(req, "From", fromtag, sizeof(fromtag));
04356
04357 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
04358
04359 if (option_debug > 4 )
04360 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);
04361 }
04362
04363 ast_mutex_lock(&iflock);
04364 for (p = iflist; p; p = p->next) {
04365
04366 int found = FALSE;
04367 if (ast_strlen_zero(p->callid))
04368 continue;
04369 if (req->method == SIP_REGISTER)
04370 found = (!strcmp(p->callid, callid));
04371 else
04372 found = (!strcmp(p->callid, callid) &&
04373 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
04374
04375 if (option_debug > 4)
04376 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);
04377
04378
04379 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) {
04380 if (p->tag[0] == '\0' && totag[0]) {
04381
04382 found = FALSE;
04383 } else if (totag[0]) {
04384 if (strcmp(totag, p->tag)) {
04385 found = FALSE;
04386 }
04387 }
04388 if (!found && option_debug > 4)
04389 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);
04390 }
04391
04392
04393 if (found) {
04394
04395 ast_mutex_unlock(&iflock);
04396 ast_mutex_lock(&p->lock);
04397 return p;
04398 }
04399 }
04400 ast_mutex_unlock(&iflock);
04401
04402
04403 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
04404 if (intended_method == SIP_REFER) {
04405
04406 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
04407 } else if (intended_method == SIP_NOTIFY) {
04408
04409
04410 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
04411 } else {
04412
04413 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
04414
04415 ast_mutex_lock(&p->lock);
04416 } else {
04417
04418
04419
04420
04421
04422
04423
04424
04425 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
04426 if (option_debug > 3)
04427 ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
04428 }
04429 }
04430 return p;
04431 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
04432
04433 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
04434 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
04435
04436
04437
04438 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
04439 }
04440
04441
04442
04443 return p;
04444 }
04445
04446
04447 static int sip_register(char *value, int lineno)
04448 {
04449 struct sip_registry *reg;
04450 int portnum = 0;
04451 char username[256] = "";
04452 char *hostname=NULL, *secret=NULL, *authuser=NULL;
04453 char *porta=NULL;
04454 char *contact=NULL;
04455
04456 if (!value)
04457 return -1;
04458 ast_copy_string(username, value, sizeof(username));
04459
04460 hostname = strrchr(username, '@');
04461 if (hostname)
04462 *hostname++ = '\0';
04463 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
04464 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
04465 return -1;
04466 }
04467
04468 secret = strchr(username, ':');
04469 if (secret) {
04470 *secret++ = '\0';
04471 authuser = strchr(secret, ':');
04472 if (authuser)
04473 *authuser++ = '\0';
04474 }
04475
04476 contact = strchr(hostname, '/');
04477 if (contact)
04478 *contact++ = '\0';
04479 if (ast_strlen_zero(contact))
04480 contact = "s";
04481 porta = strchr(hostname, ':');
04482 if (porta) {
04483 *porta++ = '\0';
04484 portnum = atoi(porta);
04485 if (portnum == 0) {
04486 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
04487 return -1;
04488 }
04489 }
04490 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
04491 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
04492 return -1;
04493 }
04494
04495 if (ast_string_field_init(reg, 256)) {
04496 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
04497 free(reg);
04498 return -1;
04499 }
04500
04501 regobjs++;
04502 ASTOBJ_INIT(reg);
04503 ast_string_field_set(reg, contact, contact);
04504 if (username)
04505 ast_string_field_set(reg, username, username);
04506 if (hostname)
04507 ast_string_field_set(reg, hostname, hostname);
04508 if (authuser)
04509 ast_string_field_set(reg, authuser, authuser);
04510 if (secret)
04511 ast_string_field_set(reg, secret, secret);
04512 reg->expire = -1;
04513 reg->timeout = -1;
04514 reg->refresh = default_expiry;
04515 reg->portno = portnum;
04516 reg->callid_valid = FALSE;
04517 reg->ocseq = INITIAL_CSEQ;
04518 ASTOBJ_CONTAINER_LINK(®l, reg);
04519 ASTOBJ_UNREF(reg,sip_registry_destroy);
04520 return 0;
04521 }
04522
04523
04524
04525 static int lws2sws(char *msgbuf, int len)
04526 {
04527 int h = 0, t = 0;
04528 int lws = 0;
04529
04530 for (; h < len;) {
04531
04532 if (msgbuf[h] == '\r') {
04533 h++;
04534 continue;
04535 }
04536
04537 if (msgbuf[h] == '\n') {
04538
04539 if (h + 1 == len)
04540 break;
04541
04542 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
04543
04544 h++;
04545 continue;
04546 }
04547
04548 msgbuf[t++] = msgbuf[h++];
04549 lws = 0;
04550 continue;
04551 }
04552 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
04553 if (lws) {
04554 h++;
04555 continue;
04556 }
04557 msgbuf[t++] = msgbuf[h++];
04558 lws = 1;
04559 continue;
04560 }
04561 msgbuf[t++] = msgbuf[h++];
04562 if (lws)
04563 lws = 0;
04564 }
04565 msgbuf[t] = '\0';
04566 return t;
04567 }
04568
04569
04570
04571
04572 static void parse_request(struct sip_request *req)
04573 {
04574
04575 char *c;
04576 int f = 0;
04577
04578 c = req->data;
04579
04580
04581 req->header[f] = c;
04582 while(*c) {
04583 if (*c == '\n') {
04584
04585 *c = 0;
04586
04587 if (sipdebug && option_debug > 3)
04588 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
04589 if (ast_strlen_zero(req->header[f])) {
04590
04591 c++;
04592 break;
04593 }
04594 if (f >= SIP_MAX_HEADERS - 1) {
04595 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
04596 } else
04597 f++;
04598 req->header[f] = c + 1;
04599 } else if (*c == '\r') {
04600
04601 *c = 0;
04602 }
04603 c++;
04604 }
04605
04606 if (!ast_strlen_zero(req->header[f])) {
04607 if (sipdebug && option_debug > 3)
04608 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
04609 f++;
04610 }
04611 req->headers = f;
04612
04613 f = 0;
04614 req->line[f] = c;
04615 while(*c) {
04616 if (*c == '\n') {
04617
04618 *c = 0;
04619 if (sipdebug && option_debug > 3)
04620 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
04621 if (f >= SIP_MAX_LINES - 1) {
04622 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
04623 } else
04624 f++;
04625 req->line[f] = c + 1;
04626 } else if (*c == '\r') {
04627
04628 *c = 0;
04629 }
04630 c++;
04631 }
04632
04633 if (!ast_strlen_zero(req->line[f]))
04634 f++;
04635 req->lines = f;
04636 if (*c)
04637 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
04638
04639 determine_firstline_parts(req);
04640 }
04641
04642
04643
04644
04645
04646
04647
04648
04649
04650 static int find_sdp(struct sip_request *req)
04651 {
04652 const char *content_type;
04653 const char *search;
04654 char *boundary;
04655 unsigned int x;
04656 int boundaryisquoted = FALSE;
04657
04658 content_type = get_header(req, "Content-Type");
04659
04660
04661 if (!strcasecmp(content_type, "application/sdp")) {
04662 req->sdp_start = 0;
04663 req->sdp_end = req->lines;
04664 return 1;
04665 }
04666
04667
04668 if (strncasecmp(content_type, "multipart/mixed", 15))
04669 return 0;
04670
04671
04672 if (!(search = strcasestr(content_type, ";boundary=")))
04673 return 0;
04674
04675 search += 10;
04676 if (ast_strlen_zero(search))
04677 return 0;
04678
04679
04680 if (*search == '\"') {
04681 search++;
04682 boundaryisquoted = TRUE;
04683 }
04684
04685
04686
04687 boundary = ast_strdupa(search - 2);
04688 boundary[0] = boundary[1] = '-';
04689
04690
04691 if (boundaryisquoted)
04692 boundary[strlen(boundary) - 1] = '\0';
04693
04694
04695
04696
04697 for (x = 0; x < (req->lines - 2); x++) {
04698 if (!strncasecmp(req->line[x], boundary, strlen(boundary)) &&
04699 !strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) {
04700 x += 2;
04701 req->sdp_start = x;
04702
04703
04704 for ( ; x < req->lines; x++) {
04705 if (!strncasecmp(req->line[x], boundary, strlen(boundary)))
04706 break;
04707 }
04708 req->sdp_end = x;
04709 return 1;
04710 }
04711 }
04712
04713 return 0;
04714 }
04715
04716
04717
04718
04719
04720
04721 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
04722 {
04723 const char *m;
04724 const char *c;
04725 const char *a;
04726 char host[258];
04727 int len = -1;
04728 int portno = -1;
04729 int vportno = -1;
04730 int udptlportno = -1;
04731 int peert38capability = 0;
04732 char s[256];
04733 int old = 0;
04734
04735
04736 int peercapability = 0, peernoncodeccapability = 0;
04737 int vpeercapability = 0, vpeernoncodeccapability = 0;
04738 struct sockaddr_in sin;
04739 struct sockaddr_in vsin;
04740
04741 const char *codecs;
04742 struct hostent *hp;
04743 struct hostent *vhp = NULL;
04744 struct ast_hostent audiohp;
04745 struct ast_hostent videohp;
04746 int codec;
04747 int destiterator = 0;
04748 int iterator;
04749 int sendonly = -1;
04750 int numberofports;
04751 struct ast_rtp *newaudiortp, *newvideortp;
04752 int newjointcapability;
04753 int newpeercapability;
04754 int newnoncodeccapability;
04755 int numberofmediastreams = 0;
04756 int debug = sip_debug_test_pvt(p);
04757
04758 int found_rtpmap_codecs[32];
04759 int last_rtpmap_codec=0;
04760
04761 if (!p->rtp) {
04762 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
04763 return -1;
04764 }
04765
04766
04767 newaudiortp = alloca(ast_rtp_alloc_size());
04768 memset(newaudiortp, 0, ast_rtp_alloc_size());
04769 ast_rtp_new_init(newaudiortp);
04770 ast_rtp_pt_clear(newaudiortp);
04771
04772 newvideortp = alloca(ast_rtp_alloc_size());
04773 memset(newvideortp, 0, ast_rtp_alloc_size());
04774 ast_rtp_new_init(newvideortp);
04775 ast_rtp_pt_clear(newvideortp);
04776
04777
04778 p->lastrtprx = p->lastrtptx = time(NULL);
04779
04780
04781
04782 m = get_sdp(req, "m");
04783 destiterator = req->sdp_start;
04784 c = get_sdp_iterate(&destiterator, req, "c");
04785 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
04786 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
04787 return -1;
04788 }
04789
04790
04791 if (sscanf(c, "IN IP4 %256s", host) != 1) {
04792 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
04793 return -1;
04794 }
04795
04796
04797 hp = ast_gethostbyname(host, &audiohp);
04798 if (!hp) {
04799 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
04800 return -1;
04801 }
04802 vhp = hp;
04803
04804 iterator = req->sdp_start;
04805 ast_set_flag(&p->flags[0], SIP_NOVIDEO);
04806
04807
04808
04809 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
04810 int x;
04811 int audio = FALSE;
04812
04813 numberofports = 1;
04814 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
04815 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
04816 audio = TRUE;
04817 numberofmediastreams++;
04818
04819 portno = x;
04820
04821 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
04822 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
04823 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
04824 return -1;
04825 }
04826 if (debug)
04827 ast_verbose("Found RTP audio format %d\n", codec);
04828 ast_rtp_set_m_type(newaudiortp, codec);
04829 }
04830 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
04831 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
04832
04833 ast_clear_flag(&p->flags[0], SIP_NOVIDEO);
04834 numberofmediastreams++;
04835 vportno = x;
04836
04837 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
04838 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
04839 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
04840 return -1;
04841 }
04842 if (debug)
04843 ast_verbose("Found RTP video format %d\n", codec);
04844 ast_rtp_set_m_type(newvideortp, codec);
04845 }
04846 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
04847 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
04848 if (debug)
04849 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
04850 udptlportno = x;
04851 numberofmediastreams++;
04852
04853 if (p->owner && p->lastinvite) {
04854 p->t38.state = T38_PEER_REINVITE;
04855 if (option_debug > 1)
04856 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
04857 } else {
04858 p->t38.state = T38_PEER_DIRECT;
04859 if (option_debug > 1)
04860 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
04861 }
04862 } else
04863 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
04864 if (numberofports > 1)
04865 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
04866
04867
04868
04869 c = get_sdp_iterate(&destiterator, req, "c");
04870 if (!ast_strlen_zero(c)) {
04871 if (sscanf(c, "IN IP4 %256s", host) != 1) {
04872 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
04873 } else {
04874
04875 if (audio) {
04876 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
04877 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
04878 return -2;
04879 }
04880 } else if (!(vhp = ast_gethostbyname(host, &videohp))) {
04881 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
04882 return -2;
04883 }
04884 }
04885
04886 }
04887 }
04888 if (portno == -1 && vportno == -1 && udptlportno == -1)
04889
04890
04891 return -2;
04892
04893 if (numberofmediastreams > 2)
04894
04895 return -3;
04896
04897
04898 sin.sin_family = AF_INET;
04899 vsin.sin_family = AF_INET;
04900 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
04901 if (vhp)
04902 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
04903
04904
04905 if (p->udptl) {
04906 if (udptlportno > 0) {
04907 sin.sin_port = htons(udptlportno);
04908 ast_udptl_set_peer(p->udptl, &sin);
04909 if (debug)
04910 ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
04911 } else {
04912 ast_udptl_stop(p->udptl);
04913 if (debug)
04914 ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
04915 }
04916 }
04917
04918
04919 if (p->rtp) {
04920 if (portno > 0) {
04921 sin.sin_port = htons(portno);
04922 ast_rtp_set_peer(p->rtp, &sin);
04923 if (debug)
04924 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
04925 } else {
04926 if (udptlportno > 0) {
04927 if (debug)
04928 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
04929 } else {
04930 ast_rtp_stop(p->rtp);
04931 if (debug)
04932 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
04933 }
04934 }
04935 }
04936
04937 if (vportno != -1)
04938 vsin.sin_port = htons(vportno);
04939
04940
04941
04942
04943
04944 iterator = req->sdp_start;
04945 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
04946 char* mimeSubtype = ast_strdupa(a);
04947 if (option_debug > 1) {
04948 int breakout = FALSE;
04949
04950
04951 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
04952 if (debug)
04953 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
04954 breakout = TRUE;
04955 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
04956
04957
04958
04959
04960 if (debug)
04961 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
04962 breakout = TRUE;
04963 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
04964
04965 if (debug)
04966 ast_verbose("Got unsupported a:framerate in SDP offer \n");
04967 breakout = TRUE;
04968 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
04969
04970 if (debug)
04971 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
04972 breakout = TRUE;
04973 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
04974
04975 if (debug)
04976 ast_verbose("Got unsupported a:crypto in SDP offer \n");
04977 breakout = TRUE;
04978 }
04979 if (breakout)
04980 continue;
04981 }
04982 if (!strcasecmp(a, "sendonly")) {
04983 if (sendonly == -1)
04984 sendonly = 1;
04985 continue;
04986 } else if (!strcasecmp(a, "inactive")) {
04987 if (sendonly == -1)
04988 sendonly = 2;
04989 continue;
04990 } else if (!strcasecmp(a, "sendrecv")) {
04991 if (sendonly == -1)
04992 sendonly = 0;
04993 continue;
04994 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
04995 char *tmp = strrchr(a, ':');
04996 long int framing = 0;
04997 if (tmp) {
04998 tmp++;
04999 framing = strtol(tmp, NULL, 10);
05000 if (framing == LONG_MIN || framing == LONG_MAX) {
05001 framing = 0;
05002 if (option_debug)
05003 ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
05004 }
05005 }
05006 if (framing && last_rtpmap_codec) {
05007 if (p->autoframing) {
05008 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
05009 int codec_n;
05010 int format = 0;
05011 for (codec_n = 0; codec_n < last_rtpmap_codec; codec_n++) {
05012 format = ast_rtp_codec_getformat(found_rtpmap_codecs[codec_n]);
05013 if (!format)
05014 continue;
05015 if (option_debug)
05016 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
05017 ast_codec_pref_setsize(pref, format, framing);
05018 }
05019 ast_rtp_codec_setpref(p->rtp, pref);
05020 }
05021 }
05022 memset(&found_rtpmap_codecs, 0, sizeof(found_rtpmap_codecs));
05023 last_rtpmap_codec = 0;
05024 continue;
05025 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
05026
05027 if (debug)
05028 ast_verbose("Found description format %s for ID %d\n", mimeSubtype, codec);
05029 found_rtpmap_codecs[last_rtpmap_codec] = codec;
05030 last_rtpmap_codec++;
05031
05032
05033 ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
05034 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0);
05035 if (p->vrtp)
05036 ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0);
05037 }
05038 }
05039
05040 if (udptlportno != -1) {
05041 int found = 0, x;
05042
05043 old = 0;
05044
05045
05046 iterator = req->sdp_start;
05047 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
05048 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
05049 found = 1;
05050 if (option_debug > 2)
05051 ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
05052 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
05053 found = 1;
05054 if (option_debug > 2)
05055 ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
05056 switch (x) {
05057 case 14400:
05058 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05059 break;
05060 case 12000:
05061 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05062 break;
05063 case 9600:
05064 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05065 break;
05066 case 7200:
05067 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
05068 break;
05069 case 4800:
05070 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
05071 break;
05072 case 2400:
05073 peert38capability |= T38FAX_RATE_2400;
05074 break;
05075 }
05076 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
05077 found = 1;
05078 if (option_debug > 2)
05079 ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
05080 if (x == 0)
05081 peert38capability |= T38FAX_VERSION_0;
05082 else if (x == 1)
05083 peert38capability |= T38FAX_VERSION_1;
05084 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
05085 found = 1;
05086 if (option_debug > 2)
05087 ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
05088 ast_udptl_set_far_max_datagram(p->udptl, x);
05089 ast_udptl_set_local_max_datagram(p->udptl, x);
05090 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
05091 found = 1;
05092 if (option_debug > 2)
05093 ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
05094 if (x == 1)
05095 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
05096 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
05097 found = 1;
05098 if (option_debug > 2)
05099 ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
05100 if (x == 1)
05101 peert38capability |= T38FAX_TRANSCODING_MMR;
05102 }
05103 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
05104 found = 1;
05105 if (option_debug > 2)
05106 ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
05107 if (x == 1)
05108 peert38capability |= T38FAX_TRANSCODING_JBIG;
05109 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
05110 found = 1;
05111 if (option_debug > 2)
05112 ast_log(LOG_DEBUG, "RateManagement: %s\n", s);
05113 if (!strcasecmp(s, "localTCF"))
05114 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
05115 else if (!strcasecmp(s, "transferredTCF"))
05116 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
05117 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
05118 found = 1;
05119 if (option_debug > 2)
05120 ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
05121 if (!strcasecmp(s, "t38UDPRedundancy")) {
05122 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
05123 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05124 } else if (!strcasecmp(s, "t38UDPFEC")) {
05125 peert38capability |= T38FAX_UDP_EC_FEC;
05126 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05127 } else {
05128 peert38capability |= T38FAX_UDP_EC_NONE;
05129 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05130 }
05131 }
05132 }
05133 if (found) {
05134 p->t38.peercapability = peert38capability;
05135 p->t38.jointcapability = (peert38capability & 255);
05136 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
05137 p->t38.jointcapability |= (peert38capability & p->t38.capability);
05138 }
05139 if (debug)
05140 ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
05141 p->t38.capability,
05142 p->t38.peercapability,
05143 p->t38.jointcapability);
05144 } else {
05145 p->t38.state = T38_DISABLED;
05146 if (option_debug > 2)
05147 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
05148 }
05149
05150
05151 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
05152 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
05153
05154 newjointcapability = p->capability & (peercapability | vpeercapability);
05155 newpeercapability = (peercapability | vpeercapability);
05156 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
05157
05158
05159 if (debug) {
05160
05161 char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ], s4[BUFSIZ];
05162
05163 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
05164 ast_getformatname_multiple(s1, BUFSIZ, p->capability),
05165 ast_getformatname_multiple(s2, BUFSIZ, newpeercapability),
05166 ast_getformatname_multiple(s3, BUFSIZ, vpeercapability),
05167 ast_getformatname_multiple(s4, BUFSIZ, newjointcapability));
05168
05169 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
05170 ast_rtp_lookup_mime_multiple(s1, BUFSIZ, p->noncodeccapability, 0, 0),
05171 ast_rtp_lookup_mime_multiple(s2, BUFSIZ, peernoncodeccapability, 0, 0),
05172 ast_rtp_lookup_mime_multiple(s3, BUFSIZ, newnoncodeccapability, 0, 0));
05173 }
05174 if (!newjointcapability) {
05175
05176 if (!p->t38.jointcapability) {
05177 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
05178
05179 return -1;
05180 } else {
05181 if (option_debug > 2)
05182 ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
05183 return 0;
05184 }
05185 }
05186
05187
05188
05189 p->jointcapability = newjointcapability;
05190 p->peercapability = newpeercapability;
05191 p->jointnoncodeccapability = newnoncodeccapability;
05192
05193 ast_rtp_pt_copy(p->rtp, newaudiortp);
05194 if (p->vrtp)
05195 ast_rtp_pt_copy(p->vrtp, newvideortp);
05196
05197 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
05198 ast_clear_flag(&p->flags[0], SIP_DTMF);
05199 if (newnoncodeccapability & AST_RTP_DTMF) {
05200
05201 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
05202
05203 ast_rtp_setdtmf(p->rtp, 1);
05204 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05205 } else {
05206 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
05207 }
05208 }
05209
05210
05211 if (p->rtp && sin.sin_port) {
05212 ast_rtp_set_peer(p->rtp, &sin);
05213 if (debug)
05214 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
05215 }
05216
05217
05218 if (p->vrtp && vsin.sin_port) {
05219 ast_rtp_set_peer(p->vrtp, &vsin);
05220 if (debug)
05221 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
05222 }
05223
05224
05225 if (option_debug > 1) {
05226 char buf[BUFSIZ];
05227 ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, BUFSIZ, p->jointcapability));
05228 }
05229
05230 if (!p->owner)
05231 return 0;
05232
05233 if (option_debug > 3)
05234 ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");
05235
05236 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05237 if (debug) {
05238 char s1[BUFSIZ], s2[BUFSIZ];
05239 ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
05240 ast_getformatname_multiple(s1, BUFSIZ, p->jointcapability),
05241 ast_getformatname_multiple(s2, BUFSIZ, p->owner->nativeformats));
05242 }
05243 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
05244 ast_set_read_format(p->owner, p->owner->readformat);
05245 ast_set_write_format(p->owner, p->owner->writeformat);
05246 }
05247
05248 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
05249 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
05250
05251 ast_queue_frame(p->owner, &ast_null_frame);
05252 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
05253 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
05254 S_OR(p->mohsuggest, NULL),
05255 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
05256 if (sendonly)
05257 ast_rtp_stop(p->rtp);
05258
05259
05260 ast_queue_frame(p->owner, &ast_null_frame);
05261 }
05262
05263
05264 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
05265 append_history(p, "Unhold", "%s", req->data);
05266 if (global_callevents)
05267 manager_event(EVENT_FLAG_CALL, "Unhold",
05268 "Channel: %s\r\n"
05269 "Uniqueid: %s\r\n",
05270 p->owner->name,
05271 p->owner->uniqueid);
05272 if (global_notifyhold)
05273 sip_peer_hold(p, 0);
05274 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
05275 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
05276
05277 append_history(p, "Hold", "%s", req->data);
05278
05279 if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05280 manager_event(EVENT_FLAG_CALL, "Hold",
05281 "Channel: %s\r\n"
05282 "Uniqueid: %s\r\n",
05283 p->owner->name,
05284 p->owner->uniqueid);
05285 }
05286 if (sendonly == 1)
05287 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
05288 else if (sendonly == 2)
05289 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
05290 else
05291 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
05292 if (global_notifyhold)
05293 sip_peer_hold(p, 1);
05294 }
05295
05296 return 0;
05297 }
05298
05299
05300
05301 static int add_header(struct sip_request *req, const char *var, const char *value)
05302 {
05303 int maxlen = sizeof(req->data) - 4 - req->len;
05304
05305 if (req->headers == SIP_MAX_HEADERS) {
05306 ast_log(LOG_WARNING, "Out of SIP header space\n");
05307 return -1;
05308 }
05309
05310 if (req->lines) {
05311 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
05312 return -1;
05313 }
05314
05315 if (maxlen <= 0) {
05316 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
05317 return -1;
05318 }
05319
05320 req->header[req->headers] = req->data + req->len;
05321
05322 if (compactheaders)
05323 var = find_alias(var, var);
05324
05325 snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
05326 req->len += strlen(req->header[req->headers]);
05327 req->headers++;
05328 if (req->headers < SIP_MAX_HEADERS)
05329 req->headers++;
05330 else
05331 ast_log(LOG_WARNING, "Out of SIP header space... Will generate broken SIP message\n");
05332
05333 return 0;
05334 }
05335
05336
05337 static int add_header_contentLength(struct sip_request *req, int len)
05338 {
05339 char clen[10];
05340
05341 snprintf(clen, sizeof(clen), "%d", len);
05342 return add_header(req, "Content-Length", clen);
05343 }
05344
05345
05346 static int add_line(struct sip_request *req, const char *line)
05347 {
05348 if (req->lines == SIP_MAX_LINES) {
05349 ast_log(LOG_WARNING, "Out of SIP line space\n");
05350 return -1;
05351 }
05352 if (!req->lines) {
05353
05354 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
05355 req->len += strlen(req->data + req->len);
05356 }
05357 if (req->len >= sizeof(req->data) - 4) {
05358 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
05359 return -1;
05360 }
05361 req->line[req->lines] = req->data + req->len;
05362 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
05363 req->len += strlen(req->line[req->lines]);
05364 req->lines++;
05365 return 0;
05366 }
05367
05368
05369 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
05370 {
05371 const char *tmp = get_header(orig, field);
05372
05373 if (!ast_strlen_zero(tmp))
05374 return add_header(req, field, tmp);
05375 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
05376 return -1;
05377 }
05378
05379
05380 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
05381 {
05382 int start = 0;
05383 int copied = 0;
05384 for (;;) {
05385 const char *tmp = __get_header(orig, field, &start);
05386
05387 if (ast_strlen_zero(tmp))
05388 break;
05389
05390 add_header(req, field, tmp);
05391 copied++;
05392 }
05393 return copied ? 0 : -1;
05394 }
05395
05396
05397
05398
05399
05400
05401
05402 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
05403 {
05404 int copied = 0;
05405 int start = 0;
05406
05407 for (;;) {
05408 char new[256];
05409 const char *oh = __get_header(orig, field, &start);
05410
05411 if (ast_strlen_zero(oh))
05412 break;
05413
05414 if (!copied) {
05415 char leftmost[256], *others, *rport;
05416
05417
05418 ast_copy_string(leftmost, oh, sizeof(leftmost));
05419 others = strchr(leftmost, ',');
05420 if (others)
05421 *others++ = '\0';
05422
05423
05424 rport = strstr(leftmost, ";rport");
05425 if (rport && *(rport+6) == '=')
05426 rport = NULL;
05427
05428
05429 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
05430
05431 char *end;
05432
05433 rport = strstr(leftmost, ";rport");
05434
05435 if (rport) {
05436 end = strchr(rport + 1, ';');
05437 if (end)
05438 memmove(rport, end, strlen(end) + 1);
05439 else
05440 *rport = '\0';
05441 }
05442
05443
05444 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
05445 leftmost, ast_inet_ntoa(p->recv.sin_addr),
05446 ntohs(p->recv.sin_port),
05447 others ? "," : "", others ? others : "");
05448 } else {
05449
05450 snprintf(new, sizeof(new), "%s;received=%s%s%s",
05451 leftmost, ast_inet_ntoa(p->recv.sin_addr),
05452 others ? "," : "", others ? others : "");
05453 }
05454 oh = new;
05455 }
05456 add_header(req, field, oh);
05457 copied++;
05458 }
05459 if (!copied) {
05460 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
05461 return -1;
05462 }
05463 return 0;
05464 }
05465
05466
05467 static void add_route(struct sip_request *req, struct sip_route *route)
05468 {
05469 char r[BUFSIZ*2], *p;
05470 int n, rem = sizeof(r);
05471
05472 if (!route)
05473 return;
05474
05475 p = r;
05476 for (;route ; route = route->next) {
05477 n = strlen(route->hop);
05478 if (rem < n+3)
05479 break;
05480 if (p != r) {
05481 *p++ = ',';
05482 --rem;
05483 }
05484 *p++ = '<';
05485 ast_copy_string(p, route->hop, rem);
05486 p += n;
05487 *p++ = '>';
05488 rem -= (n+2);
05489 }
05490 *p = '\0';
05491 add_header(req, "Route", r);
05492 }
05493
05494
05495 static void set_destination(struct sip_pvt *p, char *uri)
05496 {
05497 char *h, *maddr, hostname[256];
05498 int port, hn;
05499 struct hostent *hp;
05500 struct ast_hostent ahp;
05501 int debug=sip_debug_test_pvt(p);
05502
05503
05504
05505
05506 if (debug)
05507 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
05508
05509
05510 h = strchr(uri, '@');
05511 if (h)
05512 ++h;
05513 else {
05514 h = uri;
05515 if (strncmp(h, "sip:", 4) == 0)
05516 h += 4;
05517 else if (strncmp(h, "sips:", 5) == 0)
05518 h += 5;
05519 }
05520 hn = strcspn(h, ":;>") + 1;
05521 if (hn > sizeof(hostname))
05522 hn = sizeof(hostname);
05523 ast_copy_string(hostname, h, hn);
05524
05525 h += hn - 1;
05526
05527
05528 if (*h == ':') {
05529
05530 ++h;
05531 port = strtol(h, &h, 10);
05532 }
05533 else
05534 port = STANDARD_SIP_PORT;
05535
05536
05537 maddr = strstr(h, "maddr=");
05538 if (maddr) {
05539 maddr += 6;
05540 hn = strspn(maddr, "0123456789.") + 1;
05541 if (hn > sizeof(hostname))
05542 hn = sizeof(hostname);
05543 ast_copy_string(hostname, maddr, hn);
05544 }
05545
05546 hp = ast_gethostbyname(hostname, &ahp);
05547 if (hp == NULL) {
05548 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
05549 return;
05550 }
05551 p->sa.sin_family = AF_INET;
05552 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
05553 p->sa.sin_port = htons(port);
05554 if (debug)
05555 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
05556 }
05557
05558
05559 static int init_resp(struct sip_request *resp, const char *msg)
05560 {
05561
05562 memset(resp, 0, sizeof(*resp));
05563 resp->method = SIP_RESPONSE;
05564 resp->header[0] = resp->data;
05565 snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
05566 resp->len = strlen(resp->header[0]);
05567 resp->headers++;
05568 return 0;
05569 }
05570
05571
05572 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
05573 {
05574
05575 memset(req, 0, sizeof(*req));
05576 req->method = sipmethod;
05577 req->header[0] = req->data;
05578 snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
05579 req->len = strlen(req->header[0]);
05580 req->headers++;
05581 return 0;
05582 }
05583
05584
05585
05586 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
05587 {
05588 char newto[256];
05589 const char *ot;
05590
05591 init_resp(resp, msg);
05592 copy_via_headers(p, resp, req, "Via");
05593 if (msg[0] == '2')
05594 copy_all_header(resp, req, "Record-Route");
05595 copy_header(resp, req, "From");
05596 ot = get_header(req, "To");
05597 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
05598
05599
05600 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
05601 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
05602 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
05603 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
05604 else
05605 ast_copy_string(newto, ot, sizeof(newto));
05606 ot = newto;
05607 }
05608 add_header(resp, "To", ot);
05609 copy_header(resp, req, "Call-ID");
05610 copy_header(resp, req, "CSeq");
05611 if (!ast_strlen_zero(global_useragent))
05612 add_header(resp, "User-Agent", global_useragent);
05613 add_header(resp, "Allow", ALLOWED_METHODS);
05614 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
05615 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
05616
05617
05618 char tmp[256];
05619
05620 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
05621 add_header(resp, "Expires", tmp);
05622 if (p->expiry) {
05623 char contact[BUFSIZ];
05624 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
05625 add_header(resp, "Contact", contact);
05626 }
05627 } else if (msg[0] != '4' && p->our_contact[0]) {
05628 add_header(resp, "Contact", p->our_contact);
05629 }
05630 return 0;
05631 }
05632
05633
05634 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
05635 {
05636 struct sip_request *orig = &p->initreq;
05637 char stripped[80];
05638 char tmp[80];
05639 char newto[256];
05640 const char *c;
05641 const char *ot, *of;
05642 int is_strict = FALSE;
05643
05644 memset(req, 0, sizeof(struct sip_request));
05645
05646 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
05647
05648 if (!seqno) {
05649 p->ocseq++;
05650 seqno = p->ocseq;
05651 }
05652
05653 if (newbranch) {
05654 p->branch ^= ast_random();
05655 build_via(p);
05656 }
05657
05658
05659 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
05660 is_strict = TRUE;
05661 if (sipdebug)
05662 ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
05663 }
05664
05665 if (sipmethod == SIP_CANCEL)
05666 c = p->initreq.rlPart2;
05667 else if (sipmethod == SIP_ACK) {
05668
05669
05670 if (!ast_strlen_zero(p->okcontacturi))
05671 c = is_strict ? p->route->hop : p->okcontacturi;
05672 else
05673 c = p->initreq.rlPart2;
05674 } else if (!ast_strlen_zero(p->okcontacturi))
05675 c = is_strict ? p->route->hop : p->okcontacturi;
05676 else if (!ast_strlen_zero(p->uri))
05677 c = p->uri;
05678 else {
05679 char *n;
05680
05681 ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
05682 sizeof(stripped));
05683 n = get_in_brackets(stripped);
05684 c = strsep(&n, ";");
05685 }
05686 init_req(req, sipmethod, c);
05687
05688 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
05689
05690 add_header(req, "Via", p->via);
05691 if (p->route) {
05692 set_destination(p, p->route->hop);
05693 add_route(req, is_strict ? p->route->next : p->route);
05694 }
05695
05696 ot = get_header(orig, "To");
05697 of = get_header(orig, "From");
05698
05699
05700
05701 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
05702
05703
05704 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
05705 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
05706 else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
05707 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
05708 else
05709 snprintf(newto, sizeof(newto), "%s", ot);
05710 ot = newto;
05711 }
05712
05713 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05714 add_header(req, "From", of);
05715 add_header(req, "To", ot);
05716 } else {
05717 add_header(req, "From", ot);
05718 add_header(req, "To", of);
05719 }
05720
05721 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
05722 add_header(req, "Contact", p->our_contact);
05723
05724 copy_header(req, orig, "Call-ID");
05725 add_header(req, "CSeq", tmp);
05726
05727 if (!ast_strlen_zero(global_useragent))
05728 add_header(req, "User-Agent", global_useragent);
05729 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
05730
05731 if (!ast_strlen_zero(p->rpid))
05732 add_header(req, "Remote-Party-ID", p->rpid);
05733
05734 return 0;
05735 }
05736
05737
05738 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
05739 {
05740 struct sip_request resp;
05741 int seqno = 0;
05742
05743 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
05744 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
05745 return -1;
05746 }
05747 respprep(&resp, p, msg, req);
05748 add_header_contentLength(&resp, 0);
05749
05750
05751 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
05752 char buf[10];
05753
05754 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
05755 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
05756 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
05757 }
05758 return send_response(p, &resp, reliable, seqno);
05759 }
05760
05761 static void temp_pvt_cleanup(void *data)
05762 {
05763 struct sip_pvt *p = data;
05764
05765 ast_string_field_free_pools(p);
05766
05767 free(data);
05768 }
05769
05770
05771 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)
05772 {
05773 struct sip_pvt *p = NULL;
05774
05775 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
05776 ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
05777 return -1;
05778 }
05779
05780
05781 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
05782 ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
05783 if (ast_string_field_init(p, 512))
05784 return -1;
05785 }
05786
05787
05788 p->method = intended_method;
05789
05790 if (sin) {
05791 p->sa = *sin;
05792 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
05793 p->ourip = __ourip;
05794 } else
05795 p->ourip = __ourip;
05796
05797 p->branch = ast_random();
05798 make_our_tag(p->tag, sizeof(p->tag));
05799 p->ocseq = INITIAL_CSEQ;
05800
05801 if (useglobal_nat && sin) {
05802 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
05803 p->recv = *sin;
05804 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05805 }
05806
05807 ast_string_field_set(p, fromdomain, default_fromdomain);
05808 build_via(p);
05809 ast_string_field_set(p, callid, callid);
05810
05811
05812 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
05813
05814
05815 ast_string_field_free_all(p);
05816
05817 return 0;
05818 }
05819
05820
05821 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
05822 {
05823 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
05824 }
05825
05826
05827 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
05828 {
05829 struct sip_request resp;
05830 respprep(&resp, p, msg, req);
05831 append_date(&resp);
05832 add_header(&resp, "Unsupported", unsupported);
05833 add_header_contentLength(&resp, 0);
05834 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
05835 }
05836
05837
05838
05839
05840 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
05841 {
05842 return __transmit_response(p, msg, req, XMIT_CRITICAL);
05843 }
05844
05845
05846 static void append_date(struct sip_request *req)
05847 {
05848 char tmpdat[256];
05849 struct tm tm;
05850 time_t t = time(NULL);
05851
05852 gmtime_r(&t, &tm);
05853 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
05854 add_header(req, "Date", tmpdat);
05855 }
05856
05857
05858 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
05859 {
05860 struct sip_request resp;
05861 respprep(&resp, p, msg, req);
05862 append_date(&resp);
05863 add_header_contentLength(&resp, 0);
05864 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
05865 }
05866
05867
05868 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
05869 {
05870 struct sip_request resp;
05871 respprep(&resp, p, msg, req);
05872 add_header(&resp, "Accept", "application/sdp");
05873 add_header_contentLength(&resp, 0);
05874 return send_response(p, &resp, reliable, 0);
05875 }
05876
05877
05878 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)
05879 {
05880 struct sip_request resp;
05881 char tmp[512];
05882 int seqno = 0;
05883
05884 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
05885 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
05886 return -1;
05887 }
05888
05889
05890 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
05891 respprep(&resp, p, msg, req);
05892 add_header(&resp, header, tmp);
05893 add_header_contentLength(&resp, 0);
05894 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
05895 return send_response(p, &resp, reliable, seqno);
05896 }
05897
05898
05899 static int add_text(struct sip_request *req, const char *text)
05900 {
05901
05902 add_header(req, "Content-Type", "text/plain");
05903 add_header_contentLength(req, strlen(text));
05904 add_line(req, text);
05905 return 0;
05906 }
05907
05908
05909
05910 static int add_digit(struct sip_request *req, char digit, unsigned int duration)
05911 {
05912 char tmp[256];
05913
05914 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
05915 add_header(req, "Content-Type", "application/dtmf-relay");
05916 add_header_contentLength(req, strlen(tmp));
05917 add_line(req, tmp);
05918 return 0;
05919 }
05920
05921
05922
05923 static int add_vidupdate(struct sip_request *req)
05924 {
05925 const char *xml_is_a_huge_waste_of_space =
05926 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
05927 " <media_control>\r\n"
05928 " <vc_primitive>\r\n"
05929 " <to_encoder>\r\n"
05930 " <picture_fast_update>\r\n"
05931 " </picture_fast_update>\r\n"
05932 " </to_encoder>\r\n"
05933 " </vc_primitive>\r\n"
05934 " </media_control>\r\n";
05935 add_header(req, "Content-Type", "application/media_control+xml");
05936 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
05937 add_line(req, xml_is_a_huge_waste_of_space);
05938 return 0;
05939 }
05940
05941
05942 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
05943 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
05944 int debug, int *min_packet_size)
05945 {
05946 int rtp_code;
05947 struct ast_format_list fmt;
05948
05949
05950 if (debug)
05951 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
05952 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
05953 return;
05954
05955 if (p->rtp) {
05956 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
05957 fmt = ast_codec_pref_getsize(pref, codec);
05958 } else
05959 return;
05960 ast_build_string(m_buf, m_size, " %d", rtp_code);
05961 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
05962 ast_rtp_lookup_mime_subtype(1, codec,
05963 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
05964 sample_rate);
05965 if (codec == AST_FORMAT_G729A) {
05966
05967 ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
05968 } else if (codec == AST_FORMAT_ILBC) {
05969
05970 ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
05971 }
05972
05973 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
05974 *min_packet_size = fmt.cur_ms;
05975
05976
05977 if ((*min_packet_size) == 0 && fmt.cur_ms)
05978 *min_packet_size = fmt.cur_ms;
05979 }
05980
05981
05982 static int t38_get_rate(int t38cap)
05983 {
05984 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
05985
05986 if (maxrate & T38FAX_RATE_14400) {
05987 if (option_debug > 1)
05988 ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
05989 return 14400;
05990 } else if (maxrate & T38FAX_RATE_12000) {
05991 if (option_debug > 1)
05992 ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
05993 return 12000;
05994 } else if (maxrate & T38FAX_RATE_9600) {
05995 if (option_debug > 1)
05996 ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
05997 return 9600;
05998 } else if (maxrate & T38FAX_RATE_7200) {
05999 if (option_debug > 1)
06000 ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
06001 return 7200;
06002 } else if (maxrate & T38FAX_RATE_4800) {
06003 if (option_debug > 1)
06004 ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
06005 return 4800;
06006 } else if (maxrate & T38FAX_RATE_2400) {
06007 if (option_debug > 1)
06008 ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
06009 return 2400;
06010 } else {
06011 if (option_debug > 1)
06012 ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
06013 return 0;
06014 }
06015 }
06016
06017
06018 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
06019 {
06020 int len = 0;
06021 int x = 0;
06022 struct sockaddr_in udptlsin;
06023 char v[256] = "";
06024 char s[256] = "";
06025 char o[256] = "";
06026 char c[256] = "";
06027 char t[256] = "";
06028 char m_modem[256];
06029 char a_modem[1024];
06030 char *m_modem_next = m_modem;
06031 size_t m_modem_left = sizeof(m_modem);
06032 char *a_modem_next = a_modem;
06033 size_t a_modem_left = sizeof(a_modem);
06034 struct sockaddr_in udptldest = { 0, };
06035 int debug;
06036
06037 debug = sip_debug_test_pvt(p);
06038 len = 0;
06039 if (!p->udptl) {
06040 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
06041 return -1;
06042 }
06043
06044 if (!p->sessionid) {
06045 p->sessionid = getpid();
06046 p->sessionversion = p->sessionid;
06047 } else
06048 p->sessionversion++;
06049
06050
06051 ast_udptl_get_us(p->udptl, &udptlsin);
06052
06053
06054 if (p->udptlredirip.sin_addr.s_addr) {
06055 udptldest.sin_port = p->udptlredirip.sin_port;
06056 udptldest.sin_addr = p->udptlredirip.sin_addr;
06057 } else {
06058 udptldest.sin_addr = p->ourip;
06059 udptldest.sin_port = udptlsin.sin_port;
06060 }
06061
06062 if (debug)
06063 ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
06064
06065
06066
06067
06068 if (debug) {
06069 ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
06070 p->t38.capability,
06071 p->t38.peercapability,
06072 p->t38.jointcapability);
06073 }
06074 snprintf(v, sizeof(v), "v=0\r\n");
06075 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
06076 snprintf(s, sizeof(s), "s=session\r\n");
06077 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
06078 snprintf(t, sizeof(t), "t=0 0\r\n");
06079 ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
06080
06081 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
06082 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
06083 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
06084 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
06085 if ((x = t38_get_rate(p->t38.jointcapability)))
06086 ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
06087 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
06088 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
06089 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
06090 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
06091 x = ast_udptl_get_local_max_datagram(p->udptl);
06092 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
06093 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
06094 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
06095 ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
06096 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
06097 add_header(resp, "Content-Type", "application/sdp");
06098 add_header_contentLength(resp, len);
06099 add_line(resp, v);
06100 add_line(resp, o);
06101 add_line(resp, s);
06102 add_line(resp, c);
06103 add_line(resp, t);
06104 add_line(resp, m_modem);
06105 add_line(resp, a_modem);
06106
06107
06108 p->lastrtprx = p->lastrtptx = time(NULL);
06109
06110 return 0;
06111 }
06112
06113
06114
06115 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
06116 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
06117 int debug)
06118 {
06119 int rtp_code;
06120
06121 if (debug)
06122 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
06123 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
06124 return;
06125
06126 ast_build_string(m_buf, m_size, " %d", rtp_code);
06127 ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
06128 ast_rtp_lookup_mime_subtype(0, format, 0),
06129 sample_rate);
06130 if (format == AST_RTP_DTMF)
06131
06132 ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
06133 }
06134
06135 #define SDP_SAMPLE_RATE(x) (x == AST_FORMAT_G722) ? 16000 : 8000
06136
06137
06138 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
06139 {
06140 int len = 0;
06141 int alreadysent = 0;
06142
06143 struct sockaddr_in sin;
06144 struct sockaddr_in vsin;
06145 struct sockaddr_in dest;
06146 struct sockaddr_in vdest = { 0, };
06147
06148
06149 char *version = "v=0\r\n";
06150 char *subject = "s=session\r\n";
06151 char owner[256];
06152 char connection[256];
06153 char *stime = "t=0 0\r\n";
06154 char bandwidth[256] = "";
06155 char *hold;
06156 char m_audio[256];
06157 char m_video[256];
06158 char a_audio[1024];
06159 char a_video[1024];
06160 char *m_audio_next = m_audio;
06161 char *m_video_next = m_video;
06162 size_t m_audio_left = sizeof(m_audio);
06163 size_t m_video_left = sizeof(m_video);
06164 char *a_audio_next = a_audio;
06165 char *a_video_next = a_video;
06166 size_t a_audio_left = sizeof(a_audio);
06167 size_t a_video_left = sizeof(a_video);
06168
06169 int x;
06170 int capability;
06171 int needvideo = FALSE;
06172 int debug = sip_debug_test_pvt(p);
06173 int min_audio_packet_size = 0;
06174 int min_video_packet_size = 0;
06175
06176 m_video[0] = '\0';
06177
06178 if (!p->rtp) {
06179 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
06180 return AST_FAILURE;
06181 }
06182
06183
06184 if (!p->sessionid) {
06185 p->sessionid = getpid();
06186 p->sessionversion = p->sessionid;
06187 } else
06188 p->sessionversion++;
06189
06190
06191 ast_rtp_get_us(p->rtp, &sin);
06192 if (p->vrtp)
06193 ast_rtp_get_us(p->vrtp, &vsin);
06194
06195
06196 if (p->redirip.sin_addr.s_addr) {
06197 dest.sin_port = p->redirip.sin_port;
06198 dest.sin_addr = p->redirip.sin_addr;
06199 } else {
06200 dest.sin_addr = p->ourip;
06201 dest.sin_port = sin.sin_port;
06202 }
06203
06204 capability = p->jointcapability;
06205
06206
06207 if (option_debug > 1) {
06208 char codecbuf[BUFSIZ];
06209 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");
06210 ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
06211 }
06212
06213 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
06214 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
06215 ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
06216 ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
06217 }
06218 #endif
06219
06220
06221 if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
06222 if (p->vrtp) {
06223 needvideo = TRUE;
06224 if (option_debug > 1)
06225 ast_log(LOG_DEBUG, "This call needs video offers!\n");
06226 } else if (option_debug > 1)
06227 ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
06228 }
06229
06230
06231
06232
06233 if (needvideo) {
06234
06235 if (p->vredirip.sin_addr.s_addr) {
06236 vdest.sin_addr = p->vredirip.sin_addr;
06237 vdest.sin_port = p->vredirip.sin_port;
06238 } else {
06239 vdest.sin_addr = p->ourip;
06240 vdest.sin_port = vsin.sin_port;
06241 }
06242 ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
06243
06244
06245 if (p->maxcallbitrate)
06246 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
06247 if (debug)
06248 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));
06249 }
06250
06251 if (debug)
06252 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));
06253
06254
06255
06256
06257
06258
06259 snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
06260 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
06261 ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
06262
06263 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
06264 hold = "a=recvonly\r\n";
06265 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
06266 hold = "a=inactive\r\n";
06267 else
06268 hold = "a=sendrecv\r\n";
06269
06270
06271
06272
06273
06274
06275
06276
06277
06278
06279 if (capability & p->prefcodec) {
06280 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
06281
06282 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
06283 &m_audio_next, &m_audio_left,
06284 &a_audio_next, &a_audio_left,
06285 debug, &min_audio_packet_size);
06286 alreadysent |= codec;
06287 }
06288
06289
06290 for (x = 0; x < 32; x++) {
06291 int codec;
06292
06293 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
06294 break;
06295
06296 if (!(capability & codec))
06297 continue;
06298
06299 if (alreadysent & codec)
06300 continue;
06301
06302 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
06303 &m_audio_next, &m_audio_left,
06304 &a_audio_next, &a_audio_left,
06305 debug, &min_audio_packet_size);
06306 alreadysent |= codec;
06307 }
06308
06309
06310 for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
06311 if (!(capability & x))
06312 continue;
06313
06314 if (alreadysent & x)
06315 continue;
06316
06317 if (x <= AST_FORMAT_MAX_AUDIO)
06318 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
06319 &m_audio_next, &m_audio_left,
06320 &a_audio_next, &a_audio_left,
06321 debug, &min_audio_packet_size);
06322 else
06323 add_codec_to_sdp(p, x, 90000,
06324 &m_video_next, &m_video_left,
06325 &a_video_next, &a_video_left,
06326 debug, &min_video_packet_size);
06327 }
06328
06329
06330 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
06331 if (!(p->jointnoncodeccapability & x))
06332 continue;
06333
06334 add_noncodec_to_sdp(p, x, 8000,
06335 &m_audio_next, &m_audio_left,
06336 &a_audio_next, &a_audio_left,
06337 debug);
06338 }
06339
06340 if (option_debug > 2)
06341 ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");
06342
06343 if (!p->owner || !ast_internal_timing_enabled(p->owner))
06344 ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
06345
06346 if (min_audio_packet_size)
06347 ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);
06348
06349 if (min_video_packet_size)
06350 ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);
06351
06352 if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
06353 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
06354
06355 ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
06356 if (needvideo)
06357 ast_build_string(&m_video_next, &m_video_left, "\r\n");
06358
06359 len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
06360 if (needvideo)
06361 len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);
06362
06363 add_header(resp, "Content-Type", "application/sdp");
06364 add_header_contentLength(resp, len);
06365 add_line(resp, version);
06366 add_line(resp, owner);
06367 add_line(resp, subject);
06368 add_line(resp, connection);
06369 if (needvideo)
06370 add_line(resp, bandwidth);
06371 add_line(resp, stime);
06372 add_line(resp, m_audio);
06373 add_line(resp, a_audio);
06374 add_line(resp, hold);
06375 if (needvideo) {
06376 add_line(resp, m_video);
06377 add_line(resp, a_video);
06378 add_line(resp, hold);
06379 }
06380
06381
06382 p->lastrtprx = p->lastrtptx = time(NULL);
06383
06384 if (option_debug > 2) {
06385 char buf[BUFSIZ];
06386 ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, BUFSIZ, capability));
06387 }
06388
06389 return AST_SUCCESS;
06390 }
06391
06392
06393 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
06394 {
06395 struct sip_request resp;
06396 int seqno;
06397
06398 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
06399 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
06400 return -1;
06401 }
06402 respprep(&resp, p, msg, req);
06403 if (p->udptl) {
06404 ast_udptl_offered_from_local(p->udptl, 0);
06405 add_t38_sdp(&resp, p);
06406 } else
06407 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
06408 if (retrans && !p->pendinginvite)
06409 p->pendinginvite = seqno;
06410 return send_response(p, &resp, retrans, seqno);
06411 }
06412
06413
06414 static void copy_request(struct sip_request *dst, const struct sip_request *src)
06415 {
06416 long offset;
06417 int x;
06418 offset = ((void *)dst) - ((void *)src);
06419
06420 memcpy(dst, src, sizeof(*dst));
06421
06422 for (x=0; x < src->headers; x++)
06423 dst->header[x] += offset;
06424 for (x=0; x < src->lines; x++)
06425 dst->line[x] += offset;
06426 dst->rlPart1 += offset;
06427 dst->rlPart2 += offset;
06428 }
06429
06430
06431 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
06432 {
06433 struct sip_request resp;
06434 int seqno;
06435 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
06436 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
06437 return -1;
06438 }
06439 respprep(&resp, p, msg, req);
06440 if (p->rtp) {
06441 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06442 if (option_debug)
06443 ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
06444 ast_rtp_codec_setpref(p->rtp, &p->prefs);
06445 }
06446 try_suggested_sip_codec(p);
06447 add_sdp(&resp, p);
06448 } else
06449 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
06450 if (reliable && !p->pendinginvite)
06451 p->pendinginvite = seqno;
06452 return send_response(p, &resp, reliable, seqno);
06453 }
06454
06455
06456 static int determine_firstline_parts(struct sip_request *req)
06457 {
06458 char *e = ast_skip_blanks(req->header[0]);
06459
06460 if (!*e)
06461 return -1;
06462 req->rlPart1 = e;
06463 e = ast_skip_nonblanks(e);
06464 if (*e)
06465 *e++ = '\0';
06466
06467 e = ast_skip_blanks(e);
06468 if ( !*e )
06469 return -1;
06470 ast_trim_blanks(e);
06471
06472 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) {
06473 if (strlen(e) < 3)
06474 return -1;
06475 req->rlPart2 = e;
06476 } else {
06477 if ( *e == '<' ) {
06478 ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
06479 e++;
06480 if (!*e)
06481 return -1;
06482 }
06483 req->rlPart2 = e;
06484 e = ast_skip_nonblanks(e);
06485 if (*e)
06486 *e++ = '\0';
06487 e = ast_skip_blanks(e);
06488 if (strcasecmp(e, "SIP/2.0") ) {
06489 ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
06490 return -1;
06491 }
06492 }
06493 return 1;
06494 }
06495
06496
06497
06498
06499
06500
06501
06502 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
06503 {
06504 struct sip_request req;
06505
06506 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
06507
06508 add_header(&req, "Allow", ALLOWED_METHODS);
06509 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
06510 if (sipdebug)
06511 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
06512 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
06513 append_history(p, "ReInv", "Re-invite sent");
06514 add_sdp(&req, p);
06515
06516 initialize_initreq(p, &req);
06517 p->lastinvite = p->ocseq;
06518 ast_set_flag(&p->flags[0], SIP_OUTGOING);
06519 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
06520 }
06521
06522
06523
06524
06525
06526 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
06527 {
06528 struct sip_request req;
06529
06530 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
06531
06532 add_header(&req, "Allow", ALLOWED_METHODS);
06533 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
06534 if (sipdebug)
06535 add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
06536 ast_udptl_offered_from_local(p->udptl, 1);
06537 add_t38_sdp(&req, p);
06538
06539 initialize_initreq(p, &req);
06540 ast_set_flag(&p->flags[0], SIP_OUTGOING);
06541 p->lastinvite = p->ocseq;
06542 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
06543 }
06544
06545
06546 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
06547 {
06548 char stripped[BUFSIZ];
06549 char *c;
06550
06551 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
06552 c = get_in_brackets(stripped);
06553 c = strsep(&c, ";");
06554 if (!ast_strlen_zero(c))
06555 ast_string_field_set(p, uri, c);
06556 }
06557
06558
06559 static void build_contact(struct sip_pvt *p)
06560 {
06561
06562 if (ourport != STANDARD_SIP_PORT)
06563 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);
06564 else
06565 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
06566 }
06567
06568
06569 static void build_rpid(struct sip_pvt *p)
06570 {
06571 int send_pres_tags = TRUE;
06572 const char *privacy=NULL;
06573 const char *screen=NULL;
06574 char buf[256];
06575 const char *clid = default_callerid;
06576 const char *clin = NULL;
06577 const char *fromdomain;
06578
06579 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
06580 return;
06581
06582 if (p->owner && p->owner->cid.cid_num)
06583 clid = p->owner->cid.cid_num;
06584 if (p->owner && p->owner->cid.cid_name)
06585 clin = p->owner->cid.cid_name;
06586 if (ast_strlen_zero(clin))
06587 clin = clid;
06588
06589 switch (p->callingpres) {
06590 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
06591 privacy = "off";
06592 screen = "no";
06593 break;
06594 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
06595 privacy = "off";
06596 screen = "yes";
06597 break;
06598 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
06599 privacy = "off";
06600 screen = "no";
06601 break;
06602 case AST_PRES_ALLOWED_NETWORK_NUMBER:
06603 privacy = "off";
06604 screen = "yes";
06605 break;
06606 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
06607 privacy = "full";
06608 screen = "no";
06609 break;
06610 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
06611 privacy = "full";
06612 screen = "yes";
06613 break;
06614 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
06615 privacy = "full";
06616 screen = "no";
06617 break;
06618 case AST_PRES_PROHIB_NETWORK_NUMBER:
06619 privacy = "full";
06620 screen = "yes";
06621 break;
06622 case AST_PRES_NUMBER_NOT_AVAILABLE:
06623 send_pres_tags = FALSE;
06624 break;
06625 default:
06626 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
06627 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
06628 privacy = "full";
06629 else
06630 privacy = "off";
06631 screen = "no";
06632 break;
06633 }
06634
06635 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));
06636
06637 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
06638 if (send_pres_tags)
06639 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
06640 ast_string_field_set(p, rpid, buf);
06641
06642 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
06643 S_OR(p->fromuser, clid),
06644 fromdomain, p->tag);
06645 }
06646
06647
06648 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
06649 {
06650 char invite_buf[256] = "";
06651 char *invite = invite_buf;
06652 size_t invite_max = sizeof(invite_buf);
06653 char from[256];
06654 char to[256];
06655 char tmp[BUFSIZ/2];
06656 char tmp2[BUFSIZ/2];
06657 const char *l = NULL, *n = NULL;
06658 const char *urioptions = "";
06659
06660 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
06661 const char *s = p->username;
06662
06663
06664
06665
06666
06667
06668 if (*s == '+')
06669 s++;
06670 for (; *s; s++) {
06671 if (!strchr(AST_DIGIT_ANYNUM, *s) )
06672 break;
06673 }
06674
06675 if (*s)
06676 urioptions = ";user=phone";
06677 }
06678
06679
06680 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
06681
06682 if (p->owner) {
06683 l = p->owner->cid.cid_num;
06684 n = p->owner->cid.cid_name;
06685 }
06686
06687 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
06688 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
06689 l = CALLERID_UNKNOWN;
06690 n = l;
06691 }
06692 if (ast_strlen_zero(l))
06693 l = default_callerid;
06694 if (ast_strlen_zero(n))
06695 n = l;
06696
06697 if (!ast_strlen_zero(p->fromuser))
06698 l = p->fromuser;
06699 else
06700 ast_string_field_set(p, fromuser, l);
06701
06702
06703 if (!ast_strlen_zero(p->fromname))
06704 n = p->fromname;
06705 else
06706 ast_string_field_set(p, fromname, n);
06707
06708 if (pedanticsipchecking) {
06709 ast_uri_encode(n, tmp, sizeof(tmp), 0);
06710 n = tmp;
06711 ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
06712 l = tmp2;
06713 }
06714
06715 if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
06716 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);
06717 else
06718 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);
06719
06720
06721 if (!ast_strlen_zero(p->fullcontact)) {
06722
06723 ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
06724 } else {
06725
06726 ast_build_string(&invite, &invite_max, "sip:");
06727 if (!ast_strlen_zero(p->username)) {
06728 n = p->username;
06729 if (pedanticsipchecking) {
06730 ast_uri_encode(n, tmp, sizeof(tmp), 0);
06731 n = tmp;
06732 }
06733 ast_build_string(&invite, &invite_max, "%s@", n);
06734 }
06735 ast_build_string(&invite, &invite_max, "%s", p->tohost);
06736 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
06737 ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
06738 ast_build_string(&invite, &invite_max, "%s", urioptions);
06739 }
06740
06741
06742 if (p->options && p->options->uri_options)
06743 ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
06744
06745 ast_string_field_set(p, uri, invite_buf);
06746
06747 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
06748
06749 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", p->uri, p->theirtag);
06750 } else if (p->options && p->options->vxml_url) {
06751
06752 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
06753 } else
06754 snprintf(to, sizeof(to), "<%s>", p->uri);
06755
06756 init_req(req, sipmethod, p->uri);
06757 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
06758
06759 add_header(req, "Via", p->via);
06760
06761
06762
06763 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
06764 build_rpid(p);
06765 add_header(req, "From", p->rpid_from);
06766 } else
06767 add_header(req, "From", from);
06768 add_header(req, "To", to);
06769 ast_string_field_set(p, exten, l);
06770 build_contact(p);
06771 add_header(req, "Contact", p->our_contact);
06772 add_header(req, "Call-ID", p->callid);
06773 add_header(req, "CSeq", tmp);
06774 if (!ast_strlen_zero(global_useragent))
06775 add_header(req, "User-Agent", global_useragent);
06776 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
06777 if (!ast_strlen_zero(p->rpid))
06778 add_header(req, "Remote-Party-ID", p->rpid);
06779 }
06780
06781
06782 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
06783 {
06784 struct sip_request req;
06785
06786 req.method = sipmethod;
06787 if (init) {
06788
06789 p->branch ^= ast_random();
06790 build_via(p);
06791 if (init > 1)
06792 initreqprep(&req, p, sipmethod);
06793 else
06794 reqprep(&req, p, sipmethod, 0, 1);
06795 } else
06796 reqprep(&req, p, sipmethod, 0, 1);
06797
06798 if (p->options && p->options->auth)
06799 add_header(&req, p->options->authheader, p->options->auth);
06800 append_date(&req);
06801 if (sipmethod == SIP_REFER) {
06802 if (p->refer) {
06803 char buf[BUFSIZ];
06804 if (!ast_strlen_zero(p->refer->refer_to))
06805 add_header(&req, "Refer-To", p->refer->refer_to);
06806 if (!ast_strlen_zero(p->refer->referred_by)) {
06807 sprintf(buf, "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
06808 add_header(&req, "Referred-By", buf);
06809 }
06810 }
06811 }
06812
06813
06814 if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
06815 add_header(&req, "Replaces", p->options->replaces);
06816 add_header(&req, "Require", "replaces");
06817 }
06818
06819 add_header(&req, "Allow", ALLOWED_METHODS);
06820 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
06821 if (p->options && p->options->addsipheaders && p->owner) {
06822 struct ast_channel *ast = p->owner;
06823 struct varshead *headp = &ast->varshead;
06824
06825 if (!headp)
06826 ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
06827 else {
06828 const struct ast_var_t *current;
06829 AST_LIST_TRAVERSE(headp, current, entries) {
06830
06831 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
06832 char *content, *end;
06833 const char *header = ast_var_value(current);
06834 char *headdup = ast_strdupa(header);
06835
06836
06837 if (*headdup == '"')
06838 headdup++;
06839 if ((content = strchr(headdup, ':'))) {
06840 *content++ = '\0';
06841 content = ast_skip_blanks(content);
06842
06843 end = content + strlen(content) -1;
06844 if (*end == '"')
06845 *end = '\0';
06846
06847 add_header(&req, headdup, content);
06848 if (sipdebug)
06849 ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
06850 }
06851 }
06852 }
06853 }
06854 }
06855 if (sdp) {
06856 if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
06857 ast_udptl_offered_from_local(p->udptl, 1);
06858 if (option_debug)
06859 ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
06860 add_t38_sdp(&req, p);
06861 } else if (p->rtp)
06862 add_sdp(&req, p);
06863 } else {
06864 add_header_contentLength(&req, 0);
06865 }
06866
06867 if (!p->initreq.headers)
06868 initialize_initreq(p, &req);
06869 p->lastinvite = p->ocseq;
06870 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
06871 }
06872
06873
06874 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
06875 {
06876 char tmp[4000], from[256], to[256];
06877 char *t = tmp, *c, *mfrom, *mto;
06878 size_t maxbytes = sizeof(tmp);
06879 struct sip_request req;
06880 char hint[AST_MAX_EXTENSION];
06881 char *statestring = "terminated";
06882 const struct cfsubscription_types *subscriptiontype;
06883 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
06884 char *pidfstate = "--";
06885 char *pidfnote= "Ready";
06886
06887 memset(from, 0, sizeof(from));
06888 memset(to, 0, sizeof(to));
06889 memset(tmp, 0, sizeof(tmp));
06890
06891 switch (state) {
06892 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
06893 statestring = (global_notifyringing) ? "early" : "confirmed";
06894 local_state = NOTIFY_INUSE;
06895 pidfstate = "busy";
06896 pidfnote = "Ringing";
06897 break;
06898 case AST_EXTENSION_RINGING:
06899 statestring = "early";
06900 local_state = NOTIFY_INUSE;
06901 pidfstate = "busy";
06902 pidfnote = "Ringing";
06903 break;
06904 case AST_EXTENSION_INUSE:
06905 statestring = "confirmed";
06906 local_state = NOTIFY_INUSE;
06907 pidfstate = "busy";
06908 pidfnote = "On the phone";
06909 break;
06910 case AST_EXTENSION_BUSY:
06911 statestring = "confirmed";
06912 local_state = NOTIFY_CLOSED;
06913 pidfstate = "busy";
06914 pidfnote = "On the phone";
06915 break;
06916 case AST_EXTENSION_UNAVAILABLE:
06917 statestring = "terminated";
06918 local_state = NOTIFY_CLOSED;
06919 pidfstate = "away";
06920 pidfnote = "Unavailable";
06921 break;
06922 case AST_EXTENSION_ONHOLD:
06923 statestring = "confirmed";
06924 local_state = NOTIFY_INUSE;
06925 pidfstate = "busy";
06926 pidfnote = "On Hold";
06927 break;
06928 case AST_EXTENSION_NOT_INUSE:
06929 default:
06930
06931 break;
06932 }
06933
06934 subscriptiontype = find_subscription_type(p->subscribed);
06935
06936
06937 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
06938 char *hint2 = hint, *individual_hint = NULL;
06939 while ((individual_hint = strsep(&hint2, "&"))) {
06940
06941 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE) {
06942 local_state = NOTIFY_CLOSED;
06943 pidfstate = "away";
06944 pidfnote = "Not online";
06945 }
06946 }
06947 }
06948
06949 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
06950 c = get_in_brackets(from);
06951 if (strncmp(c, "sip:", 4)) {
06952 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
06953 return -1;
06954 }
06955 mfrom = strsep(&c, ";");
06956
06957 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
06958 c = get_in_brackets(to);
06959 if (strncmp(c, "sip:", 4)) {
06960 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
06961 return -1;
06962 }
06963 mto = strsep(&c, ";");
06964
06965 reqprep(&req, p, SIP_NOTIFY, 0, 1);
06966
06967
06968 add_header(&req, "Event", subscriptiontype->event);
06969 add_header(&req, "Content-Type", subscriptiontype->mediatype);
06970 switch(state) {
06971 case AST_EXTENSION_DEACTIVATED:
06972 if (timeout)
06973 add_header(&req, "Subscription-State", "terminated;reason=timeout");
06974 else {
06975 add_header(&req, "Subscription-State", "terminated;reason=probation");
06976 add_header(&req, "Retry-After", "60");
06977 }
06978 break;
06979 case AST_EXTENSION_REMOVED:
06980 add_header(&req, "Subscription-State", "terminated;reason=noresource");
06981 break;
06982 default:
06983 if (p->expiry)
06984 add_header(&req, "Subscription-State", "active");
06985 else
06986 add_header(&req, "Subscription-State", "terminated;reason=timeout");
06987 }
06988 switch (p->subscribed) {
06989 case XPIDF_XML:
06990 case CPIM_PIDF_XML:
06991 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
06992 ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
06993 ast_build_string(&t, &maxbytes, "<presence>\n");
06994 ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
06995 ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
06996 ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
06997 ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
06998 ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
06999 ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
07000 break;
07001 case PIDF_XML:
07002 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
07003 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);
07004 ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
07005 if (pidfstate[0] != '-')
07006 ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
07007 ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
07008 ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote);
07009 ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten);
07010 ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
07011 if (pidfstate[0] == 'b')
07012 ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
07013 else
07014 ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
07015 ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
07016 break;
07017 case DIALOG_INFO_XML:
07018 ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
07019 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);
07020 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
07021 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
07022 else
07023 ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
07024 ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
07025 if (state == AST_EXTENSION_ONHOLD) {
07026 ast_build_string(&t, &maxbytes, "<local>\n<target uri=\"%s\">\n"
07027 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
07028 "</target>\n</local>\n", mto);
07029 }
07030 ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
07031 break;
07032 case NONE:
07033 default:
07034 break;
07035 }
07036
07037 if (t > tmp + sizeof(tmp))
07038 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
07039
07040 add_header_contentLength(&req, strlen(tmp));
07041 add_line(&req, tmp);
07042
07043 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07044 }
07045
07046
07047
07048
07049
07050
07051
07052 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
07053 {
07054 struct sip_request req;
07055 char tmp[500];
07056 char *t = tmp;
07057 size_t maxbytes = sizeof(tmp);
07058
07059 initreqprep(&req, p, SIP_NOTIFY);
07060 add_header(&req, "Event", "message-summary");
07061 add_header(&req, "Content-Type", default_notifymime);
07062
07063 ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
07064 ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
07065 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
07066
07067
07068
07069 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)"));
07070
07071 if (p->subscribed) {
07072 if (p->expiry)
07073 add_header(&req, "Subscription-State", "active");
07074 else
07075 add_header(&req, "Subscription-State", "terminated;reason=timeout");
07076 }
07077
07078 if (t > tmp + sizeof(tmp))
07079 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
07080
07081 add_header_contentLength(&req, strlen(tmp));
07082 add_line(&req, tmp);
07083
07084 if (!p->initreq.headers)
07085 initialize_initreq(p, &req);
07086 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07087 }
07088
07089
07090 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
07091 {
07092 if (!p->initreq.headers)
07093 initialize_initreq(p, req);
07094 return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
07095 }
07096
07097
07098 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
07099 {
07100 struct sip_request req;
07101 char tmp[BUFSIZ/2];
07102
07103 reqprep(&req, p, SIP_NOTIFY, 0, 1);
07104 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
07105 add_header(&req, "Event", tmp);
07106 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
07107 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
07108 add_header(&req, "Allow", ALLOWED_METHODS);
07109 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
07110
07111 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
07112 add_header_contentLength(&req, strlen(tmp));
07113 add_line(&req, tmp);
07114
07115 if (!p->initreq.headers)
07116 initialize_initreq(p, &req);
07117
07118 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07119 }
07120
07121
07122 static char *regstate2str(enum sipregistrystate regstate)
07123 {
07124 switch(regstate) {
07125 case REG_STATE_FAILED:
07126 return "Failed";
07127 case REG_STATE_UNREGISTERED:
07128 return "Unregistered";
07129 case REG_STATE_REGSENT:
07130 return "Request Sent";
07131 case REG_STATE_AUTHSENT:
07132 return "Auth. Sent";
07133 case REG_STATE_REGISTERED:
07134 return "Registered";
07135 case REG_STATE_REJECTED:
07136 return "Rejected";
07137 case REG_STATE_TIMEOUT:
07138 return "Timeout";
07139 case REG_STATE_NOAUTH:
07140 return "No Authentication";
07141 default:
07142 return "Unknown";
07143 }
07144 }
07145
07146
07147 static int sip_reregister(void *data)
07148 {
07149
07150 struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
07151
07152
07153 if (!r)
07154 return 0;
07155
07156 if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
07157 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
07158
07159
07160 if (sipdebug)
07161 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
07162
07163 r->expire = -1;
07164 __sip_do_register(r);
07165 ASTOBJ_UNREF(r, sip_registry_destroy);
07166 return 0;
07167 }
07168
07169
07170 static int __sip_do_register(struct sip_registry *r)
07171 {
07172 int res;
07173
07174 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
07175 return res;
07176 }
07177
07178
07179 static int sip_reg_timeout(void *data)
07180 {
07181
07182
07183 struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
07184 struct sip_pvt *p;
07185 int res;
07186
07187
07188 if (!r)
07189 return 0;
07190
07191 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
07192 if (r->call) {
07193
07194
07195 p = r->call;
07196 if (p->registry)
07197 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
07198 r->call = NULL;
07199 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
07200
07201 __sip_pretend_ack(p);
07202 }
07203
07204 if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
07205
07206
07207
07208 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
07209 r->regstate = REG_STATE_FAILED;
07210 } else {
07211 r->regstate = REG_STATE_UNREGISTERED;
07212 r->timeout = -1;
07213 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
07214 }
07215 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));
07216 ASTOBJ_UNREF(r, sip_registry_destroy);
07217 return 0;
07218 }
07219
07220
07221 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
07222 {
07223 struct sip_request req;
07224 char from[256];
07225 char to[256];
07226 char tmp[80];
07227 char addr[80];
07228 struct sip_pvt *p;
07229
07230
07231 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
07232 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
07233 return 0;
07234 }
07235
07236 if (r->call) {
07237 if (!auth) {
07238 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
07239 return 0;
07240 } else {
07241 p = r->call;
07242 make_our_tag(p->tag, sizeof(p->tag));
07243 ast_string_field_free(p, theirtag);
07244 }
07245 } else {
07246
07247 if (!r->callid_valid) {
07248 build_callid_registry(r, __ourip, default_fromdomain);
07249 r->callid_valid = TRUE;
07250 }
07251
07252 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
07253 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
07254 return 0;
07255 }
07256 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
07257 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
07258
07259 if (create_addr(p, r->hostname)) {
07260
07261
07262 sip_destroy(p);
07263 if (r->timeout > -1) {
07264 ast_sched_del(sched, r->timeout);
07265 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
07266 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
07267 } else {
07268 r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
07269 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);
07270 }
07271 r->regattempts++;
07272 return 0;
07273 }
07274
07275 ast_string_field_set(r, callid, p->callid);
07276 if (r->portno)
07277 p->sa.sin_port = htons(r->portno);
07278 else
07279 r->portno = ntohs(p->sa.sin_port);
07280 ast_set_flag(&p->flags[0], SIP_OUTGOING);
07281 r->call=p;
07282 p->registry = ASTOBJ_REF(r);
07283 if (!ast_strlen_zero(r->secret))
07284 ast_string_field_set(p, peersecret, r->secret);
07285 if (!ast_strlen_zero(r->md5secret))
07286 ast_string_field_set(p, peermd5secret, r->md5secret);
07287
07288
07289 if (!ast_strlen_zero(r->authuser)) {
07290 ast_string_field_set(p, peername, r->authuser);
07291 ast_string_field_set(p, authname, r->authuser);
07292 } else if (!ast_strlen_zero(r->username)) {
07293 ast_string_field_set(p, peername, r->username);
07294 ast_string_field_set(p, authname, r->username);
07295 ast_string_field_set(p, fromuser, r->username);
07296 }
07297 if (!ast_strlen_zero(r->username))
07298 ast_string_field_set(p, username, r->username);
07299
07300 ast_string_field_set(p, exten, r->contact);
07301
07302
07303
07304
07305
07306
07307 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
07308 p->ourip = bindaddr.sin_addr;
07309 build_contact(p);
07310 }
07311
07312
07313 if (auth == NULL) {
07314 if (r->timeout > -1) {
07315 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
07316 ast_sched_del(sched, r->timeout);
07317 }
07318 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
07319 if (option_debug)
07320 ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
07321 }
07322
07323 if (strchr(r->username, '@')) {
07324 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
07325 if (!ast_strlen_zero(p->theirtag))
07326 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
07327 else
07328 snprintf(to, sizeof(to), "<sip:%s>", r->username);
07329 } else {
07330 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
07331 if (!ast_strlen_zero(p->theirtag))
07332 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
07333 else
07334 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
07335 }
07336
07337
07338
07339 if (!ast_strlen_zero(p->fromdomain)) {
07340 if (r->portno && r->portno != STANDARD_SIP_PORT)
07341 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
07342 else
07343 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
07344 } else {
07345 if (r->portno && r->portno != STANDARD_SIP_PORT)
07346 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
07347 else
07348 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
07349 }
07350 ast_string_field_set(p, uri, addr);
07351
07352 p->branch ^= ast_random();
07353
07354 init_req(&req, sipmethod, addr);
07355
07356
07357 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
07358 p->ocseq = r->ocseq;
07359
07360 build_via(p);
07361 add_header(&req, "Via", p->via);
07362 add_header(&req, "From", from);
07363 add_header(&req, "To", to);
07364 add_header(&req, "Call-ID", p->callid);
07365 add_header(&req, "CSeq", tmp);
07366 if (!ast_strlen_zero(global_useragent))
07367 add_header(&req, "User-Agent", global_useragent);
07368 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
07369
07370
07371 if (auth)
07372 add_header(&req, authheader, auth);
07373 else if (!ast_strlen_zero(r->nonce)) {
07374 char digest[1024];
07375
07376
07377 if (sipdebug)
07378 ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
07379 ast_string_field_set(p, realm, r->realm);
07380 ast_string_field_set(p, nonce, r->nonce);
07381 ast_string_field_set(p, domain, r->domain);
07382 ast_string_field_set(p, opaque, r->opaque);
07383 ast_string_field_set(p, qop, r->qop);
07384 r->noncecount++;
07385 p->noncecount = r->noncecount;
07386
07387 memset(digest,0,sizeof(digest));
07388 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
07389 add_header(&req, "Authorization", digest);
07390 else
07391 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
07392
07393 }
07394
07395 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
07396 add_header(&req, "Expires", tmp);
07397 add_header(&req, "Contact", p->our_contact);
07398 add_header(&req, "Event", "registration");
07399 add_header_contentLength(&req, 0);
07400
07401 initialize_initreq(p, &req);
07402 if (sip_debug_test_pvt(p))
07403 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
07404 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
07405 r->regattempts++;
07406 if (option_debug > 3)
07407 ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
07408 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
07409 }
07410
07411
07412 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
07413 {
07414 struct sip_request req;
07415
07416 reqprep(&req, p, SIP_MESSAGE, 0, 1);
07417 add_text(&req, text);
07418 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07419 }
07420
07421
07422 static int sip_refer_allocate(struct sip_pvt *p)
07423 {
07424 p->refer = ast_calloc(1, sizeof(struct sip_refer));
07425 return p->refer ? 1 : 0;
07426 }
07427
07428
07429
07430
07431
07432
07433 static int transmit_refer(struct sip_pvt *p, const char *dest)
07434 {
07435 struct sip_request req = {
07436 .headers = 0,
07437 };
07438 char from[256];
07439 const char *of;
07440 char *c;
07441 char referto[256];
07442 char *ttag, *ftag;
07443 char *theirtag = ast_strdupa(p->theirtag);
07444
07445 if (option_debug || sipdebug)
07446 ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);
07447
07448
07449 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07450 of = get_header(&p->initreq, "To");
07451 ttag = theirtag;
07452 ftag = p->tag;
07453 } else {
07454 of = get_header(&p->initreq, "From");
07455 ftag = theirtag;
07456 ttag = p->tag;
07457 }
07458
07459 ast_copy_string(from, of, sizeof(from));
07460 of = get_in_brackets(from);
07461 ast_string_field_set(p, from, of);
07462 if (strncmp(of, "sip:", 4))
07463 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
07464 else
07465 of += 4;
07466
07467 if ((c = strchr(dest, '@')))
07468 c = NULL;
07469 else if ((c = strchr(of, '@')))
07470 *c++ = '\0';
07471 if (c)
07472 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
07473 else
07474 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
07475
07476
07477 sip_refer_allocate(p);
07478 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
07479 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
07480 p->refer->status = REFER_SENT;
07481
07482 reqprep(&req, p, SIP_REFER, 0, 1);
07483 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
07484
07485 add_header(&req, "Refer-To", referto);
07486 add_header(&req, "Allow", ALLOWED_METHODS);
07487 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
07488 if (!ast_strlen_zero(p->our_contact))
07489 add_header(&req, "Referred-By", p->our_contact);
07490
07491 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07492
07493
07494
07495
07496
07497
07498
07499
07500 }
07501
07502
07503
07504 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
07505 {
07506 struct sip_request req;
07507
07508 reqprep(&req, p, SIP_INFO, 0, 1);
07509 add_digit(&req, digit, duration);
07510 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07511 }
07512
07513
07514 static int transmit_info_with_vidupdate(struct sip_pvt *p)
07515 {
07516 struct sip_request req;
07517
07518 reqprep(&req, p, SIP_INFO, 0, 1);
07519 add_vidupdate(&req);
07520 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07521 }
07522
07523
07524 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
07525 {
07526 struct sip_request resp;
07527
07528 if (sipmethod == SIP_ACK)
07529 p->invitestate = INV_CONFIRMED;
07530
07531 reqprep(&resp, p, sipmethod, seqno, newbranch);
07532 add_header_contentLength(&resp, 0);
07533 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
07534 }
07535
07536
07537 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
07538 {
07539 struct sip_request resp;
07540
07541 reqprep(&resp, p, sipmethod, seqno, newbranch);
07542 if (!ast_strlen_zero(p->realm)) {
07543 char digest[1024];
07544
07545 memset(digest, 0, sizeof(digest));
07546 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
07547 if (p->options && p->options->auth_type == PROXY_AUTH)
07548 add_header(&resp, "Proxy-Authorization", digest);
07549 else if (p->options && p->options->auth_type == WWW_AUTH)
07550 add_header(&resp, "Authorization", digest);
07551 else
07552 add_header(&resp, "Proxy-Authorization", digest);
07553 } else
07554 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
07555 }
07556
07557
07558 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
07559 char buf[10];
07560
07561 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
07562 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
07563 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
07564 }
07565
07566 add_header_contentLength(&resp, 0);
07567 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
07568 }
07569
07570
07571 static void destroy_association(struct sip_peer *peer)
07572 {
07573 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
07574 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
07575 ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
07576 else
07577 ast_db_del("SIP/Registry", peer->name);
07578 }
07579 }
07580
07581
07582 static int expire_register(void *data)
07583 {
07584 struct sip_peer *peer = data;
07585
07586 if (!peer)
07587 return 0;
07588
07589 memset(&peer->addr, 0, sizeof(peer->addr));
07590
07591 destroy_association(peer);
07592
07593 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
07594 register_peer_exten(peer, FALSE);
07595 peer->expire = -1;
07596 ast_device_state_changed("SIP/%s", peer->name);
07597
07598
07599
07600
07601 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
07602 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
07603 peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);
07604 ASTOBJ_UNREF(peer, sip_destroy_peer);
07605 }
07606
07607 return 0;
07608 }
07609
07610
07611 static int sip_poke_peer_s(void *data)
07612 {
07613 struct sip_peer *peer = data;
07614
07615 peer->pokeexpire = -1;
07616 sip_poke_peer(peer);
07617 return 0;
07618 }
07619
07620
07621 static void reg_source_db(struct sip_peer *peer)
07622 {
07623 char data[256];
07624 struct in_addr in;
07625 int expiry;
07626 int port;
07627 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
07628
07629 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
07630 return;
07631 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
07632 return;
07633
07634 scan = data;
07635 addr = strsep(&scan, ":");
07636 port_str = strsep(&scan, ":");
07637 expiry_str = strsep(&scan, ":");
07638 username = strsep(&scan, ":");
07639 contact = scan;
07640
07641 if (!inet_aton(addr, &in))
07642 return;
07643
07644 if (port_str)
07645 port = atoi(port_str);
07646 else
07647 return;
07648
07649 if (expiry_str)
07650 expiry = atoi(expiry_str);
07651 else
07652 return;
07653
07654 if (username)
07655 ast_copy_string(peer->username, username, sizeof(peer->username));
07656 if (contact)
07657 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
07658
07659 if (option_debug > 1)
07660 ast_log(LOG_DEBUG, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
07661 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
07662
07663 memset(&peer->addr, 0, sizeof(peer->addr));
07664 peer->addr.sin_family = AF_INET;
07665 peer->addr.sin_addr = in;
07666 peer->addr.sin_port = htons(port);
07667 if (sipsock < 0) {
07668
07669 if (peer->pokeexpire > -1)
07670 ast_sched_del(sched, peer->pokeexpire);
07671 peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
07672 } else
07673 sip_poke_peer(peer);
07674 if (peer->expire > -1)
07675 ast_sched_del(sched, peer->expire);
07676 peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
07677 register_peer_exten(peer, TRUE);
07678 ast_device_state_changed("SIP/%s", peer->name);
07679 }
07680
07681
07682 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
07683 {
07684 char contact[BUFSIZ];
07685 char *c;
07686
07687
07688 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
07689 c = get_in_brackets(contact);
07690
07691
07692 ast_string_field_set(pvt, fullcontact, c);
07693
07694
07695 ast_string_field_set(pvt, okcontacturi, c);
07696
07697
07698
07699 return TRUE;
07700 }
07701
07702
07703 static int set_address_from_contact(struct sip_pvt *pvt)
07704 {
07705 struct hostent *hp;
07706 struct ast_hostent ahp;
07707 int port;
07708 char *c, *host, *pt;
07709 char *contact;
07710
07711
07712 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
07713
07714
07715 pvt->sa = pvt->recv;
07716 return 0;
07717 }
07718
07719
07720
07721 contact = ast_strdupa(pvt->fullcontact);
07722
07723
07724
07725 if (strncasecmp(contact, "sip:", 4)) {
07726 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
07727 } else
07728 contact += 4;
07729
07730
07731
07732 contact = strsep(&contact, ";");
07733
07734
07735 host = strchr(contact, '@');
07736 if (!host) {
07737 host = contact;
07738 c = NULL;
07739 } else {
07740 *host++ = '\0';
07741 }
07742 pt = strchr(host, ':');
07743 if (pt) {
07744 *pt++ = '\0';
07745 port = atoi(pt);
07746 } else
07747 port = STANDARD_SIP_PORT;
07748
07749
07750
07751 hp = ast_gethostbyname(host, &ahp);
07752 if (!hp) {
07753 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
07754 return -1;
07755 }
07756 pvt->sa.sin_family = AF_INET;
07757 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
07758 pvt->sa.sin_port = htons(port);
07759
07760 return 0;
07761 }
07762
07763
07764
07765 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
07766 {
07767 char contact[BUFSIZ];
07768 char data[BUFSIZ];
07769 const char *expires = get_header(req, "Expires");
07770 int expiry = atoi(expires);
07771 char *curi, *n, *pt;
07772 int port;
07773 const char *useragent;
07774 struct hostent *hp;
07775 struct ast_hostent ahp;
07776 struct sockaddr_in oldsin;
07777
07778 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
07779
07780 if (ast_strlen_zero(expires)) {
07781 expires = strcasestr(contact, ";expires=");
07782 if (expires) {
07783
07784 expires = strsep((char **) &expires, ";");
07785 if (sscanf(expires + 9, "%d", &expiry) != 1)
07786 expiry = default_expiry;
07787 } else {
07788
07789 expiry = default_expiry;
07790 }
07791 }
07792
07793
07794 curi = contact;
07795 if (strchr(contact, '<') == NULL)
07796 strsep(&curi, ";");
07797 curi = get_in_brackets(contact);
07798
07799
07800
07801
07802
07803 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
07804
07805 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
07806 pvt->expiry = ast_sched_when(sched, peer->expire);
07807 return PARSE_REGISTER_QUERY;
07808 } else if (!strcasecmp(curi, "*") || !expiry) {
07809
07810 memset(&peer->addr, 0, sizeof(peer->addr));
07811 if (peer->expire > -1)
07812 ast_sched_del(sched, peer->expire);
07813 peer->expire = -1;
07814
07815 destroy_association(peer);
07816
07817 register_peer_exten(peer, 0);
07818 peer->fullcontact[0] = '\0';
07819 peer->useragent[0] = '\0';
07820 peer->sipoptions = 0;
07821 peer->lastms = 0;
07822
07823 if (option_verbose > 2)
07824 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
07825 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
07826 return PARSE_REGISTER_UPDATE;
07827 }
07828
07829
07830 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
07831
07832
07833 ast_string_field_build(pvt, our_contact, "<%s>", curi);
07834
07835
07836 if (strncasecmp(curi, "sip:", 4)) {
07837 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
07838 } else
07839 curi += 4;
07840
07841 curi = strsep(&curi, ";");
07842
07843 n = strchr(curi, '@');
07844 if (!n) {
07845 n = curi;
07846 curi = NULL;
07847 } else
07848 *n++ = '\0';
07849 pt = strchr(n, ':');
07850 if (pt) {
07851 *pt++ = '\0';
07852 port = atoi(pt);
07853 } else
07854 port = STANDARD_SIP_PORT;
07855 oldsin = peer->addr;
07856 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
07857
07858 hp = ast_gethostbyname(n, &ahp);
07859 if (!hp) {
07860 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
07861 return PARSE_REGISTER_FAILED;
07862 }
07863 peer->addr.sin_family = AF_INET;
07864 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
07865 peer->addr.sin_port = htons(port);
07866 } else {
07867
07868
07869 peer->addr = pvt->recv;
07870 }
07871
07872
07873 peer->sipoptions = pvt->sipoptions;
07874
07875 if (curi)
07876 ast_copy_string(peer->username, curi, sizeof(peer->username));
07877 else
07878 peer->username[0] = '\0';
07879
07880 if (peer->expire > -1) {
07881 ast_sched_del(sched, peer->expire);
07882 peer->expire = -1;
07883 }
07884 if (expiry > max_expiry)
07885 expiry = max_expiry;
07886 if (expiry < min_expiry)
07887 expiry = min_expiry;
07888 peer->expire = ast_test_flag(&peer->flags[0], SIP_REALTIME) ? -1 :
07889 ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
07890 pvt->expiry = expiry;
07891 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);
07892 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
07893 ast_db_put("SIP/Registry", peer->name, data);
07894 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
07895
07896
07897 if (inaddrcmp(&peer->addr, &oldsin)) {
07898 sip_poke_peer(peer);
07899 if (option_verbose > 2)
07900 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);
07901 register_peer_exten(peer, 1);
07902 }
07903
07904
07905 useragent = get_header(req, "User-Agent");
07906 if (strcasecmp(useragent, peer->useragent)) {
07907 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
07908 if (option_verbose > 3)
07909 ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
07910 }
07911 return PARSE_REGISTER_UPDATE;
07912 }
07913
07914
07915 static void free_old_route(struct sip_route *route)
07916 {
07917 struct sip_route *next;
07918
07919 while (route) {
07920 next = route->next;
07921 free(route);
07922 route = next;
07923 }
07924 }
07925
07926
07927 static void list_route(struct sip_route *route)
07928 {
07929 if (!route)
07930 ast_verbose("list_route: no route\n");
07931 else {
07932 for (;route; route = route->next)
07933 ast_verbose("list_route: hop: <%s>\n", route->hop);
07934 }
07935 }
07936
07937
07938 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
07939 {
07940 struct sip_route *thishop, *head, *tail;
07941 int start = 0;
07942 int len;
07943 const char *rr, *contact, *c;
07944
07945
07946 if (p->route && p->route_persistant) {
07947 if (option_debug)
07948 ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
07949 return;
07950 }
07951
07952 if (p->route) {
07953 free_old_route(p->route);
07954 p->route = NULL;
07955 }
07956
07957 p->route_persistant = backwards;
07958
07959
07960
07961
07962
07963
07964 head = NULL;
07965 tail = head;
07966
07967 for (;;) {
07968
07969 rr = __get_header(req, "Record-Route", &start);
07970 if (*rr == '\0')
07971 break;
07972 for (; (rr = strchr(rr, '<')) ; rr += len) {
07973 ++rr;
07974 len = strcspn(rr, ">") + 1;
07975
07976 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
07977
07978 ast_copy_string(thishop->hop, rr, len);
07979 if (option_debug > 1)
07980 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
07981
07982 if (backwards) {
07983
07984 thishop->next = head;
07985 head = thishop;
07986
07987 if (!tail)
07988 tail = thishop;
07989 } else {
07990 thishop->next = NULL;
07991
07992 if (tail)
07993 tail->next = thishop;
07994 else
07995 head = thishop;
07996 tail = thishop;
07997 }
07998 }
07999 }
08000 }
08001
08002
08003 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
08004
08005
08006 contact = get_header(req, "Contact");
08007 if (!ast_strlen_zero(contact)) {
08008 if (option_debug > 1)
08009 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
08010
08011 c = strchr(contact, '<');
08012 if (c) {
08013
08014 ++c;
08015 len = strcspn(c, ">") + 1;
08016 } else {
08017
08018 c = contact;
08019 len = strlen(contact) + 1;
08020 }
08021 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
08022
08023 ast_copy_string(thishop->hop, c, len);
08024 thishop->next = NULL;
08025
08026 if (tail)
08027 tail->next = thishop;
08028 else
08029 head = thishop;
08030 }
08031 }
08032 }
08033
08034
08035 p->route = head;
08036
08037
08038 if (sip_debug_test_pvt(p))
08039 list_route(p->route);
08040 }
08041
08042
08043
08044
08045
08046
08047
08048 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
08049 const char *secret, const char *md5secret, int sipmethod,
08050 char *uri, enum xmittype reliable, int ignore)
08051 {
08052 const char *response = "407 Proxy Authentication Required";
08053 const char *reqheader = "Proxy-Authorization";
08054 const char *respheader = "Proxy-Authenticate";
08055 const char *authtoken;
08056 char a1_hash[256];
08057 char resp_hash[256]="";
08058 char tmp[BUFSIZ * 2];
08059 char *c;
08060 int wrongnonce = FALSE;
08061 int good_response;
08062 const char *usednonce = p->randdata;
08063
08064
08065 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
08066 struct x {
08067 const char *key;
08068 const char *s;
08069 } *i, keys[] = {
08070 [K_RESP] = { "response=", "" },
08071 [K_URI] = { "uri=", "" },
08072 [K_USER] = { "username=", "" },
08073 [K_NONCE] = { "nonce=", "" },
08074 [K_LAST] = { NULL, NULL}
08075 };
08076
08077
08078 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
08079 return AUTH_SUCCESSFUL;
08080 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
08081
08082
08083
08084 response = "401 Unauthorized";
08085 reqheader = "Authorization";
08086 respheader = "WWW-Authenticate";
08087 }
08088 authtoken = get_header(req, reqheader);
08089 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
08090
08091
08092 if (!reliable) {
08093
08094
08095 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
08096
08097 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08098 }
08099 return AUTH_CHALLENGE_SENT;
08100 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
08101
08102 ast_string_field_build(p, randdata, "%08lx", ast_random());
08103 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
08104
08105 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08106 return AUTH_CHALLENGE_SENT;
08107 }
08108
08109
08110
08111
08112
08113
08114
08115
08116 ast_copy_string(tmp, authtoken, sizeof(tmp));
08117 c = tmp;
08118
08119 while(c && *(c = ast_skip_blanks(c)) ) {
08120 for (i = keys; i->key != NULL; i++) {
08121 const char *separator = ",";
08122
08123 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
08124 continue;
08125
08126 c += strlen(i->key);
08127 if (*c == '"') {
08128 c++;
08129 separator = "\"";
08130 }
08131 i->s = c;
08132 strsep(&c, separator);
08133 break;
08134 }
08135 if (i->key == NULL)
08136 strsep(&c, " ,");
08137 }
08138
08139
08140 if (strcmp(username, keys[K_USER].s)) {
08141 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
08142 username, keys[K_USER].s);
08143
08144 return AUTH_USERNAME_MISMATCH;
08145 }
08146
08147
08148 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
08149 wrongnonce = TRUE;
08150 usednonce = keys[K_NONCE].s;
08151 }
08152
08153 if (!ast_strlen_zero(md5secret))
08154 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
08155 else {
08156 char a1[256];
08157 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
08158 ast_md5_hash(a1_hash, a1);
08159 }
08160
08161
08162 {
08163 char a2[256];
08164 char a2_hash[256];
08165 char resp[256];
08166
08167 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
08168 S_OR(keys[K_URI].s, uri));
08169 ast_md5_hash(a2_hash, a2);
08170 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
08171 ast_md5_hash(resp_hash, resp);
08172 }
08173
08174 good_response = keys[K_RESP].s &&
08175 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
08176 if (wrongnonce) {
08177 ast_string_field_build(p, randdata, "%08lx", ast_random());
08178 if (good_response) {
08179 if (sipdebug)
08180 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
08181
08182 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
08183 } else {
08184
08185 if (sipdebug)
08186 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
08187 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
08188 }
08189
08190
08191 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08192 return AUTH_CHALLENGE_SENT;
08193 }
08194 if (good_response) {
08195 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
08196 return AUTH_SUCCESSFUL;
08197 }
08198
08199
08200
08201 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
08202 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08203
08204 return AUTH_CHALLENGE_SENT;
08205 }
08206
08207
08208 static void sip_peer_hold(struct sip_pvt *p, int hold)
08209 {
08210 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
08211
08212 if (!peer)
08213 return;
08214
08215
08216 if (hold)
08217 peer->onHold++;
08218 else
08219 peer->onHold--;
08220
08221
08222 ast_device_state_changed("SIP/%s", peer->name);
08223
08224 return;
08225 }
08226
08227
08228
08229
08230 static int cb_extensionstate(char *context, char* exten, int state, void *data)
08231 {
08232 struct sip_pvt *p = data;
08233
08234 switch(state) {
08235 case AST_EXTENSION_DEACTIVATED:
08236 case AST_EXTENSION_REMOVED:
08237 if (p->autokillid > -1)
08238 sip_cancel_destroy(p);
08239 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
08240 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);
08241 p->stateid = -1;
08242 p->subscribed = NONE;
08243 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
08244 break;
08245 default:
08246 p->laststate = state;
08247 break;
08248 }
08249 if (p->subscribed != NONE)
08250 transmit_state_notify(p, state, 1, FALSE);
08251
08252 if (option_verbose > 1)
08253 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->username);
08254 return 0;
08255 }
08256
08257
08258
08259
08260 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
08261 {
08262 ast_string_field_build(p, randdata, "%08lx", ast_random());
08263 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
08264 }
08265
08266
08267
08268
08269
08270
08271 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
08272 struct sip_request *req, char *uri)
08273 {
08274 enum check_auth_result res = AUTH_NOT_FOUND;
08275 struct sip_peer *peer;
08276 char tmp[256];
08277 char *name, *c;
08278 char *t;
08279 char *domain;
08280
08281
08282 t = uri;
08283 while(*t && (*t > 32) && (*t != ';'))
08284 t++;
08285 *t = '\0';
08286
08287 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
08288 if (pedanticsipchecking)
08289 ast_uri_decode(tmp);
08290
08291 c = get_in_brackets(tmp);
08292 c = strsep(&c, ";");
08293
08294 if (!strncmp(c, "sip:", 4)) {
08295 name = c + 4;
08296 } else {
08297 name = c;
08298 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
08299 }
08300
08301
08302 if ((c = strchr(name, '@'))) {
08303 *c++ = '\0';
08304 domain = c;
08305 if ((c = strchr(domain, ':')))
08306 *c = '\0';
08307 if (!AST_LIST_EMPTY(&domain_list)) {
08308 if (!check_sip_domain(domain, NULL, 0)) {
08309 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
08310 return AUTH_UNKNOWN_DOMAIN;
08311 }
08312 }
08313 }
08314
08315 ast_string_field_set(p, exten, name);
08316 build_contact(p);
08317 peer = find_peer(name, NULL, 1);
08318 if (!(peer && ast_apply_ha(peer->ha, sin))) {
08319
08320 if (peer)
08321 ASTOBJ_UNREF(peer, sip_destroy_peer);
08322 peer = NULL;
08323 }
08324 if (peer) {
08325
08326 if (p->rtp) {
08327 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
08328 p->autoframing = peer->autoframing;
08329 }
08330 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
08331 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
08332 } else {
08333 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
08334 transmit_response(p, "100 Trying", req);
08335 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
08336 sip_cancel_destroy(p);
08337
08338
08339
08340 switch (parse_register_contact(p, peer, req)) {
08341 case PARSE_REGISTER_FAILED:
08342 ast_log(LOG_WARNING, "Failed to parse contact info\n");
08343 transmit_response_with_date(p, "400 Bad Request", req);
08344 peer->lastmsgssent = -1;
08345 res = 0;
08346 break;
08347 case PARSE_REGISTER_QUERY:
08348 transmit_response_with_date(p, "200 OK", req);
08349 peer->lastmsgssent = -1;
08350 res = 0;
08351 break;
08352 case PARSE_REGISTER_UPDATE:
08353 update_peer(peer, p->expiry);
08354
08355 transmit_response_with_date(p, "200 OK", req);
08356 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
08357 peer->lastmsgssent = -1;
08358 res = 0;
08359 break;
08360 }
08361 }
08362 }
08363 }
08364 if (!peer && autocreatepeer) {
08365
08366 peer = temp_peer(name);
08367 if (peer) {
08368 ASTOBJ_CONTAINER_LINK(&peerl, peer);
08369 sip_cancel_destroy(p);
08370 switch (parse_register_contact(p, peer, req)) {
08371 case PARSE_REGISTER_FAILED:
08372 ast_log(LOG_WARNING, "Failed to parse contact info\n");
08373 transmit_response_with_date(p, "400 Bad Request", req);
08374 peer->lastmsgssent = -1;
08375 res = 0;
08376 break;
08377 case PARSE_REGISTER_QUERY:
08378 transmit_response_with_date(p, "200 OK", req);
08379 peer->lastmsgssent = -1;
08380 res = 0;
08381 break;
08382 case PARSE_REGISTER_UPDATE:
08383
08384 transmit_response_with_date(p, "200 OK", req);
08385 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
08386 peer->lastmsgssent = -1;
08387 res = 0;
08388 break;
08389 }
08390 }
08391 }
08392 if (!res) {
08393 ast_device_state_changed("SIP/%s", peer->name);
08394 }
08395 if (res < 0) {
08396 switch (res) {
08397 case AUTH_SECRET_FAILED:
08398
08399 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
08400 break;
08401 case AUTH_USERNAME_MISMATCH:
08402
08403
08404
08405
08406 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
08407 break;
08408 case AUTH_NOT_FOUND:
08409 if (global_alwaysauthreject) {
08410 transmit_fake_auth_response(p, &p->initreq, 1);
08411 } else {
08412
08413 transmit_response(p, "404 Not found", &p->initreq);
08414 }
08415 break;
08416 default:
08417 break;
08418 }
08419 if (option_debug > 1) {
08420 const char *reason = "";
08421
08422 switch (res) {
08423 case AUTH_SECRET_FAILED:
08424 reason = "Bad password";
08425 break;
08426 case AUTH_USERNAME_MISMATCH:
08427 reason = "Bad digest user";
08428 break;
08429 case AUTH_NOT_FOUND:
08430 reason = "Peer not found";
08431 break;
08432 default:
08433 break;
08434 }
08435 ast_log(LOG_DEBUG, "SIP REGISTER attempt failed for %s : %s\n",
08436 peer->name, reason);
08437 }
08438 }
08439 if (peer)
08440 ASTOBJ_UNREF(peer, sip_destroy_peer);
08441
08442 return res;
08443 }
08444
08445
08446 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
08447 {
08448 char tmp[256], *c, *a;
08449 struct sip_request *req;
08450
08451 req = oreq;
08452 if (!req)
08453 req = &p->initreq;
08454 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
08455 if (ast_strlen_zero(tmp))
08456 return 0;
08457 c = get_in_brackets(tmp);
08458 if (strncmp(c, "sip:", 4)) {
08459 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
08460 return -1;
08461 }
08462 c += 4;
08463 a = c;
08464 strsep(&a, "@;");
08465 if (sip_debug_test_pvt(p))
08466 ast_verbose("RDNIS is %s\n", c);
08467 ast_string_field_set(p, rdnis, c);
08468
08469 return 0;
08470 }
08471
08472
08473
08474
08475 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
08476 {
08477 char tmp[256] = "", *uri, *a;
08478 char tmpf[256] = "", *from;
08479 struct sip_request *req;
08480 char *colon;
08481
08482 req = oreq;
08483 if (!req)
08484 req = &p->initreq;
08485
08486
08487 if (req->rlPart2)
08488 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
08489
08490 if (pedanticsipchecking)
08491 ast_uri_decode(tmp);
08492
08493 uri = get_in_brackets(tmp);
08494
08495 if (strncmp(uri, "sip:", 4)) {
08496 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
08497 return -1;
08498 }
08499 uri += 4;
08500
08501
08502 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
08503 if (!ast_strlen_zero(tmpf)) {
08504 if (pedanticsipchecking)
08505 ast_uri_decode(tmpf);
08506 from = get_in_brackets(tmpf);
08507 } else {
08508 from = NULL;
08509 }
08510
08511 if (!ast_strlen_zero(from)) {
08512 if (strncmp(from, "sip:", 4)) {
08513 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
08514 return -1;
08515 }
08516 from += 4;
08517 if ((a = strchr(from, '@')))
08518 *a++ = '\0';
08519 else
08520 a = from;
08521 from = strsep(&from, ";");
08522 a = strsep(&a, ";");
08523 ast_string_field_set(p, fromdomain, a);
08524 }
08525
08526
08527
08528
08529 if ((a = strchr(uri, '@'))) {
08530 *a++ = '\0';
08531 } else {
08532 a = uri;
08533 uri = "s";
08534 }
08535 colon = strchr(a, ':');
08536 if (colon)
08537 *colon = '\0';
08538
08539 uri = strsep(&uri, ";");
08540 a = strsep(&a, ";");
08541
08542 ast_string_field_set(p, domain, a);
08543
08544 if (!AST_LIST_EMPTY(&domain_list)) {
08545 char domain_context[AST_MAX_EXTENSION];
08546
08547 domain_context[0] = '\0';
08548 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
08549 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
08550 if (option_debug)
08551 ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
08552 return -2;
08553 }
08554 }
08555
08556 if (!ast_strlen_zero(domain_context))
08557 ast_string_field_set(p, context, domain_context);
08558 }
08559
08560 if (sip_debug_test_pvt(p))
08561 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
08562
08563
08564
08565
08566 if (ast_exists_extension(NULL, p->context, uri, 1, from) ||
08567 !strcmp(uri, ast_pickup_ext())) {
08568 if (!oreq)
08569 ast_string_field_set(p, exten, uri);
08570 return 0;
08571 }
08572
08573
08574 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
08575 ast_canmatch_extension(NULL, p->context, uri, 1, from)) ||
08576 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
08577 return 1;
08578 }
08579
08580 return -1;
08581 }
08582
08583
08584
08585
08586
08587
08588 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
08589 {
08590 struct sip_pvt *sip_pvt_ptr;
08591
08592 ast_mutex_lock(&iflock);
08593
08594 if (option_debug > 3 && totag)
08595 ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
08596
08597
08598 for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
08599 if (!strcmp(sip_pvt_ptr->callid, callid)) {
08600 int match = 1;
08601 char *ourtag = sip_pvt_ptr->tag;
08602
08603
08604 ast_mutex_lock(&sip_pvt_ptr->lock);
08605
08606
08607
08608
08609
08610 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || strcmp(totag, ourtag)))
08611 match = 0;
08612
08613 if (!match) {
08614 ast_mutex_unlock(&sip_pvt_ptr->lock);
08615 continue;
08616 }
08617
08618 if (option_debug > 3 && totag)
08619 ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
08620 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
08621 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
08622
08623
08624 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
08625 ast_mutex_unlock(&sip_pvt_ptr->lock);
08626 usleep(1);
08627 ast_mutex_lock(&sip_pvt_ptr->lock);
08628 }
08629 break;
08630 }
08631 }
08632 ast_mutex_unlock(&iflock);
08633 if (option_debug > 3 && !sip_pvt_ptr)
08634 ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
08635 return sip_pvt_ptr;
08636 }
08637
08638
08639
08640 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
08641 {
08642
08643 const char *p_referred_by = NULL;
08644 char *h_refer_to = NULL;
08645 char *h_referred_by = NULL;
08646 char *refer_to;
08647 const char *p_refer_to;
08648 char *referred_by_uri = NULL;
08649 char *ptr;
08650 struct sip_request *req = NULL;
08651 const char *transfer_context = NULL;
08652 struct sip_refer *referdata;
08653
08654
08655 req = outgoing_req;
08656 referdata = transferer->refer;
08657
08658 if (!req)
08659 req = &transferer->initreq;
08660
08661 p_refer_to = get_header(req, "Refer-To");
08662 if (ast_strlen_zero(p_refer_to)) {
08663 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
08664 return -2;
08665 }
08666 h_refer_to = ast_strdupa(p_refer_to);
08667 refer_to = get_in_brackets(h_refer_to);
08668 if (pedanticsipchecking)
08669 ast_uri_decode(refer_to);
08670
08671 if (strncasecmp(refer_to, "sip:", 4)) {
08672 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
08673 return -3;
08674 }
08675 refer_to += 4;
08676
08677
08678 p_referred_by = get_header(req, "Referred-By");
08679 if (!ast_strlen_zero(p_referred_by)) {
08680 char *lessthan;
08681 h_referred_by = ast_strdupa(p_referred_by);
08682 if (pedanticsipchecking)
08683 ast_uri_decode(h_referred_by);
08684
08685
08686 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
08687 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
08688 *(lessthan - 1) = '\0';
08689 }
08690
08691 referred_by_uri = get_in_brackets(h_referred_by);
08692 if(strncasecmp(referred_by_uri, "sip:", 4)) {
08693 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
08694 referred_by_uri = (char *) NULL;
08695 } else {
08696 referred_by_uri += 4;
08697 }
08698 }
08699
08700
08701 if ((ptr = strchr(refer_to, '?'))) {
08702 *ptr++ = '\0';
08703 if (!strncasecmp(ptr, "REPLACES=", 9)) {
08704 char *to = NULL, *from = NULL;
08705
08706
08707 referdata->attendedtransfer = 1;
08708 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
08709 ast_uri_decode(referdata->replaces_callid);
08710 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
08711 *ptr++ = '\0';
08712 }
08713
08714 if (ptr) {
08715
08716 to = strcasestr(ptr, "to-tag=");
08717 from = strcasestr(ptr, "from-tag=");
08718 }
08719
08720
08721 if (to) {
08722 ptr = to + 7;
08723 if ((to = strchr(ptr, '&')))
08724 *to = '\0';
08725 if ((to = strchr(ptr, ';')))
08726 *to = '\0';
08727 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
08728 }
08729
08730 if (from) {
08731 ptr = from + 9;
08732 if ((to = strchr(ptr, '&')))
08733 *to = '\0';
08734 if ((to = strchr(ptr, ';')))
08735 *to = '\0';
08736 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
08737 }
08738
08739 if (option_debug > 1) {
08740 if (!pedanticsipchecking)
08741 ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
08742 else
08743 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>" );
08744 }
08745 }
08746 }
08747
08748 if ((ptr = strchr(refer_to, '@'))) {
08749 char *urioption;
08750
08751 *ptr++ = '\0';
08752 if ((urioption = strchr(ptr, ';')))
08753 *urioption++ = '\0';
08754
08755 ast_copy_string(referdata->refer_to_domain, ptr, sizeof(referdata->refer_to_domain));
08756 if (urioption)
08757 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
08758 }
08759
08760 if ((ptr = strchr(refer_to, ';')))
08761 *ptr = '\0';
08762 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
08763
08764 if (referred_by_uri) {
08765 if ((ptr = strchr(referred_by_uri, ';')))
08766 *ptr = '\0';
08767 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
08768 } else {
08769 referdata->referred_by[0] = '\0';
08770 }
08771
08772
08773 if (transferer->owner)
08774 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
08775
08776
08777 if (ast_strlen_zero(transfer_context)) {
08778 transfer_context = S_OR(transferer->owner->macrocontext,
08779 S_OR(transferer->context, default_context));
08780 }
08781
08782 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
08783
08784
08785 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
08786 if (sip_debug_test_pvt(transferer)) {
08787 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
08788 }
08789
08790 return 0;
08791 }
08792 if (sip_debug_test_pvt(transferer))
08793 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
08794
08795
08796 return -1;
08797 }
08798
08799
08800
08801 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
08802 {
08803 char tmp[256] = "", *c, *a;
08804 struct sip_request *req = oreq ? oreq : &p->initreq;
08805 struct sip_refer *referdata = p->refer;
08806 const char *transfer_context = NULL;
08807
08808 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
08809 c = get_in_brackets(tmp);
08810
08811 if (pedanticsipchecking)
08812 ast_uri_decode(c);
08813
08814 if (strncmp(c, "sip:", 4)) {
08815 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
08816 return -1;
08817 }
08818 c += 4;
08819 if ((a = strchr(c, ';')))
08820 *a = '\0';
08821
08822 if ((a = strchr(c, '@'))) {
08823 *a++ = '\0';
08824 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
08825 }
08826
08827 if (sip_debug_test_pvt(p))
08828 ast_verbose("Looking for %s in %s\n", c, p->context);
08829
08830 if (p->owner)
08831 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
08832
08833
08834 if (ast_strlen_zero(transfer_context)) {
08835 transfer_context = S_OR(p->owner->macrocontext,
08836 S_OR(p->context, default_context));
08837 }
08838 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
08839
08840 if (option_debug)
08841 ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
08842 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
08843 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
08844 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
08845 referdata->refer_call = NULL;
08846
08847 ast_string_field_set(p, context, transfer_context);
08848 return 0;
08849 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
08850 return 1;
08851 }
08852
08853 return -1;
08854 }
08855
08856 static void check_via(struct sip_pvt *p, struct sip_request *req)
08857 {
08858 char via[256];
08859 char *c, *pt;
08860 struct hostent *hp;
08861 struct ast_hostent ahp;
08862
08863 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
08864
08865
08866 c = strchr(via, ',');
08867 if (c)
08868 *c = '\0';
08869
08870
08871 c = strstr(via, ";rport");
08872 if (c && (c[6] != '='))
08873 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
08874
08875 c = strchr(via, ';');
08876 if (c)
08877 *c = '\0';
08878
08879 c = strchr(via, ' ');
08880 if (c) {
08881 *c = '\0';
08882 c = ast_skip_blanks(c+1);
08883 if (strcasecmp(via, "SIP/2.0/UDP")) {
08884 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
08885 return;
08886 }
08887 pt = strchr(c, ':');
08888 if (pt)
08889 *pt++ = '\0';
08890 hp = ast_gethostbyname(c, &ahp);
08891 if (!hp) {
08892 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
08893 return;
08894 }
08895 memset(&p->sa, 0, sizeof(p->sa));
08896 p->sa.sin_family = AF_INET;
08897 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
08898 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
08899
08900 if (sip_debug_test_pvt(p)) {
08901 const struct sockaddr_in *dst = sip_real_dst(p);
08902 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
08903 }
08904 }
08905 }
08906
08907
08908 static char *get_calleridname(const char *input, char *output, size_t outputsize)
08909 {
08910 const char *end = strchr(input,'<');
08911 const char *tmp = strchr(input,'"');
08912 int bytes = 0;
08913 int maxbytes = outputsize - 1;
08914
08915 if (!end || end == input)
08916 return NULL;
08917
08918 end--;
08919
08920 if (tmp && tmp <= end) {
08921
08922
08923
08924 end = strchr(tmp+1, '"');
08925 if (!end)
08926 return NULL;
08927 bytes = (int) (end - tmp);
08928
08929 if (bytes > maxbytes)
08930 bytes = maxbytes;
08931 ast_copy_string(output, tmp + 1, bytes);
08932 } else {
08933
08934
08935 input = ast_skip_blanks(input);
08936
08937 while(*end && *end < 33 && end > input)
08938 end--;
08939 if (end >= input) {
08940 bytes = (int) (end - input) + 2;
08941
08942 if (bytes > maxbytes)
08943 bytes = maxbytes;
08944 ast_copy_string(output, input, bytes);
08945 } else
08946 return NULL;
08947 }
08948 return output;
08949 }
08950
08951
08952
08953
08954
08955 static int get_rpid_num(const char *input, char *output, int maxlen)
08956 {
08957 char *start;
08958 char *end;
08959
08960 start = strchr(input,':');
08961 if (!start) {
08962 output[0] = '\0';
08963 return 0;
08964 }
08965 start++;
08966
08967
08968 ast_copy_string(output,start,maxlen);
08969 output[maxlen-1] = '\0';
08970
08971 end = strchr(output,'@');
08972 if (end)
08973 *end = '\0';
08974 else
08975 output[0] = '\0';
08976 if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
08977 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
08978
08979 return 0;
08980 }
08981
08982
08983
08984
08985
08986
08987
08988 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
08989 int sipmethod, char *uri, enum xmittype reliable,
08990 struct sockaddr_in *sin, struct sip_peer **authpeer)
08991 {
08992 struct sip_user *user = NULL;
08993 struct sip_peer *peer;
08994 char from[256], *c;
08995 char *of;
08996 char rpid_num[50];
08997 const char *rpid;
08998 enum check_auth_result res = AUTH_SUCCESSFUL;
08999 char *t;
09000 char calleridname[50];
09001 int debug=sip_debug_test_addr(sin);
09002 struct ast_variable *tmpvar = NULL, *v = NULL;
09003 char *uri2 = ast_strdupa(uri);
09004
09005
09006 t = uri2;
09007 while (*t && *t > 32 && *t != ';')
09008 t++;
09009 *t = '\0';
09010 ast_copy_string(from, get_header(req, "From"), sizeof(from));
09011 if (pedanticsipchecking)
09012 ast_uri_decode(from);
09013
09014 memset(calleridname, 0, sizeof(calleridname));
09015 get_calleridname(from, calleridname, sizeof(calleridname));
09016 if (calleridname[0])
09017 ast_string_field_set(p, cid_name, calleridname);
09018
09019 rpid = get_header(req, "Remote-Party-ID");
09020 memset(rpid_num, 0, sizeof(rpid_num));
09021 if (!ast_strlen_zero(rpid))
09022 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
09023
09024 of = get_in_brackets(from);
09025 if (ast_strlen_zero(p->exten)) {
09026 t = uri2;
09027 if (!strncmp(t, "sip:", 4))
09028 t+= 4;
09029 ast_string_field_set(p, exten, t);
09030 t = strchr(p->exten, '@');
09031 if (t)
09032 *t = '\0';
09033 if (ast_strlen_zero(p->our_contact))
09034 build_contact(p);
09035 }
09036
09037 ast_string_field_set(p, from, of);
09038 if (strncmp(of, "sip:", 4)) {
09039 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
09040 } else
09041 of += 4;
09042
09043 if ((c = strchr(of, '@'))) {
09044 char *tmp;
09045 *c = '\0';
09046 if ((c = strchr(of, ':')))
09047 *c = '\0';
09048 tmp = ast_strdupa(of);
09049
09050
09051
09052 tmp = strsep(&tmp, ";");
09053 if (ast_is_shrinkable_phonenumber(tmp))
09054 ast_shrink_phone_number(tmp);
09055 ast_string_field_set(p, cid_num, tmp);
09056 }
09057 if (ast_strlen_zero(of))
09058 return AUTH_SUCCESSFUL;
09059
09060 if (!authpeer)
09061 user = find_user(of, 1);
09062
09063
09064 if (user && ast_apply_ha(user->ha, sin)) {
09065 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
09066 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09067
09068 for (v = user->chanvars ; v ; v = v->next) {
09069 if ((tmpvar = ast_variable_new(v->name, v->value))) {
09070 tmpvar->next = p->chanvars;
09071 p->chanvars = tmpvar;
09072 }
09073 }
09074 p->prefs = user->prefs;
09075
09076 if (p->rtp) {
09077 ast_rtp_codec_setpref(p->rtp, &p->prefs);
09078 p->autoframing = user->autoframing;
09079 }
09080
09081 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
09082 char *tmp;
09083 if (*calleridname)
09084 ast_string_field_set(p, cid_name, calleridname);
09085 tmp = ast_strdupa(rpid_num);
09086 if (ast_is_shrinkable_phonenumber(tmp))
09087 ast_shrink_phone_number(tmp);
09088 ast_string_field_set(p, cid_num, tmp);
09089 }
09090
09091 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
09092
09093 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
09094 sip_cancel_destroy(p);
09095 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
09096 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09097
09098 if (p->sipoptions)
09099 user->sipoptions = p->sipoptions;
09100
09101
09102 if (user->call_limit)
09103 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
09104 if (!ast_strlen_zero(user->context))
09105 ast_string_field_set(p, context, user->context);
09106 if (!ast_strlen_zero(user->cid_num) && !ast_strlen_zero(p->cid_num)) {
09107 char *tmp = ast_strdupa(user->cid_num);
09108 if (ast_is_shrinkable_phonenumber(tmp))
09109 ast_shrink_phone_number(tmp);
09110 ast_string_field_set(p, cid_num, tmp);
09111 }
09112 if (!ast_strlen_zero(user->cid_name) && !ast_strlen_zero(p->cid_num))
09113 ast_string_field_set(p, cid_name, user->cid_name);
09114 ast_string_field_set(p, username, user->name);
09115 ast_string_field_set(p, peername, user->name);
09116 ast_string_field_set(p, peersecret, user->secret);
09117 ast_string_field_set(p, peermd5secret, user->md5secret);
09118 ast_string_field_set(p, subscribecontext, user->subscribecontext);
09119 ast_string_field_set(p, accountcode, user->accountcode);
09120 ast_string_field_set(p, language, user->language);
09121 ast_string_field_set(p, mohsuggest, user->mohsuggest);
09122 ast_string_field_set(p, mohinterpret, user->mohinterpret);
09123 p->allowtransfer = user->allowtransfer;
09124 p->amaflags = user->amaflags;
09125 p->callgroup = user->callgroup;
09126 p->pickupgroup = user->pickupgroup;
09127 if (user->callingpres)
09128 p->callingpres = user->callingpres;
09129
09130
09131 p->capability = user->capability;
09132 p->jointcapability = user->capability;
09133 if (p->peercapability)
09134 p->jointcapability &= p->peercapability;
09135 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
09136 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
09137 p->noncodeccapability |= AST_RTP_DTMF;
09138 else
09139 p->noncodeccapability &= ~AST_RTP_DTMF;
09140 p->jointnoncodeccapability = p->noncodeccapability;
09141 if (p->t38.peercapability)
09142 p->t38.jointcapability &= p->t38.peercapability;
09143 p->maxcallbitrate = user->maxcallbitrate;
09144
09145 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
09146 ast_rtp_destroy(p->vrtp);
09147 p->vrtp = NULL;
09148 }
09149 }
09150 if (user && debug)
09151 ast_verbose("Found user '%s'\n", user->name);
09152 } else {
09153 if (user) {
09154 if (!authpeer && debug)
09155 ast_verbose("Found user '%s', but fails host access\n", user->name);
09156 ASTOBJ_UNREF(user,sip_destroy_user);
09157 }
09158 user = NULL;
09159 }
09160
09161 if (!user) {
09162
09163 if (sipmethod == SIP_SUBSCRIBE)
09164
09165 peer = find_peer(of, NULL, 1);
09166 else
09167
09168
09169
09170
09171 peer = find_peer(NULL, &p->recv, 1);
09172
09173 if (peer) {
09174
09175 if (p->rtp) {
09176 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
09177 p->autoframing = peer->autoframing;
09178 }
09179 if (debug)
09180 ast_verbose("Found peer '%s'\n", peer->name);
09181
09182
09183 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
09184 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09185
09186
09187 if (p->sipoptions)
09188 peer->sipoptions = p->sipoptions;
09189
09190
09191 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
09192 char *tmp = ast_strdupa(rpid_num);
09193 if (*calleridname)
09194 ast_string_field_set(p, cid_name, calleridname);
09195 if (ast_is_shrinkable_phonenumber(tmp))
09196 ast_shrink_phone_number(tmp);
09197 ast_string_field_set(p, cid_num, tmp);
09198 }
09199 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
09200
09201 ast_string_field_set(p, peersecret, peer->secret);
09202 ast_string_field_set(p, peermd5secret, peer->md5secret);
09203 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
09204 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
09205 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
09206 if (peer->callingpres)
09207 p->callingpres = peer->callingpres;
09208 if (peer->maxms && peer->lastms)
09209 p->timer_t1 = peer->lastms;
09210 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
09211
09212 ast_string_field_free(p, peersecret);
09213 ast_string_field_free(p, peermd5secret);
09214 }
09215 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
09216 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
09217 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
09218
09219 if (peer->call_limit)
09220 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
09221 ast_string_field_set(p, peername, peer->name);
09222 ast_string_field_set(p, authname, peer->name);
09223
09224
09225 for (v = peer->chanvars ; v ; v = v->next) {
09226 if ((tmpvar = ast_variable_new(v->name, v->value))) {
09227 tmpvar->next = p->chanvars;
09228 p->chanvars = tmpvar;
09229 }
09230 }
09231 if (authpeer) {
09232 (*authpeer) = ASTOBJ_REF(peer);
09233 }
09234
09235 if (!ast_strlen_zero(peer->username)) {
09236 ast_string_field_set(p, username, peer->username);
09237
09238
09239 ast_string_field_set(p, authname, peer->username);
09240 }
09241 if (!ast_strlen_zero(peer->cid_num) && !ast_strlen_zero(p->cid_num)) {
09242 char *tmp = ast_strdupa(peer->cid_num);
09243 if (ast_is_shrinkable_phonenumber(tmp))
09244 ast_shrink_phone_number(tmp);
09245 ast_string_field_set(p, cid_num, tmp);
09246 }
09247 if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name))
09248 ast_string_field_set(p, cid_name, peer->cid_name);
09249 ast_string_field_set(p, fullcontact, peer->fullcontact);
09250 if (!ast_strlen_zero(peer->context))
09251 ast_string_field_set(p, context, peer->context);
09252 ast_string_field_set(p, peersecret, peer->secret);
09253 ast_string_field_set(p, peermd5secret, peer->md5secret);
09254 ast_string_field_set(p, language, peer->language);
09255 ast_string_field_set(p, accountcode, peer->accountcode);
09256 p->amaflags = peer->amaflags;
09257 p->callgroup = peer->callgroup;
09258 p->pickupgroup = peer->pickupgroup;
09259 p->capability = peer->capability;
09260 p->prefs = peer->prefs;
09261 p->jointcapability = peer->capability;
09262 if (p->peercapability)
09263 p->jointcapability &= p->peercapability;
09264 p->maxcallbitrate = peer->maxcallbitrate;
09265 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
09266 ast_rtp_destroy(p->vrtp);
09267 p->vrtp = NULL;
09268 }
09269 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
09270 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
09271 p->noncodeccapability |= AST_RTP_DTMF;
09272 else
09273 p->noncodeccapability &= ~AST_RTP_DTMF;
09274 p->jointnoncodeccapability = p->noncodeccapability;
09275 if (p->t38.peercapability)
09276 p->t38.jointcapability &= p->t38.peercapability;
09277 }
09278 ASTOBJ_UNREF(peer, sip_destroy_peer);
09279 } else {
09280 if (debug)
09281 ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
09282
09283
09284 if (!global_allowguest) {
09285 if (global_alwaysauthreject)
09286 res = AUTH_FAKE_AUTH;
09287 else
09288 res = AUTH_SECRET_FAILED;
09289 }
09290 }
09291
09292 }
09293
09294 if (user)
09295 ASTOBJ_UNREF(user, sip_destroy_user);
09296 return res;
09297 }
09298
09299
09300
09301
09302 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
09303 {
09304 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
09305 }
09306
09307
09308 static int get_msg_text(char *buf, int len, struct sip_request *req)
09309 {
09310 int x;
09311 int y;
09312
09313 buf[0] = '\0';
09314 y = len - strlen(buf) - 5;
09315 if (y < 0)
09316 y = 0;
09317 for (x=0;x<req->lines;x++) {
09318 strncat(buf, req->line[x], y);
09319 y -= strlen(req->line[x]) + 1;
09320 if (y < 0)
09321 y = 0;
09322 if (y != 0)
09323 strcat(buf, "\n");
09324 }
09325 return 0;
09326 }
09327
09328
09329
09330
09331
09332 static void receive_message(struct sip_pvt *p, struct sip_request *req)
09333 {
09334 char buf[1024];
09335 struct ast_frame f;
09336 const char *content_type = get_header(req, "Content-Type");
09337
09338 if (strcmp(content_type, "text/plain")) {
09339 transmit_response(p, "415 Unsupported Media Type", req);
09340 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09341 return;
09342 }
09343
09344 if (get_msg_text(buf, sizeof(buf), req)) {
09345 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
09346 transmit_response(p, "202 Accepted", req);
09347 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09348 return;
09349 }
09350
09351 if (p->owner) {
09352 if (sip_debug_test_pvt(p))
09353 ast_verbose("Message received: '%s'\n", buf);
09354 memset(&f, 0, sizeof(f));
09355 f.frametype = AST_FRAME_TEXT;
09356 f.subclass = 0;
09357 f.offset = 0;
09358 f.data = buf;
09359 f.datalen = strlen(buf);
09360 ast_queue_frame(p->owner, &f);
09361 transmit_response(p, "202 Accepted", req);
09362 } else {
09363 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);
09364 transmit_response(p, "405 Method Not Allowed", req);
09365 }
09366 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
09367 return;
09368 }
09369
09370
09371 static int sip_show_inuse(int fd, int argc, char *argv[])
09372 {
09373 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
09374 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
09375 char ilimits[40];
09376 char iused[40];
09377 int showall = FALSE;
09378
09379 if (argc < 3)
09380 return RESULT_SHOWUSAGE;
09381
09382 if (argc == 4 && !strcmp(argv[3],"all"))
09383 showall = TRUE;
09384
09385 ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
09386 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
09387 ASTOBJ_RDLOCK(iterator);
09388 if (iterator->call_limit)
09389 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
09390 else
09391 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
09392 snprintf(iused, sizeof(iused), "%d", iterator->inUse);
09393 if (showall || iterator->call_limit)
09394 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
09395 ASTOBJ_UNLOCK(iterator);
09396 } while (0) );
09397
09398 ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
09399
09400 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
09401 ASTOBJ_RDLOCK(iterator);
09402 if (iterator->call_limit)
09403 snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
09404 else
09405 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
09406 snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
09407 if (showall || iterator->call_limit)
09408 ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
09409 ASTOBJ_UNLOCK(iterator);
09410 } while (0) );
09411
09412 return RESULT_SUCCESS;
09413 #undef FORMAT
09414 #undef FORMAT2
09415 }
09416
09417
09418 static char *transfermode2str(enum transfermodes mode)
09419 {
09420 if (mode == TRANSFER_OPENFORALL)
09421 return "open";
09422 else if (mode == TRANSFER_CLOSED)
09423 return "closed";
09424 return "strict";
09425 }
09426
09427
09428 static char *nat2str(int nat)
09429 {
09430 switch(nat) {
09431 case SIP_NAT_NEVER:
09432 return "No";
09433 case SIP_NAT_ROUTE:
09434 return "Route";
09435 case SIP_NAT_ALWAYS:
09436 return "Always";
09437 case SIP_NAT_RFC3581:
09438 return "RFC3581";
09439 default:
09440 return "Unknown";
09441 }
09442 }
09443
09444
09445
09446
09447 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
09448 {
09449 int res = 0;
09450 if (peer->maxms) {
09451 if (peer->lastms < 0) {
09452 ast_copy_string(status, "UNREACHABLE", statuslen);
09453 } else if (peer->lastms > peer->maxms) {
09454 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
09455 res = 1;
09456 } else if (peer->lastms) {
09457 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
09458 res = 1;
09459 } else {
09460 ast_copy_string(status, "UNKNOWN", statuslen);
09461 }
09462 } else {
09463 ast_copy_string(status, "Unmonitored", statuslen);
09464
09465 res = -1;
09466 }
09467 return res;
09468 }
09469
09470
09471 static int sip_show_users(int fd, int argc, char *argv[])
09472 {
09473 regex_t regexbuf;
09474 int havepattern = FALSE;
09475
09476 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
09477
09478 switch (argc) {
09479 case 5:
09480 if (!strcasecmp(argv[3], "like")) {
09481 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
09482 return RESULT_SHOWUSAGE;
09483 havepattern = TRUE;
09484 } else
09485 return RESULT_SHOWUSAGE;
09486 case 3:
09487 break;
09488 default:
09489 return RESULT_SHOWUSAGE;
09490 }
09491
09492 ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
09493 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
09494 ASTOBJ_RDLOCK(iterator);
09495
09496 if (havepattern && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
09497 ASTOBJ_UNLOCK(iterator);
09498 continue;
09499 }
09500
09501 ast_cli(fd, FORMAT, iterator->name,
09502 iterator->secret,
09503 iterator->accountcode,
09504 iterator->context,
09505 iterator->ha ? "Yes" : "No",
09506 nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
09507 ASTOBJ_UNLOCK(iterator);
09508 } while (0)
09509 );
09510
09511 if (havepattern)
09512 regfree(®exbuf);
09513
09514 return RESULT_SUCCESS;
09515 #undef FORMAT
09516 }
09517
09518 static char mandescr_show_peers[] =
09519 "Description: Lists SIP peers in text format with details on current status.\n"
09520 "Variables: \n"
09521 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
09522
09523
09524
09525 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
09526 {
09527 const char *id = astman_get_header(m,"ActionID");
09528 const char *a[] = {"sip", "show", "peers"};
09529 char idtext[256] = "";
09530 int total = 0;
09531
09532 if (!ast_strlen_zero(id))
09533 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
09534
09535 astman_send_ack(s, m, "Peer status list will follow");
09536
09537 _sip_show_peers(-1, &total, s, m, 3, a);
09538
09539 astman_append(s,
09540 "Event: PeerlistComplete\r\n"
09541 "ListItems: %d\r\n"
09542 "%s"
09543 "\r\n", total, idtext);
09544 return 0;
09545 }
09546
09547
09548 static int sip_show_peers(int fd, int argc, char *argv[])
09549 {
09550 return _sip_show_peers(fd, NULL, NULL, NULL, argc, (const char **) argv);
09551 }
09552
09553
09554 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
09555 {
09556 regex_t regexbuf;
09557 int havepattern = FALSE;
09558
09559 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
09560 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"
09561
09562 char name[256];
09563 int total_peers = 0;
09564 int peers_mon_online = 0;
09565 int peers_mon_offline = 0;
09566 int peers_unmon_offline = 0;
09567 int peers_unmon_online = 0;
09568 const char *id;
09569 char idtext[256] = "";
09570 int realtimepeers;
09571
09572 realtimepeers = ast_check_realtime("sippeers");
09573
09574 if (s) {
09575 id = astman_get_header(m,"ActionID");
09576 if (!ast_strlen_zero(id))
09577 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
09578 }
09579
09580 switch (argc) {
09581 case 5:
09582 if (!strcasecmp(argv[3], "like")) {
09583 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
09584 return RESULT_SHOWUSAGE;
09585 havepattern = TRUE;
09586 } else
09587 return RESULT_SHOWUSAGE;
09588 case 3:
09589 break;
09590 default:
09591 return RESULT_SHOWUSAGE;
09592 }
09593
09594 if (!s)
09595 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
09596
09597 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
09598 char status[20] = "";
09599 char srch[2000];
09600 char pstatus;
09601
09602 ASTOBJ_RDLOCK(iterator);
09603
09604 if (havepattern && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
09605 ASTOBJ_UNLOCK(iterator);
09606 continue;
09607 }
09608
09609 if (!ast_strlen_zero(iterator->username) && !s)
09610 snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
09611 else
09612 ast_copy_string(name, iterator->name, sizeof(name));
09613
09614 pstatus = peer_status(iterator, status, sizeof(status));
09615 if (pstatus == 1)
09616 peers_mon_online++;
09617 else if (pstatus == 0)
09618 peers_mon_offline++;
09619 else {
09620 if (iterator->addr.sin_port == 0)
09621 peers_unmon_offline++;
09622 else
09623 peers_unmon_online++;
09624 }
09625
09626 snprintf(srch, sizeof(srch), FORMAT, name,
09627 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
09628 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ",
09629 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
09630 iterator->ha ? " A " : " ",
09631 ntohs(iterator->addr.sin_port), status,
09632 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
09633
09634 if (!s) {
09635 ast_cli(fd, FORMAT, name,
09636 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
09637 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : " ",
09638 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
09639 iterator->ha ? " A " : " ",
09640
09641 ntohs(iterator->addr.sin_port), status,
09642 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
09643 } else {
09644
09645 astman_append(s,
09646 "Event: PeerEntry\r\n%s"
09647 "Channeltype: SIP\r\n"
09648 "ObjectName: %s\r\n"
09649 "ChanObjectType: peer\r\n"
09650 "IPaddress: %s\r\n"
09651 "IPport: %d\r\n"
09652 "Dynamic: %s\r\n"
09653 "Natsupport: %s\r\n"
09654 "VideoSupport: %s\r\n"
09655 "ACL: %s\r\n"
09656 "Status: %s\r\n"
09657 "RealtimeDevice: %s\r\n\r\n",
09658 idtext,
09659 iterator->name,
09660 iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
09661 ntohs(iterator->addr.sin_port),
09662 ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no",
09663 ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
09664 ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
09665 iterator->ha ? "yes" : "no",
09666 status,
09667 realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
09668 }
09669
09670 ASTOBJ_UNLOCK(iterator);
09671
09672 total_peers++;
09673 } while(0) );
09674
09675 if (!s)
09676 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
09677 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
09678
09679 if (havepattern)
09680 regfree(®exbuf);
09681
09682 if (total)
09683 *total = total_peers;
09684
09685
09686 return RESULT_SUCCESS;
09687 #undef FORMAT
09688 #undef FORMAT2
09689 }
09690
09691
09692 static int sip_show_objects(int fd, int argc, char *argv[])
09693 {
09694 char tmp[256];
09695 if (argc != 3)
09696 return RESULT_SHOWUSAGE;
09697 ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
09698 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
09699 ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
09700 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
09701 ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
09702 ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), ®l);
09703 return RESULT_SUCCESS;
09704 }
09705
09706 static void print_group(int fd, ast_group_t group, int crlf)
09707 {
09708 char buf[256];
09709 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
09710 }
09711
09712
09713 static const char *dtmfmode2str(int mode)
09714 {
09715 switch (mode) {
09716 case SIP_DTMF_RFC2833:
09717 return "rfc2833";
09718 case SIP_DTMF_INFO:
09719 return "info";
09720 case SIP_DTMF_INBAND:
09721 return "inband";
09722 case SIP_DTMF_AUTO:
09723 return "auto";
09724 }
09725 return "<error>";
09726 }
09727
09728
09729 static const char *insecure2str(int port, int invite)
09730 {
09731 if (port && invite)
09732 return "port,invite";
09733 else if (port)
09734 return "port";
09735 else if (invite)
09736 return "invite";
09737 else
09738 return "no";
09739 }
09740
09741
09742
09743
09744 static void cleanup_stale_contexts(char *new, char *old)
09745 {
09746 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
09747
09748 while ((oldcontext = strsep(&old, "&"))) {
09749 stalecontext = '\0';
09750 ast_copy_string(newlist, new, sizeof(newlist));
09751 stringp = newlist;
09752 while ((newcontext = strsep(&stringp, "&"))) {
09753 if (strcmp(newcontext, oldcontext) == 0) {
09754
09755 stalecontext = '\0';
09756 break;
09757 } else if (strcmp(newcontext, oldcontext)) {
09758 stalecontext = oldcontext;
09759 }
09760
09761 }
09762 if (stalecontext)
09763 ast_context_destroy(ast_context_find(stalecontext), "SIP");
09764 }
09765 }
09766
09767
09768 static int sip_prune_realtime(int fd, int argc, char *argv[])
09769 {
09770 struct sip_peer *peer;
09771 struct sip_user *user;
09772 int pruneuser = FALSE;
09773 int prunepeer = FALSE;
09774 int multi = FALSE;
09775 char *name = NULL;
09776 regex_t regexbuf;
09777
09778 switch (argc) {
09779 case 4:
09780 if (!strcasecmp(argv[3], "user"))
09781 return RESULT_SHOWUSAGE;
09782 if (!strcasecmp(argv[3], "peer"))
09783 return RESULT_SHOWUSAGE;
09784 if (!strcasecmp(argv[3], "like"))
09785 return RESULT_SHOWUSAGE;
09786 if (!strcasecmp(argv[3], "all")) {
09787 multi = TRUE;
09788 pruneuser = prunepeer = TRUE;
09789 } else {
09790 pruneuser = prunepeer = TRUE;
09791 name = argv[3];
09792 }
09793 break;
09794 case 5:
09795 if (!strcasecmp(argv[4], "like"))
09796 return RESULT_SHOWUSAGE;
09797 if (!strcasecmp(argv[3], "all"))
09798 return RESULT_SHOWUSAGE;
09799 if (!strcasecmp(argv[3], "like")) {
09800 multi = TRUE;
09801 name = argv[4];
09802 pruneuser = prunepeer = TRUE;
09803 } else if (!strcasecmp(argv[3], "user")) {
09804 pruneuser = TRUE;
09805 if (!strcasecmp(argv[4], "all"))
09806 multi = TRUE;
09807 else
09808 name = argv[4];
09809 } else if (!strcasecmp(argv[3], "peer")) {
09810 prunepeer = TRUE;
09811 if (!strcasecmp(argv[4], "all"))
09812 multi = TRUE;
09813 else
09814 name = argv[4];
09815 } else
09816 return RESULT_SHOWUSAGE;
09817 break;
09818 case 6:
09819 if (strcasecmp(argv[4], "like"))
09820 return RESULT_SHOWUSAGE;
09821 if (!strcasecmp(argv[3], "user")) {
09822 pruneuser = TRUE;
09823 name = argv[5];
09824 } else if (!strcasecmp(argv[3], "peer")) {
09825 prunepeer = TRUE;
09826 name = argv[5];
09827 } else
09828 return RESULT_SHOWUSAGE;
09829 break;
09830 default:
09831 return RESULT_SHOWUSAGE;
09832 }
09833
09834 if (multi && name) {
09835 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
09836 return RESULT_SHOWUSAGE;
09837 }
09838
09839 if (multi) {
09840 if (prunepeer) {
09841 int pruned = 0;
09842
09843 ASTOBJ_CONTAINER_WRLOCK(&peerl);
09844 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
09845 ASTOBJ_RDLOCK(iterator);
09846 if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
09847 ASTOBJ_UNLOCK(iterator);
09848 continue;
09849 };
09850 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
09851 ASTOBJ_MARK(iterator);
09852 pruned++;
09853 }
09854 ASTOBJ_UNLOCK(iterator);
09855 } while (0) );
09856 if (pruned) {
09857 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
09858 ast_cli(fd, "%d peers pruned.\n", pruned);
09859 } else
09860 ast_cli(fd, "No peers found to prune.\n");
09861 ASTOBJ_CONTAINER_UNLOCK(&peerl);
09862 }
09863 if (pruneuser) {
09864 int pruned = 0;
09865
09866 ASTOBJ_CONTAINER_WRLOCK(&userl);
09867 ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
09868 ASTOBJ_RDLOCK(iterator);
09869 if (name && regexec(®exbuf, iterator->name, 0, NULL, 0)) {
09870 ASTOBJ_UNLOCK(iterator);
09871 continue;
09872 };
09873 if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
09874 ASTOBJ_MARK(iterator);
09875 pruned++;
09876 }
09877 ASTOBJ_UNLOCK(iterator);
09878 } while (0) );
09879 if (pruned) {
09880 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
09881 ast_cli(fd, "%d users pruned.\n", pruned);
09882 } else
09883 ast_cli(fd, "No users found to prune.\n");
09884 ASTOBJ_CONTAINER_UNLOCK(&userl);
09885 }
09886 } else {
09887 if (prunepeer) {
09888 if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
09889 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
09890 ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
09891 ASTOBJ_CONTAINER_LINK(&peerl, peer);
09892 } else
09893 ast_cli(fd, "Peer '%s' pruned.\n", name);
09894 ASTOBJ_UNREF(peer, sip_destroy_peer);
09895 } else
09896 ast_cli(fd, "Peer '%s' not found.\n", name);
09897 }
09898 if (pruneuser) {
09899 if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
09900 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
09901 ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
09902 ASTOBJ_CONTAINER_LINK(&userl, user);
09903 } else
09904 ast_cli(fd, "User '%s' pruned.\n", name);
09905 ASTOBJ_UNREF(user, sip_destroy_user);
09906 } else
09907 ast_cli(fd, "User '%s' not found.\n", name);
09908 }
09909 }
09910
09911 return RESULT_SUCCESS;
09912 }
09913
09914
09915 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
09916 {
09917 int x, codec;
09918
09919 for(x = 0; x < 32 ; x++) {
09920 codec = ast_codec_pref_index(pref, x);
09921 if (!codec)
09922 break;
09923 ast_cli(fd, "%s", ast_getformatname(codec));
09924 ast_cli(fd, ":%d", pref->framing[x]);
09925 if (x < 31 && ast_codec_pref_index(pref, x + 1))
09926 ast_cli(fd, ",");
09927 }
09928 if (!x)
09929 ast_cli(fd, "none");
09930 }
09931
09932
09933 static const char *domain_mode_to_text(const enum domain_mode mode)
09934 {
09935 switch (mode) {
09936 case SIP_DOMAIN_AUTO:
09937 return "[Automatic]";
09938 case SIP_DOMAIN_CONFIG:
09939 return "[Configured]";
09940 }
09941
09942 return "";
09943 }
09944
09945
09946 static int sip_show_domains(int fd, int argc, char *argv[])
09947 {
09948 struct domain *d;
09949 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
09950
09951 if (AST_LIST_EMPTY(&domain_list)) {
09952 ast_cli(fd, "SIP Domain support not enabled.\n\n");
09953 return RESULT_SUCCESS;
09954 } else {
09955 ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
09956 AST_LIST_LOCK(&domain_list);
09957 AST_LIST_TRAVERSE(&domain_list, d, list)
09958 ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
09959 domain_mode_to_text(d->mode));
09960 AST_LIST_UNLOCK(&domain_list);
09961 ast_cli(fd, "\n");
09962 return RESULT_SUCCESS;
09963 }
09964 }
09965 #undef FORMAT
09966
09967 static char mandescr_show_peer[] =
09968 "Description: Show one SIP peer with details on current status.\n"
09969 "Variables: \n"
09970 " Peer: <name> The peer name you want to check.\n"
09971 " ActionID: <id> Optional action ID for this AMI transaction.\n";
09972
09973
09974 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
09975 {
09976 const char *a[4];
09977 const char *peer;
09978 int ret;
09979
09980 peer = astman_get_header(m,"Peer");
09981 if (ast_strlen_zero(peer)) {
09982 astman_send_error(s, m, "Peer: <name> missing.\n");
09983 return 0;
09984 }
09985 a[0] = "sip";
09986 a[1] = "show";
09987 a[2] = "peer";
09988 a[3] = peer;
09989
09990 ret = _sip_show_peer(1, -1, s, m, 4, a);
09991 astman_append(s, "\r\n\r\n" );
09992 return ret;
09993 }
09994
09995
09996
09997
09998 static int sip_show_peer(int fd, int argc, char *argv[])
09999 {
10000 return _sip_show_peer(0, fd, NULL, NULL, argc, (const char **) argv);
10001 }
10002
10003
10004 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
10005 {
10006 char status[30] = "";
10007 char cbuf[256];
10008 struct sip_peer *peer;
10009 char codec_buf[512];
10010 struct ast_codec_pref *pref;
10011 struct ast_variable *v;
10012 struct sip_auth *auth;
10013 int x = 0, codec = 0, load_realtime;
10014 int realtimepeers;
10015
10016 realtimepeers = ast_check_realtime("sippeers");
10017
10018 if (argc < 4)
10019 return RESULT_SHOWUSAGE;
10020
10021 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10022 peer = find_peer(argv[3], NULL, load_realtime);
10023 if (s) {
10024 if (peer) {
10025 const char *id = astman_get_header(m,"ActionID");
10026
10027 astman_append(s, "Response: Success\r\n");
10028 if (!ast_strlen_zero(id))
10029 astman_append(s, "ActionID: %s\r\n",id);
10030 } else {
10031 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
10032 astman_send_error(s, m, cbuf);
10033 return 0;
10034 }
10035 }
10036 if (peer && type==0 ) {
10037 ast_cli(fd,"\n\n");
10038 ast_cli(fd, " * Name : %s\n", peer->name);
10039 if (realtimepeers) {
10040 ast_cli(fd, " Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
10041 }
10042 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
10043 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
10044 for (auth = peer->auth; auth; auth = auth->next) {
10045 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
10046 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
10047 }
10048 ast_cli(fd, " Context : %s\n", peer->context);
10049 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
10050 ast_cli(fd, " Language : %s\n", peer->language);
10051 if (!ast_strlen_zero(peer->accountcode))
10052 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
10053 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
10054 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
10055 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
10056 if (!ast_strlen_zero(peer->fromuser))
10057 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
10058 if (!ast_strlen_zero(peer->fromdomain))
10059 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
10060 ast_cli(fd, " Callgroup : ");
10061 print_group(fd, peer->callgroup, 0);
10062 ast_cli(fd, " Pickupgroup : ");
10063 print_group(fd, peer->pickupgroup, 0);
10064 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
10065 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
10066 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
10067 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
10068 ast_cli(fd, " Dynamic : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
10069 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
10070 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
10071 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
10072 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)));
10073 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10074 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
10075 ast_cli(fd, " T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
10076 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10077 ast_cli(fd, " T38 pt RTP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
10078 ast_cli(fd, " T38 pt TCP : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
10079 #endif
10080 ast_cli(fd, " CanReinvite : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
10081 ast_cli(fd, " PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
10082 ast_cli(fd, " User=Phone : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
10083 ast_cli(fd, " Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
10084 ast_cli(fd, " Trust RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
10085 ast_cli(fd, " Send RPID : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
10086 ast_cli(fd, " Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10087 ast_cli(fd, " Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10088
10089
10090 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10091 ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
10092 ast_cli(fd, " ToHost : %s\n", peer->tohost);
10093 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));
10094 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
10095 if (!ast_strlen_zero(global_regcontext))
10096 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
10097 ast_cli(fd, " Def. Username: %s\n", peer->username);
10098 ast_cli(fd, " SIP Options : ");
10099 if (peer->sipoptions) {
10100 int lastoption = -1;
10101 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10102 if (sip_options[x].id != lastoption) {
10103 if (peer->sipoptions & sip_options[x].id)
10104 ast_cli(fd, "%s ", sip_options[x].text);
10105 lastoption = x;
10106 }
10107 }
10108 } else
10109 ast_cli(fd, "(none)");
10110
10111 ast_cli(fd, "\n");
10112 ast_cli(fd, " Codecs : ");
10113 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10114 ast_cli(fd, "%s\n", codec_buf);
10115 ast_cli(fd, " Codec Order : (");
10116 print_codec_to_cli(fd, &peer->prefs);
10117 ast_cli(fd, ")\n");
10118
10119 ast_cli(fd, " Auto-Framing: %s \n", peer->autoframing ? "Yes" : "No");
10120 ast_cli(fd, " Status : ");
10121 peer_status(peer, status, sizeof(status));
10122 ast_cli(fd, "%s\n",status);
10123 ast_cli(fd, " Useragent : %s\n", peer->useragent);
10124 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
10125 if (peer->chanvars) {
10126 ast_cli(fd, " Variables :\n");
10127 for (v = peer->chanvars ; v ; v = v->next)
10128 ast_cli(fd, " %s = %s\n", v->name, v->value);
10129 }
10130 ast_cli(fd,"\n");
10131 ASTOBJ_UNREF(peer,sip_destroy_peer);
10132 } else if (peer && type == 1) {
10133 char buf[256];
10134 astman_append(s, "Channeltype: SIP\r\n");
10135 astman_append(s, "ObjectName: %s\r\n", peer->name);
10136 astman_append(s, "ChanObjectType: peer\r\n");
10137 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
10138 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
10139 astman_append(s, "Context: %s\r\n", peer->context);
10140 astman_append(s, "Language: %s\r\n", peer->language);
10141 if (!ast_strlen_zero(peer->accountcode))
10142 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
10143 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
10144 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
10145 if (!ast_strlen_zero(peer->fromuser))
10146 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
10147 if (!ast_strlen_zero(peer->fromdomain))
10148 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
10149 astman_append(s, "Callgroup: ");
10150 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
10151 astman_append(s, "Pickupgroup: ");
10152 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
10153 astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
10154 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
10155 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
10156 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
10157 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
10158 astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
10159 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
10160 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
10161 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)));
10162 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
10163 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
10164 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
10165 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
10166 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
10167 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
10168
10169
10170 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
10171 astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
10172 astman_append(s, "ToHost: %s\r\n", peer->tohost);
10173 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));
10174 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));
10175 astman_append(s, "Default-Username: %s\r\n", peer->username);
10176 if (!ast_strlen_zero(global_regcontext))
10177 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
10178 astman_append(s, "Codecs: ");
10179 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
10180 astman_append(s, "%s\r\n", codec_buf);
10181 astman_append(s, "CodecOrder: ");
10182 pref = &peer->prefs;
10183 for(x = 0; x < 32 ; x++) {
10184 codec = ast_codec_pref_index(pref,x);
10185 if (!codec)
10186 break;
10187 astman_append(s, "%s", ast_getformatname(codec));
10188 if (x < 31 && ast_codec_pref_index(pref,x+1))
10189 astman_append(s, ",");
10190 }
10191
10192 astman_append(s, "\r\n");
10193 astman_append(s, "Status: ");
10194 peer_status(peer, status, sizeof(status));
10195 astman_append(s, "%s\r\n", status);
10196 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
10197 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
10198 if (peer->chanvars) {
10199 for (v = peer->chanvars ; v ; v = v->next) {
10200 astman_append(s, "ChanVariable:\n");
10201 astman_append(s, " %s,%s\r\n", v->name, v->value);
10202 }
10203 }
10204
10205 ASTOBJ_UNREF(peer,sip_destroy_peer);
10206
10207 } else {
10208 ast_cli(fd,"Peer %s not found.\n", argv[3]);
10209 ast_cli(fd,"\n");
10210 }
10211
10212 return RESULT_SUCCESS;
10213 }
10214
10215
10216 static int sip_show_user(int fd, int argc, char *argv[])
10217 {
10218 char cbuf[256];
10219 struct sip_user *user;
10220 struct ast_variable *v;
10221 int load_realtime;
10222
10223 if (argc < 4)
10224 return RESULT_SHOWUSAGE;
10225
10226
10227 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
10228
10229 user = find_user(argv[3], load_realtime);
10230 if (user) {
10231 ast_cli(fd,"\n\n");
10232 ast_cli(fd, " * Name : %s\n", user->name);
10233 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
10234 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
10235 ast_cli(fd, " Context : %s\n", user->context);
10236 ast_cli(fd, " Language : %s\n", user->language);
10237 if (!ast_strlen_zero(user->accountcode))
10238 ast_cli(fd, " Accountcode : %s\n", user->accountcode);
10239 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
10240 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
10241 ast_cli(fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
10242 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
10243 ast_cli(fd, " Call limit : %d\n", user->call_limit);
10244 ast_cli(fd, " Callgroup : ");
10245 print_group(fd, user->callgroup, 0);
10246 ast_cli(fd, " Pickupgroup : ");
10247 print_group(fd, user->pickupgroup, 0);
10248 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
10249 ast_cli(fd, " ACL : %s\n", (user->ha?"Yes":"No"));
10250 ast_cli(fd, " Codec Order : (");
10251 print_codec_to_cli(fd, &user->prefs);
10252 ast_cli(fd, ")\n");
10253
10254 ast_cli(fd, " Auto-Framing: %s \n", user->autoframing ? "Yes" : "No");
10255 if (user->chanvars) {
10256 ast_cli(fd, " Variables :\n");
10257 for (v = user->chanvars ; v ; v = v->next)
10258 ast_cli(fd, " %s = %s\n", v->name, v->value);
10259 }
10260 ast_cli(fd,"\n");
10261 ASTOBJ_UNREF(user,sip_destroy_user);
10262 } else {
10263 ast_cli(fd,"User %s not found.\n", argv[3]);
10264 ast_cli(fd,"\n");
10265 }
10266
10267 return RESULT_SUCCESS;
10268 }
10269
10270
10271 static int sip_show_registry(int fd, int argc, char *argv[])
10272 {
10273 #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s %-25.25s\n"
10274 #define FORMAT "%-30.30s %-12.12s %8d %-20.20s %-25.25s\n"
10275 char host[80];
10276 char tmpdat[256];
10277 struct tm tm;
10278
10279
10280 if (argc != 3)
10281 return RESULT_SHOWUSAGE;
10282 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
10283 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
10284 ASTOBJ_RDLOCK(iterator);
10285 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
10286 if (iterator->regtime) {
10287 ast_localtime(&iterator->regtime, &tm, NULL);
10288 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
10289 } else {
10290 tmpdat[0] = 0;
10291 }
10292 ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
10293 ASTOBJ_UNLOCK(iterator);
10294 } while(0));
10295 return RESULT_SUCCESS;
10296 #undef FORMAT
10297 #undef FORMAT2
10298 }
10299
10300
10301 static int sip_show_settings(int fd, int argc, char *argv[])
10302 {
10303 int realtimepeers;
10304 int realtimeusers;
10305 char codec_buf[BUFSIZ];
10306
10307 realtimepeers = ast_check_realtime("sippeers");
10308 realtimeusers = ast_check_realtime("sipusers");
10309
10310 if (argc != 3)
10311 return RESULT_SHOWUSAGE;
10312 ast_cli(fd, "\n\nGlobal Settings:\n");
10313 ast_cli(fd, "----------------\n");
10314 ast_cli(fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
10315 ast_cli(fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
10316 ast_cli(fd, " Videosupport: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
10317 ast_cli(fd, " AutoCreatePeer: %s\n", autocreatepeer ? "Yes" : "No");
10318 ast_cli(fd, " Allow unknown access: %s\n", global_allowguest ? "Yes" : "No");
10319 ast_cli(fd, " Allow subscriptions: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
10320 ast_cli(fd, " Allow overlap dialing: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
10321 ast_cli(fd, " Promsic. redir: %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10322 ast_cli(fd, " SIP domain support: %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
10323 ast_cli(fd, " Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
10324 ast_cli(fd, " URI user is phone no: %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
10325 ast_cli(fd, " Our auth realm %s\n", global_realm);
10326 ast_cli(fd, " Realm. auth: %s\n", authl ? "Yes": "No");
10327 ast_cli(fd, " Always auth rejects: %s\n", global_alwaysauthreject ? "Yes" : "No");
10328 ast_cli(fd, " Call limit peers only: %s\n", global_limitonpeers ? "Yes" : "No");
10329 ast_cli(fd, " Direct RTP setup: %s\n", global_directrtpsetup ? "Yes" : "No");
10330 ast_cli(fd, " User Agent: %s\n", global_useragent);
10331 ast_cli(fd, " MWI checking interval: %d secs\n", global_mwitime);
10332 ast_cli(fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
10333 ast_cli(fd, " Caller ID: %s\n", default_callerid);
10334 ast_cli(fd, " From: Domain: %s\n", default_fromdomain);
10335 ast_cli(fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
10336 ast_cli(fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
10337 ast_cli(fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
10338 ast_cli(fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
10339 ast_cli(fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
10340 ast_cli(fd, " T38 fax pt UDPTL: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
10341 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
10342 ast_cli(fd, " T38 fax pt RTP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
10343 ast_cli(fd, " T38 fax pt TCP: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
10344 #endif
10345 ast_cli(fd, " RFC2833 Compensation: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
10346 ast_cli(fd, " Jitterbuffer enabled: %s\n", ast_test_flag(&global_jbconf, AST_JB_ENABLED) ? "Yes" : "No");
10347 ast_cli(fd, " Jitterbuffer forced: %s\n", ast_test_flag(&global_jbconf, AST_JB_FORCED) ? "Yes" : "No");
10348 ast_cli(fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
10349 ast_cli(fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
10350 ast_cli(fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
10351 ast_cli(fd, " Jitterbuffer log: %s\n", ast_test_flag(&global_jbconf, AST_JB_LOG) ? "Yes" : "No");
10352 if (!realtimepeers && !realtimeusers)
10353 ast_cli(fd, " SIP realtime: Disabled\n" );
10354 else
10355 ast_cli(fd, " SIP realtime: Enabled\n" );
10356
10357 ast_cli(fd, "\nGlobal Signalling Settings:\n");
10358 ast_cli(fd, "---------------------------\n");
10359 ast_cli(fd, " Codecs: ");
10360 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
10361 ast_cli(fd, "%s\n", codec_buf);
10362 ast_cli(fd, " Codec Order: ");
10363 print_codec_to_cli(fd, &default_prefs);
10364 ast_cli(fd, "\n");
10365 ast_cli(fd, " T1 minimum: %d\n", global_t1min);
10366 ast_cli(fd, " Relax DTMF: %s\n", global_relaxdtmf ? "Yes" : "No");
10367 ast_cli(fd, " Compact SIP headers: %s\n", compactheaders ? "Yes" : "No");
10368 ast_cli(fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
10369 ast_cli(fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
10370 ast_cli(fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
10371 ast_cli(fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
10372 ast_cli(fd, " DNS SRV lookup: %s\n", srvlookup ? "Yes" : "No");
10373 ast_cli(fd, " Pedantic SIP support: %s\n", pedanticsipchecking ? "Yes" : "No");
10374 ast_cli(fd, " Reg. min duration %d secs\n", min_expiry);
10375 ast_cli(fd, " Reg. max duration: %d secs\n", max_expiry);
10376 ast_cli(fd, " Reg. default duration: %d secs\n", default_expiry);
10377 ast_cli(fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
10378 ast_cli(fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
10379 ast_cli(fd, " Notify ringing state: %s\n", global_notifyringing ? "Yes" : "No");
10380 ast_cli(fd, " Notify hold state: %s\n", global_notifyhold ? "Yes" : "No");
10381 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
10382 ast_cli(fd, " Max Call Bitrate: %d kbps\r\n", default_maxcallbitrate);
10383 ast_cli(fd, " Auto-Framing: %s \r\n", global_autoframing ? "Yes" : "No");
10384 ast_cli(fd, "\nDefault Settings:\n");
10385 ast_cli(fd, "-----------------\n");
10386 ast_cli(fd, " Context: %s\n", default_context);
10387 ast_cli(fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
10388 ast_cli(fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
10389 ast_cli(fd, " Qualify: %d\n", default_qualify);
10390 ast_cli(fd, " Use ClientCode: %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
10391 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" );
10392 ast_cli(fd, " Language: %s\n", S_OR(default_language, "(Defaults to English)"));
10393 ast_cli(fd, " MOH Interpret: %s\n", default_mohinterpret);
10394 ast_cli(fd, " MOH Suggest: %s\n", default_mohsuggest);
10395 ast_cli(fd, " Voice Mail Extension: %s\n", default_vmexten);
10396
10397
10398 if (realtimepeers || realtimeusers) {
10399 ast_cli(fd, "\nRealtime SIP Settings:\n");
10400 ast_cli(fd, "----------------------\n");
10401 ast_cli(fd, " Realtime Peers: %s\n", realtimepeers ? "Yes" : "No");
10402 ast_cli(fd, " Realtime Users: %s\n", realtimeusers ? "Yes" : "No");
10403 ast_cli(fd, " Cache Friends: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
10404 ast_cli(fd, " Update: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
10405 ast_cli(fd, " Ignore Reg. Expire: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
10406 ast_cli(fd, " Save sys. name: %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
10407 ast_cli(fd, " Auto Clear: %d\n", global_rtautoclear);
10408 }
10409 ast_cli(fd, "\n----\n");
10410 return RESULT_SUCCESS;
10411 }
10412
10413
10414 static const char *subscription_type2str(enum subscriptiontype subtype)
10415 {
10416 int i;
10417
10418 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10419 if (subscription_types[i].type == subtype) {
10420 return subscription_types[i].text;
10421 }
10422 }
10423 return subscription_types[0].text;
10424 }
10425
10426
10427 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
10428 {
10429 int i;
10430
10431 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
10432 if (subscription_types[i].type == subtype) {
10433 return &subscription_types[i];
10434 }
10435 }
10436 return &subscription_types[0];
10437 }
10438
10439
10440 static int sip_show_channels(int fd, int argc, char *argv[])
10441 {
10442 return __sip_show_channels(fd, argc, argv, 0);
10443 }
10444
10445
10446 static int sip_show_subscriptions(int fd, int argc, char *argv[])
10447 {
10448 return __sip_show_channels(fd, argc, argv, 1);
10449 }
10450
10451
10452 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
10453 {
10454 #define FORMAT3 "%-15.15s %-10.10s %-11.11s %-15.15s %-13.13s %-15.15s %-10.10s\n"
10455 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-4.4s %-7.7s %-15.15s\n"
10456 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-4.4s %-3.3s %-3.3s %-15.15s %-10.10s\n"
10457 struct sip_pvt *cur;
10458 int numchans = 0;
10459 char *referstatus = NULL;
10460
10461 if (argc != 3)
10462 return RESULT_SHOWUSAGE;
10463 ast_mutex_lock(&iflock);
10464 cur = iflist;
10465 if (!subscriptions)
10466 ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
10467 else
10468 ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
10469 for (; cur; cur = cur->next) {
10470 referstatus = "";
10471 if (cur->refer) {
10472 referstatus = referstatus2str(cur->refer->status);
10473 }
10474 if (cur->subscribed == NONE && !subscriptions) {
10475 ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr),
10476 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10477 cur->callid,
10478 cur->ocseq, cur->icseq,
10479 ast_getformatname(cur->owner ? cur->owner->nativeformats : 0),
10480 ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
10481 ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
10482 cur->lastmsg ,
10483 referstatus
10484 );
10485 numchans++;
10486 }
10487 if (cur->subscribed != NONE && subscriptions) {
10488 ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
10489 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
10490 cur->callid,
10491
10492 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
10493 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
10494 subscription_type2str(cur->subscribed),
10495 cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
10496 );
10497 numchans++;
10498 }
10499 }
10500 ast_mutex_unlock(&iflock);
10501 if (!subscriptions)
10502 ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
10503 else
10504 ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
10505 return RESULT_SUCCESS;
10506 #undef FORMAT
10507 #undef FORMAT2
10508 #undef FORMAT3
10509 }
10510
10511
10512 static char *complete_sipch(const char *line, const char *word, int pos, int state)
10513 {
10514 int which=0;
10515 struct sip_pvt *cur;
10516 char *c = NULL;
10517 int wordlen = strlen(word);
10518
10519 ast_mutex_lock(&iflock);
10520 for (cur = iflist; cur; cur = cur->next) {
10521 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
10522 c = ast_strdup(cur->callid);
10523 break;
10524 }
10525 }
10526 ast_mutex_unlock(&iflock);
10527 return c;
10528 }
10529
10530
10531 static char *complete_sip_peer(const char *word, int state, int flags2)
10532 {
10533 char *result = NULL;
10534 int wordlen = strlen(word);
10535 int which = 0;
10536
10537 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
10538
10539 if (!strncasecmp(word, iterator->name, wordlen) &&
10540 (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
10541 ++which > state)
10542 result = ast_strdup(iterator->name);
10543 } while(0) );
10544 return result;
10545 }
10546
10547
10548 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
10549 {
10550 if (pos == 3)
10551 return complete_sip_peer(word, state, 0);
10552
10553 return NULL;
10554 }
10555
10556
10557 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
10558 {
10559 if (pos == 3)
10560 return complete_sip_peer(word, state, 0);
10561
10562 return NULL;
10563 }
10564
10565
10566 static char *complete_sip_user(const char *word, int state, int flags2)
10567 {
10568 char *result = NULL;
10569 int wordlen = strlen(word);
10570 int which = 0;
10571
10572 ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
10573
10574 if (!strncasecmp(word, iterator->name, wordlen)) {
10575 if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
10576 continue;
10577 if (++which > state) {
10578 result = ast_strdup(iterator->name);
10579 }
10580 }
10581 } while(0) );
10582 return result;
10583 }
10584
10585
10586 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
10587 {
10588 if (pos == 3)
10589 return complete_sip_user(word, state, 0);
10590
10591 return NULL;
10592 }
10593
10594
10595 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
10596 {
10597 char *c = NULL;
10598
10599 if (pos == 2) {
10600 int which = 0;
10601 char *cat = NULL;
10602 int wordlen = strlen(word);
10603
10604
10605
10606 if (!notify_types)
10607 return NULL;
10608
10609 while ( (cat = ast_category_browse(notify_types, cat)) ) {
10610 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
10611 c = ast_strdup(cat);
10612 break;
10613 }
10614 }
10615 return c;
10616 }
10617
10618 if (pos > 2)
10619 return complete_sip_peer(word, state, 0);
10620
10621 return NULL;
10622 }
10623
10624
10625 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
10626 {
10627 if (pos == 4)
10628 return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10629 return NULL;
10630 }
10631
10632
10633 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
10634 {
10635 if (pos == 4)
10636 return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
10637
10638 return NULL;
10639 }
10640
10641
10642 static int sip_show_channel(int fd, int argc, char *argv[])
10643 {
10644 struct sip_pvt *cur;
10645 size_t len;
10646 int found = 0;
10647
10648 if (argc != 4)
10649 return RESULT_SHOWUSAGE;
10650 len = strlen(argv[3]);
10651 ast_mutex_lock(&iflock);
10652 for (cur = iflist; cur; cur = cur->next) {
10653 if (!strncasecmp(cur->callid, argv[3], len)) {
10654 char formatbuf[BUFSIZ/2];
10655 ast_cli(fd,"\n");
10656 if (cur->subscribed != NONE)
10657 ast_cli(fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
10658 else
10659 ast_cli(fd, " * SIP Call\n");
10660 ast_cli(fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
10661 ast_cli(fd, " Call-ID: %s\n", cur->callid);
10662 ast_cli(fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
10663 ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
10664 ast_cli(fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
10665 ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
10666 ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
10667 ast_cli(fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
10668 ast_cli(fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
10669 ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
10670 ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
10671 ast_cli(fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
10672 ast_cli(fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
10673 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)" );
10674 ast_cli(fd, " Our Tag: %s\n", cur->tag);
10675 ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
10676 ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
10677 if (!ast_strlen_zero(cur->username))
10678 ast_cli(fd, " Username: %s\n", cur->username);
10679 if (!ast_strlen_zero(cur->peername))
10680 ast_cli(fd, " Peername: %s\n", cur->peername);
10681 if (!ast_strlen_zero(cur->uri))
10682 ast_cli(fd, " Original uri: %s\n", cur->uri);
10683 if (!ast_strlen_zero(cur->cid_num))
10684 ast_cli(fd, " Caller-ID: %s\n", cur->cid_num);
10685 ast_cli(fd, " Need Destroy: %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
10686 ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
10687 ast_cli(fd, " Promiscuous Redir: %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
10688 ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
10689 ast_cli(fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
10690 ast_cli(fd, " SIP Options: ");
10691 if (cur->sipoptions) {
10692 int x;
10693 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
10694 if (cur->sipoptions & sip_options[x].id)
10695 ast_cli(fd, "%s ", sip_options[x].text);
10696 }
10697 } else
10698 ast_cli(fd, "(none)\n");
10699 ast_cli(fd, "\n\n");
10700 found++;
10701 }
10702 }
10703 ast_mutex_unlock(&iflock);
10704 if (!found)
10705 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
10706 return RESULT_SUCCESS;
10707 }
10708
10709
10710 static int sip_show_history(int fd, int argc, char *argv[])
10711 {
10712 struct sip_pvt *cur;
10713 size_t len;
10714 int found = 0;
10715
10716 if (argc != 4)
10717 return RESULT_SHOWUSAGE;
10718 if (!recordhistory)
10719 ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
10720 len = strlen(argv[3]);
10721 ast_mutex_lock(&iflock);
10722 for (cur = iflist; cur; cur = cur->next) {
10723 if (!strncasecmp(cur->callid, argv[3], len)) {
10724 struct sip_history *hist;
10725 int x = 0;
10726
10727 ast_cli(fd,"\n");
10728 if (cur->subscribed != NONE)
10729 ast_cli(fd, " * Subscription\n");
10730 else
10731 ast_cli(fd, " * SIP Call\n");
10732 if (cur->history)
10733 AST_LIST_TRAVERSE(cur->history, hist, list)
10734 ast_cli(fd, "%d. %s\n", ++x, hist->event);
10735 if (x == 0)
10736 ast_cli(fd, "Call '%s' has no history\n", cur->callid);
10737 found++;
10738 }
10739 }
10740 ast_mutex_unlock(&iflock);
10741 if (!found)
10742 ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
10743 return RESULT_SUCCESS;
10744 }
10745
10746
10747 static void sip_dump_history(struct sip_pvt *dialog)
10748 {
10749 int x = 0;
10750 struct sip_history *hist;
10751 static int errmsg = 0;
10752
10753 if (!dialog)
10754 return;
10755
10756 if (!option_debug && !sipdebug) {
10757 if (!errmsg) {
10758 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
10759 errmsg = 1;
10760 }
10761 return;
10762 }
10763
10764 ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
10765 if (dialog->subscribed)
10766 ast_log(LOG_DEBUG, " * Subscription\n");
10767 else
10768 ast_log(LOG_DEBUG, " * SIP Call\n");
10769 if (dialog->history)
10770 AST_LIST_TRAVERSE(dialog->history, hist, list)
10771 ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
10772 if (!x)
10773 ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
10774 ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
10775 }
10776
10777
10778
10779
10780 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
10781 {
10782 char buf[1024];
10783 unsigned int event;
10784 const char *c = get_header(req, "Content-Type");
10785
10786
10787 if (!strcasecmp(c, "application/dtmf-relay") ||
10788 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
10789 unsigned int duration = 0;
10790
10791
10792 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
10793 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
10794 transmit_response(p, "200 OK", req);
10795 return;
10796 } else {
10797 ast_copy_string(buf, c, sizeof(buf));
10798 }
10799
10800 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
10801 duration = atoi(c);
10802 if (!duration)
10803 duration = 100;
10804
10805 if (!p->owner) {
10806 transmit_response(p, "481 Call leg/transaction does not exist", req);
10807 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10808 return;
10809 }
10810
10811 if (ast_strlen_zero(buf)) {
10812 transmit_response(p, "200 OK", req);
10813 return;
10814 }
10815
10816 if (buf[0] == '*')
10817 event = 10;
10818 else if (buf[0] == '#')
10819 event = 11;
10820 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
10821 event = 12 + buf[0] - 'A';
10822 else
10823 event = atoi(buf);
10824 if (event == 16) {
10825
10826 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
10827 ast_queue_frame(p->owner, &f);
10828 if (sipdebug)
10829 ast_verbose("* DTMF-relay event received: FLASH\n");
10830 } else {
10831
10832 struct ast_frame f = { AST_FRAME_DTMF, };
10833 if (event < 10) {
10834 f.subclass = '0' + event;
10835 } else if (event < 11) {
10836 f.subclass = '*';
10837 } else if (event < 12) {
10838 f.subclass = '#';
10839 } else if (event < 16) {
10840 f.subclass = 'A' + (event - 12);
10841 }
10842 f.len = duration;
10843 ast_queue_frame(p->owner, &f);
10844 if (sipdebug)
10845 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
10846 }
10847 transmit_response(p, "200 OK", req);
10848 return;
10849 } else if (!strcasecmp(c, "application/media_control+xml")) {
10850
10851 if (p->owner)
10852 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
10853 transmit_response(p, "200 OK", req);
10854 return;
10855 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
10856
10857 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
10858 if (p->owner && p->owner->cdr)
10859 ast_cdr_setuserfield(p->owner, c);
10860 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
10861 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
10862 transmit_response(p, "200 OK", req);
10863 } else {
10864 transmit_response(p, "403 Unauthorized", req);
10865 }
10866 return;
10867 }
10868
10869
10870
10871 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
10872 transmit_response(p, "415 Unsupported media type", req);
10873 return;
10874 }
10875
10876
10877 static int sip_do_debug_ip(int fd, int argc, char *argv[])
10878 {
10879 struct hostent *hp;
10880 struct ast_hostent ahp;
10881 int port = 0;
10882 char *p, *arg;
10883
10884
10885 if (argc != 5)
10886 return RESULT_SHOWUSAGE;
10887 p = arg = argv[4];
10888 strsep(&p, ":");
10889 if (p)
10890 port = atoi(p);
10891 hp = ast_gethostbyname(arg, &ahp);
10892 if (hp == NULL)
10893 return RESULT_SHOWUSAGE;
10894
10895 debugaddr.sin_family = AF_INET;
10896 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
10897 debugaddr.sin_port = htons(port);
10898 if (port == 0)
10899 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
10900 else
10901 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
10902
10903 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10904
10905 return RESULT_SUCCESS;
10906 }
10907
10908
10909 static int sip_do_debug_peer(int fd, int argc, char *argv[])
10910 {
10911 struct sip_peer *peer;
10912 if (argc != 5)
10913 return RESULT_SHOWUSAGE;
10914 peer = find_peer(argv[4], NULL, 1);
10915 if (peer) {
10916 if (peer->addr.sin_addr.s_addr) {
10917 debugaddr.sin_family = AF_INET;
10918 debugaddr.sin_addr = peer->addr.sin_addr;
10919 debugaddr.sin_port = peer->addr.sin_port;
10920 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
10921 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10922 } else
10923 ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
10924 ASTOBJ_UNREF(peer,sip_destroy_peer);
10925 } else
10926 ast_cli(fd, "No such peer '%s'\n", argv[4]);
10927 return RESULT_SUCCESS;
10928 }
10929
10930
10931 static int sip_do_debug(int fd, int argc, char *argv[])
10932 {
10933 int oldsipdebug = sipdebug_console;
10934 if (argc != 3) {
10935 if (argc != 5)
10936 return RESULT_SHOWUSAGE;
10937 else if (strcmp(argv[3], "ip") == 0)
10938 return sip_do_debug_ip(fd, argc, argv);
10939 else if (strcmp(argv[3], "peer") == 0)
10940 return sip_do_debug_peer(fd, argc, argv);
10941 else
10942 return RESULT_SHOWUSAGE;
10943 }
10944 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10945 memset(&debugaddr, 0, sizeof(debugaddr));
10946 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
10947 return RESULT_SUCCESS;
10948 }
10949
10950 static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
10951 {
10952 int oldsipdebug = sipdebug_console;
10953 char *newargv[6] = { "sip", "set", "debug", NULL };
10954 if (argc != 2) {
10955 if (argc != 4)
10956 return RESULT_SHOWUSAGE;
10957 else if (strcmp(argv[2], "ip") == 0) {
10958 newargv[3] = argv[2];
10959 newargv[4] = argv[3];
10960 return sip_do_debug_ip(fd, argc + 1, newargv);
10961 } else if (strcmp(argv[2], "peer") == 0) {
10962 newargv[3] = argv[2];
10963 newargv[4] = argv[3];
10964 return sip_do_debug_peer(fd, argc + 1, newargv);
10965 } else
10966 return RESULT_SHOWUSAGE;
10967 }
10968 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
10969 memset(&debugaddr, 0, sizeof(debugaddr));
10970 ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
10971 return RESULT_SUCCESS;
10972 }
10973
10974
10975 static int sip_notify(int fd, int argc, char *argv[])
10976 {
10977 struct ast_variable *varlist;
10978 int i;
10979
10980 if (argc < 4)
10981 return RESULT_SHOWUSAGE;
10982
10983 if (!notify_types) {
10984 ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
10985 return RESULT_FAILURE;
10986 }
10987
10988 varlist = ast_variable_browse(notify_types, argv[2]);
10989
10990 if (!varlist) {
10991 ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
10992 return RESULT_FAILURE;
10993 }
10994
10995 for (i = 3; i < argc; i++) {
10996 struct sip_pvt *p;
10997 struct sip_request req;
10998 struct ast_variable *var;
10999
11000 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
11001 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
11002 return RESULT_FAILURE;
11003 }
11004
11005 if (create_addr(p, argv[i])) {
11006
11007 sip_destroy(p);
11008 ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
11009 continue;
11010 }
11011
11012 initreqprep(&req, p, SIP_NOTIFY);
11013
11014 for (var = varlist; var; var = var->next)
11015 add_header(&req, var->name, var->value);
11016
11017
11018 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
11019 p->ourip = __ourip;
11020 build_via(p);
11021 build_callid_pvt(p);
11022 ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
11023 transmit_sip_request(p, &req);
11024 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11025 }
11026
11027 return RESULT_SUCCESS;
11028 }
11029
11030
11031 static int sip_no_debug(int fd, int argc, char *argv[])
11032 {
11033 if (argc != 4)
11034 return RESULT_SHOWUSAGE;
11035 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11036 ast_cli(fd, "SIP Debugging Disabled\n");
11037 return RESULT_SUCCESS;
11038 }
11039
11040 static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
11041 {
11042 if (argc != 3)
11043 return RESULT_SHOWUSAGE;
11044 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
11045 ast_cli(fd, "SIP Debugging Disabled\n");
11046 return RESULT_SUCCESS;
11047 }
11048
11049
11050 static int sip_do_history(int fd, int argc, char *argv[])
11051 {
11052 if (argc != 2) {
11053 return RESULT_SHOWUSAGE;
11054 }
11055 recordhistory = TRUE;
11056 ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
11057 return RESULT_SUCCESS;
11058 }
11059
11060
11061 static int sip_no_history(int fd, int argc, char *argv[])
11062 {
11063 if (argc != 3) {
11064 return RESULT_SHOWUSAGE;
11065 }
11066 recordhistory = FALSE;
11067 ast_cli(fd, "SIP History Recording Disabled\n");
11068 return RESULT_SUCCESS;
11069 }
11070
11071
11072 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
11073 {
11074 char digest[1024];
11075 p->authtries++;
11076 memset(digest,0,sizeof(digest));
11077 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
11078
11079
11080 if (sip_debug_test_pvt(p) && p->registry)
11081 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
11082
11083 return -1;
11084 }
11085 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
11086 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
11087 if (sip_debug_test_pvt(p) && p->registry)
11088 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
11089 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
11090 }
11091
11092
11093 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
11094 {
11095 char digest[1024];
11096
11097 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
11098 return -2;
11099
11100 p->authtries++;
11101 if (option_debug > 1)
11102 ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
11103 memset(digest, 0, sizeof(digest));
11104 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
11105
11106 return -1;
11107 }
11108
11109 p->options->auth = digest;
11110 p->options->authheader = respheader;
11111 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
11112 }
11113
11114
11115
11116
11117
11118 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
11119 {
11120 char tmp[512];
11121 char *c;
11122 char oldnonce[256];
11123
11124
11125 const struct x {
11126 const char *key;
11127 int field_index;
11128 } *i, keys[] = {
11129 { "realm=", ast_string_field_index(p, realm) },
11130 { "nonce=", ast_string_field_index(p, nonce) },
11131 { "opaque=", ast_string_field_index(p, opaque) },
11132 { "qop=", ast_string_field_index(p, qop) },
11133 { "domain=", ast_string_field_index(p, domain) },
11134 { NULL, 0 },
11135 };
11136
11137 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
11138 if (ast_strlen_zero(tmp))
11139 return -1;
11140 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
11141 ast_log(LOG_WARNING, "missing Digest.\n");
11142 return -1;
11143 }
11144 c = tmp + strlen("Digest ");
11145 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
11146 while (c && *(c = ast_skip_blanks(c))) {
11147 for (i = keys; i->key != NULL; i++) {
11148 char *src, *separator;
11149 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11150 continue;
11151
11152 c += strlen(i->key);
11153 if (*c == '"') {
11154 src = ++c;
11155 separator = "\"";
11156 } else {
11157 src = c;
11158 separator = ",";
11159 }
11160 strsep(&c, separator);
11161 ast_string_field_index_set(p, i->field_index, src);
11162 break;
11163 }
11164 if (i->key == NULL)
11165 strsep(&c, ",");
11166 }
11167
11168 if (strcmp(p->nonce, oldnonce))
11169 p->noncecount = 0;
11170
11171
11172 if (p->registry) {
11173 struct sip_registry *r = p->registry;
11174
11175 if (strcmp(r->nonce, p->nonce)) {
11176 ast_string_field_set(r, realm, p->realm);
11177 ast_string_field_set(r, nonce, p->nonce);
11178 ast_string_field_set(r, domain, p->domain);
11179 ast_string_field_set(r, opaque, p->opaque);
11180 ast_string_field_set(r, qop, p->qop);
11181 r->noncecount = 0;
11182 }
11183 }
11184 return build_reply_digest(p, sipmethod, digest, digest_len);
11185 }
11186
11187
11188
11189
11190
11191
11192 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
11193 {
11194 char a1[256];
11195 char a2[256];
11196 char a1_hash[256];
11197 char a2_hash[256];
11198 char resp[256];
11199 char resp_hash[256];
11200 char uri[256];
11201 char cnonce[80];
11202 const char *username;
11203 const char *secret;
11204 const char *md5secret;
11205 struct sip_auth *auth = NULL;
11206
11207 if (!ast_strlen_zero(p->domain))
11208 ast_copy_string(uri, p->domain, sizeof(uri));
11209 else if (!ast_strlen_zero(p->uri))
11210 ast_copy_string(uri, p->uri, sizeof(uri));
11211 else
11212 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));
11213
11214 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
11215
11216
11217 if ((auth = find_realm_authentication(authl, p->realm))) {
11218 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
11219 auth->username, p->peername, p->username);
11220 username = auth->username;
11221 secret = auth->secret;
11222 md5secret = auth->md5secret;
11223 if (sipdebug)
11224 ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
11225 } else {
11226
11227 username = p->authname;
11228 secret = p->peersecret;
11229 md5secret = p->peermd5secret;
11230 }
11231 if (ast_strlen_zero(username))
11232 return -1;
11233
11234
11235 snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
11236 snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
11237 if (!ast_strlen_zero(md5secret))
11238 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11239 else
11240 ast_md5_hash(a1_hash,a1);
11241 ast_md5_hash(a2_hash,a2);
11242
11243 p->noncecount++;
11244 if (!ast_strlen_zero(p->qop))
11245 snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
11246 else
11247 snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
11248 ast_md5_hash(resp_hash, resp);
11249
11250 if (!ast_strlen_zero(p->qop))
11251 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);
11252 else
11253 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);
11254
11255 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
11256
11257 return 0;
11258 }
11259
11260 static char show_domains_usage[] =
11261 "Usage: sip show domains\n"
11262 " Lists all configured SIP local domains.\n"
11263 " Asterisk only responds to SIP messages to local domains.\n";
11264
11265 static char notify_usage[] =
11266 "Usage: sip notify <type> <peer> [<peer>...]\n"
11267 " Send a NOTIFY message to a SIP peer or peers\n"
11268 " Message types are defined in sip_notify.conf\n";
11269
11270 static char show_users_usage[] =
11271 "Usage: sip show users [like <pattern>]\n"
11272 " Lists all known SIP users.\n"
11273 " Optional regular expression pattern is used to filter the user list.\n";
11274
11275 static char show_user_usage[] =
11276 "Usage: sip show user <name> [load]\n"
11277 " Shows all details on one SIP user and the current status.\n"
11278 " Option \"load\" forces lookup of peer in realtime storage.\n";
11279
11280 static char show_inuse_usage[] =
11281 "Usage: sip show inuse [all]\n"
11282 " List all SIP users and peers usage counters and limits.\n"
11283 " Add option \"all\" to show all devices, not only those with a limit.\n";
11284
11285 static char show_channels_usage[] =
11286 "Usage: sip show channels\n"
11287 " Lists all currently active SIP channels.\n";
11288
11289 static char show_channel_usage[] =
11290 "Usage: sip show channel <channel>\n"
11291 " Provides detailed status on a given SIP channel.\n";
11292
11293 static char show_history_usage[] =
11294 "Usage: sip show history <channel>\n"
11295 " Provides detailed dialog history on a given SIP channel.\n";
11296
11297 static char show_peers_usage[] =
11298 "Usage: sip show peers [like <pattern>]\n"
11299 " Lists all known SIP peers.\n"
11300 " Optional regular expression pattern is used to filter the peer list.\n";
11301
11302 static char show_peer_usage[] =
11303 "Usage: sip show peer <name> [load]\n"
11304 " Shows all details on one SIP peer and the current status.\n"
11305 " Option \"load\" forces lookup of peer in realtime storage.\n";
11306
11307 static char prune_realtime_usage[] =
11308 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
11309 " Prunes object(s) from the cache.\n"
11310 " Optional regular expression pattern is used to filter the objects.\n";
11311
11312 static char show_reg_usage[] =
11313 "Usage: sip show registry\n"
11314 " Lists all registration requests and status.\n";
11315
11316 static char debug_usage[] =
11317 "Usage: sip set debug\n"
11318 " Enables dumping of SIP packets for debugging purposes\n\n"
11319 " sip set debug ip <host[:PORT]>\n"
11320 " Enables dumping of SIP packets to and from host.\n\n"
11321 " sip set debug peer <peername>\n"
11322 " Enables dumping of SIP packets to and from host.\n"
11323 " Require peer to be registered.\n";
11324
11325 static char no_debug_usage[] =
11326 "Usage: sip set debug off\n"
11327 " Disables dumping of SIP packets for debugging purposes\n";
11328
11329 static char no_history_usage[] =
11330 "Usage: sip history off\n"
11331 " Disables recording of SIP dialog history for debugging purposes\n";
11332
11333 static char history_usage[] =
11334 "Usage: sip history\n"
11335 " Enables recording of SIP dialog history for debugging purposes.\n"
11336 "Use 'sip show history' to view the history of a call number.\n";
11337
11338 static char sip_reload_usage[] =
11339 "Usage: sip reload\n"
11340 " Reloads SIP configuration from sip.conf\n";
11341
11342 static char show_subscriptions_usage[] =
11343 "Usage: sip show subscriptions\n"
11344 " Lists active SIP subscriptions for extension states\n";
11345
11346 static char show_objects_usage[] =
11347 "Usage: sip show objects\n"
11348 " Lists status of known SIP objects\n";
11349
11350 static char show_settings_usage[] =
11351 "Usage: sip show settings\n"
11352 " Provides detailed list of the configuration of the SIP channel.\n";
11353
11354
11355 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
11356 {
11357 struct sip_pvt *p;
11358 const char *content = NULL;
11359 AST_DECLARE_APP_ARGS(args,
11360 AST_APP_ARG(header);
11361 AST_APP_ARG(number);
11362 );
11363 int i, number, start = 0;
11364
11365 if (ast_strlen_zero(data)) {
11366 ast_log(LOG_WARNING, "This function requires a header name.\n");
11367 return -1;
11368 }
11369
11370 ast_channel_lock(chan);
11371 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11372 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11373 ast_channel_unlock(chan);
11374 return -1;
11375 }
11376
11377 AST_STANDARD_APP_ARGS(args, data);
11378 if (!args.number) {
11379 number = 1;
11380 } else {
11381 sscanf(args.number, "%d", &number);
11382 if (number < 1)
11383 number = 1;
11384 }
11385
11386 p = chan->tech_pvt;
11387
11388
11389 if (!p) {
11390 ast_channel_unlock(chan);
11391 return -1;
11392 }
11393
11394 for (i = 0; i < number; i++)
11395 content = __get_header(&p->initreq, args.header, &start);
11396
11397 if (ast_strlen_zero(content)) {
11398 ast_channel_unlock(chan);
11399 return -1;
11400 }
11401
11402 ast_copy_string(buf, content, len);
11403 ast_channel_unlock(chan);
11404
11405 return 0;
11406 }
11407
11408 static struct ast_custom_function sip_header_function = {
11409 .name = "SIP_HEADER",
11410 .synopsis = "Gets the specified SIP header",
11411 .syntax = "SIP_HEADER(<name>[,<number>])",
11412 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
11413 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
11414 "that name to retrieve. Headers start at offset 1.\n",
11415 .read = func_header_read,
11416 };
11417
11418
11419 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11420 {
11421 if (ast_strlen_zero(data)) {
11422 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
11423 return -1;
11424 }
11425 if (check_sip_domain(data, NULL, 0))
11426 ast_copy_string(buf, data, len);
11427 else
11428 buf[0] = '\0';
11429 return 0;
11430 }
11431
11432 static struct ast_custom_function checksipdomain_function = {
11433 .name = "CHECKSIPDOMAIN",
11434 .synopsis = "Checks if domain is a local domain",
11435 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
11436 .read = func_check_sipdomain,
11437 .desc = "This function checks if the domain in the argument is configured\n"
11438 "as a local SIP domain that this Asterisk server is configured to handle.\n"
11439 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
11440 "Check the domain= configuration in sip.conf\n",
11441 };
11442
11443
11444 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11445 {
11446 struct sip_peer *peer;
11447 char *colname;
11448
11449 if ((colname = strchr(data, ':')))
11450 *colname++ = '\0';
11451 else if ((colname = strchr(data, '|')))
11452 *colname++ = '\0';
11453 else
11454 colname = "ip";
11455
11456 if (!(peer = find_peer(data, NULL, 1)))
11457 return -1;
11458
11459 if (!strcasecmp(colname, "ip")) {
11460 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11461 } else if (!strcasecmp(colname, "status")) {
11462 peer_status(peer, buf, len);
11463 } else if (!strcasecmp(colname, "language")) {
11464 ast_copy_string(buf, peer->language, len);
11465 } else if (!strcasecmp(colname, "regexten")) {
11466 ast_copy_string(buf, peer->regexten, len);
11467 } else if (!strcasecmp(colname, "limit")) {
11468 snprintf(buf, len, "%d", peer->call_limit);
11469 } else if (!strcasecmp(colname, "curcalls")) {
11470 snprintf(buf, len, "%d", peer->inUse);
11471 } else if (!strcasecmp(colname, "accountcode")) {
11472 ast_copy_string(buf, peer->accountcode, len);
11473 } else if (!strcasecmp(colname, "useragent")) {
11474 ast_copy_string(buf, peer->useragent, len);
11475 } else if (!strcasecmp(colname, "mailbox")) {
11476 ast_copy_string(buf, peer->mailbox, len);
11477 } else if (!strcasecmp(colname, "context")) {
11478 ast_copy_string(buf, peer->context, len);
11479 } else if (!strcasecmp(colname, "expire")) {
11480 snprintf(buf, len, "%d", peer->expire);
11481 } else if (!strcasecmp(colname, "dynamic")) {
11482 ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
11483 } else if (!strcasecmp(colname, "callerid_name")) {
11484 ast_copy_string(buf, peer->cid_name, len);
11485 } else if (!strcasecmp(colname, "callerid_num")) {
11486 ast_copy_string(buf, peer->cid_num, len);
11487 } else if (!strcasecmp(colname, "codecs")) {
11488 ast_getformatname_multiple(buf, len -1, peer->capability);
11489 } else if (!strncasecmp(colname, "codec[", 6)) {
11490 char *codecnum;
11491 int index = 0, codec = 0;
11492
11493 codecnum = colname + 6;
11494 codecnum = strsep(&codecnum, "]");
11495 index = atoi(codecnum);
11496 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
11497 ast_copy_string(buf, ast_getformatname(codec), len);
11498 }
11499 }
11500
11501 ASTOBJ_UNREF(peer, sip_destroy_peer);
11502
11503 return 0;
11504 }
11505
11506
11507 struct ast_custom_function sippeer_function = {
11508 .name = "SIPPEER",
11509 .synopsis = "Gets SIP peer information",
11510 .syntax = "SIPPEER(<peername>[|item])",
11511 .read = function_sippeer,
11512 .desc = "Valid items are:\n"
11513 "- ip (default) The IP address.\n"
11514 "- mailbox The configured mailbox.\n"
11515 "- context The configured context.\n"
11516 "- expire The epoch time of the next expire.\n"
11517 "- dynamic Is it dynamic? (yes/no).\n"
11518 "- callerid_name The configured Caller ID name.\n"
11519 "- callerid_num The configured Caller ID number.\n"
11520 "- codecs The configured codecs.\n"
11521 "- status Status (if qualify=yes).\n"
11522 "- regexten Registration extension\n"
11523 "- limit Call limit (call-limit)\n"
11524 "- curcalls Current amount of calls \n"
11525 " Only available if call-limit is set\n"
11526 "- language Default language for peer\n"
11527 "- accountcode Account code for this peer\n"
11528 "- useragent Current user agent id for peer\n"
11529 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11530 "\n"
11531 };
11532
11533
11534 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
11535 {
11536 struct sip_pvt *p;
11537
11538 *buf = 0;
11539
11540 if (!data) {
11541 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
11542 return -1;
11543 }
11544
11545 ast_channel_lock(chan);
11546 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
11547 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
11548 ast_channel_unlock(chan);
11549 return -1;
11550 }
11551
11552 p = chan->tech_pvt;
11553
11554
11555 if (!p) {
11556 ast_channel_unlock(chan);
11557 return -1;
11558 }
11559
11560 if (!strcasecmp(data, "peerip")) {
11561 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
11562 } else if (!strcasecmp(data, "recvip")) {
11563 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
11564 } else if (!strcasecmp(data, "from")) {
11565 ast_copy_string(buf, p->from, len);
11566 } else if (!strcasecmp(data, "uri")) {
11567 ast_copy_string(buf, p->uri, len);
11568 } else if (!strcasecmp(data, "useragent")) {
11569 ast_copy_string(buf, p->useragent, len);
11570 } else if (!strcasecmp(data, "peername")) {
11571 ast_copy_string(buf, p->peername, len);
11572 } else if (!strcasecmp(data, "t38passthrough")) {
11573 if (p->t38.state == T38_DISABLED)
11574 ast_copy_string(buf, "0", sizeof("0"));
11575 else
11576 ast_copy_string(buf, "1", sizeof("1"));
11577 } else {
11578 ast_channel_unlock(chan);
11579 return -1;
11580 }
11581 ast_channel_unlock(chan);
11582
11583 return 0;
11584 }
11585
11586
11587 static struct ast_custom_function sipchaninfo_function = {
11588 .name = "SIPCHANINFO",
11589 .synopsis = "Gets the specified SIP parameter from the current channel",
11590 .syntax = "SIPCHANINFO(item)",
11591 .read = function_sipchaninfo_read,
11592 .desc = "Valid items are:\n"
11593 "- peerip The IP address of the peer.\n"
11594 "- recvip The source IP address of the peer.\n"
11595 "- from The URI from the From: header.\n"
11596 "- uri The URI from the Contact: header.\n"
11597 "- useragent The useragent.\n"
11598 "- peername The name of the peer.\n"
11599 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
11600 };
11601
11602
11603 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
11604 {
11605 char tmp[BUFSIZ];
11606 char *s, *e;
11607 char *domain;
11608
11609 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
11610 s = get_in_brackets(tmp);
11611 s = strsep(&s, ";");
11612 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
11613 if (!strncasecmp(s, "sip:", 4))
11614 s += 4;
11615 e = strchr(s, '/');
11616 if (e)
11617 *e = '\0';
11618 if (option_debug)
11619 ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
11620 if (p->owner)
11621 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
11622 } else {
11623 e = strchr(tmp, '@');
11624 if (e) {
11625 *e++ = '\0';
11626 domain = e;
11627 } else {
11628
11629 domain = tmp;
11630 }
11631 e = strchr(tmp, '/');
11632 if (e)
11633 *e = '\0';
11634 if (!strncasecmp(s, "sip:", 4))
11635 s += 4;
11636 if (option_debug > 1)
11637 ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
11638 if (p->owner) {
11639 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
11640 ast_string_field_set(p->owner, call_forward, s);
11641 }
11642 }
11643 }
11644
11645
11646 static void check_pendings(struct sip_pvt *p)
11647 {
11648 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
11649
11650 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
11651 transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
11652
11653
11654 else
11655 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
11656 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
11657 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11658 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
11659 if (option_debug)
11660 ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
11661
11662 transmit_reinvite_with_sdp(p);
11663 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
11664 }
11665 }
11666
11667
11668 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
11669 {
11670 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
11671 int res = 0;
11672 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
11673 struct ast_channel *bridgepeer = NULL;
11674
11675 if (option_debug > 3) {
11676 if (reinvite)
11677 ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
11678 else
11679 ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
11680 }
11681
11682 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
11683 if (option_debug)
11684 ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
11685 return;
11686 }
11687
11688
11689 if (p->initid > -1) {
11690
11691 ast_sched_del(sched, p->initid);
11692 p->initid = -1;
11693 }
11694
11695
11696
11697
11698 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 183)
11699 resp = 183;
11700
11701
11702 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
11703 p->invitestate = INV_PROCEEDING;
11704
11705
11706 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
11707 p->invitestate = INV_COMPLETED;
11708
11709
11710 switch (resp) {
11711 case 100:
11712 case 101:
11713 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11714 sip_cancel_destroy(p);
11715 check_pendings(p);
11716 break;
11717
11718 case 180:
11719 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11720 sip_cancel_destroy(p);
11721 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11722 ast_queue_control(p->owner, AST_CONTROL_RINGING);
11723 if (p->owner->_state != AST_STATE_UP) {
11724 ast_setstate(p->owner, AST_STATE_RINGING);
11725 }
11726 }
11727 if (find_sdp(req)) {
11728 p->invitestate = INV_EARLY_MEDIA;
11729 res = process_sdp(p, req);
11730 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11731
11732 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11733 }
11734 }
11735 check_pendings(p);
11736 break;
11737
11738 case 183:
11739 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11740 sip_cancel_destroy(p);
11741
11742 if (find_sdp(req)) {
11743 p->invitestate = INV_EARLY_MEDIA;
11744 res = process_sdp(p, req);
11745 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11746
11747 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
11748 }
11749 }
11750 check_pendings(p);
11751 break;
11752
11753 case 200:
11754 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11755 sip_cancel_destroy(p);
11756 p->authtries = 0;
11757 if (find_sdp(req)) {
11758 if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
11759 if (!reinvite)
11760
11761
11762 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11763 }
11764
11765
11766
11767
11768 if (outgoing) {
11769 update_call_counter(p, DEC_CALL_RINGING);
11770 parse_ok_contact(p, req);
11771 if(set_address_from_contact(p)) {
11772
11773
11774
11775
11776
11777
11778
11779 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11780 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11781 }
11782
11783
11784 build_route(p, req, 1);
11785 }
11786
11787 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) {
11788 struct sip_pvt *bridgepvt = NULL;
11789
11790 if (!bridgepeer->tech) {
11791 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
11792 break;
11793 }
11794 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
11795 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
11796 if (bridgepvt->udptl) {
11797 if (p->t38.state == T38_PEER_REINVITE) {
11798 sip_handle_t38_reinvite(bridgepeer, p, 0);
11799 ast_rtp_set_rtptimers_onhold(p->rtp);
11800 if (p->vrtp)
11801 ast_rtp_set_rtptimers_onhold(p->vrtp);
11802 } else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
11803 ast_log(LOG_WARNING, "RTP re-inivte after T38 session not handled yet !\n");
11804
11805
11806 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11807 }
11808 } else {
11809 if (option_debug > 1)
11810 ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
11811 ast_mutex_lock(&bridgepvt->lock);
11812 bridgepvt->t38.state = T38_DISABLED;
11813 ast_mutex_unlock(&bridgepvt->lock);
11814 if (option_debug)
11815 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
11816 p->t38.state = T38_DISABLED;
11817 if (option_debug > 1)
11818 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11819 }
11820 } else {
11821
11822 if (option_debug > 1)
11823 ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
11824 p->t38.state = T38_DISABLED;
11825 if (option_debug > 1)
11826 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11827 }
11828 }
11829 if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
11830
11831 p->t38.state = T38_ENABLED;
11832 if (option_debug)
11833 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11834 }
11835
11836 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
11837 if (!reinvite) {
11838 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
11839 } else {
11840 ast_queue_frame(p->owner, &ast_null_frame);
11841 }
11842 } else {
11843
11844
11845
11846 if (!ast_test_flag(req, SIP_PKT_IGNORE))
11847 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11848 }
11849
11850 p->invitestate = INV_TERMINATED;
11851 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
11852 check_pendings(p);
11853 break;
11854 case 407:
11855 case 401:
11856
11857 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11858 if (p->options)
11859 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
11860
11861
11862 ast_string_field_free(p, theirtag);
11863 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
11864 char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
11865 char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
11866 if (p->authtries < MAX_AUTHTRIES)
11867 p->invitestate = INV_CALLING;
11868 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
11869 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
11870 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11871 sip_alreadygone(p);
11872 if (p->owner)
11873 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11874 }
11875 }
11876 break;
11877
11878 case 403:
11879
11880 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11881 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
11882 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
11883 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11884 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11885 sip_alreadygone(p);
11886 break;
11887
11888 case 404:
11889 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11890 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11891 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11892 sip_alreadygone(p);
11893 break;
11894
11895 case 481:
11896
11897 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
11898 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11899 if (p->owner)
11900 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11901 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11902 break;
11903 case 487:
11904
11905
11906
11907 transmit_request(p, SIP_ACK, seqno, 0, 0);
11908 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11909 ast_queue_hangup(p->owner);
11910 else if (!ast_test_flag(req, SIP_PKT_IGNORE))
11911 update_call_counter(p, DEC_CALL_LIMIT);
11912 break;
11913 case 488:
11914 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11915 if (reinvite && p->udptl) {
11916
11917
11918
11919
11920
11921 p->t38.state = T38_DISABLED;
11922
11923 ast_rtp_set_rtptimers_onhold(p->rtp);
11924 ast_log(LOG_ERROR, "Got error on T.38 re-invite. Bad configuration. Peer needs to have T.38 disabled.\n");
11925
11926
11927
11928
11929
11930 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11931 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11932 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11933 } else {
11934
11935 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11936 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11937 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11938 }
11939 break;
11940 case 491:
11941
11942
11943
11944 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
11945 if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
11946 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11947 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11948 break;
11949
11950 case 501:
11951 transmit_request(p, SIP_ACK, seqno, 0, 0);
11952 if (p->owner)
11953 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
11954 break;
11955 }
11956 }
11957
11958
11959
11960
11961 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
11962 {
11963 char *auth = "Proxy-Authenticate";
11964 char *auth2 = "Proxy-Authorization";
11965
11966
11967 if (!p->refer)
11968 return;
11969
11970 switch (resp) {
11971 case 202:
11972
11973
11974 p->refer->status = REFER_ACCEPTED;
11975
11976 if (option_debug > 2)
11977 ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
11978
11979 break;
11980
11981 case 401:
11982 case 407:
11983 if (ast_strlen_zero(p->authname)) {
11984 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
11985 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11986 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11987 }
11988 if (resp == 401) {
11989 auth = "WWW-Authenticate";
11990 auth2 = "Authorization";
11991 }
11992 if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
11993 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
11994 p->refer->status = REFER_NOAUTH;
11995 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
11996 }
11997 break;
11998 case 481:
11999
12000
12001
12002
12003 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
12004 if (p->owner)
12005 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12006 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12007 break;
12008
12009 case 500:
12010 case 501:
12011
12012
12013 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
12014 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12015 p->refer->status = REFER_FAILED;
12016 break;
12017 case 603:
12018 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
12019 p->refer->status = REFER_FAILED;
12020 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12021 break;
12022 }
12023 }
12024
12025
12026 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12027 {
12028 int expires, expires_ms;
12029 struct sip_registry *r;
12030 r=p->registry;
12031
12032 switch (resp) {
12033 case 401:
12034 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
12035 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
12036 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12037 }
12038 break;
12039 case 403:
12040 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
12041 if (global_regattempts_max)
12042 p->registry->regattempts = global_regattempts_max+1;
12043 ast_sched_del(sched, r->timeout);
12044 r->timeout = -1;
12045 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12046 break;
12047 case 404:
12048 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
12049 if (global_regattempts_max)
12050 p->registry->regattempts = global_regattempts_max+1;
12051 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12052 r->call = NULL;
12053 ast_sched_del(sched, r->timeout);
12054 r->timeout = -1;
12055 break;
12056 case 407:
12057 if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
12058 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
12059 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12060 }
12061 break;
12062 case 479:
12063 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
12064 if (global_regattempts_max)
12065 p->registry->regattempts = global_regattempts_max+1;
12066 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12067 r->call = NULL;
12068 ast_sched_del(sched, r->timeout);
12069 r->timeout = -1;
12070 break;
12071 case 200:
12072 if (!r) {
12073 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
12074 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12075 return 0;
12076 }
12077
12078 r->regstate = REG_STATE_REGISTERED;
12079 r->regtime = time(NULL);
12080 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
12081 r->regattempts = 0;
12082 if (option_debug)
12083 ast_log(LOG_DEBUG, "Registration successful\n");
12084 if (r->timeout > -1) {
12085 if (option_debug)
12086 ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
12087 ast_sched_del(sched, r->timeout);
12088 }
12089 r->timeout=-1;
12090 r->call = NULL;
12091 p->registry = NULL;
12092
12093 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12094
12095
12096
12097
12098 if (r->expire > -1)
12099 ast_sched_del(sched, r->expire);
12100
12101
12102 expires = 0;
12103
12104
12105 if (!ast_strlen_zero(get_header(req, "Contact"))) {
12106 const char *contact = NULL;
12107 const char *tmptmp = NULL;
12108 int start = 0;
12109 for(;;) {
12110 contact = __get_header(req, "Contact", &start);
12111
12112 if(!ast_strlen_zero(contact)) {
12113 if( (tmptmp=strstr(contact, p->our_contact))) {
12114 contact=tmptmp;
12115 break;
12116 }
12117 } else
12118 break;
12119 }
12120 tmptmp = strcasestr(contact, "expires=");
12121 if (tmptmp) {
12122 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
12123 expires = 0;
12124 }
12125
12126 }
12127 if (!expires)
12128 expires=atoi(get_header(req, "expires"));
12129 if (!expires)
12130 expires=default_expiry;
12131
12132 expires_ms = expires * 1000;
12133 if (expires <= EXPIRY_GUARD_LIMIT)
12134 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
12135 else
12136 expires_ms -= EXPIRY_GUARD_SECS * 1000;
12137 if (sipdebug)
12138 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
12139
12140 r->refresh= (int) expires_ms / 1000;
12141
12142
12143 r->expire=ast_sched_add(sched, expires_ms, sip_reregister, r);
12144 ASTOBJ_UNREF(r, sip_registry_destroy);
12145 }
12146 return 1;
12147 }
12148
12149
12150 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
12151 {
12152 struct sip_peer *peer = p->relatedpeer;
12153 int statechanged, is_reachable, was_reachable;
12154 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
12155
12156
12157
12158
12159
12160
12161 if (pingtime < 1)
12162 pingtime = 1;
12163
12164
12165
12166
12167
12168 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
12169 is_reachable = pingtime <= peer->maxms;
12170 statechanged = peer->lastms == 0
12171 || was_reachable != is_reachable;
12172
12173 peer->lastms = pingtime;
12174 peer->call = NULL;
12175 if (statechanged) {
12176 const char *s = is_reachable ? "Reachable" : "Lagged";
12177
12178 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
12179 peer->name, s, pingtime, peer->maxms);
12180 ast_device_state_changed("SIP/%s", peer->name);
12181 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
12182 "Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
12183 peer->name, s, pingtime);
12184 }
12185
12186 if (peer->pokeexpire > -1)
12187 ast_sched_del(sched, peer->pokeexpire);
12188 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12189
12190
12191 peer->pokeexpire = ast_sched_add(sched,
12192 is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
12193 sip_poke_peer_s, peer);
12194 }
12195
12196
12197 static void stop_media_flows(struct sip_pvt *p)
12198 {
12199
12200 if (p->rtp)
12201 ast_rtp_stop(p->rtp);
12202 if (p->vrtp)
12203 ast_rtp_stop(p->vrtp);
12204 if (p->udptl)
12205 ast_udptl_stop(p->udptl);
12206 }
12207
12208
12209
12210 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
12211 {
12212 struct ast_channel *owner;
12213 int sipmethod;
12214 int res = 1;
12215 const char *c = get_header(req, "Cseq");
12216 const char *msg = strchr(c, ' ');
12217
12218 if (!msg)
12219 msg = "";
12220 else
12221 msg++;
12222 sipmethod = find_sip_method(msg);
12223
12224 owner = p->owner;
12225 if (owner)
12226 owner->hangupcause = hangup_sip2cause(resp);
12227
12228
12229 if ((resp >= 100) && (resp <= 199))
12230 __sip_semi_ack(p, seqno, 0, sipmethod);
12231 else
12232 __sip_ack(p, seqno, 0, sipmethod);
12233
12234
12235 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
12236 char tag[128];
12237
12238 gettag(req, "To", tag, sizeof(tag));
12239 ast_string_field_set(p, theirtag, tag);
12240 }
12241 if (p->relatedpeer && p->method == SIP_OPTIONS) {
12242
12243
12244
12245 if (resp != 100)
12246 handle_response_peerpoke(p, resp, req);
12247 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12248 switch(resp) {
12249 case 100:
12250 case 101:
12251 if (sipmethod == SIP_INVITE)
12252 handle_response_invite(p, resp, rest, req, seqno);
12253 break;
12254 case 183:
12255 if (sipmethod == SIP_INVITE)
12256 handle_response_invite(p, resp, rest, req, seqno);
12257 break;
12258 case 180:
12259 if (sipmethod == SIP_INVITE)
12260 handle_response_invite(p, resp, rest, req, seqno);
12261 break;
12262 case 200:
12263 p->authtries = 0;
12264 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
12265
12266
12267
12268 } else if (sipmethod == SIP_INVITE) {
12269 handle_response_invite(p, resp, rest, req, seqno);
12270 } else if (sipmethod == SIP_NOTIFY) {
12271
12272 if (p->owner) {
12273 if (!p->refer) {
12274 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
12275 ast_queue_hangup(p->owner);
12276 } else if (option_debug > 3)
12277 ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
12278 } else {
12279 if (p->subscribed == NONE)
12280 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12281 }
12282 } else if (sipmethod == SIP_REGISTER)
12283 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12284 else if (sipmethod == SIP_BYE)
12285 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12286 break;
12287 case 202:
12288 if (sipmethod == SIP_REFER)
12289 handle_response_refer(p, resp, rest, req, seqno);
12290 break;
12291 case 401:
12292 if (sipmethod == SIP_INVITE)
12293 handle_response_invite(p, resp, rest, req, seqno);
12294 else if (sipmethod == SIP_REFER)
12295 handle_response_refer(p, resp, rest, req, seqno);
12296 else if (p->registry && sipmethod == SIP_REGISTER)
12297 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12298 else {
12299 ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
12300 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12301 }
12302 break;
12303 case 403:
12304 if (sipmethod == SIP_INVITE)
12305 handle_response_invite(p, resp, rest, req, seqno);
12306 else if (p->registry && sipmethod == SIP_REGISTER)
12307 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12308 else {
12309 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
12310 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12311 }
12312 break;
12313 case 404:
12314 if (p->registry && sipmethod == SIP_REGISTER)
12315 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12316 else if (sipmethod == SIP_INVITE)
12317 handle_response_invite(p, resp, rest, req, seqno);
12318 else if (owner)
12319 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12320 break;
12321 case 407:
12322 if (sipmethod == SIP_INVITE)
12323 handle_response_invite(p, resp, rest, req, seqno);
12324 else if (sipmethod == SIP_REFER)
12325 handle_response_refer(p, resp, rest, req, seqno);
12326 else if (p->registry && sipmethod == SIP_REGISTER)
12327 res = handle_response_register(p, resp, rest, req, ignore, seqno);
12328 else if (sipmethod == SIP_BYE) {
12329 if (ast_strlen_zero(p->authname))
12330 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
12331 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12332 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12333 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
12334 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12335 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12336 }
12337 } else
12338 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12339
12340 break;
12341 case 481:
12342 if (sipmethod == SIP_INVITE) {
12343 handle_response_invite(p, resp, rest, req, seqno);
12344 } else if (sipmethod == SIP_REFER) {
12345 handle_response_refer(p, resp, rest, req, seqno);
12346 } else if (sipmethod == SIP_BYE) {
12347
12348
12349 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12350 } else if (sipmethod == SIP_CANCEL) {
12351
12352
12353 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12354 } else {
12355 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
12356
12357 }
12358 break;
12359 case 487:
12360 if (sipmethod == SIP_INVITE)
12361 handle_response_invite(p, resp, rest, req, seqno);
12362 break;
12363 case 488:
12364 if (sipmethod == SIP_INVITE)
12365 handle_response_invite(p, resp, rest, req, seqno);
12366 break;
12367 case 491:
12368 if (sipmethod == SIP_INVITE)
12369 handle_response_invite(p, resp, rest, req, seqno);
12370 else {
12371 if (option_debug)
12372 ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
12373 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12374 }
12375 break;
12376 case 501:
12377 if (sipmethod == SIP_INVITE)
12378 handle_response_invite(p, resp, rest, req, seqno);
12379 else if (sipmethod == SIP_REFER)
12380 handle_response_refer(p, resp, rest, req, seqno);
12381 else
12382 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
12383 break;
12384 case 603:
12385 if (sipmethod == SIP_REFER) {
12386 handle_response_refer(p, resp, rest, req, seqno);
12387 break;
12388 }
12389
12390 default:
12391 if ((resp >= 300) && (resp < 700)) {
12392
12393 if ((option_verbose > 2) && (resp != 487))
12394 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
12395
12396 if (sipmethod == SIP_INVITE)
12397 stop_media_flows(p);
12398
12399
12400 switch(resp) {
12401 case 300:
12402 case 301:
12403 case 302:
12404 case 305:
12405 parse_moved_contact(p, req);
12406
12407 case 486:
12408 case 600:
12409 case 603:
12410 if (p->owner)
12411 ast_queue_control(p->owner, AST_CONTROL_BUSY);
12412 break;
12413 case 482:
12414
12415
12416
12417
12418 if (option_debug)
12419 ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
12420 if (p->owner)
12421 ast_string_field_build(p->owner, call_forward,
12422 "Local/%s@%s", p->username, p->context);
12423
12424 case 480:
12425 case 404:
12426 case 410:
12427 case 400:
12428 case 500:
12429 if (sipmethod == SIP_REFER) {
12430 handle_response_refer(p, resp, rest, req, seqno);
12431 break;
12432 }
12433
12434 case 503:
12435 case 504:
12436 if (owner)
12437 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
12438 break;
12439 default:
12440
12441 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
12442 ast_queue_hangup(p->owner);
12443 break;
12444 }
12445
12446 if (sipmethod == SIP_INVITE)
12447 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
12448 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
12449 sip_alreadygone(p);
12450 if (!p->owner)
12451 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12452 } else if ((resp >= 100) && (resp < 200)) {
12453 if (sipmethod == SIP_INVITE) {
12454 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12455 sip_cancel_destroy(p);
12456 if (find_sdp(req))
12457 process_sdp(p, req);
12458 if (p->owner) {
12459
12460 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
12461 }
12462 }
12463 } else
12464 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));
12465 }
12466 } else {
12467
12468
12469 if (ast_test_flag(req, SIP_PKT_DEBUG))
12470 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
12471
12472 if (sipmethod == SIP_INVITE && resp == 200) {
12473
12474
12475 char tag[128];
12476
12477 gettag(req, "To", tag, sizeof(tag));
12478 ast_string_field_set(p, theirtag, tag);
12479 }
12480
12481 switch(resp) {
12482 case 200:
12483 if (sipmethod == SIP_INVITE) {
12484 handle_response_invite(p, resp, rest, req, seqno);
12485 } else if (sipmethod == SIP_CANCEL) {
12486 if (option_debug)
12487 ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
12488
12489
12490 } else if (sipmethod == SIP_NOTIFY) {
12491
12492 if (p->owner) {
12493 if (p->refer) {
12494 if (option_debug)
12495 ast_log(LOG_DEBUG, "Got 200 OK on NOTIFY for transfer\n");
12496 } else
12497 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
12498
12499 } else {
12500 if (!p->subscribed && !p->refer)
12501 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12502 }
12503 } else if (sipmethod == SIP_BYE)
12504 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12505 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
12506
12507
12508 ;
12509 else if (sipmethod == SIP_BYE)
12510
12511 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12512 break;
12513 case 202:
12514 if (sipmethod == SIP_REFER)
12515 handle_response_refer(p, resp, rest, req, seqno);
12516 break;
12517 case 401:
12518 case 407:
12519 if (sipmethod == SIP_REFER)
12520 handle_response_refer(p, resp, rest, req, seqno);
12521 else if (sipmethod == SIP_INVITE)
12522 handle_response_invite(p, resp, rest, req, seqno);
12523 else if (sipmethod == SIP_BYE) {
12524 char *auth, *auth2;
12525
12526 auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
12527 auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
12528 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
12529 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
12530 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12531 }
12532 }
12533 break;
12534 case 481:
12535 if (sipmethod == SIP_INVITE) {
12536
12537 handle_response_invite(p, resp, rest, req, seqno);
12538 } else if (sipmethod == SIP_BYE) {
12539 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
12540 } else if (sipdebug) {
12541 ast_log (LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
12542 }
12543 break;
12544 case 501:
12545 if (sipmethod == SIP_INVITE)
12546 handle_response_invite(p, resp, rest, req, seqno);
12547 else if (sipmethod == SIP_REFER)
12548 handle_response_refer(p, resp, rest, req, seqno);
12549 break;
12550 case 603:
12551 if (sipmethod == SIP_REFER) {
12552 handle_response_refer(p, resp, rest, req, seqno);
12553 break;
12554 }
12555
12556 default:
12557 if ((resp >= 100) && (resp < 200)) {
12558 if (sipmethod == SIP_INVITE) {
12559 if (!ast_test_flag(req, SIP_PKT_IGNORE))
12560 sip_cancel_destroy(p);
12561 }
12562 }
12563 if ((resp >= 300) && (resp < 700)) {
12564 if ((option_verbose > 2) && (resp != 487))
12565 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));
12566 switch(resp) {
12567 case 488:
12568 case 603:
12569 case 500:
12570 case 503:
12571 case 504:
12572
12573 if (sipmethod == SIP_INVITE) {
12574 sip_cancel_destroy(p);
12575 }
12576 break;
12577 }
12578 }
12579 break;
12580 }
12581 }
12582 }
12583
12584
12585
12586
12587
12588
12589
12590 static void *sip_park_thread(void *stuff)
12591 {
12592 struct ast_channel *transferee, *transferer;
12593 struct sip_dual *d;
12594 struct sip_request req;
12595 int ext;
12596 int res;
12597
12598 d = stuff;
12599 transferee = d->chan1;
12600 transferer = d->chan2;
12601 copy_request(&req, &d->req);
12602 free(d);
12603
12604 if (!transferee || !transferer) {
12605 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
12606 return NULL;
12607 }
12608 if (option_debug > 3)
12609 ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
12610
12611 ast_channel_lock(transferee);
12612 if (ast_do_masquerade(transferee)) {
12613 ast_log(LOG_WARNING, "Masquerade failed.\n");
12614 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
12615 ast_channel_unlock(transferee);
12616 return NULL;
12617 }
12618 ast_channel_unlock(transferee);
12619
12620 res = ast_park_call(transferee, transferer, 0, &ext);
12621
12622
12623 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
12624 if (!res) {
12625 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
12626 } else {
12627
12628 sprintf(buf, "Call parked on extension '%d'", ext);
12629 transmit_message_with_text(transferer->tech_pvt, buf);
12630 }
12631 #endif
12632
12633
12634
12635 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
12636 if (!res) {
12637
12638 append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
12639 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
12640 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
12641 ast_hangup(transferer);
12642 if (option_debug)
12643 ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
12644 } else {
12645 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
12646 append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
12647 if (option_debug)
12648 ast_log(LOG_DEBUG, "SIP Call parked failed \n");
12649
12650 }
12651 return NULL;
12652 }
12653
12654
12655
12656
12657 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
12658 {
12659 struct sip_dual *d;
12660 struct ast_channel *transferee, *transferer;
12661
12662 pthread_t th;
12663
12664 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
12665 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
12666 if ((!transferer) || (!transferee)) {
12667 if (transferee) {
12668 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12669 ast_hangup(transferee);
12670 }
12671 if (transferer) {
12672 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12673 ast_hangup(transferer);
12674 }
12675 return -1;
12676 }
12677
12678
12679 transferee->readformat = chan1->readformat;
12680 transferee->writeformat = chan1->writeformat;
12681
12682
12683 ast_channel_masquerade(transferee, chan1);
12684
12685
12686 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
12687 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
12688 transferee->priority = chan1->priority;
12689
12690
12691
12692
12693
12694 transferer->readformat = chan2->readformat;
12695 transferer->writeformat = chan2->writeformat;
12696
12697
12698 ast_channel_masquerade(transferer, chan2);
12699
12700
12701 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
12702 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
12703 transferer->priority = chan2->priority;
12704
12705 ast_channel_lock(transferer);
12706 if (ast_do_masquerade(transferer)) {
12707 ast_log(LOG_WARNING, "Masquerade failed :(\n");
12708 ast_channel_unlock(transferer);
12709 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
12710 ast_hangup(transferer);
12711 return -1;
12712 }
12713 ast_channel_unlock(transferer);
12714 if (!transferer || !transferee) {
12715 if (!transferer) {
12716 if (option_debug)
12717 ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
12718 }
12719 if (!transferee) {
12720 if (option_debug)
12721 ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
12722 }
12723 return -1;
12724 }
12725 if ((d = ast_calloc(1, sizeof(*d)))) {
12726 pthread_attr_t attr;
12727
12728 pthread_attr_init(&attr);
12729 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
12730
12731
12732 copy_request(&d->req, req);
12733 d->chan1 = transferee;
12734 d->chan2 = transferer;
12735 d->seqno = seqno;
12736 if (ast_pthread_create_background(&th, &attr, sip_park_thread, d) < 0) {
12737
12738 free(d);
12739
12740 pthread_attr_destroy(&attr);
12741 return 0;
12742 }
12743 pthread_attr_destroy(&attr);
12744 }
12745 return -1;
12746 }
12747
12748
12749
12750
12751 static void ast_quiet_chan(struct ast_channel *chan)
12752 {
12753 if (chan && chan->_state == AST_STATE_UP) {
12754 if (chan->generatordata)
12755 ast_deactivate_generator(chan);
12756 }
12757 }
12758
12759
12760
12761 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
12762 {
12763 int res = 0;
12764 struct ast_channel *peera = NULL,
12765 *peerb = NULL,
12766 *peerc = NULL,
12767 *peerd = NULL;
12768
12769
12770
12771
12772 if (option_debug > 3) {
12773 ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
12774 if (transferer->chan1)
12775 ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
12776 else
12777 ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
12778 if (target->chan1)
12779 ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
12780 else
12781 ast_log(LOG_DEBUG, "-- No target first channel ---\n");
12782 if (transferer->chan2)
12783 ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
12784 else
12785 ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
12786 if (target->chan2)
12787 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)");
12788 else
12789 ast_log(LOG_DEBUG, "-- No target second channel ---\n");
12790 ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
12791 }
12792 if (transferer->chan2) {
12793 peera = transferer->chan1;
12794 peerb = target->chan1;
12795 peerc = transferer->chan2;
12796 peerd = target->chan2;
12797 if (option_debug > 2)
12798 ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
12799 } else if (target->chan2) {
12800 peera = target->chan1;
12801 peerb = transferer->chan1;
12802 peerc = target->chan2;
12803 peerd = transferer->chan2;
12804 if (option_debug > 2)
12805 ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
12806 }
12807
12808 if (peera && peerb && peerc && (peerb != peerc)) {
12809 ast_quiet_chan(peera);
12810 ast_quiet_chan(peerb);
12811 ast_quiet_chan(peerc);
12812 if (peerd)
12813 ast_quiet_chan(peerd);
12814
12815
12816 if (peera->cdr && peerb->cdr)
12817 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
12818 else if (peera->cdr)
12819 peerb->cdr = peera->cdr;
12820 peera->cdr = NULL;
12821
12822 if (peerb->cdr && peerc->cdr)
12823 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
12824 else if (peerc->cdr)
12825 peerb->cdr = peerc->cdr;
12826 peerc->cdr = NULL;
12827
12828 if (option_debug > 3)
12829 ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
12830 if (ast_channel_masquerade(peerb, peerc)) {
12831 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
12832 res = -1;
12833 } else
12834 ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
12835 return res;
12836 } else {
12837 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
12838 if (transferer->chan1)
12839 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
12840 if (target->chan1)
12841 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
12842 return -1;
12843 }
12844 return 0;
12845 }
12846
12847
12848
12849
12850
12851
12852 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
12853 {
12854 const char *thetag;
12855
12856 if (!tagbuf)
12857 return NULL;
12858 tagbuf[0] = '\0';
12859 thetag = get_header(req, header);
12860 thetag = strcasestr(thetag, ";tag=");
12861 if (thetag) {
12862 thetag += 5;
12863 ast_copy_string(tagbuf, thetag, tagbufsize);
12864 return strsep(&tagbuf, ";");
12865 }
12866 return NULL;
12867 }
12868
12869
12870 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
12871 {
12872
12873
12874 int res = 0;
12875 const char *event = get_header(req, "Event");
12876 char *eventid = NULL;
12877 char *sep;
12878
12879 if( (sep = strchr(event, ';')) ) {
12880 *sep++ = '\0';
12881 eventid = sep;
12882 }
12883
12884 if (option_debug > 1 && sipdebug)
12885 ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);
12886
12887 if (strcmp(event, "refer")) {
12888
12889
12890 transmit_response(p, "489 Bad event", req);
12891 res = -1;
12892 } else {
12893
12894
12895
12896
12897
12898 char buf[1024];
12899 char *cmd, *code;
12900 int respcode;
12901 int success = TRUE;
12902
12903
12904
12905
12906
12907
12908
12909
12910 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
12911
12912 transmit_response(p, "400 Bad request", req);
12913 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12914 return -1;
12915 }
12916
12917
12918 if (get_msg_text(buf, sizeof(buf), req)) {
12919 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
12920 transmit_response(p, "400 Bad request", req);
12921 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12922 return -1;
12923 }
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945 if (option_debug > 2)
12946 ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
12947 cmd = ast_skip_blanks(buf);
12948 code = cmd;
12949
12950 while(*code && (*code > 32)) {
12951 code++;
12952 }
12953 *code++ = '\0';
12954 code = ast_skip_blanks(code);
12955 sep = code;
12956 sep++;
12957 while(*sep && (*sep > 32)) {
12958 sep++;
12959 }
12960 *sep++ = '\0';
12961 respcode = atoi(code);
12962 switch (respcode) {
12963 case 100:
12964 case 101:
12965
12966 break;
12967 case 183:
12968
12969 break;
12970 case 200:
12971
12972 break;
12973 case 301:
12974 case 302:
12975
12976 success = FALSE;
12977 break;
12978 case 503:
12979
12980 success = FALSE;
12981 break;
12982 case 603:
12983
12984 success = FALSE;
12985 break;
12986 }
12987 if (!success) {
12988 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
12989 }
12990
12991
12992 transmit_response(p, "200 OK", req);
12993 };
12994
12995 if (!p->lastinvite)
12996 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12997
12998 return res;
12999 }
13000
13001
13002 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
13003 {
13004 int res;
13005
13006 res = get_destination(p, req);
13007 build_contact(p);
13008
13009 if (ast_strlen_zero(p->context))
13010 ast_string_field_set(p, context, default_context);
13011 if (res < 0)
13012 transmit_response_with_allow(p, "404 Not Found", req, 0);
13013 else
13014 transmit_response_with_allow(p, "200 OK", req, 0);
13015
13016
13017 if (!p->lastinvite)
13018 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13019
13020 return res;
13021 }
13022
13023
13024
13025 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
13026 {
13027 struct ast_frame *f;
13028 int earlyreplace = 0;
13029 int oneleggedreplace = 0;
13030 struct ast_channel *c = p->owner;
13031 struct ast_channel *replacecall = p->refer->refer_call->owner;
13032 struct ast_channel *targetcall;
13033
13034
13035 if (replacecall->_state == AST_STATE_RING)
13036 earlyreplace = 1;
13037
13038
13039 if (!(targetcall = ast_bridged_channel(replacecall))) {
13040
13041 if (!earlyreplace) {
13042 if (option_debug > 1)
13043 ast_log(LOG_DEBUG, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
13044 oneleggedreplace = 1;
13045 }
13046 }
13047 if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
13048 ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");
13049
13050 if (option_debug > 3) {
13051 if (targetcall)
13052 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);
13053 else
13054 ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
13055 }
13056
13057 if (ignore) {
13058 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
13059
13060
13061
13062 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13063
13064 ast_channel_unlock(c);
13065 ast_mutex_unlock(&p->refer->refer_call->lock);
13066 return 1;
13067 }
13068 if (!c) {
13069
13070 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
13071 transmit_response_reliable(p, "503 Service Unavailable", req);
13072 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
13073 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13074 ast_mutex_unlock(&p->refer->refer_call->lock);
13075 return 1;
13076 }
13077 append_history(p, "Xfer", "INVITE/Replace received");
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089 transmit_response(p, "100 Trying", req);
13090 ast_setstate(c, AST_STATE_RING);
13091
13092
13093
13094
13095
13096 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
13097 ast_setstate(c, AST_STATE_UP);
13098
13099
13100 ast_quiet_chan(replacecall);
13101 ast_quiet_chan(targetcall);
13102 if (option_debug > 3)
13103 ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
13104
13105 ast_channel_unlock(c);
13106
13107
13108 ast_mutex_unlock(&p->refer->refer_call->lock);
13109
13110
13111 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
13112
13113
13114 if(ast_channel_masquerade(replacecall, c))
13115 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
13116 else if (option_debug > 3)
13117 ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
13118
13119
13120
13121
13122
13123 ast_channel_unlock(c);
13124
13125 if (earlyreplace || oneleggedreplace ) {
13126
13127 if ((f = ast_read(replacecall))) {
13128 ast_frfree(f);
13129 f = NULL;
13130 if (option_debug > 3)
13131 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from RING channel!\n");
13132 } else {
13133 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
13134 }
13135 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
13136 ast_channel_unlock(replacecall);
13137 } else {
13138 if ((f = ast_read(replacecall))) {
13139
13140 ast_frfree(f);
13141 f = NULL;
13142 if (option_debug > 2)
13143 ast_log(LOG_DEBUG, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
13144 } else {
13145 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
13146 }
13147 ast_channel_unlock(replacecall);
13148 }
13149 ast_mutex_unlock(&p->refer->refer_call->lock);
13150
13151 ast_setstate(c, AST_STATE_DOWN);
13152 if (option_debug > 3) {
13153 struct ast_channel *test;
13154 ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
13155 ast_log(LOG_DEBUG, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
13156 if (replacecall)
13157 ast_log(LOG_DEBUG, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
13158 if (p->owner) {
13159 ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
13160 test = ast_bridged_channel(p->owner);
13161 if (test)
13162 ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
13163 else
13164 ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
13165 } else
13166 ast_log(LOG_DEBUG, " -- No channel yet \n");
13167 ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
13168 }
13169
13170 ast_channel_unlock(p->owner);
13171 ast_mutex_unlock(&p->lock);
13172
13173
13174 c->tech_pvt = NULL;
13175 ast_hangup(c);
13176 return 0;
13177 }
13178
13179
13180
13181
13182
13183
13184
13185
13186 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)
13187 {
13188 int res = 1;
13189 int gotdest;
13190 const char *p_replaces;
13191 char *replace_id = NULL;
13192 const char *required;
13193 unsigned int required_profile = 0;
13194 struct ast_channel *c = NULL;
13195
13196
13197 if (!p->sipoptions) {
13198 const char *supported = get_header(req, "Supported");
13199 if (!ast_strlen_zero(supported))
13200 parse_sip_options(p, supported);
13201 }
13202
13203
13204 required = get_header(req, "Require");
13205 if (!ast_strlen_zero(required)) {
13206 required_profile = parse_sip_options(NULL, required);
13207 if (required_profile && required_profile != SIP_OPT_REPLACES) {
13208
13209 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
13210 ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
13211 p->invitestate = INV_COMPLETED;
13212 if (!p->lastinvite)
13213 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13214 return -1;
13215 }
13216 }
13217
13218
13219 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
13220
13221
13222
13223
13224
13225 transmit_response(p, "482 Loop Detected", req);
13226 p->invitestate = INV_COMPLETED;
13227 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13228 return 0;
13229 }
13230
13231 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
13232
13233 transmit_response(p, "491 Request Pending", req);
13234 if (option_debug)
13235 ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
13236
13237 return 0;
13238 }
13239
13240 p_replaces = get_header(req, "Replaces");
13241 if (!ast_strlen_zero(p_replaces)) {
13242
13243 char *ptr;
13244 char *fromtag = NULL;
13245 char *totag = NULL;
13246 char *start, *to;
13247 int error = 0;
13248
13249 if (p->owner) {
13250 if (option_debug > 2)
13251 ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
13252 transmit_response(p, "400 Bad request", req);
13253
13254 return -1;
13255 }
13256
13257 if (sipdebug && option_debug > 2)
13258 ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
13259
13260 replace_id = ast_strdupa(p_replaces);
13261 ast_uri_decode(replace_id);
13262
13263 if (!p->refer && !sip_refer_allocate(p)) {
13264 transmit_response(p, "500 Server Internal Error", req);
13265 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
13266 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13267 p->invitestate = INV_COMPLETED;
13268 return -1;
13269 }
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280 replace_id = ast_skip_blanks(replace_id);
13281
13282 start = replace_id;
13283 while ( (ptr = strsep(&start, ";")) ) {
13284 ptr = ast_skip_blanks(ptr);
13285 if ( (to = strcasestr(ptr, "to-tag=") ) )
13286 totag = to + 7;
13287 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
13288 fromtag = to + 9;
13289 fromtag = strsep(&fromtag, "&");
13290 }
13291 }
13292
13293 if (sipdebug && option_debug > 3)
13294 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>");
13295
13296
13297
13298
13299
13300 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
13301 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
13302 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
13303 error = 1;
13304 }
13305
13306
13307
13308
13309
13310
13311
13312 if (p->refer->refer_call == p) {
13313 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
13314 p->refer->refer_call = NULL;
13315 transmit_response(p, "400 Bad request", req);
13316 error = 1;
13317 }
13318
13319 if (!error && !p->refer->refer_call->owner) {
13320
13321 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
13322
13323 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
13324 error = 1;
13325 }
13326
13327 if (!error && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
13328 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
13329 transmit_response(p, "603 Declined (Replaces)", req);
13330 error = 1;
13331 }
13332
13333 if (error) {
13334 append_history(p, "Xfer", "INVITE/Replace Failed.");
13335 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13336 ast_mutex_unlock(&p->lock);
13337 if (p->refer->refer_call) {
13338 ast_mutex_unlock(&p->refer->refer_call->lock);
13339 ast_channel_unlock(p->refer->refer_call->owner);
13340 }
13341 p->invitestate = INV_COMPLETED;
13342 return -1;
13343 }
13344 }
13345
13346
13347
13348
13349
13350 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13351 int newcall = (p->initreq.headers ? TRUE : FALSE);
13352
13353 sip_cancel_destroy(p);
13354
13355 p->pendinginvite = seqno;
13356 check_via(p, req);
13357
13358 copy_request(&p->initreq, req);
13359 if (!p->owner) {
13360 if (debug)
13361 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
13362 if (newcall)
13363 append_history(p, "Invite", "New call: %s", p->callid);
13364 parse_ok_contact(p, req);
13365 } else {
13366 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
13367
13368 if (find_sdp(req)) {
13369 if (process_sdp(p, req)) {
13370 transmit_response(p, "488 Not acceptable here", req);
13371 if (!p->lastinvite)
13372 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13373 return -1;
13374 }
13375 } else {
13376 p->jointcapability = p->capability;
13377 if (option_debug)
13378 ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
13379 }
13380 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
13381 append_history(p, "ReInv", "Re-invite received");
13382 }
13383 } else if (debug)
13384 ast_verbose("Ignoring this INVITE request\n");
13385
13386
13387 if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
13388
13389
13390 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
13391 if (res == AUTH_CHALLENGE_SENT) {
13392 p->invitestate = INV_COMPLETED;
13393 return 0;
13394 }
13395 if (res < 0) {
13396 if (res == AUTH_FAKE_AUTH) {
13397 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
13398 transmit_fake_auth_response(p, req, 1);
13399 } else {
13400 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
13401 transmit_response_reliable(p, "403 Forbidden", req);
13402 }
13403 p->invitestate = INV_COMPLETED;
13404 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13405 ast_string_field_free(p, theirtag);
13406 return 0;
13407 }
13408
13409
13410 if (find_sdp(req)) {
13411 if (process_sdp(p, req)) {
13412
13413 transmit_response_reliable(p, "488 Not acceptable here", req);
13414 p->invitestate = INV_COMPLETED;
13415 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13416 if (option_debug)
13417 ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
13418 return -1;
13419 }
13420 } else {
13421 p->jointcapability = p->capability;
13422 if (option_debug > 1)
13423 ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
13424 }
13425
13426
13427
13428 if (p->owner)
13429 ast_queue_frame(p->owner, &ast_null_frame);
13430
13431
13432
13433 if (ast_strlen_zero(p->context))
13434 ast_string_field_set(p, context, default_context);
13435
13436
13437
13438 if (option_debug)
13439 ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
13440 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
13441 if (res < 0) {
13442 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
13443 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
13444 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13445 p->invitestate = INV_COMPLETED;
13446 }
13447 return 0;
13448 }
13449 gotdest = get_destination(p, NULL);
13450 get_rdnis(p, NULL);
13451 extract_uri(p, req);
13452 build_contact(p);
13453
13454 if (p->rtp) {
13455 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
13456 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
13457 }
13458
13459 if (!replace_id && gotdest) {
13460 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
13461 transmit_response_reliable(p, "484 Address Incomplete", req);
13462 else
13463 transmit_response_reliable(p, "404 Not Found", req);
13464 p->invitestate = INV_COMPLETED;
13465 update_call_counter(p, DEC_CALL_LIMIT);
13466 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13467 return 0;
13468 } else {
13469
13470
13471 if (ast_strlen_zero(p->exten))
13472 ast_string_field_set(p, exten, "s");
13473
13474
13475 make_our_tag(p->tag, sizeof(p->tag));
13476
13477 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
13478 *recount = 1;
13479
13480
13481 build_route(p, req, 0);
13482
13483 if (c) {
13484
13485 ast_channel_lock(c);
13486 }
13487 }
13488 } else {
13489 if (option_debug > 1 && sipdebug) {
13490 if (!ast_test_flag(req, SIP_PKT_IGNORE))
13491 ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
13492 else
13493 ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
13494 }
13495 c = p->owner;
13496 }
13497
13498 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
13499 p->lastinvite = seqno;
13500
13501 if (replace_id) {
13502
13503 if (sipdebug && option_debug > 3)
13504 ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
13505 return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
13506 }
13507
13508
13509 if (c) {
13510 switch(c->_state) {
13511 case AST_STATE_DOWN:
13512 if (option_debug > 1)
13513 ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
13514 transmit_response(p, "100 Trying", req);
13515 p->invitestate = INV_PROCEEDING;
13516 ast_setstate(c, AST_STATE_RING);
13517 if (strcmp(p->exten, ast_pickup_ext())) {
13518 enum ast_pbx_result res;
13519
13520 res = ast_pbx_start(c);
13521
13522 switch(res) {
13523 case AST_PBX_FAILED:
13524 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
13525 p->invitestate = INV_COMPLETED;
13526 if (ast_test_flag(req, SIP_PKT_IGNORE))
13527 transmit_response(p, "503 Unavailable", req);
13528 else
13529 transmit_response_reliable(p, "503 Unavailable", req);
13530 break;
13531 case AST_PBX_CALL_LIMIT:
13532 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
13533 p->invitestate = INV_COMPLETED;
13534 if (ast_test_flag(req, SIP_PKT_IGNORE))
13535 transmit_response(p, "480 Temporarily Unavailable", req);
13536 else
13537 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
13538 break;
13539 case AST_PBX_SUCCESS:
13540
13541 break;
13542 }
13543
13544 if (res) {
13545
13546
13547 ast_mutex_unlock(&c->lock);
13548 ast_mutex_unlock(&p->lock);
13549 ast_hangup(c);
13550 ast_mutex_lock(&p->lock);
13551 c = NULL;
13552 }
13553 } else {
13554 ast_channel_unlock(c);
13555 if (ast_pickup_call(c)) {
13556 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
13557 if (ast_test_flag(req, SIP_PKT_IGNORE))
13558 transmit_response(p, "503 Unavailable", req);
13559 else
13560 transmit_response_reliable(p, "503 Unavailable", req);
13561 sip_alreadygone(p);
13562
13563 ast_mutex_unlock(&p->lock);
13564 c->hangupcause = AST_CAUSE_CALL_REJECTED;
13565 } else {
13566 ast_mutex_unlock(&p->lock);
13567 ast_setstate(c, AST_STATE_DOWN);
13568 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
13569 }
13570 p->invitestate = INV_COMPLETED;
13571 ast_hangup(c);
13572 ast_mutex_lock(&p->lock);
13573 c = NULL;
13574 }
13575 break;
13576 case AST_STATE_RING:
13577 transmit_response(p, "100 Trying", req);
13578 p->invitestate = INV_PROCEEDING;
13579 break;
13580 case AST_STATE_RINGING:
13581 transmit_response(p, "180 Ringing", req);
13582 p->invitestate = INV_PROCEEDING;
13583 break;
13584 case AST_STATE_UP:
13585 if (option_debug > 1)
13586 ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);
13587
13588 if (p->t38.state == T38_PEER_REINVITE) {
13589 struct ast_channel *bridgepeer = NULL;
13590 struct sip_pvt *bridgepvt = NULL;
13591
13592 if ((bridgepeer = ast_bridged_channel(p->owner))) {
13593
13594
13595 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
13596 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
13597 if (bridgepvt->t38.state == T38_DISABLED) {
13598 if (bridgepvt->udptl) {
13599
13600 sip_handle_t38_reinvite(bridgepeer, p, 1);
13601 } else {
13602 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
13603 ast_mutex_lock(&bridgepvt->lock);
13604 bridgepvt->t38.state = T38_DISABLED;
13605 ast_mutex_unlock(&bridgepvt->lock);
13606 if (option_debug > 1)
13607 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
13608 if (ast_test_flag(req, SIP_PKT_IGNORE))
13609 transmit_response(p, "488 Not acceptable here", req);
13610 else
13611 transmit_response_reliable(p, "488 Not acceptable here", req);
13612
13613 }
13614 } else {
13615
13616 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
13617 p->t38.state = T38_ENABLED;
13618 if (option_debug)
13619 ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13620 }
13621 } else {
13622
13623 if (ast_test_flag(req, SIP_PKT_IGNORE))
13624 transmit_response(p, "488 Not acceptable here", req);
13625 else
13626 transmit_response_reliable(p, "488 Not acceptable here", req);
13627 p->t38.state = T38_DISABLED;
13628 if (option_debug > 1)
13629 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13630
13631 if (!p->lastinvite)
13632 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13633 }
13634 } else {
13635
13636 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
13637 p->t38.state = T38_ENABLED;
13638 if (option_debug)
13639 ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
13640 }
13641 } else if (p->t38.state == T38_DISABLED) {
13642 int sendok = TRUE;
13643
13644
13645
13646 struct ast_channel *bridgepeer = NULL;
13647 struct sip_pvt *bridgepvt = NULL;
13648 if ((bridgepeer = ast_bridged_channel(p->owner))) {
13649 if (bridgepeer->tech == &sip_tech || bridgepeer->tech == &sip_tech_info) {
13650 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
13651
13652 if (bridgepvt->t38.state == T38_ENABLED) {
13653 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
13654
13655 if (ast_test_flag(req, SIP_PKT_IGNORE))
13656 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
13657 else
13658 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
13659 sendok = FALSE;
13660 }
13661
13662 }
13663 }
13664
13665 if (sendok)
13666 transmit_response_with_sdp(p, "200 OK", req, ast_test_flag(req, SIP_PKT_IGNORE) ? XMIT_UNRELIABLE : XMIT_CRITICAL);
13667 }
13668 p->invitestate = INV_TERMINATED;
13669 break;
13670 default:
13671 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
13672 transmit_response(p, "100 Trying", req);
13673 break;
13674 }
13675 } else {
13676 if (p && (p->autokillid == -1)) {
13677 const char *msg;
13678
13679 if (!p->jointcapability)
13680 msg = "488 Not Acceptable Here (codec error)";
13681 else {
13682 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
13683 msg = "503 Unavailable";
13684 }
13685 if (ast_test_flag(req, SIP_PKT_IGNORE))
13686 transmit_response(p, msg, req);
13687 else
13688 transmit_response_reliable(p, msg, req);
13689 p->invitestate = INV_COMPLETED;
13690 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13691 }
13692 }
13693 return res;
13694 }
13695
13696
13697
13698 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
13699 {
13700 struct sip_dual target;
13701
13702 int res = 0;
13703 struct sip_pvt *targetcall_pvt;
13704
13705
13706 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
13707 transferer->refer->replaces_callid_fromtag))) {
13708 if (transferer->refer->localtransfer) {
13709
13710 transmit_response(transferer, "202 Accepted", req);
13711
13712
13713 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
13714 append_history(transferer, "Xfer", "Refer failed");
13715 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
13716 transferer->refer->status = REFER_FAILED;
13717 return -1;
13718 }
13719
13720 if (option_debug > 2)
13721 ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
13722 return 0;
13723 }
13724
13725
13726 transmit_response(transferer, "202 Accepted", req);
13727 append_history(transferer, "Xfer", "Refer accepted");
13728 if (!targetcall_pvt->owner) {
13729 if (option_debug > 3)
13730 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
13731
13732 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
13733 append_history(transferer, "Xfer", "Refer failed");
13734 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
13735 transferer->refer->status = REFER_FAILED;
13736 ast_mutex_unlock(&targetcall_pvt->lock);
13737 ast_channel_unlock(current->chan1);
13738 return -1;
13739 }
13740
13741
13742 target.chan1 = targetcall_pvt->owner;
13743 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
13744
13745 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
13746
13747 if (option_debug > 3) {
13748 if (target.chan2)
13749 ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
13750 else if (target.chan1->_state != AST_STATE_RING)
13751 ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
13752 else
13753 ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
13754 }
13755 }
13756
13757
13758 if (option_debug > 3 && sipdebug) {
13759 if (current->chan2)
13760 ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
13761 else
13762 ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
13763 }
13764
13765 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
13766
13767
13768 res = attempt_transfer(current, &target);
13769 ast_mutex_unlock(&targetcall_pvt->lock);
13770 if (res) {
13771
13772
13773 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy", TRUE);
13774 append_history(transferer, "Xfer", "Refer failed");
13775 if (targetcall_pvt->owner)
13776 ast_channel_unlock(targetcall_pvt->owner);
13777
13778 ast_hangup(transferer->owner);
13779 } else {
13780
13781
13782
13783 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
13784 append_history(transferer, "Xfer", "Refer succeeded");
13785 transferer->refer->status = REFER_200OK;
13786 if (targetcall_pvt->owner) {
13787 if (option_debug)
13788 ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
13789 ast_channel_unlock(targetcall_pvt->owner);
13790 }
13791 }
13792 return 1;
13793 }
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
13860 {
13861 struct sip_dual current;
13862
13863
13864 int res = 0;
13865
13866 if (ast_test_flag(req, SIP_PKT_DEBUG))
13867 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");
13868
13869 if (!p->owner) {
13870
13871
13872 if (option_debug > 2)
13873 ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
13874 transmit_response(p, "603 Declined (No dialog)", req);
13875 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
13876 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
13877 sip_alreadygone(p);
13878 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
13879 }
13880 return 0;
13881 }
13882
13883
13884
13885 if (p->allowtransfer == TRANSFER_CLOSED ) {
13886
13887 transmit_response(p, "603 Declined (policy)", req);
13888 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
13889
13890 return 0;
13891 }
13892
13893 if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
13894
13895 transmit_response(p, "491 Request pending", req);
13896 append_history(p, "Xfer", "Refer failed. Request pending.");
13897 return 0;
13898 }
13899
13900
13901 if (!p->refer && !sip_refer_allocate(p)) {
13902 transmit_response(p, "500 Internal Server Error", req);
13903 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
13904 return -3;
13905 }
13906
13907 res = get_refer_info(p, req);
13908
13909 p->refer->status = REFER_SENT;
13910
13911 if (res != 0) {
13912 switch (res) {
13913 case -2:
13914 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
13915 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
13916 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
13917 ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
13918 break;
13919 case -3:
13920 transmit_response(p, "603 Declined (Non sip: uri)", req);
13921 append_history(p, "Xfer", "Refer failed. Non SIP uri");
13922 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
13923 ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
13924 break;
13925 default:
13926
13927 transmit_response(p, "202 Accepted", req);
13928 append_history(p, "Xfer", "Refer failed. Bad extension.");
13929 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
13930 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
13931 if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
13932 ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
13933 break;
13934 }
13935 return 0;
13936 }
13937 if (ast_strlen_zero(p->context))
13938 ast_string_field_set(p, context, default_context);
13939
13940
13941 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
13942 p->refer->localtransfer = 1;
13943 if (sipdebug && option_debug > 2)
13944 ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
13945 } else if (AST_LIST_EMPTY(&domain_list)) {
13946
13947 p->refer->localtransfer = 1;
13948 } else
13949 if (sipdebug && option_debug > 2)
13950 ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
13951
13952
13953
13954 if (ignore)
13955 return res;
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983 current.chan1 = p->owner;
13984
13985
13986 current.chan2 = ast_bridged_channel(current.chan1);
13987
13988 if (sipdebug && option_debug > 2)
13989 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>");
13990
13991 if (!current.chan2 && !p->refer->attendedtransfer) {
13992
13993
13994
13995 if (sipdebug && option_debug > 2)
13996 ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
13997 p->refer->status = REFER_FAILED;
13998 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
13999 transmit_response(p, "603 Declined", req);
14000 return -1;
14001 }
14002
14003 if (current.chan2) {
14004 if (sipdebug && option_debug > 3)
14005 ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
14006
14007 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
14008 }
14009
14010 ast_set_flag(&p->flags[0], SIP_GOTREFER);
14011
14012
14013 if (p->refer->attendedtransfer) {
14014 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
14015 return res;
14016
14017 if (sipdebug && option_debug > 3)
14018 ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
14019
14020 }
14021
14022
14023
14024 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
14025
14026 *nounlock = 1;
14027 ast_channel_unlock(current.chan1);
14028 copy_request(¤t.req, req);
14029 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14030 p->refer->status = REFER_200OK;
14031 append_history(p, "Xfer", "REFER to call parking.");
14032 if (sipdebug && option_debug > 3)
14033 ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
14034 sip_park(current.chan2, current.chan1, req, seqno);
14035 return res;
14036 }
14037
14038
14039 transmit_response(p, "202 Accepted", req);
14040
14041 if (current.chan1 && current.chan2) {
14042 if (option_debug > 2)
14043 ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
14044 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
14045 }
14046 if (current.chan2) {
14047 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
14048 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
14049 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
14050
14051 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
14052
14053 if (p->refer->referred_by)
14054 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
14055 }
14056
14057 if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
14058 char tempheader[BUFSIZ];
14059 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
14060 p->refer->replaces_callid_totag ? ";to-tag=" : "",
14061 p->refer->replaces_callid_totag,
14062 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
14063 p->refer->replaces_callid_fromtag);
14064 if (current.chan2)
14065 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
14066 }
14067
14068
14069 *nounlock = 1;
14070 ast_channel_unlock(current.chan1);
14071 ast_channel_unlock(current.chan2);
14072
14073
14074
14075
14076 if (!p->refer->attendedtransfer)
14077 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
14078
14079
14080
14081
14082
14083 if (!current.chan2) {
14084
14085
14086
14087
14088
14089
14090
14091 p->refer->status = REFER_FAILED;
14092 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
14093 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14094 append_history(p, "Xfer", "Refer failed (only bridged calls).");
14095 return -1;
14096 }
14097 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14098
14099
14100
14101 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
14102
14103 if (!res) {
14104
14105 if (option_debug > 2)
14106 ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14107 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
14108 if (p->refer->localtransfer)
14109 p->refer->status = REFER_200OK;
14110 if (p->owner)
14111 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
14112 append_history(p, "Xfer", "Refer succeeded.");
14113 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14114
14115
14116 res = 0;
14117 } else {
14118 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
14119 if (option_debug > 2)
14120 ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
14121 append_history(p, "Xfer", "Refer failed.");
14122
14123 p->refer->status = REFER_FAILED;
14124 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
14125 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
14126 res = -1;
14127 }
14128 return res;
14129 }
14130
14131
14132 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
14133 {
14134
14135 check_via(p, req);
14136 sip_alreadygone(p);
14137 p->invitestate = INV_CANCELLED;
14138
14139 if (p->owner && p->owner->_state == AST_STATE_UP) {
14140
14141 transmit_response(p, "200 OK", req);
14142 if (option_debug)
14143 ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
14144 return 0;
14145 }
14146 stop_media_flows(p);
14147
14148 if (p->owner)
14149 ast_queue_hangup(p->owner);
14150 else
14151 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14152 if (p->initreq.len > 0) {
14153 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14154 transmit_response(p, "200 OK", req);
14155 return 1;
14156 } else {
14157 transmit_response(p, "481 Call Leg Does Not Exist", req);
14158 return 0;
14159 }
14160 }
14161
14162 static int acf_channel_read(struct ast_channel *chan, char *funcname, char *preparse, char *buf, size_t buflen)
14163 {
14164 struct ast_rtp_quality qos;
14165 struct sip_pvt *p = chan->tech_pvt;
14166 char *all = "", *parse = ast_strdupa(preparse);
14167 AST_DECLARE_APP_ARGS(args,
14168 AST_APP_ARG(param);
14169 AST_APP_ARG(type);
14170 AST_APP_ARG(field);
14171 );
14172 AST_STANDARD_APP_ARGS(args, parse);
14173
14174
14175 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
14176 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
14177 return 0;
14178 }
14179
14180 if (strcasecmp(args.param, "rtpqos"))
14181 return 0;
14182
14183 memset(buf, 0, buflen);
14184 memset(&qos, 0, sizeof(qos));
14185
14186 if (strcasecmp(args.type, "AUDIO") == 0) {
14187 all = ast_rtp_get_quality(p->rtp, &qos);
14188 } else if (strcasecmp(args.type, "VIDEO") == 0) {
14189 all = ast_rtp_get_quality(p->vrtp, &qos);
14190 }
14191
14192 if (strcasecmp(args.field, "local_ssrc") == 0)
14193 snprintf(buf, buflen, "%u", qos.local_ssrc);
14194 else if (strcasecmp(args.field, "local_lostpackets") == 0)
14195 snprintf(buf, buflen, "%u", qos.local_lostpackets);
14196 else if (strcasecmp(args.field, "local_jitter") == 0)
14197 snprintf(buf, buflen, "%.0lf", qos.local_jitter * 1000.0);
14198 else if (strcasecmp(args.field, "local_count") == 0)
14199 snprintf(buf, buflen, "%u", qos.local_count);
14200 else if (strcasecmp(args.field, "remote_ssrc") == 0)
14201 snprintf(buf, buflen, "%u", qos.remote_ssrc);
14202 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
14203 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
14204 else if (strcasecmp(args.field, "remote_jitter") == 0)
14205 snprintf(buf, buflen, "%.0lf", qos.remote_jitter * 1000.0);
14206 else if (strcasecmp(args.field, "remote_count") == 0)
14207 snprintf(buf, buflen, "%u", qos.remote_count);
14208 else if (strcasecmp(args.field, "rtt") == 0)
14209 snprintf(buf, buflen, "%.0lf", qos.rtt * 1000.0);
14210 else if (strcasecmp(args.field, "all") == 0)
14211 ast_copy_string(buf, all, buflen);
14212 else {
14213 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
14214 return -1;
14215 }
14216 return 0;
14217 }
14218
14219
14220 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
14221 {
14222 struct ast_channel *c=NULL;
14223 int res;
14224 struct ast_channel *bridged_to;
14225
14226
14227 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner)
14228 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
14229
14230 p->invitestate = INV_TERMINATED;
14231
14232 copy_request(&p->initreq, req);
14233 check_via(p, req);
14234 sip_alreadygone(p);
14235
14236
14237 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
14238 char *audioqos, *videoqos;
14239 if (p->rtp) {
14240 audioqos = ast_rtp_get_quality(p->rtp, NULL);
14241 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14242 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
14243 if (p->owner)
14244 pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
14245 }
14246 if (p->vrtp) {
14247 videoqos = ast_rtp_get_quality(p->vrtp, NULL);
14248 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14249 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
14250 if (p->owner)
14251 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
14252 }
14253 }
14254
14255 stop_media_flows(p);
14256
14257 if (!ast_strlen_zero(get_header(req, "Also"))) {
14258 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
14259 ast_inet_ntoa(p->recv.sin_addr));
14260 if (ast_strlen_zero(p->context))
14261 ast_string_field_set(p, context, default_context);
14262 res = get_also_info(p, req);
14263 if (!res) {
14264 c = p->owner;
14265 if (c) {
14266 bridged_to = ast_bridged_channel(c);
14267 if (bridged_to) {
14268
14269 ast_queue_control(c, AST_CONTROL_UNHOLD);
14270 ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
14271 } else
14272 ast_queue_hangup(p->owner);
14273 }
14274 } else {
14275 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
14276 if (p->owner)
14277 ast_queue_hangup(p->owner);
14278 }
14279 } else if (p->owner) {
14280 ast_queue_hangup(p->owner);
14281 if (option_debug > 2)
14282 ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
14283 } else {
14284 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14285 if (option_debug > 2)
14286 ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
14287 }
14288 transmit_response(p, "200 OK", req);
14289
14290 return 1;
14291 }
14292
14293
14294 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
14295 {
14296 if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
14297 if (ast_test_flag(req, SIP_PKT_DEBUG))
14298 ast_verbose("Receiving message!\n");
14299 receive_message(p, req);
14300 } else
14301 transmit_response(p, "202 Accepted", req);
14302 return 1;
14303 }
14304
14305
14306 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
14307 {
14308 int gotdest;
14309 int res = 0;
14310 int firststate = AST_EXTENSION_REMOVED;
14311 struct sip_peer *authpeer = NULL;
14312 const char *eventheader = get_header(req, "Event");
14313 const char *accept = get_header(req, "Accept");
14314 int resubscribe = (p->subscribed != NONE);
14315 char *temp, *event;
14316
14317 if (p->initreq.headers) {
14318
14319 if (p->initreq.method != SIP_SUBSCRIBE) {
14320
14321
14322 transmit_response(p, "403 Forbidden (within dialog)", req);
14323
14324 if (option_debug)
14325 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);
14326 return 0;
14327 } else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
14328 if (option_debug) {
14329 if (resubscribe)
14330 ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
14331 else
14332 ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
14333 }
14334 }
14335 }
14336
14337
14338
14339
14340 if (!global_allowsubscribe) {
14341 transmit_response(p, "403 Forbidden (policy)", req);
14342 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14343 return 0;
14344 }
14345
14346 if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) {
14347
14348 if (ast_test_flag(req, SIP_PKT_DEBUG))
14349 ast_verbose("Creating new subscription\n");
14350
14351 copy_request(&p->initreq, req);
14352 check_via(p, req);
14353 } else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
14354 ast_verbose("Ignoring this SUBSCRIBE request\n");
14355
14356
14357 if (ast_strlen_zero(eventheader)) {
14358 transmit_response(p, "489 Bad Event", req);
14359 if (option_debug > 1)
14360 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
14361 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14362 return 0;
14363 }
14364
14365 if ( (strchr(eventheader, ';'))) {
14366 event = ast_strdupa(eventheader);
14367 temp = strchr(event, ';');
14368 *temp = '\0';
14369
14370 } else
14371 event = (char *) eventheader;
14372
14373
14374 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
14375
14376 if (res == AUTH_CHALLENGE_SENT) {
14377 if (authpeer)
14378 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14379 return 0;
14380 }
14381 if (res < 0) {
14382 if (res == AUTH_FAKE_AUTH) {
14383 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
14384 transmit_fake_auth_response(p, req, 1);
14385 } else {
14386 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
14387 transmit_response_reliable(p, "403 Forbidden", req);
14388 }
14389 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14390 if (authpeer)
14391 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14392 return 0;
14393 }
14394
14395
14396 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
14397 transmit_response(p, "403 Forbidden (policy)", req);
14398 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14399 if (authpeer)
14400 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14401 return 0;
14402 }
14403
14404
14405 gotdest = get_destination(p, NULL);
14406
14407
14408
14409
14410
14411
14412 if (!ast_strlen_zero(p->subscribecontext))
14413 ast_string_field_set(p, context, p->subscribecontext);
14414 else if (ast_strlen_zero(p->context))
14415 ast_string_field_set(p, context, default_context);
14416
14417
14418 parse_ok_contact(p, req);
14419
14420 build_contact(p);
14421 if (gotdest) {
14422 transmit_response(p, "404 Not Found", req);
14423 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14424 if (authpeer)
14425 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14426 return 0;
14427 }
14428
14429
14430 if (ast_strlen_zero(p->tag))
14431 make_our_tag(p->tag, sizeof(p->tag));
14432
14433 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
14434 if (authpeer)
14435 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14436
14437
14438
14439
14440
14441 if (strstr(p->useragent, "Polycom")) {
14442 p->subscribed = XPIDF_XML;
14443 } else if (strstr(accept, "application/pidf+xml")) {
14444 p->subscribed = PIDF_XML;
14445 } else if (strstr(accept, "application/dialog-info+xml")) {
14446 p->subscribed = DIALOG_INFO_XML;
14447
14448 } else if (strstr(accept, "application/cpim-pidf+xml")) {
14449 p->subscribed = CPIM_PIDF_XML;
14450 } else if (strstr(accept, "application/xpidf+xml")) {
14451 p->subscribed = XPIDF_XML;
14452 } else if (ast_strlen_zero(accept)) {
14453 if (p->subscribed == NONE) {
14454 transmit_response(p, "489 Bad Event", req);
14455
14456 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
14457 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
14458 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14459 return 0;
14460 }
14461
14462
14463 } else {
14464
14465 char mybuf[200];
14466 snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
14467 transmit_response(p, mybuf, req);
14468
14469 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
14470 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
14471 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14472 return 0;
14473 }
14474 } else if (!strcmp(event, "message-summary")) {
14475 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
14476
14477 transmit_response(p, "406 Not Acceptable", req);
14478 if (option_debug > 1)
14479 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
14480 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14481 if (authpeer)
14482 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14483 return 0;
14484 }
14485
14486
14487
14488
14489
14490 if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
14491 transmit_response(p, "404 Not found (no mailbox)", req);
14492 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14493 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
14494 if (authpeer)
14495 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14496 return 0;
14497 }
14498
14499 p->subscribed = MWI_NOTIFICATION;
14500 if (authpeer->mwipvt && authpeer->mwipvt != p)
14501
14502 sip_destroy(authpeer->mwipvt);
14503 authpeer->mwipvt = p;
14504 p->relatedpeer = authpeer;
14505 } else {
14506 transmit_response(p, "489 Bad Event", req);
14507 if (option_debug > 1)
14508 ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
14509 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14510 if (authpeer)
14511 ASTOBJ_UNREF(authpeer, sip_destroy_peer);
14512 return 0;
14513 }
14514
14515 if (p->subscribed != MWI_NOTIFICATION && !resubscribe)
14516 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
14517
14518 if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
14519 p->lastinvite = seqno;
14520 if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
14521 p->expiry = atoi(get_header(req, "Expires"));
14522
14523
14524 if (p->expiry > max_expiry)
14525 p->expiry = max_expiry;
14526 if (p->expiry < min_expiry && p->expiry > 0)
14527 p->expiry = min_expiry;
14528
14529 if (sipdebug || option_debug > 1) {
14530 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
14531 ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
14532 else
14533 ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
14534 }
14535 if (p->autokillid > -1)
14536 sip_cancel_destroy(p);
14537 if (p->expiry > 0)
14538 sip_scheddestroy(p, (p->expiry + 10) * 1000);
14539
14540 if (p->subscribed == MWI_NOTIFICATION) {
14541 transmit_response(p, "200 OK", req);
14542 if (p->relatedpeer) {
14543 ASTOBJ_WRLOCK(p->relatedpeer);
14544 sip_send_mwi_to_peer(p->relatedpeer);
14545 ASTOBJ_UNLOCK(p->relatedpeer);
14546 }
14547 } else {
14548 struct sip_pvt *p_old;
14549
14550 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
14551
14552 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));
14553 transmit_response(p, "404 Not found", req);
14554 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14555 return 0;
14556 }
14557
14558 transmit_response(p, "200 OK", req);
14559 transmit_state_notify(p, firststate, 1, FALSE);
14560 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
14561
14562 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
14563
14564
14565
14566
14567
14568
14569 ast_mutex_lock(&iflock);
14570 for (p_old = iflist; p_old; p_old = p_old->next) {
14571 if (p_old == p)
14572 continue;
14573 if (p_old->initreq.method != SIP_SUBSCRIBE)
14574 continue;
14575 if (p_old->subscribed == NONE)
14576 continue;
14577 ast_mutex_lock(&p_old->lock);
14578 if (!strcmp(p_old->username, p->username)) {
14579 if (!strcmp(p_old->exten, p->exten) &&
14580 !strcmp(p_old->context, p->context)) {
14581 ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
14582 ast_mutex_unlock(&p_old->lock);
14583 break;
14584 }
14585 }
14586 ast_mutex_unlock(&p_old->lock);
14587 }
14588 ast_mutex_unlock(&iflock);
14589 }
14590 if (!p->expiry)
14591 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14592 }
14593 return 1;
14594 }
14595
14596
14597 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
14598 {
14599 enum check_auth_result res;
14600
14601
14602 if (ast_test_flag(req, SIP_PKT_DEBUG))
14603 ast_verbose("Using latest REGISTER request as basis request\n");
14604 copy_request(&p->initreq, req);
14605 check_via(p, req);
14606 if ((res = register_verify(p, sin, req, e)) < 0) {
14607 const char *reason = "";
14608
14609 switch (res) {
14610 case AUTH_SECRET_FAILED:
14611 reason = "Wrong password";
14612 break;
14613 case AUTH_USERNAME_MISMATCH:
14614 reason = "Username/auth name mismatch";
14615 break;
14616 case AUTH_NOT_FOUND:
14617 reason = "No matching peer found";
14618 break;
14619 case AUTH_UNKNOWN_DOMAIN:
14620 reason = "Not a local domain";
14621 break;
14622 default:
14623 break;
14624 }
14625 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
14626 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
14627 reason);
14628 }
14629 if (res < 1) {
14630
14631
14632 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14633 }
14634 append_history(p, "RegRequest", "%s : Account %s", res ? "Failed": "Succeeded", get_header(req, "To"));
14635 return res;
14636 }
14637
14638
14639
14640
14641 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
14642 {
14643
14644
14645 const char *cmd;
14646 const char *cseq;
14647 const char *useragent;
14648 int seqno;
14649 int len;
14650 int ignore = FALSE;
14651 int respid;
14652 int res = 0;
14653 int debug = sip_debug_test_pvt(p);
14654 char *e;
14655 int error = 0;
14656
14657
14658 cseq = get_header(req, "Cseq");
14659 cmd = req->header[0];
14660
14661
14662 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
14663 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
14664 error = 1;
14665 }
14666 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
14667 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
14668 error = 1;
14669 }
14670 if (error) {
14671 if (!p->initreq.headers)
14672 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14673 return -1;
14674 }
14675
14676
14677 cmd = req->rlPart1;
14678 e = req->rlPart2;
14679
14680
14681 useragent = get_header(req, "User-Agent");
14682 if (!ast_strlen_zero(useragent))
14683 ast_string_field_set(p, useragent, useragent);
14684
14685
14686 if (req->method == SIP_RESPONSE) {
14687
14688 if (!p->initreq.headers) {
14689 if (option_debug)
14690 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
14691 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14692 return 0;
14693 } else if (p->ocseq && (p->ocseq < seqno)) {
14694 if (option_debug)
14695 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
14696 return -1;
14697 } else if (p->ocseq && (p->ocseq != seqno)) {
14698
14699
14700 ignore = TRUE;
14701 ast_set_flag(req, SIP_PKT_IGNORE);
14702 ast_set_flag(req, SIP_PKT_IGNORE_RESP);
14703 append_history(p, "Ignore", "Ignoring this retransmit\n");
14704 } else if (e) {
14705 e = ast_skip_blanks(e);
14706 if (sscanf(e, "%d %n", &respid, &len) != 1) {
14707 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
14708 } else {
14709 if (respid <= 0) {
14710 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
14711 return 0;
14712 }
14713
14714 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
14715 extract_uri(p, req);
14716 handle_response(p, respid, e + len, req, ignore, seqno);
14717 }
14718 }
14719 return 0;
14720 }
14721
14722
14723
14724
14725
14726 p->method = req->method;
14727 if (option_debug > 3)
14728 ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
14729
14730 if (p->icseq && (p->icseq > seqno)) {
14731 if (option_debug)
14732 ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
14733 if (req->method != SIP_ACK)
14734 transmit_response(p, "503 Server error", req);
14735 return -1;
14736 } else if (p->icseq &&
14737 p->icseq == seqno &&
14738 req->method != SIP_ACK &&
14739 (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
14740
14741
14742
14743 ignore = 2;
14744 ast_set_flag(req, SIP_PKT_IGNORE);
14745 ast_set_flag(req, SIP_PKT_IGNORE_REQ);
14746 if (option_debug > 2)
14747 ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
14748 }
14749
14750 if (seqno >= p->icseq)
14751
14752
14753
14754 p->icseq = seqno;
14755
14756
14757 if (ast_strlen_zero(p->theirtag)) {
14758 char tag[128];
14759
14760 gettag(req, "From", tag, sizeof(tag));
14761 ast_string_field_set(p, theirtag, tag);
14762 }
14763 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
14764
14765 if (pedanticsipchecking) {
14766
14767
14768
14769
14770 if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
14771
14772 if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
14773 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
14774
14775 } else if (req->method != SIP_ACK) {
14776 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
14777 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14778 }
14779 return res;
14780 }
14781 }
14782
14783 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
14784 transmit_response(p, "400 Bad request", req);
14785 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14786 return -1;
14787 }
14788
14789
14790 switch (p->method) {
14791 case SIP_OPTIONS:
14792 res = handle_request_options(p, req);
14793 break;
14794 case SIP_INVITE:
14795 res = handle_request_invite(p, req, debug, seqno, sin, recount, e);
14796 break;
14797 case SIP_REFER:
14798 res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
14799 break;
14800 case SIP_CANCEL:
14801 res = handle_request_cancel(p, req);
14802 break;
14803 case SIP_BYE:
14804 res = handle_request_bye(p, req);
14805 break;
14806 case SIP_MESSAGE:
14807 res = handle_request_message(p, req);
14808 break;
14809 case SIP_SUBSCRIBE:
14810 res = handle_request_subscribe(p, req, sin, seqno, e);
14811 break;
14812 case SIP_REGISTER:
14813 res = handle_request_register(p, req, sin, e);
14814 break;
14815 case SIP_INFO:
14816 if (ast_test_flag(req, SIP_PKT_DEBUG))
14817 ast_verbose("Receiving INFO!\n");
14818 if (!ignore)
14819 handle_request_info(p, req);
14820 else
14821 transmit_response(p, "200 OK", req);
14822 break;
14823 case SIP_NOTIFY:
14824 res = handle_request_notify(p, req, sin, seqno, e);
14825 break;
14826 case SIP_ACK:
14827
14828 if (seqno == p->pendinginvite) {
14829 p->invitestate = INV_TERMINATED;
14830 p->pendinginvite = 0;
14831 __sip_ack(p, seqno, FLAG_RESPONSE, 0);
14832 if (find_sdp(req)) {
14833 if (process_sdp(p, req))
14834 return -1;
14835 }
14836 check_pendings(p);
14837 }
14838
14839 if (!p->lastinvite && ast_strlen_zero(p->randdata))
14840 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14841 break;
14842 default:
14843 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
14844 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
14845 cmd, ast_inet_ntoa(p->sa.sin_addr));
14846
14847 if (!p->initreq.headers)
14848 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
14849 break;
14850 }
14851 return res;
14852 }
14853
14854
14855
14856
14857
14858
14859 static int sipsock_read(int *id, int fd, short events, void *ignore)
14860 {
14861 struct sip_request req;
14862 struct sockaddr_in sin = { 0, };
14863 struct sip_pvt *p;
14864 int res;
14865 socklen_t len = sizeof(sin);
14866 int nounlock;
14867 int recount = 0;
14868 int lockretry;
14869
14870 memset(&req, 0, sizeof(req));
14871 res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
14872 if (res < 0) {
14873 #if !defined(__FreeBSD__)
14874 if (errno == EAGAIN)
14875 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
14876 else
14877 #endif
14878 if (errno != ECONNREFUSED)
14879 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
14880 return 1;
14881 }
14882 if (option_debug && res == sizeof(req.data)) {
14883 ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
14884 req.data[sizeof(req.data) - 1] = '\0';
14885 } else
14886 req.data[res] = '\0';
14887 req.len = res;
14888 if(sip_debug_test_addr(&sin))
14889 ast_set_flag(&req, SIP_PKT_DEBUG);
14890 if (pedanticsipchecking)
14891 req.len = lws2sws(req.data, req.len);
14892 if (ast_test_flag(&req, SIP_PKT_DEBUG))
14893 ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);
14894
14895 parse_request(&req);
14896 req.method = find_sip_method(req.rlPart1);
14897
14898 if (ast_test_flag(&req, SIP_PKT_DEBUG))
14899 ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
14900
14901 if (req.headers < 2)
14902 return 1;
14903
14904
14905 for (lockretry = 100; lockretry > 0; lockretry--) {
14906 ast_mutex_lock(&netlock);
14907
14908
14909 p = find_call(&req, &sin, req.method);
14910 if (p == NULL) {
14911 if (option_debug)
14912 ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
14913 ast_mutex_unlock(&netlock);
14914 return 1;
14915 }
14916
14917
14918 if (!p->owner || !ast_channel_trylock(p->owner))
14919 break;
14920 if (option_debug)
14921 ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
14922 ast_mutex_unlock(&p->lock);
14923 ast_mutex_unlock(&netlock);
14924
14925 usleep(1);
14926 }
14927 p->recv = sin;
14928
14929 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
14930 append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);
14931
14932 if (!lockretry) {
14933 if (p->owner)
14934 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
14935 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
14936 if (req.method != SIP_ACK)
14937 transmit_response(p, "503 Server error", &req);
14938
14939 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
14940 return 1;
14941 }
14942 nounlock = 0;
14943 if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
14944
14945 if (option_debug)
14946 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
14947 }
14948
14949 if (p->owner && !nounlock)
14950 ast_channel_unlock(p->owner);
14951 ast_mutex_unlock(&p->lock);
14952 ast_mutex_unlock(&netlock);
14953 if (recount)
14954 ast_update_use_count();
14955
14956 return 1;
14957 }
14958
14959
14960 static int sip_send_mwi_to_peer(struct sip_peer *peer)
14961 {
14962
14963 struct sip_pvt *p;
14964 int newmsgs, oldmsgs;
14965
14966
14967 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
14968 return 0;
14969
14970
14971 ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
14972
14973 peer->lastmsgcheck = time(NULL);
14974
14975
14976 if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
14977 return 0;
14978 }
14979
14980
14981 peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
14982
14983 if (peer->mwipvt) {
14984
14985 p = peer->mwipvt;
14986 } else {
14987
14988 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
14989 return -1;
14990 if (create_addr_from_peer(p, peer)) {
14991
14992 sip_destroy(p);
14993 return 0;
14994 }
14995
14996 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
14997 p->ourip = __ourip;
14998 build_via(p);
14999 build_callid_pvt(p);
15000
15001 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15002 }
15003
15004 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15005 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
15006 return 0;
15007 }
15008
15009
15010 static int does_peer_need_mwi(struct sip_peer *peer)
15011 {
15012 time_t t = time(NULL);
15013
15014 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
15015 !peer->mwipvt) {
15016 peer->lastmsgcheck = t;
15017 return FALSE;
15018 }
15019
15020 if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
15021 return TRUE;
15022
15023 return FALSE;
15024 }
15025
15026
15027
15028
15029
15030
15031 static void *do_monitor(void *data)
15032 {
15033 int res;
15034 struct sip_pvt *sip;
15035 struct sip_peer *peer = NULL;
15036 time_t t;
15037 int fastrestart = FALSE;
15038 int lastpeernum = -1;
15039 int curpeernum;
15040 int reloading;
15041
15042
15043 if (sipsock > -1)
15044 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
15045
15046
15047 for(;;) {
15048
15049 ast_mutex_lock(&sip_reload_lock);
15050 reloading = sip_reloading;
15051 sip_reloading = FALSE;
15052 ast_mutex_unlock(&sip_reload_lock);
15053 if (reloading) {
15054 if (option_verbose > 0)
15055 ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
15056 sip_do_reload(sip_reloadreason);
15057
15058
15059 if (sipsock > -1)
15060 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
15061 }
15062
15063 ast_mutex_lock(&iflock);
15064 restartsearch:
15065 t = time(NULL);
15066
15067
15068
15069
15070 for (sip = iflist; !fastrestart && sip; sip = sip->next) {
15071 ast_mutex_lock(&sip->lock);
15072
15073 if (sip->rtp && sip->owner &&
15074 (sip->owner->_state == AST_STATE_UP) &&
15075 !sip->redirip.sin_addr.s_addr) {
15076 if (sip->lastrtptx &&
15077 ast_rtp_get_rtpkeepalive(sip->rtp) &&
15078 (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
15079
15080 sip->lastrtptx = time(NULL);
15081 ast_rtp_sendcng(sip->rtp, 0);
15082 }
15083 if (sip->lastrtprx &&
15084 (ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
15085 (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
15086
15087 struct sockaddr_in sin;
15088 ast_rtp_get_peer(sip->rtp, &sin);
15089 if (sin.sin_addr.s_addr ||
15090 (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
15091 (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
15092
15093 if (ast_rtp_get_rtptimeout(sip->rtp)) {
15094 while (sip->owner && ast_channel_trylock(sip->owner)) {
15095 ast_mutex_unlock(&sip->lock);
15096 usleep(1);
15097 ast_mutex_lock(&sip->lock);
15098 }
15099 if (sip->owner) {
15100 if (!(ast_rtp_get_bridged(sip->rtp))) {
15101 ast_log(LOG_NOTICE,
15102 "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
15103 sip->owner->name,
15104 (long) (t - sip->lastrtprx));
15105
15106 ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
15107 } else
15108 ast_log(LOG_NOTICE, "'%s' will not be disconnected in %ld seconds because it is directly bridged to another RTP stream\n", sip->owner->name, (long) (t - sip->lastrtprx));
15109 ast_channel_unlock(sip->owner);
15110
15111
15112
15113
15114 ast_rtp_set_rtptimeout(sip->rtp, 0);
15115 ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
15116 if (sip->vrtp) {
15117 ast_rtp_set_rtptimeout(sip->vrtp, 0);
15118 ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
15119 }
15120 }
15121 }
15122 }
15123 }
15124 }
15125
15126 if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
15127 !sip->owner) {
15128 ast_mutex_unlock(&sip->lock);
15129 __sip_destroy(sip, 1);
15130 goto restartsearch;
15131 }
15132 ast_mutex_unlock(&sip->lock);
15133 }
15134 ast_mutex_unlock(&iflock);
15135
15136 pthread_testcancel();
15137
15138 res = ast_sched_wait(sched);
15139 if ((res < 0) || (res > 1000))
15140 res = 1000;
15141
15142 if (fastrestart)
15143 res = 1;
15144 res = ast_io_wait(io, res);
15145 if (option_debug && res > 20)
15146 ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
15147 ast_mutex_lock(&monlock);
15148 if (res >= 0) {
15149 res = ast_sched_runq(sched);
15150 if (option_debug && res >= 20)
15151 ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
15152 }
15153
15154
15155 t = time(NULL);
15156 fastrestart = FALSE;
15157 curpeernum = 0;
15158 peer = NULL;
15159
15160 ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
15161 if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
15162 fastrestart = TRUE;
15163 lastpeernum = curpeernum;
15164 peer = ASTOBJ_REF(iterator);
15165 };
15166 curpeernum++;
15167 } while (0)
15168 );
15169
15170 if (peer) {
15171 ASTOBJ_WRLOCK(peer);
15172 sip_send_mwi_to_peer(peer);
15173 ASTOBJ_UNLOCK(peer);
15174 ASTOBJ_UNREF(peer,sip_destroy_peer);
15175 } else {
15176
15177 lastpeernum = -1;
15178 }
15179 ast_mutex_unlock(&monlock);
15180 }
15181
15182 return NULL;
15183
15184 }
15185
15186
15187 static int restart_monitor(void)
15188 {
15189
15190 if (monitor_thread == AST_PTHREADT_STOP)
15191 return 0;
15192 ast_mutex_lock(&monlock);
15193 if (monitor_thread == pthread_self()) {
15194 ast_mutex_unlock(&monlock);
15195 ast_log(LOG_WARNING, "Cannot kill myself\n");
15196 return -1;
15197 }
15198 if (monitor_thread != AST_PTHREADT_NULL) {
15199
15200 pthread_kill(monitor_thread, SIGURG);
15201 } else {
15202
15203 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
15204 ast_mutex_unlock(&monlock);
15205 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
15206 return -1;
15207 }
15208 }
15209 ast_mutex_unlock(&monlock);
15210 return 0;
15211 }
15212
15213
15214 static int sip_poke_noanswer(void *data)
15215 {
15216 struct sip_peer *peer = data;
15217
15218 peer->pokeexpire = -1;
15219 if (peer->lastms > -1) {
15220 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
15221 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
15222 }
15223 if (peer->call)
15224 sip_destroy(peer->call);
15225 peer->call = NULL;
15226 peer->lastms = -1;
15227 ast_device_state_changed("SIP/%s", peer->name);
15228
15229 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
15230 return 0;
15231 }
15232
15233
15234
15235
15236 static int sip_poke_peer(struct sip_peer *peer)
15237 {
15238 struct sip_pvt *p;
15239
15240 if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
15241
15242
15243 if (peer->pokeexpire > -1)
15244 ast_sched_del(sched, peer->pokeexpire);
15245 peer->lastms = 0;
15246 peer->pokeexpire = -1;
15247 peer->call = NULL;
15248 return 0;
15249 }
15250 if (peer->call) {
15251 if (sipdebug)
15252 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
15253 sip_destroy(peer->call);
15254 }
15255 if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
15256 return -1;
15257
15258 p->sa = peer->addr;
15259 p->recv = peer->addr;
15260 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15261 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15262
15263
15264 if (!ast_strlen_zero(peer->fullcontact))
15265 ast_string_field_set(p, fullcontact, peer->fullcontact);
15266
15267 if (!ast_strlen_zero(peer->tohost))
15268 ast_string_field_set(p, tohost, peer->tohost);
15269 else
15270 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
15271
15272
15273 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15274 p->ourip = __ourip;
15275 build_via(p);
15276 build_callid_pvt(p);
15277
15278 if (peer->pokeexpire > -1)
15279 ast_sched_del(sched, peer->pokeexpire);
15280 p->relatedpeer = peer;
15281 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15282 #ifdef VOCAL_DATA_HACK
15283 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
15284 transmit_invite(p, SIP_INVITE, 0, 2);
15285 #else
15286 transmit_invite(p, SIP_OPTIONS, 0, 2);
15287 #endif
15288 gettimeofday(&peer->ps, NULL);
15289 peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
15290
15291 return 0;
15292 }
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327 static int sip_devicestate(void *data)
15328 {
15329 char *host;
15330 char *tmp;
15331
15332 struct hostent *hp;
15333 struct ast_hostent ahp;
15334 struct sip_peer *p;
15335
15336 int res = AST_DEVICE_INVALID;
15337
15338
15339 host = ast_strdupa(data ? data : "");
15340 if ((tmp = strchr(host, '@')))
15341 host = tmp + 1;
15342
15343 if (option_debug > 2)
15344 ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
15345
15346 if ((p = find_peer(host, NULL, 1))) {
15347 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359 if (p->onHold)
15360
15361 res = AST_DEVICE_ONHOLD;
15362 else if (p->inRinging) {
15363 if (p->inRinging == p->inUse)
15364 res = AST_DEVICE_RINGING;
15365 else
15366 res = AST_DEVICE_RINGINUSE;
15367 } else if (p->call_limit && (p->inUse == p->call_limit))
15368
15369 res = AST_DEVICE_BUSY;
15370 else if (p->call_limit && p->inUse)
15371
15372 res = AST_DEVICE_INUSE;
15373 else if (p->maxms && (p->lastms > p->maxms))
15374
15375 res = AST_DEVICE_UNAVAILABLE;
15376 else
15377 res = AST_DEVICE_NOT_INUSE;
15378 } else {
15379
15380 res = AST_DEVICE_UNAVAILABLE;
15381 }
15382 ASTOBJ_UNREF(p,sip_destroy_peer);
15383 } else {
15384 hp = ast_gethostbyname(host, &ahp);
15385 if (hp)
15386 res = AST_DEVICE_UNKNOWN;
15387 }
15388
15389 return res;
15390 }
15391
15392
15393
15394 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
15395 {
15396 int oldformat;
15397 struct sip_pvt *p;
15398 struct ast_channel *tmpc = NULL;
15399 char *ext, *host;
15400 char tmp[256];
15401 char *dest = data;
15402
15403 oldformat = format;
15404 if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
15405 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));
15406 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
15407 return NULL;
15408 }
15409 if (option_debug)
15410 ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
15411
15412 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
15413 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
15414 *cause = AST_CAUSE_SWITCH_CONGESTION;
15415 return NULL;
15416 }
15417
15418 ast_set_flag(&p->flags[1], SIP_PAGE2_OUTGOING_CALL);
15419
15420 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
15421 sip_destroy(p);
15422 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
15423 *cause = AST_CAUSE_SWITCH_CONGESTION;
15424 return NULL;
15425 }
15426
15427 ast_copy_string(tmp, dest, sizeof(tmp));
15428 host = strchr(tmp, '@');
15429 if (host) {
15430 *host++ = '\0';
15431 ext = tmp;
15432 } else {
15433 ext = strchr(tmp, '/');
15434 if (ext)
15435 *ext++ = '\0';
15436 host = tmp;
15437 }
15438
15439 if (create_addr(p, host)) {
15440 *cause = AST_CAUSE_UNREGISTERED;
15441 if (option_debug > 2)
15442 ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
15443 sip_destroy(p);
15444 return NULL;
15445 }
15446 if (ast_strlen_zero(p->peername) && ext)
15447 ast_string_field_set(p, peername, ext);
15448
15449 if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
15450 p->ourip = __ourip;
15451 build_via(p);
15452 build_callid_pvt(p);
15453
15454
15455
15456
15457
15458 if (ext) {
15459 ast_string_field_set(p, username, ext);
15460 ast_string_field_free(p, fullcontact);
15461 }
15462 #if 0
15463 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
15464 #endif
15465 p->prefcodec = oldformat;
15466 ast_mutex_lock(&p->lock);
15467 tmpc = sip_new(p, AST_STATE_DOWN, host);
15468 ast_mutex_unlock(&p->lock);
15469 if (!tmpc)
15470 sip_destroy(p);
15471 ast_update_use_count();
15472 restart_monitor();
15473 return tmpc;
15474 }
15475
15476
15477
15478
15479
15480
15481
15482
15483 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
15484 {
15485 int res = 1;
15486 static int dep_insecure_very = 0;
15487 static int dep_insecure_yes = 0;
15488
15489 if (!strcasecmp(v->name, "trustrpid")) {
15490 ast_set_flag(&mask[0], SIP_TRUSTRPID);
15491 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
15492 } else if (!strcasecmp(v->name, "sendrpid")) {
15493 ast_set_flag(&mask[0], SIP_SENDRPID);
15494 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
15495 } else if (!strcasecmp(v->name, "g726nonstandard")) {
15496 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
15497 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
15498 } else if (!strcasecmp(v->name, "useclientcode")) {
15499 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
15500 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
15501 } else if (!strcasecmp(v->name, "dtmfmode")) {
15502 ast_set_flag(&mask[0], SIP_DTMF);
15503 ast_clear_flag(&flags[0], SIP_DTMF);
15504 if (!strcasecmp(v->value, "inband"))
15505 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
15506 else if (!strcasecmp(v->value, "rfc2833"))
15507 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
15508 else if (!strcasecmp(v->value, "info"))
15509 ast_set_flag(&flags[0], SIP_DTMF_INFO);
15510 else if (!strcasecmp(v->value, "auto"))
15511 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
15512 else {
15513 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
15514 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
15515 }
15516 } else if (!strcasecmp(v->name, "nat")) {
15517 ast_set_flag(&mask[0], SIP_NAT);
15518 ast_clear_flag(&flags[0], SIP_NAT);
15519 if (!strcasecmp(v->value, "never"))
15520 ast_set_flag(&flags[0], SIP_NAT_NEVER);
15521 else if (!strcasecmp(v->value, "route"))
15522 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
15523 else if (ast_true(v->value))
15524 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
15525 else
15526 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
15527 } else if (!strcasecmp(v->name, "canreinvite")) {
15528 ast_set_flag(&mask[0], SIP_REINVITE);
15529 ast_clear_flag(&flags[0], SIP_REINVITE);
15530 if (ast_true(v->value)) {
15531 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
15532 } else if (!ast_false(v->value)) {
15533 char buf[64];
15534 char *word, *next = buf;
15535
15536 ast_copy_string(buf, v->value, sizeof(buf));
15537 while ((word = strsep(&next, ","))) {
15538 if (!strcasecmp(word, "update")) {
15539 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
15540 } else if (!strcasecmp(word, "nonat")) {
15541 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
15542 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
15543 } else {
15544 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
15545 }
15546 }
15547 }
15548 } else if (!strcasecmp(v->name, "insecure")) {
15549 ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
15550 ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
15551 if (!strcasecmp(v->value, "very")) {
15552 ast_set_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
15553 if (!dep_insecure_very) {
15554 ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", v->lineno);
15555 dep_insecure_very = 1;
15556 }
15557 }
15558 else if (ast_true(v->value)) {
15559 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
15560 if (!dep_insecure_yes) {
15561 ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", v->value, v->lineno);
15562 dep_insecure_yes = 1;
15563 }
15564 }
15565 else if (!ast_false(v->value)) {
15566 char buf[64];
15567 char *word, *next;
15568
15569 ast_copy_string(buf, v->value, sizeof(buf));
15570 next = buf;
15571 while ((word = strsep(&next, ","))) {
15572 if (!strcasecmp(word, "port"))
15573 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
15574 else if (!strcasecmp(word, "invite"))
15575 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
15576 else
15577 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", v->value, v->lineno);
15578 }
15579 }
15580 } else if (!strcasecmp(v->name, "progressinband")) {
15581 ast_set_flag(&mask[0], SIP_PROG_INBAND);
15582 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
15583 if (ast_true(v->value))
15584 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
15585 else if (strcasecmp(v->value, "never"))
15586 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
15587 } else if (!strcasecmp(v->name, "promiscredir")) {
15588 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
15589 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
15590 } else if (!strcasecmp(v->name, "videosupport")) {
15591 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
15592 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
15593 } else if (!strcasecmp(v->name, "allowoverlap")) {
15594 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
15595 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
15596 } else if (!strcasecmp(v->name, "allowsubscribe")) {
15597 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
15598 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
15599 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
15600 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
15601 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
15602 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
15603 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
15604 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
15605 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
15606 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
15607 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
15608 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
15609 #endif
15610 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
15611 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
15612 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
15613 } else if (!strcasecmp(v->name, "buggymwi")) {
15614 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
15615 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
15616 } else
15617 res = 0;
15618
15619 return res;
15620 }
15621
15622
15623 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
15624 {
15625 struct domain *d;
15626
15627 if (ast_strlen_zero(domain)) {
15628 ast_log(LOG_WARNING, "Zero length domain.\n");
15629 return 1;
15630 }
15631
15632 if (!(d = ast_calloc(1, sizeof(*d))))
15633 return 0;
15634
15635 ast_copy_string(d->domain, domain, sizeof(d->domain));
15636
15637 if (!ast_strlen_zero(context))
15638 ast_copy_string(d->context, context, sizeof(d->context));
15639
15640 d->mode = mode;
15641
15642 AST_LIST_LOCK(&domain_list);
15643 AST_LIST_INSERT_TAIL(&domain_list, d, list);
15644 AST_LIST_UNLOCK(&domain_list);
15645
15646 if (sipdebug)
15647 ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
15648
15649 return 1;
15650 }
15651
15652
15653 static int check_sip_domain(const char *domain, char *context, size_t len)
15654 {
15655 struct domain *d;
15656 int result = 0;
15657
15658 AST_LIST_LOCK(&domain_list);
15659 AST_LIST_TRAVERSE(&domain_list, d, list) {
15660 if (strcasecmp(d->domain, domain))
15661 continue;
15662
15663 if (len && !ast_strlen_zero(d->context))
15664 ast_copy_string(context, d->context, len);
15665
15666 result = 1;
15667 break;
15668 }
15669 AST_LIST_UNLOCK(&domain_list);
15670
15671 return result;
15672 }
15673
15674
15675 static void clear_sip_domains(void)
15676 {
15677 struct domain *d;
15678
15679 AST_LIST_LOCK(&domain_list);
15680 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
15681 free(d);
15682 AST_LIST_UNLOCK(&domain_list);
15683 }
15684
15685
15686
15687 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
15688 {
15689 char authcopy[256];
15690 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
15691 char *stringp;
15692 struct sip_auth *a, *b, *auth;
15693
15694 if (ast_strlen_zero(configuration))
15695 return authlist;
15696
15697 if (option_debug)
15698 ast_log(LOG_DEBUG, "Auth config :: %s\n", configuration);
15699
15700 ast_copy_string(authcopy, configuration, sizeof(authcopy));
15701 stringp = authcopy;
15702
15703 username = stringp;
15704 realm = strrchr(stringp, '@');
15705 if (realm)
15706 *realm++ = '\0';
15707 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
15708 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
15709 return authlist;
15710 }
15711 stringp = username;
15712 username = strsep(&stringp, ":");
15713 if (username) {
15714 secret = strsep(&stringp, ":");
15715 if (!secret) {
15716 stringp = username;
15717 md5secret = strsep(&stringp,"#");
15718 }
15719 }
15720 if (!(auth = ast_calloc(1, sizeof(*auth))))
15721 return authlist;
15722
15723 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
15724 ast_copy_string(auth->username, username, sizeof(auth->username));
15725 if (secret)
15726 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
15727 if (md5secret)
15728 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
15729
15730
15731 for (b = NULL, a = authlist; a ; b = a, a = a->next)
15732 ;
15733 if (b)
15734 b->next = auth;
15735 else
15736 authlist = auth;
15737
15738 if (option_verbose > 2)
15739 ast_verbose("Added authentication for realm %s\n", realm);
15740
15741 return authlist;
15742
15743 }
15744
15745
15746 static int clear_realm_authentication(struct sip_auth *authlist)
15747 {
15748 struct sip_auth *a = authlist;
15749 struct sip_auth *b;
15750
15751 while (a) {
15752 b = a;
15753 a = a->next;
15754 free(b);
15755 }
15756
15757 return 1;
15758 }
15759
15760
15761 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
15762 {
15763 struct sip_auth *a;
15764
15765 for (a = authlist; a; a = a->next) {
15766 if (!strcasecmp(a->realm, realm))
15767 break;
15768 }
15769
15770 return a;
15771 }
15772
15773
15774 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime)
15775 {
15776 struct sip_user *user;
15777 int format;
15778 struct ast_ha *oldha = NULL;
15779 char *varname = NULL, *varval = NULL;
15780 struct ast_variable *tmpvar = NULL;
15781 struct ast_flags userflags[2] = {{(0)}};
15782 struct ast_flags mask[2] = {{(0)}};
15783
15784
15785 if (!(user = ast_calloc(1, sizeof(*user))))
15786 return NULL;
15787
15788 suserobjs++;
15789 ASTOBJ_INIT(user);
15790 ast_copy_string(user->name, name, sizeof(user->name));
15791 oldha = user->ha;
15792 user->ha = NULL;
15793 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
15794 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15795 user->capability = global_capability;
15796 user->allowtransfer = global_allowtransfer;
15797 user->maxcallbitrate = default_maxcallbitrate;
15798 user->autoframing = global_autoframing;
15799 user->prefs = default_prefs;
15800
15801 strcpy(user->context, default_context);
15802 strcpy(user->language, default_language);
15803 strcpy(user->mohinterpret, default_mohinterpret);
15804 strcpy(user->mohsuggest, default_mohsuggest);
15805 for (; v; v = v->next) {
15806 if (handle_common_options(&userflags[0], &mask[0], v))
15807 continue;
15808
15809 if (!strcasecmp(v->name, "context")) {
15810 ast_copy_string(user->context, v->value, sizeof(user->context));
15811 } else if (!strcasecmp(v->name, "subscribecontext")) {
15812 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
15813 } else if (!strcasecmp(v->name, "setvar")) {
15814 varname = ast_strdupa(v->value);
15815 if ((varval = strchr(varname,'='))) {
15816 *varval++ = '\0';
15817 if ((tmpvar = ast_variable_new(varname, varval))) {
15818 tmpvar->next = user->chanvars;
15819 user->chanvars = tmpvar;
15820 }
15821 }
15822 } else if (!strcasecmp(v->name, "permit") ||
15823 !strcasecmp(v->name, "deny")) {
15824 user->ha = ast_append_ha(v->name, v->value, user->ha);
15825 } else if (!strcasecmp(v->name, "allowtransfer")) {
15826 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
15827 } else if (!strcasecmp(v->name, "secret")) {
15828 ast_copy_string(user->secret, v->value, sizeof(user->secret));
15829 } else if (!strcasecmp(v->name, "md5secret")) {
15830 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
15831 } else if (!strcasecmp(v->name, "callerid")) {
15832 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
15833 } else if (!strcasecmp(v->name, "fullname")) {
15834 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
15835 } else if (!strcasecmp(v->name, "cid_number")) {
15836 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
15837 } else if (!strcasecmp(v->name, "callgroup")) {
15838 user->callgroup = ast_get_group(v->value);
15839 } else if (!strcasecmp(v->name, "pickupgroup")) {
15840 user->pickupgroup = ast_get_group(v->value);
15841 } else if (!strcasecmp(v->name, "language")) {
15842 ast_copy_string(user->language, v->value, sizeof(user->language));
15843 } else if (!strcasecmp(v->name, "mohinterpret")
15844 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
15845 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
15846 } else if (!strcasecmp(v->name, "mohsuggest")) {
15847 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
15848 } else if (!strcasecmp(v->name, "accountcode")) {
15849 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
15850 } else if (!strcasecmp(v->name, "call-limit")) {
15851 user->call_limit = atoi(v->value);
15852 if (user->call_limit < 0)
15853 user->call_limit = 0;
15854 } else if (!strcasecmp(v->name, "amaflags")) {
15855 format = ast_cdr_amaflags2int(v->value);
15856 if (format < 0) {
15857 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
15858 } else {
15859 user->amaflags = format;
15860 }
15861 } else if (!strcasecmp(v->name, "allow")) {
15862 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
15863 } else if (!strcasecmp(v->name, "disallow")) {
15864 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
15865 } else if (!strcasecmp(v->name, "autoframing")) {
15866 user->autoframing = ast_true(v->value);
15867 } else if (!strcasecmp(v->name, "callingpres")) {
15868 user->callingpres = ast_parse_caller_presentation(v->value);
15869 if (user->callingpres == -1)
15870 user->callingpres = atoi(v->value);
15871 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
15872 user->maxcallbitrate = atoi(v->value);
15873 if (user->maxcallbitrate < 0)
15874 user->maxcallbitrate = default_maxcallbitrate;
15875 }
15876
15877
15878
15879 }
15880 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
15881 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
15882 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
15883 global_allowsubscribe = TRUE;
15884 ast_free_ha(oldha);
15885 return user;
15886 }
15887
15888
15889 static void set_peer_defaults(struct sip_peer *peer)
15890 {
15891 if (peer->expire == 0) {
15892
15893
15894
15895 peer->expire = -1;
15896 peer->pokeexpire = -1;
15897 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
15898 }
15899 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
15900 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15901 strcpy(peer->context, default_context);
15902 strcpy(peer->subscribecontext, default_subscribecontext);
15903 strcpy(peer->language, default_language);
15904 strcpy(peer->mohinterpret, default_mohinterpret);
15905 strcpy(peer->mohsuggest, default_mohsuggest);
15906 peer->addr.sin_family = AF_INET;
15907 peer->defaddr.sin_family = AF_INET;
15908 peer->capability = global_capability;
15909 peer->maxcallbitrate = default_maxcallbitrate;
15910 peer->rtptimeout = global_rtptimeout;
15911 peer->rtpholdtimeout = global_rtpholdtimeout;
15912 peer->rtpkeepalive = global_rtpkeepalive;
15913 peer->allowtransfer = global_allowtransfer;
15914 peer->autoframing = global_autoframing;
15915 strcpy(peer->vmexten, default_vmexten);
15916 peer->secret[0] = '\0';
15917 peer->md5secret[0] = '\0';
15918 peer->cid_num[0] = '\0';
15919 peer->cid_name[0] = '\0';
15920 peer->fromdomain[0] = '\0';
15921 peer->fromuser[0] = '\0';
15922 peer->regexten[0] = '\0';
15923 peer->mailbox[0] = '\0';
15924 peer->callgroup = 0;
15925 peer->pickupgroup = 0;
15926 peer->maxms = default_qualify;
15927 peer->prefs = default_prefs;
15928 }
15929
15930
15931 static struct sip_peer *temp_peer(const char *name)
15932 {
15933 struct sip_peer *peer;
15934
15935 if (!(peer = ast_calloc(1, sizeof(*peer))))
15936 return NULL;
15937
15938 apeerobjs++;
15939 ASTOBJ_INIT(peer);
15940 set_peer_defaults(peer);
15941
15942 ast_copy_string(peer->name, name, sizeof(peer->name));
15943
15944 ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
15945 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
15946 peer->prefs = default_prefs;
15947 reg_source_db(peer);
15948
15949 return peer;
15950 }
15951
15952
15953 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
15954 {
15955 struct sip_peer *peer = NULL;
15956 struct ast_ha *oldha = NULL;
15957 int obproxyfound=0;
15958 int found=0;
15959 int firstpass=1;
15960 int format=0;
15961 time_t regseconds = 0;
15962 char *varname = NULL, *varval = NULL;
15963 struct ast_variable *tmpvar = NULL;
15964 struct ast_flags peerflags[2] = {{(0)}};
15965 struct ast_flags mask[2] = {{(0)}};
15966
15967
15968 if (!realtime)
15969
15970
15971
15972
15973
15974 peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
15975
15976 if (peer) {
15977
15978 found = 1;
15979 if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
15980 firstpass = 0;
15981 } else {
15982 if (!(peer = ast_calloc(1, sizeof(*peer))))
15983 return NULL;
15984
15985 if (realtime)
15986 rpeerobjs++;
15987 else
15988 speerobjs++;
15989 ASTOBJ_INIT(peer);
15990 }
15991
15992 if (firstpass) {
15993 peer->lastmsgssent = -1;
15994 oldha = peer->ha;
15995 peer->ha = NULL;
15996 set_peer_defaults(peer);
15997 }
15998 if (!found && name)
15999 ast_copy_string(peer->name, name, sizeof(peer->name));
16000
16001
16002 if (peer->chanvars) {
16003 ast_variables_destroy(peer->chanvars);
16004 peer->chanvars = NULL;
16005
16006 }
16007 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
16008 if (handle_common_options(&peerflags[0], &mask[0], v))
16009 continue;
16010 if (realtime && !strcasecmp(v->name, "regseconds")) {
16011 ast_get_time_t(v->value, ®seconds, 0, NULL);
16012 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
16013 inet_aton(v->value, &(peer->addr.sin_addr));
16014 } else if (realtime && !strcasecmp(v->name, "name"))
16015 ast_copy_string(peer->name, v->value, sizeof(peer->name));
16016 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
16017 ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
16018 ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
16019 } else if (!strcasecmp(v->name, "secret"))
16020 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
16021 else if (!strcasecmp(v->name, "md5secret"))
16022 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
16023 else if (!strcasecmp(v->name, "auth"))
16024 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
16025 else if (!strcasecmp(v->name, "callerid")) {
16026 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
16027 } else if (!strcasecmp(v->name, "fullname")) {
16028 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
16029 } else if (!strcasecmp(v->name, "cid_number")) {
16030 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
16031 } else if (!strcasecmp(v->name, "context")) {
16032 ast_copy_string(peer->context, v->value, sizeof(peer->context));
16033 } else if (!strcasecmp(v->name, "subscribecontext")) {
16034 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
16035 } else if (!strcasecmp(v->name, "fromdomain")) {
16036 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
16037 } else if (!strcasecmp(v->name, "usereqphone")) {
16038 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
16039 } else if (!strcasecmp(v->name, "fromuser")) {
16040 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
16041 } else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
16042 if (!strcasecmp(v->value, "dynamic")) {
16043 if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
16044 ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
16045 } else {
16046
16047 if (!found || !ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
16048
16049
16050 memset(&peer->addr.sin_addr, 0, 4);
16051 if (peer->addr.sin_port) {
16052
16053 peer->defaddr.sin_port = peer->addr.sin_port;
16054 peer->addr.sin_port = 0;
16055 }
16056 }
16057 ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16058 }
16059 } else {
16060
16061 if (peer->expire > -1)
16062 ast_sched_del(sched, peer->expire);
16063 peer->expire = -1;
16064 ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
16065 if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
16066 if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
16067 ASTOBJ_UNREF(peer, sip_destroy_peer);
16068 return NULL;
16069 }
16070 }
16071 if (!strcasecmp(v->name, "outboundproxy"))
16072 obproxyfound=1;
16073 else {
16074 ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
16075 if (!peer->addr.sin_port)
16076 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
16077 }
16078 }
16079 } else if (!strcasecmp(v->name, "defaultip")) {
16080 if (ast_get_ip(&peer->defaddr, v->value)) {
16081 ASTOBJ_UNREF(peer, sip_destroy_peer);
16082 return NULL;
16083 }
16084 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
16085 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
16086 } else if (!strcasecmp(v->name, "port")) {
16087 if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
16088 peer->defaddr.sin_port = htons(atoi(v->value));
16089 else
16090 peer->addr.sin_port = htons(atoi(v->value));
16091 } else if (!strcasecmp(v->name, "callingpres")) {
16092 peer->callingpres = ast_parse_caller_presentation(v->value);
16093 if (peer->callingpres == -1)
16094 peer->callingpres = atoi(v->value);
16095 } else if (!strcasecmp(v->name, "username")) {
16096 ast_copy_string(peer->username, v->value, sizeof(peer->username));
16097 } else if (!strcasecmp(v->name, "language")) {
16098 ast_copy_string(peer->language, v->value, sizeof(peer->language));
16099 } else if (!strcasecmp(v->name, "regexten")) {
16100 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
16101 } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
16102 peer->call_limit = atoi(v->value);
16103 if (peer->call_limit < 0)
16104 peer->call_limit = 0;
16105 } else if (!strcasecmp(v->name, "amaflags")) {
16106 format = ast_cdr_amaflags2int(v->value);
16107 if (format < 0) {
16108 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
16109 } else {
16110 peer->amaflags = format;
16111 }
16112 } else if (!strcasecmp(v->name, "accountcode")) {
16113 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
16114 } else if (!strcasecmp(v->name, "mohinterpret")
16115 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16116 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
16117 } else if (!strcasecmp(v->name, "mohsuggest")) {
16118 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
16119 } else if (!strcasecmp(v->name, "mailbox")) {
16120 ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
16121 } else if (!strcasecmp(v->name, "subscribemwi")) {
16122 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
16123 } else if (!strcasecmp(v->name, "vmexten")) {
16124 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
16125 } else if (!strcasecmp(v->name, "callgroup")) {
16126 peer->callgroup = ast_get_group(v->value);
16127 } else if (!strcasecmp(v->name, "allowtransfer")) {
16128 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16129 } else if (!strcasecmp(v->name, "pickupgroup")) {
16130 peer->pickupgroup = ast_get_group(v->value);
16131 } else if (!strcasecmp(v->name, "allow")) {
16132 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
16133 } else if (!strcasecmp(v->name, "disallow")) {
16134 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
16135 } else if (!strcasecmp(v->name, "autoframing")) {
16136 peer->autoframing = ast_true(v->value);
16137 } else if (!strcasecmp(v->name, "rtptimeout")) {
16138 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
16139 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16140 peer->rtptimeout = global_rtptimeout;
16141 }
16142 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16143 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
16144 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16145 peer->rtpholdtimeout = global_rtpholdtimeout;
16146 }
16147 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16148 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
16149 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16150 peer->rtpkeepalive = global_rtpkeepalive;
16151 }
16152 } else if (!strcasecmp(v->name, "setvar")) {
16153
16154 varname = ast_strdupa(v->value);
16155 if ((varval = strchr(varname, '='))) {
16156 *varval++ = '\0';
16157 if ((tmpvar = ast_variable_new(varname, varval))) {
16158 tmpvar->next = peer->chanvars;
16159 peer->chanvars = tmpvar;
16160 }
16161 }
16162 } else if (!strcasecmp(v->name, "qualify")) {
16163 if (!strcasecmp(v->value, "no")) {
16164 peer->maxms = 0;
16165 } else if (!strcasecmp(v->value, "yes")) {
16166 peer->maxms = DEFAULT_MAXMS;
16167 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
16168 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);
16169 peer->maxms = 0;
16170 }
16171 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16172 peer->maxcallbitrate = atoi(v->value);
16173 if (peer->maxcallbitrate < 0)
16174 peer->maxcallbitrate = default_maxcallbitrate;
16175 }
16176 }
16177 if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
16178 time_t nowtime = time(NULL);
16179
16180 if ((nowtime - regseconds) > 0) {
16181 destroy_association(peer);
16182 memset(&peer->addr, 0, sizeof(peer->addr));
16183 if (option_debug)
16184 ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
16185 }
16186 }
16187 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
16188 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
16189 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
16190 global_allowsubscribe = TRUE;
16191 if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
16192 reg_source_db(peer);
16193 ASTOBJ_UNMARK(peer);
16194 ast_free_ha(oldha);
16195 return peer;
16196 }
16197
16198
16199
16200
16201
16202
16203
16204 static int reload_config(enum channelreloadreason reason)
16205 {
16206 struct ast_config *cfg, *ucfg;
16207 struct ast_variable *v;
16208 struct sip_peer *peer;
16209 struct sip_user *user;
16210 struct ast_hostent ahp;
16211 char *cat, *stringp, *context, *oldregcontext;
16212 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
16213 struct hostent *hp;
16214 int format;
16215 struct ast_flags dummy[2];
16216 int auto_sip_domains = FALSE;
16217 struct sockaddr_in old_bindaddr = bindaddr;
16218 int registry_count = 0, peer_count = 0, user_count = 0;
16219 unsigned int temp_tos = 0;
16220 struct ast_flags debugflag = {0};
16221
16222 cfg = ast_config_load(config);
16223
16224
16225 if (!cfg) {
16226 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
16227 return -1;
16228 }
16229
16230
16231 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
16232 oldregcontext = oldcontexts;
16233
16234
16235
16236 ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
16237 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
16238 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
16239 ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);
16240
16241
16242 memset(&bindaddr, 0, sizeof(bindaddr));
16243 memset(&localaddr, 0, sizeof(localaddr));
16244 memset(&externip, 0, sizeof(externip));
16245 memset(&default_prefs, 0 , sizeof(default_prefs));
16246 outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
16247 outboundproxyip.sin_family = AF_INET;
16248 ourport = STANDARD_SIP_PORT;
16249 srvlookup = DEFAULT_SRVLOOKUP;
16250 global_tos_sip = DEFAULT_TOS_SIP;
16251 global_tos_audio = DEFAULT_TOS_AUDIO;
16252 global_tos_video = DEFAULT_TOS_VIDEO;
16253 externhost[0] = '\0';
16254 externexpire = 0;
16255 externrefresh = 10;
16256 memset(&outboundproxyip, 0, sizeof(outboundproxyip));
16257
16258
16259 allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
16260 global_regcontext[0] = '\0';
16261 expiry = DEFAULT_EXPIRY;
16262 global_notifyringing = DEFAULT_NOTIFYRINGING;
16263 global_limitonpeers = FALSE;
16264 global_directrtpsetup = FALSE;
16265 global_notifyhold = FALSE;
16266 global_alwaysauthreject = 0;
16267 global_allowsubscribe = FALSE;
16268 ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
16269 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
16270 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
16271 ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
16272 else
16273 ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
16274 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
16275 compactheaders = DEFAULT_COMPACTHEADERS;
16276 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
16277 global_regattempts_max = 0;
16278 pedanticsipchecking = DEFAULT_PEDANTIC;
16279 global_mwitime = DEFAULT_MWITIME;
16280 autocreatepeer = DEFAULT_AUTOCREATEPEER;
16281 global_autoframing = 0;
16282 global_allowguest = DEFAULT_ALLOWGUEST;
16283 global_rtptimeout = 0;
16284 global_rtpholdtimeout = 0;
16285 global_rtpkeepalive = 0;
16286 global_allowtransfer = TRANSFER_OPENFORALL;
16287 global_rtautoclear = 120;
16288 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
16289 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
16290 ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);
16291
16292
16293 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
16294 default_subscribecontext[0] = '\0';
16295 default_language[0] = '\0';
16296 default_fromdomain[0] = '\0';
16297 default_qualify = DEFAULT_QUALIFY;
16298 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
16299 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
16300 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
16301 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
16302 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
16303 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
16304 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);
16305
16306
16307 dumphistory = FALSE;
16308 recordhistory = FALSE;
16309 ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
16310
16311
16312 global_relaxdtmf = FALSE;
16313 global_callevents = FALSE;
16314 global_t1min = DEFAULT_T1MIN;
16315
16316 global_matchexterniplocally = FALSE;
16317
16318
16319 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
16320
16321 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
16322
16323
16324 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
16325 if (handle_common_options(&global_flags[0], &dummy[0], v))
16326 continue;
16327
16328 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
16329 continue;
16330
16331
16332 if (!strcasecmp(v->name, "context")) {
16333 ast_copy_string(default_context, v->value, sizeof(default_context));
16334 } else if (!strcasecmp(v->name, "allowguest")) {
16335 global_allowguest = ast_true(v->value) ? 1 : 0;
16336 } else if (!strcasecmp(v->name, "realm")) {
16337 ast_copy_string(global_realm, v->value, sizeof(global_realm));
16338 } else if (!strcasecmp(v->name, "useragent")) {
16339 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
16340 if (option_debug)
16341 ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
16342 } else if (!strcasecmp(v->name, "allowtransfer")) {
16343 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
16344 } else if (!strcasecmp(v->name, "rtcachefriends")) {
16345 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
16346 } else if (!strcasecmp(v->name, "rtsavesysname")) {
16347 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);
16348 } else if (!strcasecmp(v->name, "rtupdate")) {
16349 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);
16350 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
16351 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
16352 } else if (!strcasecmp(v->name, "t1min")) {
16353 global_t1min = atoi(v->value);
16354 } else if (!strcasecmp(v->name, "rtautoclear")) {
16355 int i = atoi(v->value);
16356 if (i > 0)
16357 global_rtautoclear = i;
16358 else
16359 i = 0;
16360 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
16361 } else if (!strcasecmp(v->name, "usereqphone")) {
16362 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
16363 } else if (!strcasecmp(v->name, "relaxdtmf")) {
16364 global_relaxdtmf = ast_true(v->value);
16365 } else if (!strcasecmp(v->name, "checkmwi")) {
16366 if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
16367 ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d. Using default (10).\n", v->value, v->lineno);
16368 global_mwitime = DEFAULT_MWITIME;
16369 }
16370 } else if (!strcasecmp(v->name, "vmexten")) {
16371 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
16372 } else if (!strcasecmp(v->name, "rtptimeout")) {
16373 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
16374 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16375 global_rtptimeout = 0;
16376 }
16377 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
16378 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
16379 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
16380 global_rtpholdtimeout = 0;
16381 }
16382 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
16383 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
16384 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
16385 global_rtpkeepalive = 0;
16386 }
16387 } else if (!strcasecmp(v->name, "compactheaders")) {
16388 compactheaders = ast_true(v->value);
16389 } else if (!strcasecmp(v->name, "notifymimetype")) {
16390 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
16391 } else if (!strncasecmp(v->name, "limitonpeer", 11)) {
16392 global_limitonpeers = ast_true(v->value);
16393 } else if (!strcasecmp(v->name, "directrtpsetup")) {
16394 global_directrtpsetup = ast_true(v->value);
16395 } else if (!strcasecmp(v->name, "notifyringing")) {
16396 global_notifyringing = ast_true(v->value);
16397 } else if (!strcasecmp(v->name, "notifyhold")) {
16398 global_notifyhold = ast_true(v->value);
16399 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
16400 global_alwaysauthreject = ast_true(v->value);
16401 } else if (!strcasecmp(v->name, "mohinterpret")
16402 || !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
16403 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
16404 } else if (!strcasecmp(v->name, "mohsuggest")) {
16405 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
16406 } else if (!strcasecmp(v->name, "language")) {
16407 ast_copy_string(default_language, v->value, sizeof(default_language));
16408 } else if (!strcasecmp(v->name, "regcontext")) {
16409 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
16410 stringp = newcontexts;
16411
16412 cleanup_stale_contexts(stringp, oldregcontext);
16413
16414 while ((context = strsep(&stringp, "&"))) {
16415 if (!ast_context_find(context))
16416 ast_context_create(NULL, context,"SIP");
16417 }
16418 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
16419 } else if (!strcasecmp(v->name, "callerid")) {
16420 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
16421 } else if (!strcasecmp(v->name, "fromdomain")) {
16422 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
16423 } else if (!strcasecmp(v->name, "outboundproxy")) {
16424 if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
16425 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
16426 } else if (!strcasecmp(v->name, "outboundproxyport")) {
16427
16428 sscanf(v->value, "%d", &format);
16429 outboundproxyip.sin_port = htons(format);
16430 } else if (!strcasecmp(v->name, "autocreatepeer")) {
16431 autocreatepeer = ast_true(v->value);
16432 } else if (!strcasecmp(v->name, "srvlookup")) {
16433 srvlookup = ast_true(v->value);
16434 } else if (!strcasecmp(v->name, "pedantic")) {
16435 pedanticsipchecking = ast_true(v->value);
16436 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
16437 max_expiry = atoi(v->value);
16438 if (max_expiry < 1)
16439 max_expiry = DEFAULT_MAX_EXPIRY;
16440 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
16441 min_expiry = atoi(v->value);
16442 if (min_expiry < 1)
16443 min_expiry = DEFAULT_MIN_EXPIRY;
16444 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
16445 default_expiry = atoi(v->value);
16446 if (default_expiry < 1)
16447 default_expiry = DEFAULT_DEFAULT_EXPIRY;
16448 } else if (!strcasecmp(v->name, "sipdebug")) {
16449 if (ast_true(v->value))
16450 ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
16451 } else if (!strcasecmp(v->name, "dumphistory")) {
16452 dumphistory = ast_true(v->value);
16453 } else if (!strcasecmp(v->name, "recordhistory")) {
16454 recordhistory = ast_true(v->value);
16455 } else if (!strcasecmp(v->name, "registertimeout")) {
16456 global_reg_timeout = atoi(v->value);
16457 if (global_reg_timeout < 1)
16458 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
16459 } else if (!strcasecmp(v->name, "registerattempts")) {
16460 global_regattempts_max = atoi(v->value);
16461 } else if (!strcasecmp(v->name, "bindaddr")) {
16462 if (!(hp = ast_gethostbyname(v->value, &ahp))) {
16463 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
16464 } else {
16465 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
16466 }
16467 } else if (!strcasecmp(v->name, "localnet")) {
16468 struct ast_ha *na;
16469 if (!(na = ast_append_ha("d", v->value, localaddr)))
16470 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
16471 else
16472 localaddr = na;
16473 } else if (!strcasecmp(v->name, "localmask")) {
16474 ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
16475 } else if (!strcasecmp(v->name, "externip")) {
16476 if (!(hp = ast_gethostbyname(v->value, &ahp)))
16477 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
16478 else
16479 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
16480 externexpire = 0;
16481 } else if (!strcasecmp(v->name, "externhost")) {
16482 ast_copy_string(externhost, v->value, sizeof(externhost));
16483 if (!(hp = ast_gethostbyname(externhost, &ahp)))
16484 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
16485 else
16486 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
16487 externexpire = time(NULL);
16488 } else if (!strcasecmp(v->name, "externrefresh")) {
16489 if (sscanf(v->value, "%d", &externrefresh) != 1) {
16490 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
16491 externrefresh = 10;
16492 }
16493 } else if (!strcasecmp(v->name, "allow")) {
16494 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
16495 } else if (!strcasecmp(v->name, "disallow")) {
16496 ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
16497 } else if (!strcasecmp(v->name, "autoframing")) {
16498 global_autoframing = ast_true(v->value);
16499 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
16500 allow_external_domains = ast_true(v->value);
16501 } else if (!strcasecmp(v->name, "autodomain")) {
16502 auto_sip_domains = ast_true(v->value);
16503 } else if (!strcasecmp(v->name, "domain")) {
16504 char *domain = ast_strdupa(v->value);
16505 char *context = strchr(domain, ',');
16506
16507 if (context)
16508 *context++ = '\0';
16509
16510 if (option_debug && ast_strlen_zero(context))
16511 ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
16512 if (ast_strlen_zero(domain))
16513 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
16514 else
16515 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
16516 } else if (!strcasecmp(v->name, "register")) {
16517 if (sip_register(v->value, v->lineno) == 0)
16518 registry_count++;
16519 } else if (!strcasecmp(v->name, "tos")) {
16520 if (!ast_str2tos(v->value, &temp_tos)) {
16521 global_tos_sip = temp_tos;
16522 global_tos_audio = temp_tos;
16523 global_tos_video = temp_tos;
16524 ast_log(LOG_WARNING, "tos value at line %d is deprecated. See doc/ip-tos.txt for more information.\n", v->lineno);
16525 } else
16526 ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
16527 } else if (!strcasecmp(v->name, "tos_sip")) {
16528 if (ast_str2tos(v->value, &global_tos_sip))
16529 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
16530 } else if (!strcasecmp(v->name, "tos_audio")) {
16531 if (ast_str2tos(v->value, &global_tos_audio))
16532 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
16533 } else if (!strcasecmp(v->name, "tos_video")) {
16534 if (ast_str2tos(v->value, &global_tos_video))
16535 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
16536 } else if (!strcasecmp(v->name, "bindport")) {
16537 if (sscanf(v->value, "%d", &ourport) == 1) {
16538 bindaddr.sin_port = htons(ourport);
16539 } else {
16540 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
16541 }
16542 } else if (!strcasecmp(v->name, "qualify")) {
16543 if (!strcasecmp(v->value, "no")) {
16544 default_qualify = 0;
16545 } else if (!strcasecmp(v->value, "yes")) {
16546 default_qualify = DEFAULT_MAXMS;
16547 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
16548 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
16549 default_qualify = 0;
16550 }
16551 } else if (!strcasecmp(v->name, "callevents")) {
16552 global_callevents = ast_true(v->value);
16553 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
16554 default_maxcallbitrate = atoi(v->value);
16555 if (default_maxcallbitrate < 0)
16556 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
16557 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
16558 global_matchexterniplocally = ast_true(v->value);
16559 }
16560 }
16561
16562 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
16563 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
16564 allow_external_domains = 1;
16565 }
16566
16567
16568 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
16569
16570 if (!strcasecmp(v->name, "auth"))
16571 authl = add_realm_authentication(authl, v->value, v->lineno);
16572 }
16573
16574 ucfg = ast_config_load("users.conf");
16575 if (ucfg) {
16576 struct ast_variable *gen;
16577 int genhassip, genregistersip;
16578 const char *hassip, *registersip;
16579
16580 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
16581 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
16582 gen = ast_variable_browse(ucfg, "general");
16583 cat = ast_category_browse(ucfg, NULL);
16584 while (cat) {
16585 if (strcasecmp(cat, "general")) {
16586 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
16587 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
16588 if (ast_true(hassip) || (!hassip && genhassip)) {
16589 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
16590 if (peer) {
16591 ast_device_state_changed("SIP/%s", peer->name);
16592 ASTOBJ_CONTAINER_LINK(&peerl,peer);
16593 ASTOBJ_UNREF(peer, sip_destroy_peer);
16594 peer_count++;
16595 }
16596 }
16597 if (ast_true(registersip) || (!registersip && genregistersip)) {
16598 char tmp[256];
16599 const char *host = ast_variable_retrieve(ucfg, cat, "host");
16600 const char *username = ast_variable_retrieve(ucfg, cat, "username");
16601 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
16602 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
16603 if (!host)
16604 host = ast_variable_retrieve(ucfg, "general", "host");
16605 if (!username)
16606 username = ast_variable_retrieve(ucfg, "general", "username");
16607 if (!secret)
16608 secret = ast_variable_retrieve(ucfg, "general", "secret");
16609 if (!contact)
16610 contact = "s";
16611 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
16612 if (!ast_strlen_zero(secret))
16613 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
16614 else
16615 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
16616 if (sip_register(tmp, 0) == 0)
16617 registry_count++;
16618 }
16619 }
16620 }
16621 cat = ast_category_browse(ucfg, cat);
16622 }
16623 ast_config_destroy(ucfg);
16624 }
16625
16626
16627
16628 cat = NULL;
16629 while ( (cat = ast_category_browse(cfg, cat)) ) {
16630 const char *utype;
16631 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
16632 continue;
16633 utype = ast_variable_retrieve(cfg, cat, "type");
16634 if (!utype) {
16635 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
16636 continue;
16637 } else {
16638 int is_user = 0, is_peer = 0;
16639 if (!strcasecmp(utype, "user"))
16640 is_user = 1;
16641 else if (!strcasecmp(utype, "friend"))
16642 is_user = is_peer = 1;
16643 else if (!strcasecmp(utype, "peer"))
16644 is_peer = 1;
16645 else {
16646 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
16647 continue;
16648 }
16649 if (is_user) {
16650 user = build_user(cat, ast_variable_browse(cfg, cat), 0);
16651 if (user) {
16652 ASTOBJ_CONTAINER_LINK(&userl,user);
16653 ASTOBJ_UNREF(user, sip_destroy_user);
16654 user_count++;
16655 }
16656 }
16657 if (is_peer) {
16658 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
16659 if (peer) {
16660 ASTOBJ_CONTAINER_LINK(&peerl,peer);
16661 ASTOBJ_UNREF(peer, sip_destroy_peer);
16662 peer_count++;
16663 }
16664 }
16665 }
16666 }
16667 if (ast_find_ourip(&__ourip, bindaddr)) {
16668 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
16669 return 0;
16670 }
16671 if (!ntohs(bindaddr.sin_port))
16672 bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
16673 bindaddr.sin_family = AF_INET;
16674 ast_mutex_lock(&netlock);
16675 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
16676 close(sipsock);
16677 sipsock = -1;
16678 }
16679 if (sipsock < 0) {
16680 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
16681 if (sipsock < 0) {
16682 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
16683 return -1;
16684 } else {
16685
16686 const int reuseFlag = 1;
16687
16688 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
16689 (const char*)&reuseFlag,
16690 sizeof reuseFlag);
16691
16692 ast_enable_packet_fragmentation(sipsock);
16693
16694 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
16695 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
16696 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
16697 strerror(errno));
16698 close(sipsock);
16699 sipsock = -1;
16700 } else {
16701 if (option_verbose > 1) {
16702 ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
16703 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
16704 ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
16705 }
16706 if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip)))
16707 ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
16708 }
16709 }
16710 }
16711 ast_mutex_unlock(&netlock);
16712
16713
16714
16715
16716
16717 if (auto_sip_domains) {
16718 char temp[MAXHOSTNAMELEN];
16719
16720
16721 if (bindaddr.sin_addr.s_addr)
16722 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
16723 else
16724 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
16725
16726
16727 if (externip.sin_addr.s_addr)
16728 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
16729
16730
16731 if (!ast_strlen_zero(externhost))
16732 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
16733
16734
16735 if (!gethostname(temp, sizeof(temp)))
16736 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
16737 }
16738
16739
16740 ast_config_destroy(cfg);
16741
16742
16743 if (notify_types)
16744 ast_config_destroy(notify_types);
16745 notify_types = ast_config_load(notify_config);
16746
16747
16748 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\r\n", channelreloadreason2txt(reason), registry_count, peer_count, user_count);
16749
16750 return 0;
16751 }
16752
16753 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
16754 {
16755 struct sip_pvt *p;
16756 struct ast_udptl *udptl = NULL;
16757
16758 p = chan->tech_pvt;
16759 if (!p)
16760 return NULL;
16761
16762 ast_mutex_lock(&p->lock);
16763 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16764 udptl = p->udptl;
16765 ast_mutex_unlock(&p->lock);
16766 return udptl;
16767 }
16768
16769 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
16770 {
16771 struct sip_pvt *p;
16772
16773 p = chan->tech_pvt;
16774 if (!p)
16775 return -1;
16776 ast_mutex_lock(&p->lock);
16777 if (udptl)
16778 ast_udptl_get_peer(udptl, &p->udptlredirip);
16779 else
16780 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16781 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16782 if (!p->pendinginvite) {
16783 if (option_debug > 2) {
16784 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);
16785 }
16786 transmit_reinvite_with_t38_sdp(p);
16787 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16788 if (option_debug > 2) {
16789 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);
16790 }
16791 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16792 }
16793 }
16794
16795 p->lastrtprx = p->lastrtptx = time(NULL);
16796 ast_mutex_unlock(&p->lock);
16797 return 0;
16798 }
16799
16800
16801
16802
16803
16804
16805 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
16806 {
16807 struct sip_pvt *p;
16808 int flag = 0;
16809
16810 p = chan->tech_pvt;
16811 if (!p || !pvt->udptl)
16812 return -1;
16813
16814
16815 ast_mutex_lock(&p->lock);
16816
16817
16818
16819 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
16820
16821 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
16822 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
16823 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
16824
16825 if (reinvite) {
16826
16827
16828
16829
16830
16831 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
16832 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
16833 flag =1;
16834 } else {
16835 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16836 }
16837 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16838 if (!p->pendinginvite) {
16839 if (option_debug > 2) {
16840 if (flag)
16841 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));
16842 else
16843 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));
16844 }
16845 transmit_reinvite_with_t38_sdp(p);
16846 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16847 if (option_debug > 2) {
16848 if (flag)
16849 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));
16850 else
16851 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));
16852 }
16853 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16854 }
16855 }
16856
16857 p->lastrtprx = p->lastrtptx = time(NULL);
16858 ast_mutex_unlock(&p->lock);
16859 return 0;
16860 } else {
16861 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
16862 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
16863 flag = 1;
16864 } else {
16865 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
16866 }
16867 if (option_debug > 2) {
16868 if (flag)
16869 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));
16870 else
16871 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));
16872 }
16873 pvt->t38.state = T38_ENABLED;
16874 p->t38.state = T38_ENABLED;
16875 if (option_debug > 1) {
16876 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
16877 ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
16878 }
16879 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
16880 p->lastrtprx = p->lastrtptx = time(NULL);
16881 ast_mutex_unlock(&p->lock);
16882 return 0;
16883 }
16884 }
16885
16886
16887
16888 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
16889 {
16890 struct sip_pvt *p = NULL;
16891 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
16892
16893 if (!(p = chan->tech_pvt))
16894 return AST_RTP_GET_FAILED;
16895
16896 ast_mutex_lock(&p->lock);
16897 if (!(p->rtp)) {
16898 ast_mutex_unlock(&p->lock);
16899 return AST_RTP_GET_FAILED;
16900 }
16901
16902 *rtp = p->rtp;
16903
16904 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
16905 res = AST_RTP_TRY_PARTIAL;
16906 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16907 res = AST_RTP_TRY_NATIVE;
16908 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
16909 res = AST_RTP_GET_FAILED;
16910
16911 ast_mutex_unlock(&p->lock);
16912
16913 return res;
16914 }
16915
16916
16917 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
16918 {
16919 struct sip_pvt *p = NULL;
16920 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
16921
16922 if (!(p = chan->tech_pvt))
16923 return AST_RTP_GET_FAILED;
16924
16925 ast_mutex_lock(&p->lock);
16926 if (!(p->vrtp)) {
16927 ast_mutex_unlock(&p->lock);
16928 return AST_RTP_GET_FAILED;
16929 }
16930
16931 *rtp = p->vrtp;
16932
16933 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
16934 res = AST_RTP_TRY_NATIVE;
16935
16936 ast_mutex_unlock(&p->lock);
16937
16938 return res;
16939 }
16940
16941
16942 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
16943 {
16944 struct sip_pvt *p;
16945 int changed = 0;
16946
16947 p = chan->tech_pvt;
16948 if (!p)
16949 return -1;
16950
16951
16952 if (chan->_state != AST_STATE_UP && !global_directrtpsetup)
16953 return 0;
16954
16955 ast_mutex_lock(&p->lock);
16956 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
16957
16958 ast_mutex_unlock(&p->lock);
16959 return 0;
16960 }
16961
16962
16963
16964
16965 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
16966 ast_mutex_unlock(&p->lock);
16967 return 0;
16968 }
16969
16970 if (rtp) {
16971 changed |= ast_rtp_get_peer(rtp, &p->redirip);
16972 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
16973 memset(&p->redirip, 0, sizeof(p->redirip));
16974 changed = 1;
16975 }
16976 if (vrtp) {
16977 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
16978 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
16979 memset(&p->vredirip, 0, sizeof(p->vredirip));
16980 changed = 1;
16981 }
16982 if (codecs && (p->redircodecs != codecs)) {
16983 p->redircodecs = codecs;
16984 changed = 1;
16985 }
16986 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
16987 if (chan->_state != AST_STATE_UP) {
16988 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
16989 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
16990 if (option_debug)
16991 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));
16992 } else if (!p->pendinginvite) {
16993 if (option_debug > 2) {
16994 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));
16995 }
16996 transmit_reinvite_with_sdp(p);
16997 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16998 if (option_debug > 2) {
16999 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));
17000 }
17001
17002 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17003 }
17004 }
17005
17006 p->lastrtprx = p->lastrtptx = time(NULL);
17007 ast_mutex_unlock(&p->lock);
17008 return 0;
17009 }
17010
17011 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
17012 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
17013 static char *app_dtmfmode = "SIPDtmfMode";
17014
17015 static char *app_sipaddheader = "SIPAddHeader";
17016 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
17017
17018 static char *descrip_sipaddheader = ""
17019 " SIPAddHeader(Header: Content)\n"
17020 "Adds a header to a SIP call placed with DIAL.\n"
17021 "Remember to user the X-header if you are adding non-standard SIP\n"
17022 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
17023 "Adding the wrong headers may jeopardize the SIP dialog.\n"
17024 "Always returns 0\n";
17025
17026
17027
17028 static int sip_dtmfmode(struct ast_channel *chan, void *data)
17029 {
17030 struct sip_pvt *p;
17031 char *mode;
17032 if (data)
17033 mode = (char *)data;
17034 else {
17035 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
17036 return 0;
17037 }
17038 ast_channel_lock(chan);
17039 if (chan->tech != &sip_tech && chan->tech != &sip_tech_info) {
17040 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
17041 ast_channel_unlock(chan);
17042 return 0;
17043 }
17044 p = chan->tech_pvt;
17045 if (!p) {
17046 ast_channel_unlock(chan);
17047 return 0;
17048 }
17049 ast_mutex_lock(&p->lock);
17050 if (!strcasecmp(mode,"info")) {
17051 ast_clear_flag(&p->flags[0], SIP_DTMF);
17052 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
17053 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17054 } else if (!strcasecmp(mode,"rfc2833")) {
17055 ast_clear_flag(&p->flags[0], SIP_DTMF);
17056 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
17057 p->jointnoncodeccapability |= AST_RTP_DTMF;
17058 } else if (!strcasecmp(mode,"inband")) {
17059 ast_clear_flag(&p->flags[0], SIP_DTMF);
17060 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
17061 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
17062 } else
17063 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
17064 if (p->rtp)
17065 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
17066 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
17067 if (!p->vad) {
17068 p->vad = ast_dsp_new();
17069 ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
17070 }
17071 } else {
17072 if (p->vad) {
17073 ast_dsp_free(p->vad);
17074 p->vad = NULL;
17075 }
17076 }
17077 ast_mutex_unlock(&p->lock);
17078 ast_channel_unlock(chan);
17079 return 0;
17080 }
17081
17082
17083 static int sip_addheader(struct ast_channel *chan, void *data)
17084 {
17085 int no = 0;
17086 int ok = FALSE;
17087 char varbuf[30];
17088 char *inbuf = (char *) data;
17089
17090 if (ast_strlen_zero(inbuf)) {
17091 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
17092 return 0;
17093 }
17094 ast_channel_lock(chan);
17095
17096
17097 while (!ok && no <= 50) {
17098 no++;
17099 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
17100
17101
17102 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
17103 ok = TRUE;
17104 }
17105 if (ok) {
17106 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
17107 if (sipdebug)
17108 ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
17109 } else {
17110 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
17111 }
17112 ast_channel_unlock(chan);
17113 return 0;
17114 }
17115
17116
17117
17118
17119
17120
17121
17122 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
17123 {
17124 char *cdest;
17125 char *extension, *host, *port;
17126 char tmp[80];
17127
17128 cdest = ast_strdupa(dest);
17129
17130 extension = strsep(&cdest, "@");
17131 host = strsep(&cdest, ":");
17132 port = strsep(&cdest, ":");
17133 if (ast_strlen_zero(extension)) {
17134 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
17135 return 0;
17136 }
17137
17138
17139 if (!host) {
17140 char *localtmp;
17141 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
17142 if (ast_strlen_zero(tmp)) {
17143 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
17144 return 0;
17145 }
17146 if ((localtmp = strstr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
17147 char lhost[80], lport[80];
17148 memset(lhost, 0, sizeof(lhost));
17149 memset(lport, 0, sizeof(lport));
17150 localtmp++;
17151
17152 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
17153 if (ast_strlen_zero(lhost)) {
17154 ast_log(LOG_ERROR, "Can't find the host address\n");
17155 return 0;
17156 }
17157 host = ast_strdupa(lhost);
17158 if (!ast_strlen_zero(lport)) {
17159 port = ast_strdupa(lport);
17160 }
17161 }
17162 }
17163
17164 sip_alreadygone(p);
17165 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
17166 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
17167
17168 sip_scheddestroy(p, 32000);
17169
17170 return 0;
17171 }
17172
17173
17174 static int sip_get_codec(struct ast_channel *chan)
17175 {
17176 struct sip_pvt *p = chan->tech_pvt;
17177 return p->peercapability ? p->peercapability : p->capability;
17178 }
17179
17180
17181
17182
17183
17184 static void sip_poke_all_peers(void)
17185 {
17186 int ms = 0;
17187
17188 if (!speerobjs)
17189 return;
17190
17191 ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
17192 ASTOBJ_WRLOCK(iterator);
17193 if (iterator->pokeexpire > -1)
17194 ast_sched_del(sched, iterator->pokeexpire);
17195 ms += 100;
17196 iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, iterator);
17197 ASTOBJ_UNLOCK(iterator);
17198 } while (0)
17199 );
17200 }
17201
17202
17203 static void sip_send_all_registers(void)
17204 {
17205 int ms;
17206 int regspacing;
17207 if (!regobjs)
17208 return;
17209 regspacing = default_expiry * 1000/regobjs;
17210 if (regspacing > 100)
17211 regspacing = 100;
17212 ms = regspacing;
17213 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
17214 ASTOBJ_WRLOCK(iterator);
17215 if (iterator->expire > -1)
17216 ast_sched_del(sched, iterator->expire);
17217 ms += regspacing;
17218 iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
17219 ASTOBJ_UNLOCK(iterator);
17220 } while (0)
17221 );
17222 }
17223
17224
17225 static int sip_do_reload(enum channelreloadreason reason)
17226 {
17227 if (option_debug > 3)
17228 ast_log(LOG_DEBUG, "--------------- SIP reload started\n");
17229
17230 clear_realm_authentication(authl);
17231 clear_sip_domains();
17232 authl = NULL;
17233
17234
17235
17236 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
17237 ASTOBJ_RDLOCK(iterator);
17238 if (iterator->call) {
17239 if (option_debug > 2)
17240 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
17241
17242 sip_destroy(iterator->call);
17243 }
17244 ASTOBJ_UNLOCK(iterator);
17245
17246 } while(0));
17247
17248
17249 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
17250 if (option_debug > 3)
17251 ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
17252 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
17253 if (option_debug > 3)
17254 ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
17255 ASTOBJ_CONTAINER_MARKALL(&peerl);
17256 reload_config(reason);
17257
17258
17259 ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
17260 if (option_debug > 3)
17261 ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");
17262
17263
17264 sip_poke_all_peers();
17265
17266
17267 sip_send_all_registers();
17268
17269 if (option_debug > 3)
17270 ast_log(LOG_DEBUG, "--------------- SIP reload done\n");
17271
17272 return 0;
17273 }
17274
17275
17276 static int sip_reload(int fd, int argc, char *argv[])
17277 {
17278 ast_mutex_lock(&sip_reload_lock);
17279 if (sip_reloading)
17280 ast_verbose("Previous SIP reload not yet done\n");
17281 else {
17282 sip_reloading = TRUE;
17283 if (fd)
17284 sip_reloadreason = CHANNEL_CLI_RELOAD;
17285 else
17286 sip_reloadreason = CHANNEL_MODULE_RELOAD;
17287 }
17288 ast_mutex_unlock(&sip_reload_lock);
17289 restart_monitor();
17290
17291 return 0;
17292 }
17293
17294
17295 static int reload(void)
17296 {
17297 return sip_reload(0, 0, NULL);
17298 }
17299
17300 static struct ast_cli_entry cli_sip_debug_deprecated =
17301 { { "sip", "debug", NULL },
17302 sip_do_debug_deprecated, "Enable SIP debugging",
17303 debug_usage };
17304
17305 static struct ast_cli_entry cli_sip_no_debug_deprecated =
17306 { { "sip", "no", "debug", NULL },
17307 sip_no_debug_deprecated, "Disable SIP debugging",
17308 debug_usage };
17309
17310 static struct ast_cli_entry cli_sip[] = {
17311 { { "sip", "show", "channels", NULL },
17312 sip_show_channels, "List active SIP channels",
17313 show_channels_usage },
17314
17315 { { "sip", "show", "domains", NULL },
17316 sip_show_domains, "List our local SIP domains.",
17317 show_domains_usage },
17318
17319 { { "sip", "show", "inuse", NULL },
17320 sip_show_inuse, "List all inuse/limits",
17321 show_inuse_usage },
17322
17323 { { "sip", "show", "objects", NULL },
17324 sip_show_objects, "List all SIP object allocations",
17325 show_objects_usage },
17326
17327 { { "sip", "show", "peers", NULL },
17328 sip_show_peers, "List defined SIP peers",
17329 show_peers_usage },
17330
17331 { { "sip", "show", "registry", NULL },
17332 sip_show_registry, "List SIP registration status",
17333 show_reg_usage },
17334
17335 { { "sip", "show", "settings", NULL },
17336 sip_show_settings, "Show SIP global settings",
17337 show_settings_usage },
17338
17339 { { "sip", "show", "subscriptions", NULL },
17340 sip_show_subscriptions, "List active SIP subscriptions",
17341 show_subscriptions_usage },
17342
17343 { { "sip", "show", "users", NULL },
17344 sip_show_users, "List defined SIP users",
17345 show_users_usage },
17346
17347 { { "sip", "notify", NULL },
17348 sip_notify, "Send a notify packet to a SIP peer",
17349 notify_usage, complete_sipnotify },
17350
17351 { { "sip", "show", "channel", NULL },
17352 sip_show_channel, "Show detailed SIP channel info",
17353 show_channel_usage, complete_sipch },
17354
17355 { { "sip", "show", "history", NULL },
17356 sip_show_history, "Show SIP dialog history",
17357 show_history_usage, complete_sipch },
17358
17359 { { "sip", "show", "peer", NULL },
17360 sip_show_peer, "Show details on specific SIP peer",
17361 show_peer_usage, complete_sip_show_peer },
17362
17363 { { "sip", "show", "user", NULL },
17364 sip_show_user, "Show details on specific SIP user",
17365 show_user_usage, complete_sip_show_user },
17366
17367 { { "sip", "prune", "realtime", NULL },
17368 sip_prune_realtime, "Prune cached Realtime object(s)",
17369 prune_realtime_usage },
17370
17371 { { "sip", "prune", "realtime", "peer", NULL },
17372 sip_prune_realtime, "Prune cached Realtime peer(s)",
17373 prune_realtime_usage, complete_sip_prune_realtime_peer },
17374
17375 { { "sip", "prune", "realtime", "user", NULL },
17376 sip_prune_realtime, "Prune cached Realtime user(s)",
17377 prune_realtime_usage, complete_sip_prune_realtime_user },
17378
17379 { { "sip", "set", "debug", NULL },
17380 sip_do_debug, "Enable SIP debugging",
17381 debug_usage, NULL, &cli_sip_debug_deprecated },
17382
17383 { { "sip", "set", "debug", "ip", NULL },
17384 sip_do_debug, "Enable SIP debugging on IP",
17385 debug_usage },
17386
17387 { { "sip", "set", "debug", "peer", NULL },
17388 sip_do_debug, "Enable SIP debugging on Peername",
17389 debug_usage, complete_sip_debug_peer },
17390
17391 { { "sip", "set", "debug", "off", NULL },
17392 sip_no_debug, "Disable SIP debugging",
17393 no_debug_usage, NULL, &cli_sip_no_debug_deprecated },
17394
17395 { { "sip", "history", NULL },
17396 sip_do_history, "Enable SIP history",
17397 history_usage },
17398
17399 { { "sip", "history", "off", NULL },
17400 sip_no_history, "Disable SIP history",
17401 no_history_usage },
17402
17403 { { "sip", "reload", NULL },
17404 sip_reload, "Reload SIP configuration",
17405 sip_reload_usage },
17406 };
17407
17408
17409 static int load_module(void)
17410 {
17411 ASTOBJ_CONTAINER_INIT(&userl);
17412 ASTOBJ_CONTAINER_INIT(&peerl);
17413 ASTOBJ_CONTAINER_INIT(®l);
17414
17415 if (!(sched = sched_context_create())) {
17416 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
17417 return AST_MODULE_LOAD_FAILURE;
17418 }
17419
17420 if (!(io = io_context_create())) {
17421 ast_log(LOG_ERROR, "Unable to create I/O context\n");
17422 sched_context_destroy(sched);
17423 return AST_MODULE_LOAD_FAILURE;
17424 }
17425
17426 sip_reloadreason = CHANNEL_MODULE_LOAD;
17427
17428 if(reload_config(sip_reloadreason))
17429 return AST_MODULE_LOAD_DECLINE;
17430
17431
17432 if (ast_channel_register(&sip_tech)) {
17433 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
17434 io_context_destroy(io);
17435 sched_context_destroy(sched);
17436 return AST_MODULE_LOAD_FAILURE;
17437 }
17438
17439
17440 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
17441
17442
17443 ast_rtp_proto_register(&sip_rtp);
17444
17445
17446 ast_udptl_proto_register(&sip_udptl);
17447
17448
17449 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
17450 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
17451
17452
17453 ast_custom_function_register(&sip_header_function);
17454 ast_custom_function_register(&sippeer_function);
17455 ast_custom_function_register(&sipchaninfo_function);
17456 ast_custom_function_register(&checksipdomain_function);
17457
17458
17459 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
17460 "List SIP peers (text format)", mandescr_show_peers);
17461 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
17462 "Show SIP peer (text format)", mandescr_show_peer);
17463
17464 sip_poke_all_peers();
17465 sip_send_all_registers();
17466
17467
17468 restart_monitor();
17469
17470 return AST_MODULE_LOAD_SUCCESS;
17471 }
17472
17473
17474 static int unload_module(void)
17475 {
17476 struct sip_pvt *p, *pl;
17477
17478
17479 ast_channel_unregister(&sip_tech);
17480
17481
17482 ast_custom_function_unregister(&sipchaninfo_function);
17483 ast_custom_function_unregister(&sippeer_function);
17484 ast_custom_function_unregister(&sip_header_function);
17485 ast_custom_function_unregister(&checksipdomain_function);
17486
17487
17488 ast_unregister_application(app_dtmfmode);
17489 ast_unregister_application(app_sipaddheader);
17490
17491
17492 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
17493
17494
17495 ast_rtp_proto_unregister(&sip_rtp);
17496
17497
17498 ast_udptl_proto_unregister(&sip_udptl);
17499
17500
17501 ast_manager_unregister("SIPpeers");
17502 ast_manager_unregister("SIPshowpeer");
17503
17504 ast_mutex_lock(&iflock);
17505
17506 for (p = iflist; p ; p = p->next) {
17507 if (p->owner)
17508 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
17509 }
17510 ast_mutex_unlock(&iflock);
17511
17512 ast_mutex_lock(&monlock);
17513 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
17514 pthread_cancel(monitor_thread);
17515 pthread_kill(monitor_thread, SIGURG);
17516 pthread_join(monitor_thread, NULL);
17517 }
17518 monitor_thread = AST_PTHREADT_STOP;
17519 ast_mutex_unlock(&monlock);
17520
17521 ast_mutex_lock(&iflock);
17522
17523 p = iflist;
17524 while (p) {
17525 pl = p;
17526 p = p->next;
17527 __sip_destroy(pl, TRUE);
17528 }
17529 iflist = NULL;
17530 ast_mutex_unlock(&iflock);
17531
17532
17533 ast_free_ha(localaddr);
17534
17535 ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
17536 ASTOBJ_CONTAINER_DESTROY(&userl);
17537 ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
17538 ASTOBJ_CONTAINER_DESTROY(&peerl);
17539 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
17540 ASTOBJ_CONTAINER_DESTROY(®l);
17541
17542 clear_realm_authentication(authl);
17543 clear_sip_domains();
17544 close(sipsock);
17545 sched_context_destroy(sched);
17546
17547 return 0;
17548 }
17549
17550 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
17551 .load = load_module,
17552 .unload = unload_module,
17553 .reload = reload,
17554 );