00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137 #include "asterisk.h"
00138
00139 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 244385 $")
00140
00141 #include <ctype.h>
00142 #include <sys/ioctl.h>
00143 #include <fcntl.h>
00144 #include <signal.h>
00145 #include <sys/signal.h>
00146 #include <regex.h>
00147 #include <time.h>
00148
00149 #include "asterisk/network.h"
00150 #include "asterisk/paths.h"
00151
00152 #include "asterisk/lock.h"
00153 #include "asterisk/channel.h"
00154 #include "asterisk/config.h"
00155 #include "asterisk/module.h"
00156 #include "asterisk/pbx.h"
00157 #include "asterisk/sched.h"
00158 #include "asterisk/io.h"
00159 #include "asterisk/rtp.h"
00160 #include "asterisk/udptl.h"
00161 #include "asterisk/acl.h"
00162 #include "asterisk/manager.h"
00163 #include "asterisk/callerid.h"
00164 #include "asterisk/cli.h"
00165 #include "asterisk/app.h"
00166 #include "asterisk/musiconhold.h"
00167 #include "asterisk/dsp.h"
00168 #include "asterisk/features.h"
00169 #include "asterisk/srv.h"
00170 #include "asterisk/astdb.h"
00171 #include "asterisk/causes.h"
00172 #include "asterisk/utils.h"
00173 #include "asterisk/file.h"
00174 #include "asterisk/astobj.h"
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187 #include "asterisk/astobj2.h"
00188 #include "asterisk/dnsmgr.h"
00189 #include "asterisk/devicestate.h"
00190 #include "asterisk/linkedlists.h"
00191 #include "asterisk/stringfields.h"
00192 #include "asterisk/monitor.h"
00193 #include "asterisk/netsock.h"
00194 #include "asterisk/localtime.h"
00195 #include "asterisk/abstract_jb.h"
00196 #include "asterisk/threadstorage.h"
00197 #include "asterisk/translate.h"
00198 #include "asterisk/ast_version.h"
00199 #include "asterisk/event.h"
00200 #include "asterisk/tcptls.h"
00201
00202 #ifndef FALSE
00203 #define FALSE 0
00204 #endif
00205
00206 #ifndef TRUE
00207 #define TRUE 1
00208 #endif
00209
00210 #define SIPBUFSIZE 512
00211
00212
00213 #define FINDUSERS (1 << 0)
00214 #define FINDPEERS (1 << 1)
00215 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00216
00217 #define XMIT_ERROR -2
00218
00219 #define SIP_RESERVED ";/?:@&=+$,# "
00220
00221
00222
00223 #define DEFAULT_DEFAULT_EXPIRY 120
00224 #define DEFAULT_MIN_EXPIRY 60
00225 #define DEFAULT_MAX_EXPIRY 3600
00226 #define DEFAULT_REGISTRATION_TIMEOUT 20
00227 #define DEFAULT_MAX_FORWARDS "70"
00228
00229
00230
00231 #define EXPIRY_GUARD_SECS 15
00232 #define EXPIRY_GUARD_LIMIT 30
00233
00234 #define EXPIRY_GUARD_MIN 500
00235
00236
00237
00238 #define EXPIRY_GUARD_PCT 0.20
00239
00240 #define DEFAULT_EXPIRY 900
00241
00242 static int min_expiry = DEFAULT_MIN_EXPIRY;
00243 static int max_expiry = DEFAULT_MAX_EXPIRY;
00244 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00245
00246 #define CALLERID_UNKNOWN "Anonymous"
00247 #define FROMDOMAIN_INVALID "anonymous.invalid"
00248
00249 #define DEFAULT_MAXMS 2000
00250 #define DEFAULT_QUALIFYFREQ 60 * 1000
00251 #define DEFAULT_FREQ_NOTOK 10 * 1000
00252
00253 #define DEFAULT_RETRANS 1000
00254 #define MAX_RETRANS 6
00255 #define SIP_TIMER_T1 500
00256 #define SIP_TRANS_TIMEOUT 64 * SIP_TIMER_T1
00257
00258
00259 #define DEFAULT_TRANS_TIMEOUT -1
00260 #define PROVIS_KEEPALIVE_TIMEOUT 60000
00261 #define MAX_AUTHTRIES 3
00262
00263 #define SIP_MAX_HEADERS 64
00264 #define SIP_MAX_LINES 64
00265 #define SIP_MAX_PACKET 4096
00266 #define SIP_MIN_PACKET 1024
00267
00268 #define INITIAL_CSEQ 101
00269
00270 #define DEFAULT_MAX_SE 1800
00271 #define DEFAULT_MIN_SE 90
00272
00273 #define SDP_MAX_RTPMAP_CODECS 32
00274
00275
00276 static struct ast_jb_conf default_jbconf =
00277 {
00278 .flags = 0,
00279 .max_size = -1,
00280 .resync_threshold = -1,
00281 .impl = ""
00282 };
00283 static struct ast_jb_conf global_jbconf;
00284
00285 static const char config[] = "sip.conf";
00286 static const char notify_config[] = "sip_notify.conf";
00287
00288 #define RTP 1
00289 #define NO_RTP 0
00290
00291
00292
00293
00294 enum transfermodes {
00295 TRANSFER_OPENFORALL,
00296 TRANSFER_CLOSED,
00297 };
00298
00299
00300
00301 enum sip_result {
00302 AST_SUCCESS = 0,
00303 AST_FAILURE = -1,
00304 };
00305
00306
00307
00308
00309 enum invitestates {
00310 INV_NONE = 0,
00311 INV_CALLING = 1,
00312 INV_PROCEEDING = 2,
00313 INV_EARLY_MEDIA = 3,
00314 INV_COMPLETED = 4,
00315 INV_CONFIRMED = 5,
00316 INV_TERMINATED = 6,
00317
00318 INV_CANCELLED = 7,
00319 };
00320
00321
00322
00323 static const struct invstate2stringtable {
00324 const enum invitestates state;
00325 const char *desc;
00326 } invitestate2string[] = {
00327 {INV_NONE, "None" },
00328 {INV_CALLING, "Calling (Trying)"},
00329 {INV_PROCEEDING, "Proceeding "},
00330 {INV_EARLY_MEDIA, "Early media"},
00331 {INV_COMPLETED, "Completed (done)"},
00332 {INV_CONFIRMED, "Confirmed (up)"},
00333 {INV_TERMINATED, "Done"},
00334 {INV_CANCELLED, "Cancelled"}
00335 };
00336
00337
00338
00339
00340 enum xmittype {
00341 XMIT_CRITICAL = 2,
00342
00343 XMIT_RELIABLE = 1,
00344 XMIT_UNRELIABLE = 0,
00345 };
00346
00347 enum parse_register_result {
00348 PARSE_REGISTER_DENIED,
00349 PARSE_REGISTER_FAILED,
00350 PARSE_REGISTER_UPDATE,
00351 PARSE_REGISTER_QUERY,
00352 };
00353
00354
00355 enum subscriptiontype {
00356 NONE = 0,
00357 XPIDF_XML,
00358 DIALOG_INFO_XML,
00359 CPIM_PIDF_XML,
00360 PIDF_XML,
00361 MWI_NOTIFICATION
00362 };
00363
00364
00365
00366
00367
00368
00369 static const struct cfsubscription_types {
00370 enum subscriptiontype type;
00371 const char * const event;
00372 const char * const mediatype;
00373 const char * const text;
00374 } subscription_types[] = {
00375 { NONE, "-", "unknown", "unknown" },
00376
00377 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00378 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00379 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00380 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00381 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00382 };
00383
00384
00385
00386
00387
00388
00389
00390 enum sip_auth_type {
00391 PROXY_AUTH = 407,
00392 WWW_AUTH = 401,
00393 };
00394
00395
00396 enum check_auth_result {
00397 AUTH_DONT_KNOW = -100,
00398
00399
00400 AUTH_SUCCESSFUL = 0,
00401 AUTH_CHALLENGE_SENT = 1,
00402 AUTH_SECRET_FAILED = -1,
00403 AUTH_USERNAME_MISMATCH = -2,
00404 AUTH_NOT_FOUND = -3,
00405 AUTH_FAKE_AUTH = -4,
00406 AUTH_UNKNOWN_DOMAIN = -5,
00407 AUTH_PEER_NOT_DYNAMIC = -6,
00408 AUTH_ACL_FAILED = -7,
00409 AUTH_BAD_TRANSPORT = -8,
00410 };
00411
00412
00413 enum sipregistrystate {
00414 REG_STATE_UNREGISTERED = 0,
00415
00416
00417
00418
00419 REG_STATE_REGSENT,
00420
00421
00422
00423
00424 REG_STATE_AUTHSENT,
00425
00426
00427
00428
00429 REG_STATE_REGISTERED,
00430
00431 REG_STATE_REJECTED,
00432
00433
00434
00435
00436
00437 REG_STATE_TIMEOUT,
00438
00439
00440 REG_STATE_NOAUTH,
00441
00442
00443 REG_STATE_FAILED,
00444
00445 };
00446
00447
00448 enum st_mode {
00449 SESSION_TIMER_MODE_INVALID = 0,
00450 SESSION_TIMER_MODE_ACCEPT,
00451 SESSION_TIMER_MODE_ORIGINATE,
00452 SESSION_TIMER_MODE_REFUSE
00453 };
00454
00455
00456 enum st_refresher {
00457 SESSION_TIMER_REFRESHER_AUTO,
00458 SESSION_TIMER_REFRESHER_UAC,
00459 SESSION_TIMER_REFRESHER_UAS
00460 };
00461
00462
00463
00464
00465 enum sip_transport {
00466 SIP_TRANSPORT_UDP = 1,
00467 SIP_TRANSPORT_TCP = 1 << 1,
00468 SIP_TRANSPORT_TLS = 1 << 2,
00469 };
00470
00471
00472
00473
00474
00475
00476
00477 struct sip_proxy {
00478 char name[MAXHOSTNAMELEN];
00479 struct sockaddr_in ip;
00480 time_t last_dnsupdate;
00481 enum sip_transport transport;
00482 int force;
00483
00484 };
00485
00486
00487 struct __show_chan_arg {
00488 int fd;
00489 int subscriptions;
00490 int numchans;
00491 };
00492
00493
00494
00495 enum can_create_dialog {
00496 CAN_NOT_CREATE_DIALOG,
00497 CAN_CREATE_DIALOG,
00498 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00499 };
00500
00501
00502
00503
00504
00505
00506
00507
00508
00509
00510
00511 enum sipmethod {
00512 SIP_UNKNOWN,
00513 SIP_RESPONSE,
00514 SIP_REGISTER,
00515 SIP_OPTIONS,
00516 SIP_NOTIFY,
00517 SIP_INVITE,
00518 SIP_ACK,
00519 SIP_PRACK,
00520 SIP_BYE,
00521 SIP_REFER,
00522 SIP_SUBSCRIBE,
00523 SIP_MESSAGE,
00524 SIP_UPDATE,
00525 SIP_INFO,
00526 SIP_CANCEL,
00527 SIP_PUBLISH,
00528 SIP_PING,
00529 };
00530
00531
00532
00533
00534
00535 static const struct cfsip_methods {
00536 enum sipmethod id;
00537 int need_rtp;
00538 char * const text;
00539 enum can_create_dialog can_create;
00540 } sip_methods[] = {
00541 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
00542 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00543 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00544 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00545 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00546 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00547 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00548 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00549 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00550 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00551 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
00552 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00553 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00554 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00555 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00556 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00557 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00558 };
00559
00560 static unsigned int chan_idx;
00561
00562
00563
00564
00565
00566
00567
00568
00569
00570
00571
00572 #define SUPPORTED 1
00573 #define NOT_SUPPORTED 0
00574
00575
00576 #define SIP_OPT_REPLACES (1 << 0)
00577 #define SIP_OPT_100REL (1 << 1)
00578 #define SIP_OPT_TIMER (1 << 2)
00579 #define SIP_OPT_EARLY_SESSION (1 << 3)
00580 #define SIP_OPT_JOIN (1 << 4)
00581 #define SIP_OPT_PATH (1 << 5)
00582 #define SIP_OPT_PREF (1 << 6)
00583 #define SIP_OPT_PRECONDITION (1 << 7)
00584 #define SIP_OPT_PRIVACY (1 << 8)
00585 #define SIP_OPT_SDP_ANAT (1 << 9)
00586 #define SIP_OPT_SEC_AGREE (1 << 10)
00587 #define SIP_OPT_EVENTLIST (1 << 11)
00588 #define SIP_OPT_GRUU (1 << 12)
00589 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00590 #define SIP_OPT_NOREFERSUB (1 << 14)
00591 #define SIP_OPT_HISTINFO (1 << 15)
00592 #define SIP_OPT_RESPRIORITY (1 << 16)
00593 #define SIP_OPT_FROMCHANGE (1 << 17)
00594 #define SIP_OPT_RECLISTINV (1 << 18)
00595 #define SIP_OPT_RECLISTSUB (1 << 19)
00596 #define SIP_OPT_UNKNOWN (1 << 20)
00597
00598
00599
00600
00601 static const struct cfsip_options {
00602 int id;
00603 int supported;
00604 char * const text;
00605 } sip_options[] = {
00606
00607 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
00608
00609 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
00610
00611 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00612
00613 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
00614
00615 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
00616
00617 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
00618
00619 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
00620
00621 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
00622
00623 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
00624
00625 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
00626
00627 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00628
00629 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
00630
00631 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
00632
00633 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
00634
00635 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
00636
00637 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
00638
00639 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
00640
00641 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00642
00643 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
00644
00645 { SIP_OPT_TIMER, SUPPORTED, "timer" },
00646
00647 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00648 };
00649
00650
00651
00652
00653
00654
00655 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00656
00657
00658
00659
00660
00661
00662 #define SUPPORTED_EXTENSIONS "replaces, timer"
00663
00664
00665 #define STANDARD_SIP_PORT 5060
00666
00667 #define STANDARD_TLS_PORT 5061
00668
00669
00670
00671
00672
00673
00674
00675
00676
00677
00678
00679
00680
00681
00682
00683
00684
00685 #define DEFAULT_CONTEXT "default"
00686 #define DEFAULT_MOHINTERPRET "default"
00687 #define DEFAULT_MOHSUGGEST ""
00688 #define DEFAULT_VMEXTEN "asterisk"
00689 #define DEFAULT_CALLERID "asterisk"
00690 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
00691 #define DEFAULT_ALLOWGUEST TRUE
00692 #define DEFAULT_CALLCOUNTER FALSE
00693 #define DEFAULT_SRVLOOKUP TRUE
00694 #define DEFAULT_COMPACTHEADERS FALSE
00695 #define DEFAULT_TOS_SIP 0
00696 #define DEFAULT_TOS_AUDIO 0
00697 #define DEFAULT_TOS_VIDEO 0
00698 #define DEFAULT_TOS_TEXT 0
00699 #define DEFAULT_COS_SIP 4
00700 #define DEFAULT_COS_AUDIO 5
00701 #define DEFAULT_COS_VIDEO 6
00702 #define DEFAULT_COS_TEXT 5
00703 #define DEFAULT_ALLOW_EXT_DOM TRUE
00704 #define DEFAULT_REALM "asterisk"
00705 #define DEFAULT_NOTIFYRINGING TRUE
00706 #define DEFAULT_PEDANTIC FALSE
00707 #define DEFAULT_AUTOCREATEPEER FALSE
00708 #define DEFAULT_QUALIFY FALSE
00709 #define DEFAULT_REGEXTENONQUALIFY FALSE
00710 #define DEFAULT_T1MIN 100
00711 #define DEFAULT_MAX_CALL_BITRATE (384)
00712 #ifndef DEFAULT_USERAGENT
00713 #define DEFAULT_USERAGENT "Asterisk PBX"
00714 #define DEFAULT_SDPSESSION "Asterisk PBX"
00715 #define DEFAULT_SDPOWNER "root"
00716 #endif
00717
00718
00719
00720
00721
00722
00723
00724 static char default_context[AST_MAX_CONTEXT];
00725 static char default_subscribecontext[AST_MAX_CONTEXT];
00726 static char default_language[MAX_LANGUAGE];
00727 static char default_callerid[AST_MAX_EXTENSION];
00728 static char default_fromdomain[AST_MAX_EXTENSION];
00729 static char default_notifymime[AST_MAX_EXTENSION];
00730 static int default_qualify;
00731 static char default_vmexten[AST_MAX_EXTENSION];
00732 static char default_mohinterpret[MAX_MUSICCLASS];
00733 static char default_mohsuggest[MAX_MUSICCLASS];
00734
00735 static char default_parkinglot[AST_MAX_CONTEXT];
00736 static int default_maxcallbitrate;
00737 static struct ast_codec_pref default_prefs;
00738
00739
00740 struct sip_settings {
00741 int peer_rtupdate;
00742 int rtsave_sysname;
00743 int ignore_regexpire;
00744 };
00745
00746 static struct sip_settings sip_cfg;
00747
00748
00749
00750
00751
00752
00753
00754 static int global_directrtpsetup;
00755 static int global_rtautoclear;
00756 static int global_notifyringing;
00757 static int global_notifyhold;
00758 static int global_alwaysauthreject;
00759 static int global_srvlookup;
00760 static int pedanticsipchecking;
00761 static int autocreatepeer;
00762 static int global_match_auth_username;
00763 static int global_relaxdtmf;
00764 static int global_prematuremediafilter;
00765 static int global_relaxdtmf;
00766 static int global_rtptimeout;
00767 static int global_rtpholdtimeout;
00768 static int global_rtpkeepalive;
00769 static int global_reg_timeout;
00770 static int global_regattempts_max;
00771 static int global_shrinkcallerid;
00772 static int global_allowguest;
00773 static int global_callcounter;
00774
00775
00776 static int global_allowsubscribe;
00777
00778 static unsigned int global_tos_sip;
00779 static unsigned int global_tos_audio;
00780 static unsigned int global_tos_video;
00781 static unsigned int global_tos_text;
00782 static unsigned int global_cos_sip;
00783 static unsigned int global_cos_audio;
00784 static unsigned int global_cos_video;
00785 static unsigned int global_cos_text;
00786 static int compactheaders;
00787 static int recordhistory;
00788 static int dumphistory;
00789 static char global_realm[MAXHOSTNAMELEN];
00790 static char global_regcontext[AST_MAX_CONTEXT];
00791 static char global_useragent[AST_MAX_EXTENSION];
00792 static char global_sdpsession[AST_MAX_EXTENSION];
00793 static char global_sdpowner[AST_MAX_EXTENSION];
00794 static int allow_external_domains;
00795 static int global_callevents;
00796 static int global_authfailureevents;
00797 static int global_t1;
00798 static int global_t1min;
00799 static int global_timer_b;
00800 static int global_regextenonqualify;
00801 static int global_autoframing;
00802 static enum transfermodes global_allowtransfer;
00803 static struct sip_proxy global_outboundproxy;
00804 static int global_matchexterniplocally;
00805 static int global_qualifyfreq;
00806
00807
00808
00809 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00810
00811 static enum st_mode global_st_mode;
00812 static enum st_refresher global_st_refresher;
00813 static int global_min_se;
00814 static int global_max_se;
00815
00816 static int global_dynamic_exclude_static = 0;
00817
00818
00819
00820 static struct ast_ha *global_contact_ha = NULL;
00821
00822
00823
00824
00825 static int speerobjs = 0;
00826 static int rpeerobjs = 0;
00827 static int apeerobjs = 0;
00828 static int regobjs = 0;
00829
00830
00831 static struct ast_flags global_flags[2] = {{0}};
00832 static int global_t38_maxdatagram;
00833
00834 static char used_context[AST_MAX_CONTEXT];
00835
00836
00837 AST_MUTEX_DEFINE_STATIC(netlock);
00838
00839
00840
00841 AST_MUTEX_DEFINE_STATIC(monlock);
00842
00843 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00844
00845
00846
00847 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00848
00849 static int sip_reloading = FALSE;
00850 static enum channelreloadreason sip_reloadreason;
00851
00852 static struct sched_context *sched;
00853 static struct io_context *io;
00854 static int *sipsock_read_id;
00855
00856 #define DEC_CALL_LIMIT 0
00857 #define INC_CALL_LIMIT 1
00858 #define DEC_CALL_RINGING 2
00859 #define INC_CALL_RINGING 3
00860
00861
00862 struct sip_socket {
00863 enum sip_transport type;
00864 int fd;
00865 uint16_t port;
00866 struct ast_tcptls_session_instance *tcptls_session;
00867 };
00868
00869
00870
00871
00872
00873
00874
00875
00876
00877
00878
00879
00880
00881
00882
00883
00884
00885
00886
00887
00888
00889
00890
00891
00892
00893 struct sip_request {
00894 ptrdiff_t rlPart1;
00895 ptrdiff_t rlPart2;
00896 int len;
00897 int headers;
00898 int method;
00899 int lines;
00900 unsigned int sdp_start;
00901 unsigned int sdp_count;
00902 char debug;
00903 char has_to_tag;
00904 char ignore;
00905
00906 ptrdiff_t header[SIP_MAX_HEADERS];
00907
00908 ptrdiff_t line[SIP_MAX_LINES];
00909 struct ast_str *data;
00910
00911 struct sip_socket socket;
00912 AST_LIST_ENTRY(sip_request) next;
00913 };
00914
00915
00916
00917
00918
00919
00920
00921
00922 #define REQ_OFFSET_TO_STR(req,offset) ((req)->data->str + ((req)->offset))
00923
00924
00925 struct sip_dual {
00926 struct ast_channel *chan1;
00927 struct ast_channel *chan2;
00928 struct sip_request req;
00929 int seqno;
00930 };
00931
00932 struct sip_pkt;
00933
00934
00935 struct sip_invite_param {
00936 int addsipheaders;
00937 const char *uri_options;
00938 const char *vxml_url;
00939 char *auth;
00940 char *authheader;
00941 enum sip_auth_type auth_type;
00942 const char *replaces;
00943 int transfer;
00944 };
00945
00946
00947 struct sip_route {
00948 struct sip_route *next;
00949 char hop[0];
00950 };
00951
00952
00953 enum domain_mode {
00954 SIP_DOMAIN_AUTO,
00955 SIP_DOMAIN_CONFIG,
00956 };
00957
00958
00959
00960
00961
00962 struct domain {
00963 char domain[MAXHOSTNAMELEN];
00964 char context[AST_MAX_EXTENSION];
00965 enum domain_mode mode;
00966 AST_LIST_ENTRY(domain) list;
00967 };
00968
00969 static AST_LIST_HEAD_STATIC(domain_list, domain);
00970
00971
00972
00973 struct sip_history {
00974 AST_LIST_ENTRY(sip_history) list;
00975 char event[0];
00976 };
00977
00978 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00979
00980
00981 struct sip_auth {
00982 char realm[AST_MAX_EXTENSION];
00983 char username[256];
00984 char secret[256];
00985 char md5secret[256];
00986 struct sip_auth *next;
00987 };
00988
00989
00990
00991
00992
00993
00994
00995
00996
00997
00998
00999 #define SIP_OUTGOING (1 << 0)
01000 #define SIP_RINGING (1 << 2)
01001 #define SIP_PROGRESS_SENT (1 << 3)
01002 #define SIP_NEEDREINVITE (1 << 4)
01003 #define SIP_PENDINGBYE (1 << 5)
01004 #define SIP_GOTREFER (1 << 6)
01005 #define SIP_CALL_LIMIT (1 << 7)
01006 #define SIP_INC_COUNT (1 << 8)
01007 #define SIP_INC_RINGING (1 << 9)
01008 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10)
01009
01010 #define SIP_PROMISCREDIR (1 << 11)
01011 #define SIP_TRUSTRPID (1 << 12)
01012 #define SIP_USEREQPHONE (1 << 13)
01013 #define SIP_USECLIENTCODE (1 << 14)
01014
01015
01016 #define SIP_DTMF (7 << 15)
01017 #define SIP_DTMF_RFC2833 (0 << 15)
01018 #define SIP_DTMF_INBAND (1 << 15)
01019 #define SIP_DTMF_INFO (2 << 15)
01020 #define SIP_DTMF_AUTO (3 << 15)
01021 #define SIP_DTMF_SHORTINFO (4 << 15)
01022
01023
01024 #define SIP_NAT (3 << 18)
01025 #define SIP_NAT_NEVER (0 << 18)
01026 #define SIP_NAT_RFC3581 (1 << 18)
01027 #define SIP_NAT_ROUTE (2 << 18)
01028 #define SIP_NAT_ALWAYS (3 << 18)
01029
01030
01031 #define SIP_REINVITE (7 << 20)
01032 #define SIP_REINVITE_NONE (0 << 20)
01033 #define SIP_CAN_REINVITE (1 << 20)
01034 #define SIP_CAN_REINVITE_NAT (2 << 20)
01035 #define SIP_REINVITE_UPDATE (4 << 20)
01036
01037
01038 #define SIP_INSECURE (3 << 23)
01039 #define SIP_INSECURE_NONE (0 << 23)
01040 #define SIP_INSECURE_PORT (1 << 23)
01041 #define SIP_INSECURE_INVITE (1 << 24)
01042
01043
01044 #define SIP_PROG_INBAND (3 << 25)
01045 #define SIP_PROG_INBAND_NEVER (0 << 25)
01046 #define SIP_PROG_INBAND_NO (1 << 25)
01047 #define SIP_PROG_INBAND_YES (2 << 25)
01048
01049 #define SIP_SENDRPID (1 << 29)
01050 #define SIP_G726_NONSTANDARD (1 << 31)
01051
01052
01053 #define SIP_FLAGS_TO_COPY \
01054 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01055 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01056 SIP_USEREQPHONE | SIP_INSECURE)
01057
01058
01059
01060
01061
01062
01063 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
01064 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
01065
01066 #define SIP_PAGE2_CONSTANT_SSRC (1 << 8)
01067 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9)
01068
01069 #define SIP_PAGE2_RPORT_PRESENT (1 << 10)
01070 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14)
01071 #define SIP_PAGE2_TEXTSUPPORT (1 << 15)
01072 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)
01073 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17)
01074 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18)
01075 #define SIP_PAGE2_IGNORESDPVERSION (1 << 19)
01076
01077 #define SIP_PAGE2_T38SUPPORT (3 << 20)
01078 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20)
01079 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC (2 << 20)
01080 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY (3 << 20)
01081
01082 #define SIP_PAGE2_CALL_ONHOLD (3 << 23)
01083 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23)
01084 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23)
01085 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)
01086
01087 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
01088 #define SIP_PAGE2_BUGGY_MWI (1 << 26)
01089 #define SIP_PAGE2_DIALOG_ESTABLISHED (1 << 27)
01090 #define SIP_PAGE2_FAX_DETECT (1 << 28)
01091 #define SIP_PAGE2_REGISTERTRYING (1 << 29)
01092 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30)
01093 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS (1 << 31)
01094
01095 #define SIP_PAGE2_FLAGS_TO_COPY \
01096 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01097 SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01098 SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | \
01099 SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | SIP_PAGE2_CONSTANT_SSRC | SIP_PAGE2_FAX_DETECT)
01100
01101
01102
01103
01104
01105
01106
01107
01108
01109 enum sip_debug_e {
01110 sip_debug_none = 0,
01111 sip_debug_config = 1,
01112 sip_debug_console = 2,
01113 };
01114
01115 static enum sip_debug_e sipdebug;
01116
01117
01118
01119
01120
01121 static int sipdebug_text;
01122
01123
01124 enum t38state {
01125 T38_DISABLED = 0,
01126 T38_LOCAL_REINVITE,
01127 T38_PEER_REINVITE,
01128 T38_ENABLED
01129 };
01130
01131
01132 struct t38properties {
01133 enum t38state state;
01134 struct ast_control_t38_parameters our_parms;
01135 struct ast_control_t38_parameters their_parms;
01136 };
01137
01138
01139 enum referstatus {
01140 REFER_IDLE,
01141 REFER_SENT,
01142 REFER_RECEIVED,
01143 REFER_CONFIRMED,
01144 REFER_ACCEPTED,
01145 REFER_RINGING,
01146 REFER_200OK,
01147 REFER_FAILED,
01148 REFER_NOAUTH
01149 };
01150
01151
01152
01153
01154
01155
01156 struct _map_x_s {
01157 int x;
01158 const char *s;
01159 };
01160
01161 static const struct _map_x_s referstatusstrings[] = {
01162 { REFER_IDLE, "<none>" },
01163 { REFER_SENT, "Request sent" },
01164 { REFER_RECEIVED, "Request received" },
01165 { REFER_CONFIRMED, "Confirmed" },
01166 { REFER_ACCEPTED, "Accepted" },
01167 { REFER_RINGING, "Target ringing" },
01168 { REFER_200OK, "Done" },
01169 { REFER_FAILED, "Failed" },
01170 { REFER_NOAUTH, "Failed - auth failure" },
01171 { -1, NULL}
01172 };
01173
01174
01175
01176 struct sip_refer {
01177 char refer_to[AST_MAX_EXTENSION];
01178 char refer_to_domain[AST_MAX_EXTENSION];
01179 char refer_to_urioption[AST_MAX_EXTENSION];
01180 char refer_to_context[AST_MAX_EXTENSION];
01181 char referred_by[AST_MAX_EXTENSION];
01182 char referred_by_name[AST_MAX_EXTENSION];
01183 char refer_contact[AST_MAX_EXTENSION];
01184 char replaces_callid[SIPBUFSIZE];
01185 char replaces_callid_totag[SIPBUFSIZE/2];
01186 char replaces_callid_fromtag[SIPBUFSIZE/2];
01187 struct sip_pvt *refer_call;
01188
01189
01190
01191 int attendedtransfer;
01192 int localtransfer;
01193 enum referstatus status;
01194 };
01195
01196
01197
01198
01199
01200 struct sip_st_dlg {
01201 int st_active;
01202 int st_interval;
01203 int st_schedid;
01204 enum st_refresher st_ref;
01205 int st_expirys;
01206 int st_active_peer_ua;
01207 int st_cached_min_se;
01208 int st_cached_max_se;
01209 enum st_mode st_cached_mode;
01210 enum st_refresher st_cached_ref;
01211 unsigned char quit_flag:1;
01212 };
01213
01214
01215
01216
01217
01218 struct sip_st_cfg {
01219 enum st_mode st_mode_oper;
01220 enum st_refresher st_ref;
01221 int st_min_se;
01222 int st_max_se;
01223 };
01224
01225 struct offered_media {
01226 int offered;
01227 char text[128];
01228 };
01229
01230
01231
01232
01233
01234 struct sip_pvt {
01235 struct sip_pvt *next;
01236 enum invitestates invitestate;
01237 int method;
01238 AST_DECLARE_STRING_FIELDS(
01239 AST_STRING_FIELD(callid);
01240 AST_STRING_FIELD(randdata);
01241 AST_STRING_FIELD(accountcode);
01242 AST_STRING_FIELD(realm);
01243 AST_STRING_FIELD(nonce);
01244 AST_STRING_FIELD(opaque);
01245 AST_STRING_FIELD(qop);
01246 AST_STRING_FIELD(domain);
01247 AST_STRING_FIELD(from);
01248 AST_STRING_FIELD(useragent);
01249 AST_STRING_FIELD(exten);
01250 AST_STRING_FIELD(context);
01251 AST_STRING_FIELD(subscribecontext);
01252 AST_STRING_FIELD(subscribeuri);
01253 AST_STRING_FIELD(fromdomain);
01254 AST_STRING_FIELD(fromuser);
01255 AST_STRING_FIELD(fromname);
01256 AST_STRING_FIELD(tohost);
01257 AST_STRING_FIELD(todnid);
01258 AST_STRING_FIELD(language);
01259 AST_STRING_FIELD(mohinterpret);
01260 AST_STRING_FIELD(mohsuggest);
01261 AST_STRING_FIELD(rdnis);
01262 AST_STRING_FIELD(redircause);
01263 AST_STRING_FIELD(theirtag);
01264 AST_STRING_FIELD(username);
01265 AST_STRING_FIELD(peername);
01266 AST_STRING_FIELD(authname);
01267 AST_STRING_FIELD(uri);
01268 AST_STRING_FIELD(okcontacturi);
01269 AST_STRING_FIELD(peersecret);
01270 AST_STRING_FIELD(peermd5secret);
01271 AST_STRING_FIELD(cid_num);
01272 AST_STRING_FIELD(cid_name);
01273 AST_STRING_FIELD(fullcontact);
01274
01275 AST_STRING_FIELD(our_contact);
01276 AST_STRING_FIELD(rpid);
01277 AST_STRING_FIELD(rpid_from);
01278 AST_STRING_FIELD(url);
01279 AST_STRING_FIELD(parkinglot);
01280 );
01281 char via[128];
01282 struct sip_socket socket;
01283 unsigned int ocseq;
01284 unsigned int icseq;
01285 ast_group_t callgroup;
01286 ast_group_t pickupgroup;
01287 int lastinvite;
01288 struct ast_flags flags[2];
01289
01290
01291 char do_history;
01292 char alreadygone;
01293 char needdestroy;
01294 char outgoing_call;
01295 char answered_elsewhere;
01296 char novideo;
01297 char notext;
01298
01299 int timer_t1;
01300 int timer_b;
01301 unsigned int sipoptions;
01302 unsigned int reqsipoptions;
01303 struct ast_codec_pref prefs;
01304 int capability;
01305 int jointcapability;
01306 int peercapability;
01307 int prefcodec;
01308 int noncodeccapability;
01309 int jointnoncodeccapability;
01310 int redircodecs;
01311 int maxcallbitrate;
01312 struct sip_proxy *outboundproxy;
01313 int t38_maxdatagram;
01314 struct t38properties t38;
01315 struct sockaddr_in udptlredirip;
01316 struct ast_udptl *udptl;
01317 int callingpres;
01318 int authtries;
01319 int expiry;
01320 long branch;
01321 long invite_branch;
01322 char tag[11];
01323 int sessionid;
01324 int sessionversion;
01325 int64_t sessionversion_remote;
01326 int session_modify;
01327 unsigned int portinuri:1;
01328 struct sockaddr_in sa;
01329 struct sockaddr_in redirip;
01330 struct sockaddr_in vredirip;
01331 struct sockaddr_in tredirip;
01332 time_t lastrtprx;
01333 time_t lastrtptx;
01334 int rtptimeout;
01335 struct sockaddr_in recv;
01336 struct sockaddr_in ourip;
01337 struct ast_channel *owner;
01338 struct sip_route *route;
01339 int route_persistant;
01340 struct ast_variable *notify_headers;
01341 struct sip_auth *peerauth;
01342 int noncecount;
01343 unsigned int stalenonce:1;
01344 char lastmsg[256];
01345 int amaflags;
01346 int pendinginvite;
01347 int glareinvite;
01348
01349
01350 struct sip_request initreq;
01351
01352
01353
01354 int initid;
01355 int waitid;
01356 int autokillid;
01357 int t38id;
01358 enum transfermodes allowtransfer;
01359 struct sip_refer *refer;
01360 enum subscriptiontype subscribed;
01361 int stateid;
01362 int laststate;
01363 int dialogver;
01364
01365 struct ast_dsp *dsp;
01366
01367 struct sip_peer *relatedpeer;
01368
01369 struct sip_registry *registry;
01370 struct ast_rtp *rtp;
01371 struct ast_rtp *vrtp;
01372 struct ast_rtp *trtp;
01373 struct sip_pkt *packets;
01374 struct sip_history_head *history;
01375 size_t history_entries;
01376 struct ast_variable *chanvars;
01377 AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue;
01378 int request_queue_sched_id;
01379 int provisional_keepalive_sched_id;
01380 const char *last_provisional;
01381 struct sip_invite_param *options;
01382 int autoframing;
01383
01384
01385
01386 struct sip_st_dlg *stimer;
01387 int red;
01388 int hangupcause;
01389
01390
01391
01392
01393
01394
01395
01396
01397
01398
01399
01400
01401
01402
01403 struct offered_media offered_media[4];
01404 };
01405
01406
01407 #define MAX_HISTORY_ENTRIES 50
01408
01409
01410
01411
01412
01413
01414
01415
01416
01417 struct ao2_container *dialogs;
01418
01419 #define sip_pvt_lock(x) ao2_lock(x)
01420 #define sip_pvt_trylock(x) ao2_trylock(x)
01421 #define sip_pvt_unlock(x) ao2_unlock(x)
01422
01423
01424
01425
01426
01427
01428 #ifdef REF_DEBUG
01429 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01430 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01431
01432 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01433 {
01434 if (p)
01435 _ao2_ref_debug(p, 1, tag, file, line, func);
01436 else
01437 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01438 return p;
01439 }
01440
01441 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01442 {
01443 if (p)
01444 _ao2_ref_debug(p, -1, tag, file, line, func);
01445 return NULL;
01446 }
01447 #else
01448 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01449 {
01450 if (p)
01451 ao2_ref(p, 1);
01452 else
01453 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01454 return p;
01455 }
01456
01457 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01458 {
01459 if (p)
01460 ao2_ref(p, -1);
01461 return NULL;
01462 }
01463 #endif
01464
01465
01466
01467
01468
01469
01470
01471 struct sip_pkt {
01472 struct sip_pkt *next;
01473 int retrans;
01474 int method;
01475 int seqno;
01476 char is_resp;
01477 char is_fatal;
01478 int response_code;
01479 struct sip_pvt *owner;
01480 int retransid;
01481 int timer_a;
01482 int timer_t1;
01483 int packetlen;
01484 struct ast_str *data;
01485 };
01486
01487
01488
01489
01490
01491
01492
01493 struct sip_mailbox {
01494 char *mailbox;
01495 char *context;
01496
01497 struct ast_event_sub *event_sub;
01498 AST_LIST_ENTRY(sip_mailbox) entry;
01499 };
01500
01501 enum sip_peer_type {
01502 SIP_TYPE_PEER = (1 << 0),
01503 SIP_TYPE_USER = (1 << 1),
01504 };
01505
01506
01507
01508
01509 struct sip_peer {
01510 char name[80];
01511 struct sip_socket socket;
01512 enum sip_transport default_outbound_transport;
01513 unsigned int transports:3;
01514 char secret[80];
01515 char md5secret[80];
01516 struct sip_auth *auth;
01517 char context[AST_MAX_CONTEXT];
01518 char subscribecontext[AST_MAX_CONTEXT];
01519 char username[80];
01520 char accountcode[AST_MAX_ACCOUNT_CODE];
01521 int amaflags;
01522 char tohost[MAXHOSTNAMELEN];
01523 char regexten[AST_MAX_EXTENSION];
01524 char fromuser[80];
01525 char fromdomain[MAXHOSTNAMELEN];
01526 char fullcontact[256];
01527 char cid_num[80];
01528 char cid_name[80];
01529 int callingpres;
01530 int inUse;
01531 int inRinging;
01532 int onHold;
01533 int call_limit;
01534 int t38_maxdatagram;
01535 int busy_level;
01536 enum transfermodes allowtransfer;
01537 char vmexten[AST_MAX_EXTENSION];
01538 char language[MAX_LANGUAGE];
01539 char mohinterpret[MAX_MUSICCLASS];
01540 char mohsuggest[MAX_MUSICCLASS];
01541 char parkinglot[AST_MAX_CONTEXT];
01542 char useragent[256];
01543 struct ast_codec_pref prefs;
01544 int lastmsgssent;
01545 unsigned int sipoptions;
01546 struct ast_flags flags[2];
01547
01548
01549 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01550
01551
01552 char is_realtime;
01553 char rt_fromcontact;
01554 char host_dynamic;
01555 char selfdestruct;
01556 char the_mark;
01557
01558 int expire;
01559 int capability;
01560 int rtptimeout;
01561 int rtpholdtimeout;
01562 int rtpkeepalive;
01563 ast_group_t callgroup;
01564 ast_group_t pickupgroup;
01565 struct sip_proxy *outboundproxy;
01566 struct ast_dnsmgr_entry *dnsmgr;
01567 struct sockaddr_in addr;
01568 int maxcallbitrate;
01569 unsigned int portinuri:1;
01570
01571
01572 struct sip_pvt *call;
01573 int pokeexpire;
01574 int lastms;
01575 int maxms;
01576 int qualifyfreq;
01577 struct timeval ps;
01578 struct sockaddr_in defaddr;
01579 struct ast_ha *ha;
01580 struct ast_ha *contactha;
01581 struct ast_variable *chanvars;
01582 struct sip_pvt *mwipvt;
01583 int autoframing;
01584 struct sip_st_cfg stimer;
01585 int timer_t1;
01586 int timer_b;
01587 int deprecated_username;
01588 enum sip_peer_type type;
01589 };
01590
01591
01592
01593
01594
01595
01596
01597
01598
01599
01600
01601
01602
01603
01604 struct sip_registry {
01605 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01606 AST_DECLARE_STRING_FIELDS(
01607 AST_STRING_FIELD(callid);
01608 AST_STRING_FIELD(realm);
01609 AST_STRING_FIELD(nonce);
01610 AST_STRING_FIELD(opaque);
01611 AST_STRING_FIELD(qop);
01612 AST_STRING_FIELD(domain);
01613 AST_STRING_FIELD(username);
01614 AST_STRING_FIELD(authuser);
01615 AST_STRING_FIELD(hostname);
01616 AST_STRING_FIELD(secret);
01617 AST_STRING_FIELD(md5secret);
01618 AST_STRING_FIELD(callback);
01619 AST_STRING_FIELD(random);
01620 AST_STRING_FIELD(peername);
01621 );
01622 enum sip_transport transport;
01623 int portno;
01624 int expire;
01625 int configured_expiry;
01626 int expiry;
01627 int regattempts;
01628 int timeout;
01629 int refresh;
01630 struct sip_pvt *call;
01631 enum sipregistrystate regstate;
01632 struct timeval regtime;
01633 int callid_valid;
01634 unsigned int ocseq;
01635 struct ast_dnsmgr_entry *dnsmgr;
01636 struct sockaddr_in us;
01637 int noncecount;
01638 char lastmsg[256];
01639 };
01640
01641 enum sip_tcptls_alert {
01642
01643 TCPTLS_ALERT_DATA,
01644
01645 TCPTLS_ALERT_STOP,
01646 };
01647
01648 struct tcptls_packet {
01649 AST_LIST_ENTRY(tcptls_packet) entry;
01650 struct ast_str *data;
01651 size_t len;
01652 };
01653
01654 struct sip_threadinfo {
01655 int stop;
01656 int alert_pipe[2];
01657 pthread_t threadid;
01658 struct ast_tcptls_session_instance *tcptls_session;
01659 enum sip_transport type;
01660 AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01661 };
01662
01663
01664
01665 #ifdef LOW_MEMORY
01666 static int hash_peer_size = 17;
01667 static int hash_dialog_size = 17;
01668 static int hash_user_size = 17;
01669 #else
01670 static int hash_peer_size = 563;
01671 static int hash_dialog_size = 563;
01672 static int hash_user_size = 563;
01673 #endif
01674
01675
01676 static struct ao2_container *threadt;
01677
01678
01679 struct ao2_container *peers;
01680 struct ao2_container *peers_by_ip;
01681
01682
01683 static struct ast_register_list {
01684 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01685 int recheck;
01686 } regl;
01687
01688
01689
01690
01691 static int peer_hash_cb(const void *obj, const int flags)
01692 {
01693 const struct sip_peer *peer = obj;
01694
01695 return ast_str_case_hash(peer->name);
01696 }
01697
01698
01699
01700
01701 static int peer_cmp_cb(void *obj, void *arg, int flags)
01702 {
01703 struct sip_peer *peer = obj, *peer2 = arg;
01704
01705 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01706 }
01707
01708
01709
01710
01711 static int peer_iphash_cb(const void *obj, const int flags)
01712 {
01713 const struct sip_peer *peer = obj;
01714 int ret1 = peer->addr.sin_addr.s_addr;
01715 if (ret1 < 0)
01716 ret1 = -ret1;
01717
01718 return ret1;
01719 }
01720
01721
01722
01723
01724
01725
01726
01727
01728
01729
01730
01731
01732
01733
01734
01735
01736
01737
01738
01739 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
01740 {
01741 struct sip_peer *peer = obj, *peer2 = arg;
01742
01743 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
01744
01745 return 0;
01746 }
01747
01748
01749 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
01750
01751 return CMP_MATCH | CMP_STOP;
01752 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
01753
01754
01755 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
01756 (CMP_MATCH | CMP_STOP) : 0;
01757 }
01758
01759
01760 return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
01761 }
01762
01763
01764 static int threadt_hash_cb(const void *obj, const int flags)
01765 {
01766 const struct sip_threadinfo *th = obj;
01767
01768 return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
01769 }
01770
01771 static int threadt_cmp_cb(void *obj, void *arg, int flags)
01772 {
01773 struct sip_threadinfo *th = obj, *th2 = arg;
01774
01775 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
01776 }
01777
01778
01779
01780
01781 static int dialog_hash_cb(const void *obj, const int flags)
01782 {
01783 const struct sip_pvt *pvt = obj;
01784
01785 return ast_str_case_hash(pvt->callid);
01786 }
01787
01788
01789
01790
01791 static int dialog_cmp_cb(void *obj, void *arg, int flags)
01792 {
01793 struct sip_pvt *pvt = obj, *pvt2 = arg;
01794
01795 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
01796 }
01797
01798 static int temp_pvt_init(void *);
01799 static void temp_pvt_cleanup(void *);
01800
01801
01802 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01803
01804 #ifdef LOW_MEMORY
01805 static void ts_ast_rtp_destroy(void *);
01806
01807 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
01808 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
01809 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
01810 #endif
01811
01812
01813
01814 static struct sip_auth *authl = NULL;
01815
01816
01817
01818
01819
01820
01821
01822
01823
01824
01825
01826
01827
01828
01829
01830
01831
01832
01833 static int sipsock = -1;
01834
01835 static struct sockaddr_in bindaddr;
01836
01837
01838
01839
01840
01841
01842
01843 static struct sockaddr_in internip;
01844
01845
01846
01847
01848
01849
01850
01851
01852
01853
01854
01855
01856
01857
01858
01859
01860
01861
01862
01863 static struct sockaddr_in externip;
01864
01865 static char externhost[MAXHOSTNAMELEN];
01866 static time_t externexpire;
01867 static int externrefresh = 10;
01868 static struct sockaddr_in stunaddr;
01869
01870
01871
01872
01873
01874
01875
01876 static struct ast_ha *localaddr;
01877
01878 static int ourport_tcp;
01879 static int ourport_tls;
01880 static struct sockaddr_in debugaddr;
01881
01882 static struct ast_config *notify_types;
01883
01884
01885
01886 #define UNLINK(element, head, prev) do { \
01887 if (prev) \
01888 (prev)->next = (element)->next; \
01889 else \
01890 (head) = (element)->next; \
01891 } while (0)
01892
01893 enum t38_action_flag {
01894 SDP_T38_NONE = 0,
01895 SDP_T38_INITIATE,
01896 SDP_T38_ACCEPT,
01897 };
01898
01899
01900
01901
01902
01903
01904 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
01905 static int sip_devicestate(void *data);
01906 static int sip_sendtext(struct ast_channel *ast, const char *text);
01907 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01908 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01909 static int sip_hangup(struct ast_channel *ast);
01910 static int sip_answer(struct ast_channel *ast);
01911 static struct ast_frame *sip_read(struct ast_channel *ast);
01912 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01913 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01914 static int sip_transfer(struct ast_channel *ast, const char *dest);
01915 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01916 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01917 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01918 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01919 static const char *sip_get_callid(struct ast_channel *chan);
01920
01921 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
01922 static int sip_standard_port(enum sip_transport type, int port);
01923 static int sip_prepare_socket(struct sip_pvt *p);
01924 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
01925
01926
01927 static int sipsock_read(int *id, int fd, short events, void *ignore);
01928 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
01929 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
01930 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01931 static int retrans_pkt(const void *data);
01932 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);
01933 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01934 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01935 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01936 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
01937 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01938 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);
01939 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01940 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01941 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01942 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01943 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01944 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
01945 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01946 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01947 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01948 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01949 static int transmit_refer(struct sip_pvt *p, const char *dest);
01950 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
01951 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01952 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
01953 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01954 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01955 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01956 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01957 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01958 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
01959 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
01960
01961
01962 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
01963 int useglobal_nat, const int intended_method, struct sip_request *req);
01964 static int __sip_autodestruct(const void *data);
01965 static void sip_scheddestroy(struct sip_pvt *p, int ms);
01966 static int sip_cancel_destroy(struct sip_pvt *p);
01967 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
01968 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
01969 static void *registry_unref(struct sip_registry *reg, char *tag);
01970 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
01971 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01972 static void __sip_pretend_ack(struct sip_pvt *p);
01973 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01974 static int auto_congest(const void *arg);
01975 static int update_call_counter(struct sip_pvt *fup, int event);
01976 static int hangup_sip2cause(int cause);
01977 static const char *hangup_cause2sip(int cause);
01978 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
01979 static void free_old_route(struct sip_route *route);
01980 static void list_route(struct sip_route *route);
01981 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01982 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
01983 struct sip_request *req, char *uri);
01984 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01985 static void check_pendings(struct sip_pvt *p);
01986 static void *sip_park_thread(void *stuff);
01987 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
01988 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01989
01990
01991 static void try_suggested_sip_codec(struct sip_pvt *p);
01992 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01993 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01994 static int find_sdp(struct sip_request *req);
01995 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01996 static int process_sdp_o(const char *o, struct sip_pvt *p);
01997 static int process_sdp_c(const char *c, struct ast_hostent *hp);
01998 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01999 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02000 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02001 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
02002 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02003 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
02004 struct ast_str **m_buf, struct ast_str **a_buf,
02005 int debug, int *min_packet_size);
02006 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
02007 struct ast_str **m_buf, struct ast_str **a_buf,
02008 int debug);
02009 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02010 static void do_setnat(struct sip_pvt *p, int natflags);
02011 static void stop_media_flows(struct sip_pvt *p);
02012
02013
02014 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02015 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02016 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02017 const char *secret, const char *md5secret, int sipmethod,
02018 char *uri, enum xmittype reliable, int ignore);
02019 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02020 int sipmethod, char *uri, enum xmittype reliable,
02021 struct sockaddr_in *sin, struct sip_peer **authpeer);
02022 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02023
02024
02025 static int check_sip_domain(const char *domain, char *context, size_t len);
02026 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02027 static void clear_sip_domains(void);
02028
02029
02030 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02031 static int clear_realm_authentication(struct sip_auth *authlist);
02032 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02033
02034
02035 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02036 static int sip_do_reload(enum channelreloadreason reason);
02037 static int reload_config(enum channelreloadreason reason);
02038 static int expire_register(const void *data);
02039 static void *do_monitor(void *data);
02040 static int restart_monitor(void);
02041 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02042
02043 static int sip_refer_allocate(struct sip_pvt *p);
02044 static void ast_quiet_chan(struct ast_channel *chan);
02045 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02046
02047
02048
02049
02050
02051
02052
02053 #define check_request_transport(peer, tmpl) ({ \
02054 int ret = 0; \
02055 if (peer->socket.type == tmpl->socket.type) \
02056 ; \
02057 else if (!(peer->transports & tmpl->socket.type)) {\
02058 ast_log(LOG_ERROR, \
02059 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02060 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer) \
02061 ); \
02062 ret = 1; \
02063 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02064 ast_log(LOG_WARNING, \
02065 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02066 peer->name, get_transport(tmpl->socket.type) \
02067 ); \
02068 } else { \
02069 ast_debug(1, \
02070 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02071 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02072 ); \
02073 }\
02074 (ret); \
02075 })
02076
02077
02078
02079 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02080 static int sip_devicestate(void *data);
02081 static int sip_poke_noanswer(const void *data);
02082 static int sip_poke_peer(struct sip_peer *peer, int force);
02083 static void sip_poke_all_peers(void);
02084 static void sip_peer_hold(struct sip_pvt *p, int hold);
02085 static void mwi_event_cb(const struct ast_event *, void *);
02086
02087
02088 static const char *sip_nat_mode(const struct sip_pvt *p);
02089 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02090 static char *transfermode2str(enum transfermodes mode) attribute_const;
02091 static const char *nat2str(int nat) attribute_const;
02092 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02093 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02094 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02095 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02096 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02097 static void print_group(int fd, ast_group_t group, int crlf);
02098 static const char *dtmfmode2str(int mode) attribute_const;
02099 static int str2dtmfmode(const char *str) attribute_unused;
02100 static const char *insecure2str(int mode) attribute_const;
02101 static void cleanup_stale_contexts(char *new, char *old);
02102 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02103 static const char *domain_mode_to_text(const enum domain_mode mode);
02104 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02105 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02106 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02107 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02108 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02109 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02110 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02111 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02112 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02113 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02114 static char *complete_sip_peer(const char *word, int state, int flags2);
02115 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02116 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02117 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02118 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02119 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02120 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02121 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02122 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02123 static char *sip_do_debug_ip(int fd, char *arg);
02124 static char *sip_do_debug_peer(int fd, char *arg);
02125 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02126 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02127 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02128 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02129 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02130 static int sip_addheader(struct ast_channel *chan, void *data);
02131 static int sip_do_reload(enum channelreloadreason reason);
02132 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02133 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02134
02135
02136
02137
02138
02139 static void sip_dump_history(struct sip_pvt *dialog);
02140 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02141 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02142
02143
02144
02145
02146 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02147 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02148 static void sip_dump_history(struct sip_pvt *dialog);
02149
02150
02151 static struct sip_peer *temp_peer(const char *name);
02152 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02153 static int update_call_counter(struct sip_pvt *fup, int event);
02154 static void sip_destroy_peer(struct sip_peer *peer);
02155 static void sip_destroy_peer_fn(void *peer);
02156 static void set_peer_defaults(struct sip_peer *peer);
02157 static struct sip_peer *temp_peer(const char *name);
02158 static void register_peer_exten(struct sip_peer *peer, int onoff);
02159 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport);
02160 static int sip_poke_peer_s(const void *data);
02161 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02162 static void reg_source_db(struct sip_peer *peer);
02163 static void destroy_association(struct sip_peer *peer);
02164 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02165 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02166 static void set_socket_transport(struct sip_socket *socket, int transport);
02167
02168
02169 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms);
02170 static void update_peer(struct sip_peer *p, int expire);
02171 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02172 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02173 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02174 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02175
02176
02177 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02178 static void sip_registry_destroy(struct sip_registry *reg);
02179 static int sip_register(const char *value, int lineno);
02180 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02181 static int sip_reregister(const void *data);
02182 static int __sip_do_register(struct sip_registry *r);
02183 static int sip_reg_timeout(const void *data);
02184 static void sip_send_all_registers(void);
02185 static int sip_reinvite_retry(const void *data);
02186
02187
02188 static void append_date(struct sip_request *req);
02189 static int determine_firstline_parts(struct sip_request *req);
02190 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02191 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02192 static int find_sip_method(const char *msg);
02193 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02194 static int parse_request(struct sip_request *req);
02195 static const char *get_header(const struct sip_request *req, const char *name);
02196 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02197 static int method_match(enum sipmethod id, const char *name);
02198 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02199 static char *get_in_brackets(char *tmp);
02200 static const char *find_alias(const char *name, const char *_default);
02201 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02202 static int lws2sws(char *msgbuf, int len);
02203 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02204 static char *remove_uri_parameters(char *uri);
02205 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02206 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02207 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02208 static int set_address_from_contact(struct sip_pvt *pvt);
02209 static void check_via(struct sip_pvt *p, struct sip_request *req);
02210 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02211 static int get_rpid_num(const char *input, char *output, int maxlen);
02212 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02213 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02214 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02215 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02216
02217
02218 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02219 static void *sip_tcp_worker_fn(void *);
02220
02221
02222 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02223 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02224 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02225 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02226 static int init_resp(struct sip_request *resp, const char *msg);
02227 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02228 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02229 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02230 static void build_via(struct sip_pvt *p);
02231 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02232 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02233 static char *generate_random_string(char *buf, size_t size);
02234 static void build_callid_pvt(struct sip_pvt *pvt);
02235 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02236 static void make_our_tag(char *tagbuf, size_t len);
02237 static int add_header(struct sip_request *req, const char *var, const char *value);
02238 static int add_header_contentLength(struct sip_request *req, int len);
02239 static int add_line(struct sip_request *req, const char *line);
02240 static int add_text(struct sip_request *req, const char *text);
02241 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02242 static int add_vidupdate(struct sip_request *req);
02243 static void add_route(struct sip_request *req, struct sip_route *route);
02244 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02245 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02246 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02247 static void set_destination(struct sip_pvt *p, char *uri);
02248 static void append_date(struct sip_request *req);
02249 static void build_contact(struct sip_pvt *p);
02250 static void build_rpid(struct sip_pvt *p);
02251
02252
02253 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02254 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
02255 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02256 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02257 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02258 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02259 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02260 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02261 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02262 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02263 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02264 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02265 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02266
02267
02268 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02269 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02270 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02271 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02272 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02273
02274
02275 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active);
02276 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02277 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02278 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02279 static int sip_get_codec(struct ast_channel *chan);
02280 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02281
02282
02283 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02284 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02285 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02286 static void change_t38_state(struct sip_pvt *p, int state);
02287
02288
02289 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02290 static int proc_session_timer(const void *vp);
02291 static void stop_session_timer(struct sip_pvt *p);
02292 static void start_session_timer(struct sip_pvt *p);
02293 static void restart_session_timer(struct sip_pvt *p);
02294 static const char *strefresher2str(enum st_refresher r);
02295 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02296 static int parse_minse(const char *p_hdrval, int *const p_interval);
02297 static int st_get_se(struct sip_pvt *, int max);
02298 static enum st_refresher st_get_refresher(struct sip_pvt *);
02299 static enum st_mode st_get_mode(struct sip_pvt *);
02300 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02301
02302
02303
02304 static const struct ast_channel_tech sip_tech = {
02305 .type = "SIP",
02306 .description = "Session Initiation Protocol (SIP)",
02307 .capabilities = AST_FORMAT_AUDIO_MASK,
02308 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02309 .requester = sip_request_call,
02310 .devicestate = sip_devicestate,
02311 .call = sip_call,
02312 .send_html = sip_sendhtml,
02313 .hangup = sip_hangup,
02314 .answer = sip_answer,
02315 .read = sip_read,
02316 .write = sip_write,
02317 .write_video = sip_write,
02318 .write_text = sip_write,
02319 .indicate = sip_indicate,
02320 .transfer = sip_transfer,
02321 .fixup = sip_fixup,
02322 .send_digit_begin = sip_senddigit_begin,
02323 .send_digit_end = sip_senddigit_end,
02324 .bridge = ast_rtp_bridge,
02325 .early_bridge = ast_rtp_early_bridge,
02326 .send_text = sip_sendtext,
02327 .func_channel_read = acf_channel_read,
02328 .queryoption = sip_queryoption,
02329 .get_pvt_uniqueid = sip_get_callid,
02330 };
02331
02332
02333
02334
02335
02336
02337
02338 static struct ast_channel_tech sip_tech_info;
02339
02340
02341
02342 static struct ast_tls_config sip_tls_cfg;
02343
02344
02345 static struct ast_tls_config default_tls_cfg;
02346
02347
02348 static struct ast_tcptls_session_args sip_tcp_desc = {
02349 .accept_fd = -1,
02350 .master = AST_PTHREADT_NULL,
02351 .tls_cfg = NULL,
02352 .poll_timeout = -1,
02353 .name = "sip tcp server",
02354 .accept_fn = ast_tcptls_server_root,
02355 .worker_fn = sip_tcp_worker_fn,
02356 };
02357
02358
02359 static struct ast_tcptls_session_args sip_tls_desc = {
02360 .accept_fd = -1,
02361 .master = AST_PTHREADT_NULL,
02362 .tls_cfg = &sip_tls_cfg,
02363 .poll_timeout = -1,
02364 .name = "sip tls server",
02365 .accept_fn = ast_tcptls_server_root,
02366 .worker_fn = sip_tcp_worker_fn,
02367 };
02368
02369
02370 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
02371
02372
02373
02374
02375 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02376 {
02377 const struct _map_x_s *cur;
02378
02379 for (cur = table; cur->s; cur++)
02380 if (cur->x == x)
02381 return cur->s;
02382 return errorstring;
02383 }
02384
02385
02386
02387
02388 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02389 {
02390 const struct _map_x_s *cur;
02391
02392 for (cur = table; cur->s; cur++)
02393 if (!strcasecmp(cur->s, s))
02394 return cur->x;
02395 return errorvalue;
02396 }
02397
02398
02399
02400 static struct ast_rtp_protocol sip_rtp = {
02401 .type = "SIP",
02402 .get_rtp_info = sip_get_rtp_peer,
02403 .get_vrtp_info = sip_get_vrtp_peer,
02404 .get_trtp_info = sip_get_trtp_peer,
02405 .set_rtp_peer = sip_set_rtp_peer,
02406 .get_codec = sip_get_codec,
02407 };
02408
02409
02410 static void tcptls_packet_destructor(void *obj)
02411 {
02412 struct tcptls_packet *packet = obj;
02413
02414 ast_free(packet->data);
02415 }
02416
02417 static void sip_tcptls_client_args_destructor(void *obj)
02418 {
02419 struct ast_tcptls_session_args *args = obj;
02420 if (args->tls_cfg) {
02421 ast_free(args->tls_cfg->certfile);
02422 ast_free(args->tls_cfg->cipher);
02423 ast_free(args->tls_cfg->cafile);
02424 ast_free(args->tls_cfg->capath);
02425 }
02426 ast_free(args->tls_cfg);
02427 ast_free((char *) args->name);
02428 }
02429
02430 static void sip_threadinfo_destructor(void *obj)
02431 {
02432 struct sip_threadinfo *th = obj;
02433 struct tcptls_packet *packet;
02434 if (th->alert_pipe[1] > -1) {
02435 close(th->alert_pipe[0]);
02436 }
02437 if (th->alert_pipe[1] > -1) {
02438 close(th->alert_pipe[1]);
02439 }
02440 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02441
02442 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02443 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02444 }
02445
02446 if (th->tcptls_session) {
02447 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02448 }
02449 }
02450
02451
02452 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02453 {
02454 struct sip_threadinfo *th;
02455
02456 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02457 return NULL;
02458 }
02459
02460 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02461
02462 if (pipe(th->alert_pipe) == -1) {
02463 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02464 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02465 return NULL;
02466 }
02467 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02468 th->tcptls_session = tcptls_session;
02469 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02470 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02471 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02472 return th;
02473 }
02474
02475
02476 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02477 {
02478 int res = len;
02479 struct sip_threadinfo *th = NULL;
02480 struct tcptls_packet *packet = NULL;
02481 struct sip_threadinfo tmp = {
02482 .tcptls_session = tcptls_session,
02483 };
02484 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02485
02486 if (!tcptls_session) {
02487 return XMIT_ERROR;
02488 }
02489
02490 ast_mutex_lock(&tcptls_session->lock);
02491
02492 if ((tcptls_session->fd == -1) ||
02493 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02494 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02495 !(packet->data = ast_str_create(len))) {
02496 goto tcptls_write_setup_error;
02497 }
02498
02499
02500 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02501 packet->len = len;
02502
02503
02504
02505
02506 ao2_lock(th);
02507 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02508 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02509 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02510 packet = NULL;
02511 res = XMIT_ERROR;
02512 } else {
02513 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02514 }
02515 ao2_unlock(th);
02516
02517 ast_mutex_unlock(&tcptls_session->lock);
02518 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02519 return res;
02520
02521 tcptls_write_setup_error:
02522 if (th) {
02523 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02524 }
02525 if (packet) {
02526 ao2_t_ref(packet, -1, "could not allocate packet's data");
02527 }
02528 ast_mutex_unlock(&tcptls_session->lock);
02529
02530 return XMIT_ERROR;
02531 }
02532
02533
02534 static void *sip_tcp_worker_fn(void *data)
02535 {
02536 struct ast_tcptls_session_instance *tcptls_session = data;
02537
02538 return _sip_tcp_helper_thread(NULL, tcptls_session);
02539 }
02540
02541
02542 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02543 {
02544 int res, cl;
02545 struct sip_request req = { 0, } , reqcpy = { 0, };
02546 struct sip_threadinfo *me = NULL;
02547 char buf[1024] = "";
02548 struct pollfd fds[2] = { { 0 }, { 0 }, };
02549 struct ast_tcptls_session_args *ca = NULL;
02550
02551
02552
02553
02554
02555
02556
02557
02558
02559
02560
02561 if (!tcptls_session->client) {
02562 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02563 goto cleanup;
02564 }
02565 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02566 } else {
02567 struct sip_threadinfo tmp = {
02568 .tcptls_session = tcptls_session,
02569 };
02570
02571 if ((!(ca = tcptls_session->parent)) ||
02572 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02573 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02574 goto cleanup;
02575 }
02576 }
02577
02578 me->threadid = pthread_self();
02579 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02580
02581
02582 fds[0].fd = tcptls_session->fd;
02583 fds[1].fd = me->alert_pipe[0];
02584 fds[0].events = fds[1].events = POLLIN | POLLPRI;
02585
02586 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02587 goto cleanup;
02588 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02589 goto cleanup;
02590
02591 for (;;) {
02592 struct ast_str *str_save;
02593
02594 res = ast_poll(fds, 2, -1);
02595 if (res < 0) {
02596 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02597 goto cleanup;
02598 }
02599
02600
02601
02602 if (fds[0].revents) {
02603
02604 fds[0].revents = 0;
02605
02606
02607 str_save = req.data;
02608 memset(&req, 0, sizeof(req));
02609 req.data = str_save;
02610 ast_str_reset(req.data);
02611
02612 str_save = reqcpy.data;
02613 memset(&reqcpy, 0, sizeof(reqcpy));
02614 reqcpy.data = str_save;
02615 ast_str_reset(reqcpy.data);
02616
02617 memset(buf, 0, sizeof(buf));
02618
02619 if (tcptls_session->ssl) {
02620 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02621 req.socket.port = htons(ourport_tls);
02622 } else {
02623 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02624 req.socket.port = htons(ourport_tcp);
02625 }
02626 req.socket.fd = tcptls_session->fd;
02627
02628
02629 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
02630 ast_mutex_lock(&tcptls_session->lock);
02631 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02632 ast_mutex_unlock(&tcptls_session->lock);
02633 goto cleanup;
02634 }
02635 ast_mutex_unlock(&tcptls_session->lock);
02636 if (me->stop)
02637 goto cleanup;
02638 ast_str_append(&req.data, 0, "%s", buf);
02639 req.len = req.data->used;
02640 }
02641 copy_request(&reqcpy, &req);
02642 parse_request(&reqcpy);
02643
02644 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02645 while (cl > 0) {
02646 size_t bytes_read;
02647 ast_mutex_lock(&tcptls_session->lock);
02648 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02649 ast_mutex_unlock(&tcptls_session->lock);
02650 goto cleanup;
02651 }
02652 buf[bytes_read] = '\0';
02653 ast_mutex_unlock(&tcptls_session->lock);
02654 if (me->stop)
02655 goto cleanup;
02656 cl -= strlen(buf);
02657 ast_str_append(&req.data, 0, "%s", buf);
02658 req.len = req.data->used;
02659 }
02660 }
02661
02662
02663
02664 req.socket.tcptls_session = tcptls_session;
02665 handle_request_do(&req, &tcptls_session->remote_address);
02666 }
02667 if (fds[1].revents) {
02668 enum sip_tcptls_alert alert;
02669 struct tcptls_packet *packet;
02670
02671 fds[1].revents = 0;
02672
02673 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02674 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02675 continue;
02676 }
02677
02678 switch (alert) {
02679 case TCPTLS_ALERT_STOP:
02680 goto cleanup;
02681 case TCPTLS_ALERT_DATA:
02682 ao2_lock(me);
02683 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02684 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
02685 } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02686 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02687 }
02688
02689 if (packet) {
02690 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02691 }
02692 ao2_unlock(me);
02693 break;
02694 default:
02695 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02696 }
02697 }
02698 }
02699
02700 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02701
02702 cleanup:
02703 if (me) {
02704 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02705 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02706 }
02707 if (reqcpy.data) {
02708 ast_free(reqcpy.data);
02709 }
02710
02711 if (req.data) {
02712 ast_free(req.data);
02713 req.data = NULL;
02714 }
02715
02716
02717 if (ca) {
02718 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02719 }
02720
02721 if (tcptls_session) {
02722 ast_mutex_lock(&tcptls_session->lock);
02723 if (tcptls_session->f) {
02724 fclose(tcptls_session->f);
02725 tcptls_session->f = NULL;
02726 }
02727 if (tcptls_session->fd != -1) {
02728 close(tcptls_session->fd);
02729 tcptls_session->fd = -1;
02730 }
02731 tcptls_session->parent = NULL;
02732 ast_mutex_unlock(&tcptls_session->lock);
02733
02734 ao2_ref(tcptls_session, -1);
02735 tcptls_session = NULL;
02736 }
02737
02738 return NULL;
02739 }
02740
02741
02742
02743
02744
02745
02746
02747 static void *unref_peer(struct sip_peer *peer, char *tag)
02748 {
02749 ao2_t_ref(peer, -1, tag);
02750 return NULL;
02751 }
02752
02753 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02754 {
02755 ao2_t_ref(peer, 1, tag);
02756 return peer;
02757 }
02758
02759
02760
02761
02762
02763
02764
02765
02766
02767
02768
02769
02770 static struct sip_proxy *ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02771 {
02772 struct sip_proxy *old_obproxy = pvt->outboundproxy;
02773
02774 if (proxy && proxy != &global_outboundproxy) {
02775 ao2_ref(proxy, +1);
02776 }
02777 pvt->outboundproxy = proxy;
02778 if (old_obproxy && old_obproxy != &global_outboundproxy) {
02779 ao2_ref(old_obproxy, -1);
02780 }
02781 return proxy;
02782 }
02783
02784
02785
02786
02787
02788
02789
02790
02791 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
02792 {
02793 struct sip_pkt *cp;
02794
02795 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02796
02797 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02798
02799
02800 if (dialog->owner) {
02801 if (lockowner)
02802 ast_channel_lock(dialog->owner);
02803 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
02804 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02805 if (lockowner)
02806 ast_channel_unlock(dialog->owner);
02807 }
02808 if (dialog->registry) {
02809 if (dialog->registry->call == dialog)
02810 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02811 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02812 }
02813 if (dialog->stateid > -1) {
02814 ast_extension_state_del(dialog->stateid, NULL);
02815 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
02816 dialog->stateid = -1;
02817 }
02818
02819 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
02820 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02821 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
02822 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02823
02824
02825 while((cp = dialog->packets)) {
02826 dialog->packets = dialog->packets->next;
02827 AST_SCHED_DEL(sched, cp->retransid);
02828 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02829 if (cp->data) {
02830 ast_free(cp->data);
02831 }
02832 ast_free(cp);
02833 }
02834
02835 AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
02836
02837 AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
02838
02839 if (dialog->autokillid > -1)
02840 AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));
02841
02842 if (dialog->request_queue_sched_id > -1) {
02843 AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
02844 }
02845
02846 AST_SCHED_DEL_UNREF(sched, dialog->provisional_keepalive_sched_id, dialog_unref(dialog, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
02847
02848 if (dialog->t38id > -1) {
02849 AST_SCHED_DEL_UNREF(sched, dialog->t38id, dialog_unref(dialog, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
02850 }
02851
02852 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
02853 return NULL;
02854 }
02855
02856 static void *registry_unref(struct sip_registry *reg, char *tag)
02857 {
02858 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
02859 ASTOBJ_UNREF(reg, sip_registry_destroy);
02860 return NULL;
02861 }
02862
02863
02864 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
02865 {
02866 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
02867 return ASTOBJ_REF(reg);
02868 }
02869
02870
02871 static struct ast_udptl_protocol sip_udptl = {
02872 type: "SIP",
02873 get_udptl_info: sip_get_udptl_peer,
02874 set_udptl_peer: sip_set_udptl_peer,
02875 };
02876
02877 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
02878 __attribute__((format(printf, 2, 3)));
02879
02880
02881
02882 static const char *referstatus2str(enum referstatus rstatus)
02883 {
02884 return map_x_s(referstatusstrings, rstatus, "");
02885 }
02886
02887
02888
02889
02890 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
02891 {
02892 if (p->initreq.headers)
02893 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
02894 else
02895 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
02896
02897 copy_request(&p->initreq, req);
02898 parse_request(&p->initreq);
02899 if (req->debug)
02900 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
02901 }
02902
02903
02904 static void sip_alreadygone(struct sip_pvt *dialog)
02905 {
02906 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
02907 dialog->alreadygone = 1;
02908 }
02909
02910
02911 static int proxy_update(struct sip_proxy *proxy)
02912 {
02913
02914
02915 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
02916
02917
02918 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
02919 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
02920 return FALSE;
02921 }
02922 }
02923 proxy->last_dnsupdate = time(NULL);
02924 return TRUE;
02925 }
02926
02927
02928
02929
02930
02931 static int port_str2int(const char *pt, unsigned int standard)
02932 {
02933 int port = standard;
02934 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
02935 port = standard;
02936 }
02937
02938 return port;
02939 }
02940
02941
02942 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
02943 {
02944 struct sip_proxy *proxy;
02945
02946 if (ast_strlen_zero(name)) {
02947 return NULL;
02948 }
02949
02950 proxy = ao2_alloc(sizeof(*proxy), NULL);
02951 if (!proxy)
02952 return NULL;
02953 proxy->force = force;
02954 ast_copy_string(proxy->name, name, sizeof(proxy->name));
02955 proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
02956 proxy_update(proxy);
02957 return proxy;
02958 }
02959
02960
02961 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
02962 {
02963 if (peer && peer->outboundproxy) {
02964 if (sipdebug)
02965 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
02966 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
02967 return peer->outboundproxy;
02968 }
02969 if (global_outboundproxy.name[0]) {
02970 if (sipdebug)
02971 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
02972 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
02973 return &global_outboundproxy;
02974 }
02975 if (sipdebug)
02976 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
02977 return NULL;
02978 }
02979
02980
02981
02982
02983
02984
02985
02986 static int method_match(enum sipmethod id, const char *name)
02987 {
02988 int len = strlen(sip_methods[id].text);
02989 int l_name = name ? strlen(name) : 0;
02990
02991 return (l_name >= len && name[len] < 33 &&
02992 !strncasecmp(sip_methods[id].text, name, len));
02993 }
02994
02995
02996 static int find_sip_method(const char *msg)
02997 {
02998 int i, res = 0;
02999
03000 if (ast_strlen_zero(msg))
03001 return 0;
03002 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03003 if (method_match(i, msg))
03004 res = sip_methods[i].id;
03005 }
03006 return res;
03007 }
03008
03009
03010 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03011 {
03012 char *next, *sep;
03013 char *temp;
03014 unsigned int profile = 0;
03015 int i, found;
03016
03017 if (ast_strlen_zero(supported) )
03018 return 0;
03019 temp = ast_strdupa(supported);
03020
03021 if (sipdebug)
03022 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03023
03024 for (next = temp; next; next = sep) {
03025 found = FALSE;
03026 if ( (sep = strchr(next, ',')) != NULL)
03027 *sep++ = '\0';
03028 next = ast_skip_blanks(next);
03029 if (sipdebug)
03030 ast_debug(3, "Found SIP option: -%s-\n", next);
03031 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03032 if (!strcasecmp(next, sip_options[i].text)) {
03033 profile |= sip_options[i].id;
03034 found = TRUE;
03035 if (sipdebug)
03036 ast_debug(3, "Matched SIP option: %s\n", next);
03037 break;
03038 }
03039 }
03040
03041
03042
03043
03044
03045 if (!found)
03046 profile |= SIP_OPT_UNKNOWN;
03047
03048 if (!found && sipdebug) {
03049 if (!strncasecmp(next, "x-", 2))
03050 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03051 else
03052 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03053 }
03054 }
03055
03056 if (pvt)
03057 pvt->sipoptions = profile;
03058 return profile;
03059 }
03060
03061
03062 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
03063 {
03064 if (!sipdebug)
03065 return 0;
03066 if (debugaddr.sin_addr.s_addr) {
03067 if (((ntohs(debugaddr.sin_port) != 0)
03068 && (debugaddr.sin_port != addr->sin_port))
03069 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03070 return 0;
03071 }
03072 return 1;
03073 }
03074
03075
03076 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03077 {
03078 if (p->outboundproxy)
03079 return &p->outboundproxy->ip;
03080
03081 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03082 }
03083
03084
03085 static const char *sip_nat_mode(const struct sip_pvt *p)
03086 {
03087 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03088 }
03089
03090
03091 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03092 {
03093 if (!sipdebug)
03094 return 0;
03095 return sip_debug_test_addr(sip_real_dst(p));
03096 }
03097
03098 static int get_transport_str2enum(const char *transport)
03099 {
03100 int res = 0;
03101
03102 if (ast_strlen_zero(transport)) {
03103 return res;
03104 }
03105
03106 if (!strcasecmp(transport, "udp")) {
03107 res |= SIP_TRANSPORT_UDP;
03108 }
03109 if (!strcasecmp(transport, "tcp")) {
03110 res |= SIP_TRANSPORT_TCP;
03111 }
03112 if (!strcasecmp(transport, "tls")) {
03113 res |= SIP_TRANSPORT_TLS;
03114 }
03115
03116 return res;
03117 }
03118
03119 static inline const char *get_transport_list(struct sip_peer *peer) {
03120 switch (peer->transports) {
03121 case SIP_TRANSPORT_UDP:
03122 return "UDP";
03123 case SIP_TRANSPORT_TCP:
03124 return "TCP";
03125 case SIP_TRANSPORT_TLS:
03126 return "TLS";
03127 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03128 return "TCP,UDP";
03129 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03130 return "TLS,UDP";
03131 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03132 return "TLS,TCP";
03133 default:
03134 return peer->transports ?
03135 "TLS,TCP,UDP" : "UNKNOWN";
03136 }
03137 }
03138
03139 static inline const char *get_transport(enum sip_transport t)
03140 {
03141 switch (t) {
03142 case SIP_TRANSPORT_UDP:
03143 return "UDP";
03144 case SIP_TRANSPORT_TCP:
03145 return "TCP";
03146 case SIP_TRANSPORT_TLS:
03147 return "TLS";
03148 }
03149
03150 return "UNKNOWN";
03151 }
03152
03153 static inline const char *get_transport_pvt(struct sip_pvt *p)
03154 {
03155 if (p->outboundproxy && p->outboundproxy->transport) {
03156 set_socket_transport(&p->socket, p->outboundproxy->transport);
03157 }
03158
03159 return get_transport(p->socket.type);
03160 }
03161
03162
03163
03164
03165
03166
03167 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03168 {
03169 int res = 0;
03170 const struct sockaddr_in *dst = sip_real_dst(p);
03171
03172 ast_debug(1, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
03173
03174 if (sip_prepare_socket(p) < 0)
03175 return XMIT_ERROR;
03176
03177 if (p->socket.type == SIP_TRANSPORT_UDP) {
03178 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03179 } else if (p->socket.tcptls_session) {
03180 res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03181 } else {
03182 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03183 return XMIT_ERROR;
03184 }
03185
03186 if (res == -1) {
03187 switch (errno) {
03188 case EBADF:
03189 case EHOSTUNREACH:
03190 case ENETDOWN:
03191 case ENETUNREACH:
03192 case ECONNREFUSED:
03193 res = XMIT_ERROR;
03194 }
03195 }
03196 if (res != len)
03197 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));
03198
03199 return res;
03200 }
03201
03202
03203 static void build_via(struct sip_pvt *p)
03204 {
03205
03206 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03207
03208
03209 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03210 get_transport_pvt(p),
03211 ast_inet_ntoa(p->ourip.sin_addr),
03212 ntohs(p->ourip.sin_port), (int) p->branch, rport);
03213 }
03214
03215
03216
03217
03218
03219
03220
03221
03222 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03223 {
03224 struct sockaddr_in theirs;
03225
03226
03227
03228
03229
03230
03231
03232
03233
03234
03235
03236
03237 int want_remap;
03238
03239 *us = internip;
03240
03241 ast_ouraddrfor(them, &us->sin_addr);
03242 theirs.sin_addr = *them;
03243
03244 want_remap = localaddr &&
03245 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03246 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03247
03248 if (want_remap &&
03249 (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03250
03251 if (externexpire && time(NULL) >= externexpire) {
03252 if (stunaddr.sin_addr.s_addr) {
03253 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03254 } else {
03255 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03256 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03257 }
03258 externexpire = time(NULL) + externrefresh;
03259 }
03260 if (externip.sin_addr.s_addr)
03261 *us = externip;
03262 else
03263 ast_log(LOG_WARNING, "stun failed\n");
03264 ast_debug(1, "Target address %s is not local, substituting externip\n",
03265 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03266 } else if (p) {
03267
03268 switch (p->socket.type) {
03269 case SIP_TRANSPORT_TCP:
03270 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03271 *us = sip_tcp_desc.local_address;
03272 } else {
03273 us->sin_port = sip_tcp_desc.local_address.sin_port;
03274 }
03275 break;
03276 case SIP_TRANSPORT_TLS:
03277 if (sip_tls_desc.local_address.sin_addr.s_addr) {
03278 *us = sip_tls_desc.local_address;
03279 } else {
03280 us->sin_port = sip_tls_desc.local_address.sin_port;
03281 }
03282 break;
03283 case SIP_TRANSPORT_UDP:
03284
03285 default:
03286 if (bindaddr.sin_addr.s_addr) {
03287 *us = bindaddr;
03288 }
03289 }
03290 } else if (bindaddr.sin_addr.s_addr) {
03291 *us = bindaddr;
03292 }
03293 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
03294 }
03295
03296
03297 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03298 {
03299 char buf[80], *c = buf;
03300 struct sip_history *hist;
03301 int l;
03302
03303 vsnprintf(buf, sizeof(buf), fmt, ap);
03304 strsep(&c, "\r\n");
03305 l = strlen(buf) + 1;
03306 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03307 return;
03308 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03309 ast_free(hist);
03310 return;
03311 }
03312 memcpy(hist->event, buf, l);
03313 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03314 struct sip_history *oldest;
03315 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03316 p->history_entries--;
03317 ast_free(oldest);
03318 }
03319 AST_LIST_INSERT_TAIL(p->history, hist, list);
03320 p->history_entries++;
03321 }
03322
03323
03324 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03325 {
03326 va_list ap;
03327
03328 if (!p)
03329 return;
03330
03331 if (!p->do_history && !recordhistory && !dumphistory)
03332 return;
03333
03334 va_start(ap, fmt);
03335 append_history_va(p, fmt, ap);
03336 va_end(ap);
03337
03338 return;
03339 }
03340
03341
03342 static int retrans_pkt(const void *data)
03343 {
03344 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03345 int reschedule = DEFAULT_RETRANS;
03346 int xmitres = 0;
03347
03348
03349 sip_pvt_lock(pkt->owner);
03350
03351 if (pkt->retrans < MAX_RETRANS) {
03352 pkt->retrans++;
03353 if (!pkt->timer_t1) {
03354 if (sipdebug)
03355 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
03356 } else {
03357 int siptimer_a;
03358
03359 if (sipdebug)
03360 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03361 if (!pkt->timer_a)
03362 pkt->timer_a = 2 ;
03363 else
03364 pkt->timer_a = 2 * pkt->timer_a;
03365
03366
03367 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03368 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03369 siptimer_a = 4000;
03370
03371
03372 reschedule = siptimer_a;
03373 ast_debug(4, "** 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);
03374 }
03375
03376 if (sip_debug_test_pvt(pkt->owner)) {
03377 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03378 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03379 pkt->retrans, sip_nat_mode(pkt->owner),
03380 ast_inet_ntoa(dst->sin_addr),
03381 ntohs(dst->sin_port), pkt->data->str);
03382 }
03383
03384 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03385 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03386 sip_pvt_unlock(pkt->owner);
03387 if (xmitres == XMIT_ERROR)
03388 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03389 else
03390 return reschedule;
03391 }
03392
03393 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03394 if (pkt->is_fatal || sipdebug)
03395 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03396 pkt->owner->callid, pkt->seqno,
03397 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03398 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03399 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03400
03401 }
03402 if (xmitres == XMIT_ERROR) {
03403 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03404 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03405 } else
03406 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03407
03408 pkt->retransid = -1;
03409
03410 if (pkt->is_fatal) {
03411 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03412 sip_pvt_unlock(pkt->owner);
03413 usleep(1);
03414 sip_pvt_lock(pkt->owner);
03415 }
03416
03417 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
03418 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03419
03420 if (pkt->owner->owner) {
03421 sip_alreadygone(pkt->owner);
03422 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03423 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03424 ast_channel_unlock(pkt->owner->owner);
03425 } else {
03426
03427
03428
03429 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03430 pkt->owner->needdestroy = 1;
03431 sip_alreadygone(pkt->owner);
03432 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03433 }
03434 }
03435 }
03436
03437 if (pkt->method == SIP_BYE) {
03438
03439 if (pkt->owner->owner)
03440 ast_channel_unlock(pkt->owner->owner);
03441 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03442 pkt->owner->needdestroy = 1;
03443 }
03444
03445
03446 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03447 if (cur == pkt) {
03448 UNLINK(cur, pkt->owner->packets, prev);
03449 sip_pvt_unlock(pkt->owner);
03450 if (pkt->owner)
03451 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03452 if (pkt->data)
03453 ast_free(pkt->data);
03454 pkt->data = NULL;
03455 ast_free(pkt);
03456 return 0;
03457 }
03458 }
03459
03460 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03461 sip_pvt_unlock(pkt->owner);
03462 return 0;
03463 }
03464
03465
03466
03467
03468 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
03469 {
03470 struct sip_pkt *pkt = NULL;
03471 int siptimer_a = DEFAULT_RETRANS;
03472 int xmitres = 0;
03473 int respid;
03474
03475 if (sipmethod == SIP_INVITE) {
03476
03477 p->pendinginvite = seqno;
03478 }
03479
03480
03481
03482
03483 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03484 xmitres = __sip_xmit(p, data, len);
03485 if (xmitres == XMIT_ERROR) {
03486 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03487 return AST_FAILURE;
03488 } else
03489 return AST_SUCCESS;
03490 }
03491
03492 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03493 return AST_FAILURE;
03494
03495 if (!(pkt->data = ast_str_create(len))) {
03496 ast_free(pkt);
03497 return AST_FAILURE;
03498 }
03499 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03500 pkt->packetlen = len;
03501
03502 pkt->method = sipmethod;
03503 pkt->seqno = seqno;
03504 pkt->is_resp = resp;
03505 pkt->is_fatal = fatal;
03506 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03507 pkt->next = p->packets;
03508 p->packets = pkt;
03509 if (resp) {
03510
03511 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03512 pkt->response_code = respid;
03513 }
03514 }
03515 pkt->timer_t1 = p->timer_t1;
03516 pkt->retransid = -1;
03517 if (pkt->timer_t1)
03518 siptimer_a = pkt->timer_t1 * 2;
03519
03520
03521 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03522 if (sipdebug)
03523 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
03524
03525 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03526
03527 if (xmitres == XMIT_ERROR) {
03528 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03529 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03530 AST_SCHED_DEL(sched, pkt->retransid);
03531 p->packets = pkt->next;
03532 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03533 ast_free(pkt->data);
03534 ast_free(pkt);
03535 return AST_FAILURE;
03536 } else {
03537 return AST_SUCCESS;
03538 }
03539 }
03540
03541
03542
03543
03544
03545
03546 static int __sip_autodestruct(const void *data)
03547 {
03548 struct sip_pvt *p = (struct sip_pvt *)data;
03549
03550
03551 if (p->subscribed) {
03552 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
03553 p->subscribed = NONE;
03554 append_history(p, "Subscribestatus", "timeout");
03555 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03556 return 10000;
03557 }
03558
03559
03560 if (p->packets) {
03561 if (!p->needdestroy) {
03562 char method_str[31];
03563 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03564 append_history(p, "ReliableXmit", "timeout");
03565 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03566 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03567 p->needdestroy = 1;
03568 }
03569 }
03570 return 10000;
03571 } else {
03572
03573 __sip_pretend_ack(p);
03574 }
03575 }
03576
03577 if (p->subscribed == MWI_NOTIFICATION)
03578 if (p->relatedpeer)
03579 p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");
03580
03581
03582 p->autokillid = -1;
03583
03584 if (p->owner) {
03585 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03586 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03587 } else if (p->refer && !p->alreadygone) {
03588 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03589 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03590 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03591 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03592 } else {
03593 append_history(p, "AutoDestroy", "%s", p->callid);
03594 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03595 dialog_unlink_all(p, TRUE, TRUE);
03596
03597
03598
03599 }
03600 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03601 return 0;
03602 }
03603
03604
03605 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03606 {
03607 if (ms < 0) {
03608 if (p->timer_t1 == 0) {
03609 p->timer_t1 = global_t1;
03610 p->timer_b = global_timer_b;
03611 }
03612 ms = p->timer_t1 * 64;
03613 }
03614 if (sip_debug_test_pvt(p))
03615 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03616 if (sip_cancel_destroy(p))
03617 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
03618
03619 if (p->do_history)
03620 append_history(p, "SchedDestroy", "%d ms", ms);
03621 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03622
03623 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
03624 stop_session_timer(p);
03625 }
03626
03627
03628
03629
03630
03631 static int sip_cancel_destroy(struct sip_pvt *p)
03632 {
03633 int res = 0;
03634 if (p->autokillid > -1) {
03635 int res3;
03636
03637 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
03638 append_history(p, "CancelDestroy", "");
03639 p->autokillid = -1;
03640 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
03641 }
03642 }
03643 return res;
03644 }
03645
03646
03647
03648 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03649 {
03650 struct sip_pkt *cur, *prev = NULL;
03651 const char *msg = "Not Found";
03652 int res = FALSE;
03653
03654
03655
03656
03657
03658
03659 if (p->outboundproxy && !p->outboundproxy->force){
03660 ref_proxy(p, NULL);
03661 }
03662
03663 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
03664 if (cur->seqno != seqno || cur->is_resp != resp)
03665 continue;
03666 if (cur->is_resp || cur->method == sipmethod) {
03667 res = TRUE;
03668 msg = "Found";
03669 if (!resp && (seqno == p->pendinginvite)) {
03670 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
03671 p->pendinginvite = 0;
03672 }
03673 if (cur->retransid > -1) {
03674 if (sipdebug)
03675 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
03676 }
03677
03678
03679
03680
03681
03682
03683
03684
03685
03686
03687
03688
03689
03690
03691
03692
03693 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
03694 sip_pvt_unlock(p);
03695 usleep(1);
03696 sip_pvt_lock(p);
03697 }
03698 UNLINK(cur, p->packets, prev);
03699 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
03700 if (cur->data)
03701 ast_free(cur->data);
03702 ast_free(cur);
03703 break;
03704 }
03705 }
03706 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
03707 p->callid, resp ? "Response" : "Request", seqno, msg);
03708 return res;
03709 }
03710
03711
03712
03713 static void __sip_pretend_ack(struct sip_pvt *p)
03714 {
03715 struct sip_pkt *cur = NULL;
03716
03717 while (p->packets) {
03718 int method;
03719 if (cur == p->packets) {
03720 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
03721 return;
03722 }
03723 cur = p->packets;
03724 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
03725 __sip_ack(p, cur->seqno, cur->is_resp, method);
03726 }
03727 }
03728
03729
03730 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03731 {
03732 struct sip_pkt *cur;
03733 int res = FALSE;
03734
03735 for (cur = p->packets; cur; cur = cur->next) {
03736 if (cur->seqno == seqno && cur->is_resp == resp &&
03737 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
03738
03739 if (cur->retransid > -1) {
03740 if (sipdebug)
03741 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
03742 }
03743 AST_SCHED_DEL(sched, cur->retransid);
03744 res = TRUE;
03745 break;
03746 }
03747 }
03748 ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
03749 return res;
03750 }
03751
03752
03753
03754 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
03755 {
03756 copy_request(dst, src);
03757 parse_request(dst);
03758 }
03759
03760
03761 static void add_blank(struct sip_request *req)
03762 {
03763 if (!req->lines) {
03764
03765 ast_str_append(&req->data, 0, "\r\n");
03766 req->len = req->data->used;
03767 }
03768 }
03769
03770 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
03771 {
03772 const char *msg = NULL;
03773
03774 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
03775 msg = "183 Session Progress";
03776 }
03777
03778 if (pvt->invitestate < INV_COMPLETED) {
03779 if (with_sdp) {
03780 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
03781 } else {
03782 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
03783 }
03784 return PROVIS_KEEPALIVE_TIMEOUT;
03785 }
03786
03787 return 0;
03788 }
03789
03790 static int send_provisional_keepalive(const void *data) {
03791 struct sip_pvt *pvt = (struct sip_pvt *) data;
03792
03793 return send_provisional_keepalive_full(pvt, 0);
03794 }
03795
03796 static int send_provisional_keepalive_with_sdp(const void *data) {
03797 struct sip_pvt *pvt = (void *)data;
03798
03799 return send_provisional_keepalive_full(pvt, 1);
03800 }
03801
03802 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
03803 {
03804 AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
03805
03806 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
03807 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
03808 }
03809
03810
03811 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03812 {
03813 int res;
03814
03815 add_blank(req);
03816 if (sip_debug_test_pvt(p)) {
03817 const struct sockaddr_in *dst = sip_real_dst(p);
03818
03819 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
03820 reliable ? "Reliably " : "", sip_nat_mode(p),
03821 ast_inet_ntoa(dst->sin_addr),
03822 ntohs(dst->sin_port), req->data->str);
03823 }
03824 if (p->do_history) {
03825 struct sip_request tmp = { .rlPart1 = 0, };
03826 parse_copy(&tmp, req);
03827 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
03828 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
03829 ast_free(tmp.data);
03830 }
03831
03832
03833 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
03834 AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
03835 }
03836
03837 res = (reliable) ?
03838 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03839 __sip_xmit(p, req->data, req->len);
03840 ast_free(req->data);
03841 req->data = NULL;
03842 if (res > 0)
03843 return 0;
03844 return res;
03845 }
03846
03847
03848 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03849 {
03850 int res;
03851
03852
03853
03854
03855 if (p->outboundproxy) {
03856 p->sa = p->outboundproxy->ip;
03857 }
03858
03859 add_blank(req);
03860 if (sip_debug_test_pvt(p)) {
03861 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
03862 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->str);
03863 else
03864 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->str);
03865 }
03866 if (p->do_history) {
03867 struct sip_request tmp = { .rlPart1 = 0, };
03868 parse_copy(&tmp, req);
03869 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
03870 ast_free(tmp.data);
03871 }
03872 res = (reliable) ?
03873 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03874 __sip_xmit(p, req->data, req->len);
03875 if (req->data) {
03876 ast_free(req->data);
03877 req->data = NULL;
03878 }
03879 return res;
03880 }
03881
03882
03883 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
03884 {
03885 int res = -1;
03886 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
03887 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
03888
03889 switch (option) {
03890 case AST_OPTION_T38_STATE:
03891
03892 if (*datalen != sizeof(enum ast_t38_state)) {
03893 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
03894 return -1;
03895 }
03896
03897 sip_pvt_lock(p);
03898
03899
03900 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
03901 switch (p->t38.state) {
03902 case T38_LOCAL_REINVITE:
03903 case T38_PEER_REINVITE:
03904 state = T38_STATE_NEGOTIATING;
03905 break;
03906 case T38_ENABLED:
03907 state = T38_STATE_NEGOTIATED;
03908 break;
03909 default:
03910 state = T38_STATE_UNKNOWN;
03911 }
03912 }
03913
03914 sip_pvt_unlock(p);
03915
03916 *((enum ast_t38_state *) data) = state;
03917 res = 0;
03918
03919 break;
03920 default:
03921 break;
03922 }
03923
03924 return res;
03925 }
03926
03927
03928
03929
03930
03931 static const char *find_closing_quote(const char *start, const char *lim)
03932 {
03933 char last_char = '\0';
03934 const char *s;
03935 for (s = start; *s && s != lim; last_char = *s++) {
03936 if (*s == '"' && last_char != '\\')
03937 break;
03938 }
03939 return s;
03940 }
03941
03942
03943
03944
03945
03946
03947
03948
03949
03950
03951
03952
03953
03954 static char *get_in_brackets(char *tmp)
03955 {
03956 const char *parse = tmp;
03957 char *first_bracket;
03958
03959
03960
03961
03962
03963 while ( (first_bracket = strchr(parse, '<')) ) {
03964 char *first_quote = strchr(parse, '"');
03965
03966 if (!first_quote || first_quote > first_bracket)
03967 break;
03968
03969 parse = find_closing_quote(first_quote + 1, NULL);
03970 if (!*parse) {
03971
03972 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
03973 break;
03974 }
03975 parse++;
03976 }
03977 if (first_bracket) {
03978 char *second_bracket = strchr(first_bracket + 1, '>');
03979 if (second_bracket) {
03980 *second_bracket = '\0';
03981 tmp = first_bracket + 1;
03982 } else {
03983 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
03984 }
03985 }
03986
03987 return tmp;
03988 }
03989
03990
03991
03992
03993
03994
03995
03996
03997
03998
03999
04000
04001
04002
04003
04004
04005
04006
04007
04008 static int parse_uri(char *uri, const char *scheme,
04009 char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04010 {
04011 char *name = NULL;
04012 int error = 0;
04013
04014
04015 if (pass)
04016 *pass = "";
04017 if (port)
04018 *port = "";
04019 if (scheme) {
04020 int l;
04021 char *scheme2 = ast_strdupa(scheme);
04022 char *cur = strsep(&scheme2, ",");
04023 for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04024 l = strlen(cur);
04025 if (!strncasecmp(uri, cur, l)) {
04026 uri += l;
04027 break;
04028 }
04029 }
04030 if (ast_strlen_zero(cur)) {
04031 ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04032 error = -1;
04033 }
04034 }
04035 if (transport) {
04036 char *t, *type = "";
04037 *transport = "";
04038 if ((t = strstr(uri, "transport="))) {
04039 strsep(&t, "=");
04040 if ((type = strsep(&t, ";"))) {
04041 *transport = type;
04042 }
04043 }
04044 }
04045
04046 if (!domain) {
04047
04048
04049
04050 } else {
04051
04052
04053
04054 char *c, *dom = "";
04055
04056 if ((c = strchr(uri, '@')) == NULL) {
04057
04058 dom = uri;
04059 name = "";
04060 } else {
04061 *c++ = '\0';
04062 dom = c;
04063 name = uri;
04064 }
04065
04066
04067 dom = strsep(&dom, ";");
04068 name = strsep(&name, ";");
04069
04070 if (port && (c = strchr(dom, ':'))) {
04071 *c++ = '\0';
04072 *port = c;
04073 }
04074 if (pass && (c = strchr(name, ':'))) {
04075 *c++ = '\0';
04076 *pass = c;
04077 }
04078 *domain = dom;
04079 }
04080 if (ret_name)
04081 *ret_name = name;
04082 if (options)
04083 *options = uri ? uri : "";
04084
04085 return error;
04086 }
04087
04088
04089 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04090 {
04091 struct sip_pvt *p = chan->tech_pvt;
04092
04093 if (subclass != AST_HTML_URL)
04094 return -1;
04095
04096 ast_string_field_build(p, url, "<%s>;mode=active", data);
04097
04098 if (sip_debug_test_pvt(p))
04099 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04100
04101 switch (chan->_state) {
04102 case AST_STATE_RING:
04103 transmit_response(p, "100 Trying", &p->initreq);
04104 break;
04105 case AST_STATE_RINGING:
04106 transmit_response(p, "180 Ringing", &p->initreq);
04107 break;
04108 case AST_STATE_UP:
04109 if (!p->pendinginvite) {
04110 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04111 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04112 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04113 }
04114 break;
04115 default:
04116 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04117 }
04118
04119 return 0;
04120 }
04121
04122
04123 static const char *sip_get_callid(struct ast_channel *chan)
04124 {
04125 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04126 }
04127
04128
04129
04130 static int sip_sendtext(struct ast_channel *ast, const char *text)
04131 {
04132 struct sip_pvt *p = ast->tech_pvt;
04133 int debug = sip_debug_test_pvt(p);
04134
04135 if (debug)
04136 ast_verbose("Sending text %s on %s\n", text, ast->name);
04137 if (!p)
04138 return -1;
04139
04140
04141 if (!text)
04142 return 0;
04143 if (debug)
04144 ast_verbose("Really sending text %s on %s\n", text, ast->name);
04145 transmit_message_with_text(p, text);
04146 return 0;
04147 }
04148
04149
04150
04151
04152
04153
04154 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms)
04155 {
04156 char port[10];
04157 char ipaddr[INET_ADDRSTRLEN];
04158 char regseconds[20];
04159 char *tablename = NULL;
04160 char str_lastms[20];
04161
04162 const char *sysname = ast_config_AST_SYSTEM_NAME;
04163 char *syslabel = NULL;
04164
04165 time_t nowtime = time(NULL) + expirey;
04166 const char *fc = fullcontact ? "fullcontact" : NULL;
04167
04168 int realtimeregs = ast_check_realtime("sipregs");
04169
04170 tablename = realtimeregs ? "sipregs" : "sippeers";
04171
04172
04173 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04174 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04175 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04176 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04177
04178 if (ast_strlen_zero(sysname))
04179 sysname = NULL;
04180 else if (sip_cfg.rtsave_sysname)
04181 syslabel = "regserver";
04182
04183 if (fc) {
04184 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04185 "port", port, "regseconds", regseconds,
04186 deprecated_username ? "username" : "defaultuser", defaultuser,
04187 "useragent", useragent, "lastms", str_lastms,
04188 fc, fullcontact, syslabel, sysname, SENTINEL);
04189 } else {
04190 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04191 "port", port, "regseconds", regseconds,
04192 "useragent", useragent, "lastms", str_lastms,
04193 deprecated_username ? "username" : "defaultuser", defaultuser,
04194 syslabel, sysname, SENTINEL);
04195 }
04196 }
04197
04198
04199 static void register_peer_exten(struct sip_peer *peer, int onoff)
04200 {
04201 char multi[256];
04202 char *stringp, *ext, *context;
04203 struct pbx_find_info q = { .stacklen = 0 };
04204
04205
04206
04207
04208
04209 if (ast_strlen_zero(global_regcontext))
04210 return;
04211
04212 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04213 stringp = multi;
04214 while ((ext = strsep(&stringp, "&"))) {
04215 if ((context = strchr(ext, '@'))) {
04216 *context++ = '\0';
04217 if (!ast_context_find(context)) {
04218 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04219 continue;
04220 }
04221 } else {
04222 context = global_regcontext;
04223 }
04224 if (onoff) {
04225 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04226 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04227 ast_strdup(peer->name), ast_free_ptr, "SIP");
04228 }
04229 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04230 ast_context_remove_extension(context, ext, 1, NULL);
04231 }
04232 }
04233 }
04234
04235
04236 static void destroy_mailbox(struct sip_mailbox *mailbox)
04237 {
04238 if (mailbox->mailbox)
04239 ast_free(mailbox->mailbox);
04240 if (mailbox->context)
04241 ast_free(mailbox->context);
04242 if (mailbox->event_sub)
04243 ast_event_unsubscribe(mailbox->event_sub);
04244 ast_free(mailbox);
04245 }
04246
04247
04248 static void clear_peer_mailboxes(struct sip_peer *peer)
04249 {
04250 struct sip_mailbox *mailbox;
04251
04252 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04253 destroy_mailbox(mailbox);
04254 }
04255
04256 static void sip_destroy_peer_fn(void *peer)
04257 {
04258 sip_destroy_peer(peer);
04259 }
04260
04261
04262 static void sip_destroy_peer(struct sip_peer *peer)
04263 {
04264 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04265 if (peer->outboundproxy)
04266 ao2_ref(peer->outboundproxy, -1);
04267 peer->outboundproxy = NULL;
04268
04269
04270 if (peer->call) {
04271 dialog_unlink_all(peer->call, TRUE, TRUE);
04272 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04273 }
04274
04275
04276 if (peer->mwipvt) {
04277 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04278 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04279 }
04280
04281 if (peer->chanvars) {
04282 ast_variables_destroy(peer->chanvars);
04283 peer->chanvars = NULL;
04284 }
04285
04286 register_peer_exten(peer, FALSE);
04287 ast_free_ha(peer->ha);
04288 if (peer->selfdestruct)
04289 ast_atomic_fetchadd_int(&apeerobjs, -1);
04290 else if (peer->is_realtime) {
04291 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04292 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04293 } else
04294 ast_atomic_fetchadd_int(&speerobjs, -1);
04295 clear_realm_authentication(peer->auth);
04296 peer->auth = NULL;
04297 if (peer->dnsmgr)
04298 ast_dnsmgr_release(peer->dnsmgr);
04299 clear_peer_mailboxes(peer);
04300
04301 if (peer->socket.tcptls_session) {
04302 ao2_ref(peer->socket.tcptls_session, -1);
04303 peer->socket.tcptls_session = NULL;
04304 }
04305 }
04306
04307
04308 static void update_peer(struct sip_peer *p, int expire)
04309 {
04310 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04311 if (sip_cfg.peer_rtupdate &&
04312 (p->is_realtime || rtcachefriends)) {
04313 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04314 }
04315 }
04316
04317 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04318 {
04319 struct ast_variable *var = NULL;
04320 struct ast_flags flags = {0};
04321 char *cat = NULL;
04322 const char *insecure;
04323 while ((cat = ast_category_browse(cfg, cat))) {
04324 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04325 set_insecure_flags(&flags, insecure, -1);
04326 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04327 var = ast_category_root(cfg, cat);
04328 break;
04329 }
04330 }
04331 return var;
04332 }
04333
04334 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04335 {
04336 struct ast_variable *tmp;
04337 for (tmp = var; tmp; tmp = tmp->next) {
04338 if (!newpeername && !strcasecmp(tmp->name, "name"))
04339 newpeername = tmp->value;
04340 }
04341 return newpeername;
04342 }
04343
04344
04345
04346
04347
04348
04349
04350 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04351 {
04352 struct sip_peer *peer;
04353 struct ast_variable *var = NULL;
04354 struct ast_variable *varregs = NULL;
04355 struct ast_variable *tmp;
04356 struct ast_config *peerlist = NULL;
04357 char ipaddr[INET_ADDRSTRLEN];
04358 char portstring[6];
04359 char *cat = NULL;
04360 unsigned short portnum;
04361 int realtimeregs = ast_check_realtime("sipregs");
04362
04363
04364 if (newpeername) {
04365 if (realtimeregs)
04366 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04367
04368 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04369 if (!var && sin)
04370 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04371 if (!var) {
04372 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04373
04374
04375
04376
04377
04378
04379 if (var && sin) {
04380 for (tmp = var; tmp; tmp = tmp->next) {
04381 if (!strcasecmp(tmp->name, "host")) {
04382 struct hostent *hp;
04383 struct ast_hostent ahp;
04384 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04385
04386 ast_variables_destroy(var);
04387 var = NULL;
04388 }
04389 break;
04390 }
04391 }
04392 }
04393 }
04394 }
04395
04396 if (!var && sin) {
04397 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04398 portnum = ntohs(sin->sin_port);
04399 sprintf(portstring, "%u", portnum);
04400 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);
04401 if (var) {
04402 if (realtimeregs) {
04403 newpeername = get_name_from_variable(var, newpeername);
04404 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04405 }
04406 } else {
04407 if (realtimeregs)
04408 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04409 else
04410 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04411 if (varregs) {
04412 newpeername = get_name_from_variable(varregs, newpeername);
04413 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04414 }
04415 }
04416 if (!var) {
04417 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04418 if (peerlist) {
04419 var = get_insecure_variable_from_config(peerlist);
04420 if(var) {
04421 if (realtimeregs) {
04422 newpeername = get_name_from_variable(var, newpeername);
04423 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04424 }
04425 } else {
04426 peerlist = NULL;
04427 cat = NULL;
04428 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04429 if(peerlist) {
04430 var = get_insecure_variable_from_config(peerlist);
04431 if(var) {
04432 if (realtimeregs) {
04433 newpeername = get_name_from_variable(var, newpeername);
04434 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04435 }
04436 }
04437 }
04438 }
04439 } else {
04440 if (realtimeregs) {
04441 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04442 if (peerlist) {
04443 varregs = get_insecure_variable_from_config(peerlist);
04444 if (varregs) {
04445 newpeername = get_name_from_variable(varregs, newpeername);
04446 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04447 }
04448 }
04449 } else {
04450 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04451 if (peerlist) {
04452 var = get_insecure_variable_from_config(peerlist);
04453 if (var) {
04454 newpeername = get_name_from_variable(var, newpeername);
04455 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04456 }
04457 }
04458 }
04459 }
04460 }
04461 }
04462
04463 if (!var) {
04464 if (peerlist)
04465 ast_config_destroy(peerlist);
04466 return NULL;
04467 }
04468
04469 for (tmp = var; tmp; tmp = tmp->next) {
04470
04471 if (!strcasecmp(tmp->name, "type") &&
04472 !strcasecmp(tmp->value, "user")) {
04473 if(peerlist)
04474 ast_config_destroy(peerlist);
04475 else {
04476 ast_variables_destroy(var);
04477 ast_variables_destroy(varregs);
04478 }
04479 return NULL;
04480 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
04481 newpeername = tmp->value;
04482 }
04483 }
04484
04485 if (!newpeername) {
04486 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04487 if(peerlist)
04488 ast_config_destroy(peerlist);
04489 else
04490 ast_variables_destroy(var);
04491 return NULL;
04492 }
04493
04494
04495
04496 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04497 if (!peer) {
04498 if(peerlist)
04499 ast_config_destroy(peerlist);
04500 else {
04501 ast_variables_destroy(var);
04502 ast_variables_destroy(varregs);
04503 }
04504 return NULL;
04505 }
04506
04507 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04508
04509 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04510
04511 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04512 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04513 AST_SCHED_REPLACE_UNREF(peer->expire, sched, global_rtautoclear * 1000, expire_register, peer,
04514 unref_peer(_data, "remove registration ref"),
04515 unref_peer(peer, "remove registration ref"),
04516 ref_peer(peer, "add registration ref"));
04517 }
04518 ao2_t_link(peers, peer, "link peer into peers table");
04519 if (peer->addr.sin_addr.s_addr) {
04520 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04521 }
04522 }
04523 peer->is_realtime = 1;
04524 if (peerlist)
04525 ast_config_destroy(peerlist);
04526 else {
04527 ast_variables_destroy(var);
04528 ast_variables_destroy(varregs);
04529 }
04530
04531 return peer;
04532 }
04533
04534
04535
04536
04537
04538
04539 struct peer_finding_info {
04540 struct sip_peer tmp_peer;
04541 int which_objects;
04542 };
04543
04544
04545 static int find_by_name(void *obj, void *arg, int flags)
04546 {
04547 struct sip_peer *search = obj;
04548 struct peer_finding_info *pfi = arg;
04549
04550
04551 if (strcmp(search->name, pfi->tmp_peer.name)) {
04552 return 0;
04553 }
04554
04555 switch (pfi->which_objects) {
04556 case FINDUSERS:
04557 if (!(search->type & SIP_TYPE_USER)) {
04558 return 0;
04559 }
04560 break;
04561 case FINDPEERS:
04562 if (!(search->type & SIP_TYPE_PEER)) {
04563 return 0;
04564 }
04565 break;
04566 case FINDALLDEVICES:
04567 break;
04568 }
04569
04570 return CMP_MATCH | CMP_STOP;
04571 }
04572
04573
04574
04575
04576
04577
04578
04579
04580
04581
04582
04583
04584
04585
04586 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
04587 {
04588 struct sip_peer *p = NULL;
04589
04590 if (peer) {
04591 struct peer_finding_info pfi = {
04592 .which_objects = which_objects,
04593 };
04594 ast_copy_string(pfi.tmp_peer.name, peer, sizeof(pfi.tmp_peer.name));
04595 p = ao2_t_callback(peers, OBJ_POINTER, find_by_name, &pfi, "ao2_callback in peers table");
04596 } else if (sin) {
04597 struct sip_peer tmp_peer;
04598 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04599 tmp_peer.addr.sin_port = sin->sin_port;
04600 tmp_peer.flags[0].flags = 0;
04601 tmp_peer.transports = transport;
04602 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
04603 if (!p) {
04604 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04605 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
04606 if (p) {
04607 return p;
04608 }
04609 }
04610 }
04611
04612 if (!p && (realtime || devstate_only))
04613 p = realtime_peer(peer, sin, devstate_only);
04614
04615 return p;
04616 }
04617
04618
04619 static void do_setnat(struct sip_pvt *p, int natflags)
04620 {
04621 const char *mode = natflags ? "On" : "Off";
04622
04623 if (p->rtp) {
04624 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
04625 ast_rtp_setnat(p->rtp, natflags);
04626 }
04627 if (p->vrtp) {
04628 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
04629 ast_rtp_setnat(p->vrtp, natflags);
04630 }
04631 if (p->udptl) {
04632 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
04633 ast_udptl_setnat(p->udptl, natflags);
04634 }
04635 if (p->trtp) {
04636 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
04637 ast_rtp_setnat(p->trtp, natflags);
04638 }
04639 }
04640
04641
04642 static void change_t38_state(struct sip_pvt *p, int state)
04643 {
04644 int old = p->t38.state;
04645 struct ast_channel *chan = p->owner;
04646 struct ast_control_t38_parameters parameters = { .request_response = 0 };
04647
04648
04649 if (old == state)
04650 return;
04651
04652 p->t38.state = state;
04653 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
04654
04655
04656 if (!chan)
04657 return;
04658
04659
04660 switch (state) {
04661 case T38_PEER_REINVITE:
04662 parameters = p->t38.their_parms;
04663 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04664 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
04665 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
04666 break;
04667 case T38_ENABLED:
04668 parameters = p->t38.their_parms;
04669 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04670 parameters.request_response = AST_T38_NEGOTIATED;
04671 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
04672 break;
04673 case T38_DISABLED:
04674 if (old == T38_ENABLED) {
04675 parameters.request_response = AST_T38_TERMINATED;
04676 } else if (old == T38_LOCAL_REINVITE) {
04677 parameters.request_response = AST_T38_REFUSED;
04678 }
04679 break;
04680 case T38_LOCAL_REINVITE:
04681
04682 break;
04683 }
04684
04685
04686 if (parameters.request_response)
04687 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
04688 }
04689
04690
04691 static void set_t38_capabilities(struct sip_pvt *p)
04692 {
04693 if (p->udptl) {
04694 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
04695 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
04696 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
04697 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
04698 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
04699 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
04700 }
04701 }
04702 }
04703
04704 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
04705 {
04706 if (to_sock->tcptls_session) {
04707 ao2_ref(to_sock->tcptls_session, -1);
04708 to_sock->tcptls_session = NULL;
04709 }
04710
04711 if (from_sock->tcptls_session) {
04712 ao2_ref(from_sock->tcptls_session, +1);
04713 }
04714
04715 *to_sock = *from_sock;
04716 }
04717
04718
04719
04720
04721
04722
04723
04724
04725 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
04726 {
04727
04728
04729
04730 if (dialog->socket.type && check_request_transport(peer, dialog))
04731 return -1;
04732 copy_socket_data(&dialog->socket, &peer->socket);
04733
04734 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
04735 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
04736 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
04737 dialog->recv = dialog->sa;
04738 } else
04739 return -1;
04740
04741 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
04742 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04743 dialog->capability = peer->capability;
04744 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
04745 (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
04746 !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
04747 dialog->vrtp) {
04748 ast_rtp_destroy(dialog->vrtp);
04749 dialog->vrtp = NULL;
04750 }
04751 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
04752 ast_rtp_destroy(dialog->trtp);
04753 dialog->trtp = NULL;
04754 }
04755 dialog->prefs = peer->prefs;
04756 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
04757 if (!dialog->udptl) {
04758
04759 dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
04760 }
04761 dialog->t38_maxdatagram = peer->t38_maxdatagram;
04762 set_t38_capabilities(dialog);
04763 } else if (dialog->udptl) {
04764 ast_udptl_destroy(dialog->udptl);
04765 dialog->udptl = NULL;
04766 }
04767 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04768
04769 if (dialog->rtp) {
04770 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04771 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04772 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
04773 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
04774 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
04775 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
04776 ast_rtp_set_constantssrc(dialog->rtp);
04777 }
04778
04779 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
04780 dialog->autoframing = peer->autoframing;
04781 }
04782 if (dialog->vrtp) {
04783 ast_rtp_setdtmf(dialog->vrtp, 0);
04784 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
04785 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
04786 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
04787 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
04788 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
04789 ast_rtp_set_constantssrc(dialog->vrtp);
04790 }
04791 }
04792 if (dialog->trtp) {
04793 ast_rtp_setdtmf(dialog->trtp, 0);
04794 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
04795 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
04796 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
04797 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
04798 }
04799
04800 ast_string_field_set(dialog, peername, peer->name);
04801 ast_string_field_set(dialog, authname, peer->username);
04802 ast_string_field_set(dialog, username, peer->username);
04803 ast_string_field_set(dialog, peersecret, peer->secret);
04804 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
04805 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
04806 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
04807 ast_string_field_set(dialog, tohost, peer->tohost);
04808 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
04809 ast_string_field_set(dialog, context, peer->context);
04810 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
04811 ref_proxy(dialog, obproxy_get(dialog, peer));
04812 dialog->callgroup = peer->callgroup;
04813 dialog->pickupgroup = peer->pickupgroup;
04814 dialog->allowtransfer = peer->allowtransfer;
04815 dialog->jointnoncodeccapability = dialog->noncodeccapability;
04816 dialog->rtptimeout = peer->rtptimeout;
04817 dialog->peerauth = peer->auth;
04818 dialog->maxcallbitrate = peer->maxcallbitrate;
04819 if (ast_strlen_zero(dialog->tohost))
04820 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
04821 if (!ast_strlen_zero(peer->fromdomain)) {
04822 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
04823 if (!dialog->initreq.headers) {
04824 char *c;
04825 char *tmpcall = ast_strdupa(dialog->callid);
04826
04827 c = strchr(tmpcall, '@');
04828 if (c) {
04829 *c = '\0';
04830 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
04831 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
04832 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
04833 }
04834 }
04835 }
04836 if (!ast_strlen_zero(peer->fromuser))
04837 ast_string_field_set(dialog, fromuser, peer->fromuser);
04838 if (!ast_strlen_zero(peer->language))
04839 ast_string_field_set(dialog, language, peer->language);
04840
04841
04842
04843
04844 if (peer->maxms && peer->lastms)
04845 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
04846 else
04847 dialog->timer_t1 = peer->timer_t1;
04848
04849
04850
04851 if (peer->timer_b)
04852 dialog->timer_b = peer->timer_b;
04853 else
04854 dialog->timer_b = 64 * dialog->timer_t1;
04855
04856 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
04857 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
04858 dialog->noncodeccapability |= AST_RTP_DTMF;
04859 else
04860 dialog->noncodeccapability &= ~AST_RTP_DTMF;
04861 if (peer->call_limit)
04862 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
04863 if (!dialog->portinuri)
04864 dialog->portinuri = peer->portinuri;
04865
04866 return 0;
04867 }
04868
04869
04870
04871
04872 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
04873 {
04874 struct hostent *hp;
04875 struct ast_hostent ahp;
04876 struct sip_peer *peer;
04877 char *port;
04878 int portno = 0;
04879 char host[MAXHOSTNAMELEN], *hostn;
04880 char peername[256];
04881 int srv_ret = 0;
04882
04883 ast_copy_string(peername, opeer, sizeof(peername));
04884 port = strchr(peername, ':');
04885 if (port) {
04886 *port++ = '\0';
04887 dialog->portinuri = 1;
04888 }
04889 dialog->sa.sin_family = AF_INET;
04890 dialog->timer_t1 = global_t1;
04891 dialog->timer_b = global_timer_b;
04892 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
04893
04894 if (peer) {
04895 int res;
04896 if (newdialog) {
04897 set_socket_transport(&dialog->socket, 0);
04898 }
04899 res = create_addr_from_peer(dialog, peer);
04900 if (!ast_strlen_zero(port)) {
04901 if ((portno = atoi(port))) {
04902 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
04903 }
04904 }
04905 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
04906 return res;
04907 }
04908
04909 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04910
04911 ast_string_field_set(dialog, tohost, peername);
04912
04913
04914 ref_proxy(dialog, obproxy_get(dialog, NULL));
04915
04916 if (sin) {
04917
04918 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
04919 if (!sin->sin_port) {
04920 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
04921 } else {
04922 portno = ntohs(sin->sin_port);
04923 }
04924 } else {
04925
04926
04927
04928
04929
04930
04931 hostn = peername;
04932
04933
04934
04935 if (!port && global_srvlookup) {
04936 char service[MAXHOSTNAMELEN];
04937 int tportno;
04938
04939 snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
04940 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
04941 if (srv_ret > 0) {
04942 hostn = host;
04943 portno = tportno;
04944 }
04945 }
04946 if (!portno)
04947 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
04948 hp = ast_gethostbyname(hostn, &ahp);
04949 if (!hp) {
04950 ast_log(LOG_WARNING, "No such host: %s\n", peername);
04951 return -1;
04952 }
04953 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
04954 }
04955
04956 if (!dialog->socket.type)
04957 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
04958 if (!dialog->socket.port)
04959 dialog->socket.port = bindaddr.sin_port;
04960 dialog->sa.sin_port = htons(portno);
04961 dialog->recv = dialog->sa;
04962 return 0;
04963 }
04964
04965
04966
04967
04968 static int auto_congest(const void *arg)
04969 {
04970 struct sip_pvt *p = (struct sip_pvt *)arg;
04971
04972 sip_pvt_lock(p);
04973 p->initid = -1;
04974 if (p->owner) {
04975
04976 if (!ast_channel_trylock(p->owner)) {
04977 append_history(p, "Cong", "Auto-congesting (timer)");
04978 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
04979 ast_channel_unlock(p->owner);
04980 }
04981
04982
04983 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04984 }
04985 sip_pvt_unlock(p);
04986 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
04987 return 0;
04988 }
04989
04990
04991
04992
04993 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
04994 {
04995 int res;
04996 struct sip_pvt *p = ast->tech_pvt;
04997 struct varshead *headp;
04998 struct ast_var_t *current;
04999 const char *referer = NULL;
05000
05001 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05002 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05003 return -1;
05004 }
05005
05006
05007 headp=&ast->varshead;
05008 AST_LIST_TRAVERSE(headp, current, entries) {
05009
05010 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05011 p->options->vxml_url = ast_var_value(current);
05012 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05013 p->options->uri_options = ast_var_value(current);
05014 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05015
05016 p->options->addsipheaders = 1;
05017 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05018
05019 p->options->transfer = 1;
05020 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05021
05022 referer = ast_var_value(current);
05023 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05024
05025 p->options->replaces = ast_var_value(current);
05026 }
05027 }
05028
05029 res = 0;
05030 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05031
05032 if (p->options->transfer) {
05033 char buf[SIPBUFSIZE/2];
05034
05035 if (referer) {
05036 if (sipdebug)
05037 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05038 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05039 } else
05040 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05041 ast_string_field_set(p, cid_name, buf);
05042 }
05043 ast_debug(1, "Outgoing Call for %s\n", p->username);
05044
05045 res = update_call_counter(p, INC_CALL_RINGING);
05046
05047 if (res == -1) {
05048 ast->hangupcause = AST_CAUSE_USER_BUSY;
05049 return res;
05050 }
05051 p->callingpres = ast->cid.cid_pres;
05052 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05053 p->jointnoncodeccapability = p->noncodeccapability;
05054
05055
05056 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05057 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05058 res = -1;
05059 } else {
05060 int xmitres;
05061
05062 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05063 if (xmitres == XMIT_ERROR)
05064 return -1;
05065 p->invitestate = INV_CALLING;
05066
05067
05068 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05069 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05070 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05071 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05072 }
05073 return res;
05074 }
05075
05076
05077
05078 static void sip_registry_destroy(struct sip_registry *reg)
05079 {
05080
05081 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05082
05083 if (reg->call) {
05084
05085
05086 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05087 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05088 dialog_unlink_all(reg->call, TRUE, TRUE);
05089 reg->call = dialog_unref(reg->call, "unref reg->call");
05090
05091 }
05092 AST_SCHED_DEL(sched, reg->expire);
05093 AST_SCHED_DEL(sched, reg->timeout);
05094
05095 ast_string_field_free_memory(reg);
05096 ast_atomic_fetchadd_int(®objs, -1);
05097 ast_dnsmgr_release(reg->dnsmgr);
05098 ast_free(reg);
05099 }
05100
05101
05102 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05103 {
05104 struct sip_request *req;
05105
05106 if (p->stimer) {
05107 ast_free(p->stimer);
05108 p->stimer = NULL;
05109 }
05110
05111 if (sip_debug_test_pvt(p))
05112 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05113
05114 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05115 update_call_counter(p, DEC_CALL_LIMIT);
05116 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05117 }
05118
05119
05120 if (p->owner) {
05121 if (lockowner)
05122 ast_channel_lock(p->owner);
05123 if (option_debug)
05124 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05125 p->owner->tech_pvt = NULL;
05126
05127 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05128 if (lockowner)
05129 ast_channel_unlock(p->owner);
05130
05131 usleep(1);
05132 }
05133
05134
05135 if (p->relatedpeer && p->relatedpeer->mwipvt)
05136 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05137 if (p->relatedpeer && p->relatedpeer->call == p)
05138 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05139
05140 if (p->relatedpeer)
05141 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05142
05143 if (p->registry) {
05144 if (p->registry->call == p)
05145 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05146 p->registry = registry_unref(p->registry, "delete p->registry");
05147 }
05148
05149 if (dumphistory)
05150 sip_dump_history(p);
05151
05152 if (p->options)
05153 ast_free(p->options);
05154
05155 if (p->notify_headers) {
05156 ast_variables_destroy(p->notify_headers);
05157 p->notify_headers = NULL;
05158 }
05159 if (p->rtp) {
05160 ast_rtp_destroy(p->rtp);
05161 }
05162 if (p->vrtp) {
05163 ast_rtp_destroy(p->vrtp);
05164 }
05165 if (p->trtp) {
05166 while (ast_rtp_get_bridged(p->trtp))
05167 usleep(1);
05168 ast_rtp_destroy(p->trtp);
05169 }
05170 if (p->udptl)
05171 ast_udptl_destroy(p->udptl);
05172 if (p->refer)
05173 ast_free(p->refer);
05174 if (p->route) {
05175 free_old_route(p->route);
05176 p->route = NULL;
05177 }
05178 if (p->initreq.data)
05179 ast_free(p->initreq.data);
05180
05181
05182 if (p->stimer) {
05183 p->stimer->quit_flag = 1;
05184 if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05185 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05186 dialog_unref(p, "removing session timer ref"));
05187 }
05188 ast_free(p->stimer);
05189 p->stimer = NULL;
05190 }
05191
05192
05193 if (p->history) {
05194 struct sip_history *hist;
05195 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05196 ast_free(hist);
05197 p->history_entries--;
05198 }
05199 ast_free(p->history);
05200 p->history = NULL;
05201 }
05202
05203 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05204 ast_free(req);
05205 }
05206
05207 if (p->chanvars) {
05208 ast_variables_destroy(p->chanvars);
05209 p->chanvars = NULL;
05210 }
05211
05212 ast_string_field_free_memory(p);
05213
05214 if (p->socket.tcptls_session) {
05215 ao2_ref(p->socket.tcptls_session, -1);
05216 p->socket.tcptls_session = NULL;
05217 }
05218 }
05219
05220
05221
05222
05223
05224
05225
05226
05227
05228
05229
05230
05231
05232
05233
05234 static int update_call_counter(struct sip_pvt *fup, int event)
05235 {
05236 char name[256];
05237 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05238 int outgoing = fup->outgoing_call;
05239 struct sip_peer *p = NULL;
05240
05241 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05242
05243
05244
05245
05246 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05247 return 0;
05248
05249 ast_copy_string(name, fup->username, sizeof(name));
05250
05251
05252 if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) {
05253 inuse = &p->inUse;
05254 call_limit = &p->call_limit;
05255 inringing = &p->inRinging;
05256 ast_copy_string(name, fup->peername, sizeof(name));
05257 }
05258 if (!p) {
05259 ast_debug(2, "%s is not a local device, no call limit\n", name);
05260 return 0;
05261 }
05262
05263 switch(event) {
05264
05265 case DEC_CALL_LIMIT:
05266
05267 if (inuse) {
05268 sip_pvt_lock(fup);
05269 ao2_lock(p);
05270 if (*inuse > 0) {
05271 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05272 (*inuse)--;
05273 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05274 }
05275 } else {
05276 *inuse = 0;
05277 }
05278 ao2_unlock(p);
05279 sip_pvt_unlock(fup);
05280 }
05281
05282
05283 if (inringing) {
05284 sip_pvt_lock(fup);
05285 ao2_lock(p);
05286 if (*inringing > 0) {
05287 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05288 (*inringing)--;
05289 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05290 }
05291 } else {
05292 *inringing = 0;
05293 }
05294 ao2_unlock(p);
05295 sip_pvt_unlock(fup);
05296 }
05297
05298
05299 sip_pvt_lock(fup);
05300 ao2_lock(p);
05301 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
05302 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05303 ao2_unlock(p);
05304 sip_pvt_unlock(fup);
05305 sip_peer_hold(fup, FALSE);
05306 } else {
05307 ao2_unlock(p);
05308 sip_pvt_unlock(fup);
05309 }
05310 if (sipdebug)
05311 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05312 break;
05313
05314 case INC_CALL_RINGING:
05315 case INC_CALL_LIMIT:
05316
05317 if (*call_limit > 0 ) {
05318 if (*inuse >= *call_limit) {
05319 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05320 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05321 return -1;
05322 }
05323 }
05324 if (inringing && (event == INC_CALL_RINGING)) {
05325 sip_pvt_lock(fup);
05326 ao2_lock(p);
05327 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05328 (*inringing)++;
05329 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05330 }
05331 ao2_unlock(p);
05332 sip_pvt_unlock(fup);
05333 }
05334 if (inuse) {
05335 sip_pvt_lock(fup);
05336 ao2_lock(p);
05337 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05338 (*inuse)++;
05339 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05340 }
05341 ao2_unlock(p);
05342 sip_pvt_unlock(fup);
05343 }
05344 if (sipdebug) {
05345 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05346 }
05347 break;
05348
05349 case DEC_CALL_RINGING:
05350 if (inringing) {
05351 sip_pvt_lock(fup);
05352 ao2_lock(p);
05353 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05354 if (*inringing > 0) {
05355 (*inringing)--;
05356 }
05357 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05358 }
05359 ao2_unlock(p);
05360 sip_pvt_unlock(fup);
05361 }
05362 break;
05363
05364 default:
05365 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05366 }
05367
05368 if (p) {
05369 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05370 unref_peer(p, "update_call_counter: unref_peer from call counter");
05371 }
05372 return 0;
05373 }
05374
05375
05376 static void sip_destroy_fn(void *p)
05377 {
05378 sip_destroy(p);
05379 }
05380
05381
05382
05383
05384
05385
05386 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05387 {
05388 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05389 __sip_destroy(p, TRUE, TRUE);
05390 return NULL;
05391 }
05392
05393
05394 static int hangup_sip2cause(int cause)
05395 {
05396
05397
05398 switch(cause) {
05399 case 401:
05400 return AST_CAUSE_CALL_REJECTED;
05401 case 403:
05402 return AST_CAUSE_CALL_REJECTED;
05403 case 404:
05404 return AST_CAUSE_UNALLOCATED;
05405 case 405:
05406 return AST_CAUSE_INTERWORKING;
05407 case 407:
05408 return AST_CAUSE_CALL_REJECTED;
05409 case 408:
05410 return AST_CAUSE_NO_USER_RESPONSE;
05411 case 409:
05412 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05413 case 410:
05414 return AST_CAUSE_NUMBER_CHANGED;
05415 case 411:
05416 return AST_CAUSE_INTERWORKING;
05417 case 413:
05418 return AST_CAUSE_INTERWORKING;
05419 case 414:
05420 return AST_CAUSE_INTERWORKING;
05421 case 415:
05422 return AST_CAUSE_INTERWORKING;
05423 case 420:
05424 return AST_CAUSE_NO_ROUTE_DESTINATION;
05425 case 480:
05426 return AST_CAUSE_NO_ANSWER;
05427 case 481:
05428 return AST_CAUSE_INTERWORKING;
05429 case 482:
05430 return AST_CAUSE_INTERWORKING;
05431 case 483:
05432 return AST_CAUSE_NO_ANSWER;
05433 case 484:
05434 return AST_CAUSE_INVALID_NUMBER_FORMAT;
05435 case 485:
05436 return AST_CAUSE_UNALLOCATED;
05437 case 486:
05438 return AST_CAUSE_BUSY;
05439 case 487:
05440 return AST_CAUSE_INTERWORKING;
05441 case 488:
05442 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05443 case 491:
05444 return AST_CAUSE_INTERWORKING;
05445 case 493:
05446 return AST_CAUSE_INTERWORKING;
05447 case 500:
05448 return AST_CAUSE_FAILURE;
05449 case 501:
05450 return AST_CAUSE_FACILITY_REJECTED;
05451 case 502:
05452 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05453 case 503:
05454 return AST_CAUSE_CONGESTION;
05455 case 504:
05456 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05457 case 505:
05458 return AST_CAUSE_INTERWORKING;
05459 case 600:
05460 return AST_CAUSE_USER_BUSY;
05461 case 603:
05462 return AST_CAUSE_CALL_REJECTED;
05463 case 604:
05464 return AST_CAUSE_UNALLOCATED;
05465 case 606:
05466 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05467 default:
05468 return AST_CAUSE_NORMAL;
05469 }
05470
05471 return 0;
05472 }
05473
05474
05475
05476
05477
05478
05479
05480
05481
05482
05483
05484
05485
05486
05487
05488
05489
05490
05491
05492
05493
05494
05495
05496
05497
05498
05499
05500
05501
05502
05503
05504
05505
05506 static const char *hangup_cause2sip(int cause)
05507 {
05508 switch (cause) {
05509 case AST_CAUSE_UNALLOCATED:
05510 case AST_CAUSE_NO_ROUTE_DESTINATION:
05511 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
05512 return "404 Not Found";
05513 case AST_CAUSE_CONGESTION:
05514 case AST_CAUSE_SWITCH_CONGESTION:
05515 return "503 Service Unavailable";
05516 case AST_CAUSE_NO_USER_RESPONSE:
05517 return "408 Request Timeout";
05518 case AST_CAUSE_NO_ANSWER:
05519 case AST_CAUSE_UNREGISTERED:
05520 return "480 Temporarily unavailable";
05521 case AST_CAUSE_CALL_REJECTED:
05522 return "403 Forbidden";
05523 case AST_CAUSE_NUMBER_CHANGED:
05524 return "410 Gone";
05525 case AST_CAUSE_NORMAL_UNSPECIFIED:
05526 return "480 Temporarily unavailable";
05527 case AST_CAUSE_INVALID_NUMBER_FORMAT:
05528 return "484 Address incomplete";
05529 case AST_CAUSE_USER_BUSY:
05530 return "486 Busy here";
05531 case AST_CAUSE_FAILURE:
05532 return "500 Server internal failure";
05533 case AST_CAUSE_FACILITY_REJECTED:
05534 return "501 Not Implemented";
05535 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05536 return "503 Service Unavailable";
05537
05538 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05539 return "502 Bad Gateway";
05540 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
05541 return "488 Not Acceptable Here";
05542
05543 case AST_CAUSE_NOTDEFINED:
05544 default:
05545 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05546 return NULL;
05547 }
05548
05549
05550 return 0;
05551 }
05552
05553
05554
05555
05556 static int sip_hangup(struct ast_channel *ast)
05557 {
05558 struct sip_pvt *p = ast->tech_pvt;
05559 int needcancel = FALSE;
05560 int needdestroy = 0;
05561 struct ast_channel *oldowner = ast;
05562
05563 if (!p) {
05564 ast_debug(1, "Asked to hangup channel that was not connected\n");
05565 return 0;
05566 }
05567 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
05568 ast_debug(1, "This call was answered elsewhere");
05569 append_history(p, "Cancel", "Call answered elsewhere");
05570 p->answered_elsewhere = TRUE;
05571 }
05572
05573
05574 if (p->owner)
05575 p->hangupcause = p->owner->hangupcause;
05576
05577 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05578 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05579 if (sipdebug)
05580 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05581 update_call_counter(p, DEC_CALL_LIMIT);
05582 }
05583 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05584 if (p->autokillid > -1 && sip_cancel_destroy(p))
05585 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
05586 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05587 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
05588 p->needdestroy = 0;
05589 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05590 sip_pvt_lock(p);
05591 p->owner = NULL;
05592 sip_pvt_unlock(p);
05593 return 0;
05594 }
05595
05596 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
05597 if (p->refer)
05598 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
05599 else
05600 ast_debug(1, "Hanging up zombie call. Be scared.\n");
05601 } else
05602 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
05603
05604 sip_pvt_lock(p);
05605 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05606 if (sipdebug)
05607 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05608 update_call_counter(p, DEC_CALL_LIMIT);
05609 }
05610
05611
05612 if (p->owner != ast) {
05613 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
05614 sip_pvt_unlock(p);
05615 return 0;
05616 }
05617
05618
05619 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
05620 needcancel = TRUE;
05621 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
05622 }
05623
05624 stop_media_flows(p);
05625
05626 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
05627
05628
05629 if (p->dsp)
05630 ast_dsp_free(p->dsp);
05631
05632 p->owner = NULL;
05633 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
05634
05635 ast_module_unref(ast_module_info->self);
05636
05637
05638
05639
05640
05641
05642 if (p->alreadygone)
05643 needdestroy = 1;
05644 else if (p->invitestate != INV_CALLING)
05645 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05646
05647
05648 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
05649 if (needcancel) {
05650 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05651
05652
05653 if (p->invitestate == INV_CALLING) {
05654
05655 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
05656 __sip_pretend_ack(p);
05657
05658 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05659 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
05660 } else {
05661 struct sip_pkt *cur;
05662
05663 for (cur = p->packets; cur; cur = cur->next) {
05664 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
05665 }
05666 p->invitestate = INV_CANCELLED;
05667
05668 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
05669
05670
05671 needdestroy = 0;
05672 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05673 }
05674 } else {
05675 const char *res;
05676 AST_SCHED_DEL(sched, p->provisional_keepalive_sched_id);
05677 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
05678 transmit_response_reliable(p, res, &p->initreq);
05679 else
05680 transmit_response_reliable(p, "603 Declined", &p->initreq);
05681 p->invitestate = INV_TERMINATED;
05682 }
05683 } else {
05684 if (p->stimer->st_active == TRUE) {
05685 stop_session_timer(p);
05686 }
05687
05688 if (!p->pendinginvite) {
05689 struct ast_channel *bridge = ast_bridged_channel(oldowner);
05690 char *audioqos = "";
05691 char *videoqos = "";
05692 char *textqos = "";
05693
05694
05695
05696
05697 while (bridge && ast_channel_trylock(bridge)) {
05698 sip_pvt_unlock(p);
05699 do {
05700
05701 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
05702 } while (sip_pvt_trylock(p));
05703 bridge = ast_bridged_channel(oldowner);
05704 }
05705
05706 if (p->rtp)
05707 ast_rtp_set_vars(oldowner, p->rtp);
05708
05709 if (bridge) {
05710 struct sip_pvt *q = bridge->tech_pvt;
05711
05712 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
05713 ast_rtp_set_vars(bridge, q->rtp);
05714 ast_channel_unlock(bridge);
05715 }
05716
05717 if (p->vrtp)
05718 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
05719 if (p->trtp)
05720 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
05721
05722 if (oldowner->_state == AST_STATE_UP) {
05723 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
05724 }
05725
05726
05727 if (p->do_history) {
05728 if (p->rtp)
05729 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
05730 if (p->vrtp)
05731 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
05732 if (p->trtp)
05733 append_history(p, "RTCPtext", "Quality:%s", textqos);
05734 }
05735 if (p->rtp && oldowner)
05736 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
05737 if (p->vrtp && oldowner)
05738 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
05739 if (p->trtp && oldowner)
05740 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
05741 } else {
05742
05743
05744 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
05745 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
05746 AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
05747 if (sip_cancel_destroy(p))
05748 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
05749 }
05750 }
05751 }
05752 if (needdestroy)
05753 p->needdestroy = 1;
05754 sip_pvt_unlock(p);
05755 return 0;
05756 }
05757
05758
05759 static void try_suggested_sip_codec(struct sip_pvt *p)
05760 {
05761 int fmt;
05762 const char *codec;
05763
05764 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
05765 if (!codec)
05766 return;
05767
05768 fmt = ast_getformatbyname(codec);
05769 if (fmt) {
05770 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
05771 if (p->jointcapability & fmt) {
05772 p->jointcapability &= fmt;
05773 p->capability &= fmt;
05774 } else
05775 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
05776 } else
05777 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
05778 return;
05779 }
05780
05781
05782
05783 static int sip_answer(struct ast_channel *ast)
05784 {
05785 int res = 0;
05786 struct sip_pvt *p = ast->tech_pvt;
05787
05788 sip_pvt_lock(p);
05789 if (ast->_state != AST_STATE_UP) {
05790 try_suggested_sip_codec(p);
05791
05792 ast_setstate(ast, AST_STATE_UP);
05793 ast_debug(1, "SIP answering channel: %s\n", ast->name);
05794 ast_rtp_new_source(p->rtp);
05795 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
05796 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
05797 }
05798 sip_pvt_unlock(p);
05799 return res;
05800 }
05801
05802
05803 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
05804 {
05805 struct sip_pvt *p = ast->tech_pvt;
05806 int res = 0;
05807
05808 switch (frame->frametype) {
05809 case AST_FRAME_VOICE:
05810 if (!(frame->subclass & ast->nativeformats)) {
05811 char s1[512], s2[512], s3[512];
05812 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
05813 frame->subclass,
05814 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
05815 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
05816 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
05817 ast->readformat,
05818 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
05819 ast->writeformat);
05820 return 0;
05821 }
05822 if (p) {
05823 sip_pvt_lock(p);
05824 if (p->rtp) {
05825
05826 if ((ast->_state != AST_STATE_UP) &&
05827 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05828 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05829 ast_rtp_new_source(p->rtp);
05830 if (!global_prematuremediafilter) {
05831 p->invitestate = INV_EARLY_MEDIA;
05832 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
05833 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05834 }
05835 } else if (p->t38.state == T38_ENABLED) {
05836
05837 } else {
05838 p->lastrtptx = time(NULL);
05839 res = ast_rtp_write(p->rtp, frame);
05840 }
05841 }
05842 sip_pvt_unlock(p);
05843 }
05844 break;
05845 case AST_FRAME_VIDEO:
05846 if (p) {
05847 sip_pvt_lock(p);
05848 if (p->vrtp) {
05849
05850 if ((ast->_state != AST_STATE_UP) &&
05851 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05852 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05853 p->invitestate = INV_EARLY_MEDIA;
05854 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
05855 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05856 }
05857 p->lastrtptx = time(NULL);
05858 res = ast_rtp_write(p->vrtp, frame);
05859 }
05860 sip_pvt_unlock(p);
05861 }
05862 break;
05863 case AST_FRAME_TEXT:
05864 if (p) {
05865 sip_pvt_lock(p);
05866 if (p->red) {
05867 red_buffer_t140(p->trtp, frame);
05868 } else {
05869 if (p->trtp) {
05870
05871 if ((ast->_state != AST_STATE_UP) &&
05872 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05873 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05874 p->invitestate = INV_EARLY_MEDIA;
05875 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
05876 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05877 }
05878 p->lastrtptx = time(NULL);
05879 res = ast_rtp_write(p->trtp, frame);
05880 }
05881 }
05882 sip_pvt_unlock(p);
05883 }
05884 break;
05885 case AST_FRAME_IMAGE:
05886 return 0;
05887 break;
05888 case AST_FRAME_MODEM:
05889 if (p) {
05890 sip_pvt_lock(p);
05891
05892
05893
05894
05895 if ((ast->_state == AST_STATE_UP) &&
05896 p->udptl &&
05897 (p->t38.state == T38_ENABLED)) {
05898 res = ast_udptl_write(p->udptl, frame);
05899 }
05900 sip_pvt_unlock(p);
05901 }
05902 break;
05903 default:
05904 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
05905 return 0;
05906 }
05907
05908 return res;
05909 }
05910
05911
05912
05913 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
05914 {
05915 int ret = -1;
05916 struct sip_pvt *p;
05917
05918 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
05919 ast_debug(1, "New channel is zombie\n");
05920 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
05921 ast_debug(1, "Old channel is zombie\n");
05922
05923 if (!newchan || !newchan->tech_pvt) {
05924 if (!newchan)
05925 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
05926 else
05927 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
05928 return -1;
05929 }
05930 p = newchan->tech_pvt;
05931
05932 sip_pvt_lock(p);
05933 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
05934 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
05935 if (p->owner != oldchan)
05936 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
05937 else {
05938 p->owner = newchan;
05939
05940
05941
05942
05943
05944
05945 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
05946 ret = 0;
05947 }
05948 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
05949
05950 sip_pvt_unlock(p);
05951 return ret;
05952 }
05953
05954 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
05955 {
05956 struct sip_pvt *p = ast->tech_pvt;
05957 int res = 0;
05958
05959 sip_pvt_lock(p);
05960 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
05961 case SIP_DTMF_INBAND:
05962 res = -1;
05963 break;
05964 case SIP_DTMF_RFC2833:
05965 if (p->rtp)
05966 ast_rtp_senddigit_begin(p->rtp, digit);
05967 break;
05968 default:
05969 break;
05970 }
05971 sip_pvt_unlock(p);
05972
05973 return res;
05974 }
05975
05976
05977
05978 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
05979 {
05980 struct sip_pvt *p = ast->tech_pvt;
05981 int res = 0;
05982
05983 sip_pvt_lock(p);
05984 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
05985 case SIP_DTMF_INFO:
05986 case SIP_DTMF_SHORTINFO:
05987 transmit_info_with_digit(p, digit, duration);
05988 break;
05989 case SIP_DTMF_RFC2833:
05990 if (p->rtp)
05991 ast_rtp_senddigit_end(p->rtp, digit);
05992 break;
05993 case SIP_DTMF_INBAND:
05994 res = -1;
05995 break;
05996 }
05997 sip_pvt_unlock(p);
05998
05999 return res;
06000 }
06001
06002
06003 static int sip_transfer(struct ast_channel *ast, const char *dest)
06004 {
06005 struct sip_pvt *p = ast->tech_pvt;
06006 int res;
06007
06008 if (dest == NULL)
06009 dest = "";
06010 sip_pvt_lock(p);
06011 if (ast->_state == AST_STATE_RING)
06012 res = sip_sipredirect(p, dest);
06013 else
06014 res = transmit_refer(p, dest);
06015 sip_pvt_unlock(p);
06016 return res;
06017 }
06018
06019
06020 static void interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06021 {
06022 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06023 return;
06024 }
06025 switch (parameters->request_response) {
06026 case AST_T38_NEGOTIATED:
06027 case AST_T38_REQUEST_NEGOTIATE:
06028
06029 if (!parameters->max_ifp) {
06030 change_t38_state(p, T38_DISABLED);
06031 if (p->t38.state == T38_PEER_REINVITE) {
06032 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
06033 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06034 }
06035 break;
06036 } else if (p->t38.state == T38_PEER_REINVITE) {
06037 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
06038 p->t38.our_parms = *parameters;
06039
06040
06041
06042 if (!p->t38.their_parms.fill_bit_removal) {
06043 p->t38.our_parms.fill_bit_removal = FALSE;
06044 }
06045 if (!p->t38.their_parms.transcoding_mmr) {
06046 p->t38.our_parms.transcoding_mmr = FALSE;
06047 }
06048 if (!p->t38.their_parms.transcoding_jbig) {
06049 p->t38.our_parms.transcoding_jbig = FALSE;
06050 }
06051 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06052 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06053 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06054 change_t38_state(p, T38_ENABLED);
06055 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06056 } else if (p->t38.state != T38_ENABLED) {
06057 p->t38.our_parms = *parameters;
06058 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06059 change_t38_state(p, T38_LOCAL_REINVITE);
06060 if (!p->pendinginvite) {
06061 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06062 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06063 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06064 }
06065 }
06066 break;
06067 case AST_T38_TERMINATED:
06068 case AST_T38_REFUSED:
06069 case AST_T38_REQUEST_TERMINATE:
06070 if (p->t38.state == T38_PEER_REINVITE) {
06071 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
06072 change_t38_state(p, T38_DISABLED);
06073 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06074 } else if (p->t38.state == T38_ENABLED)
06075 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06076 break;
06077 default:
06078 break;
06079 }
06080 }
06081
06082
06083
06084
06085
06086
06087 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06088 {
06089 struct sip_pvt *p = ast->tech_pvt;
06090 int res = 0;
06091
06092 sip_pvt_lock(p);
06093 switch(condition) {
06094 case AST_CONTROL_RINGING:
06095 if (ast->_state == AST_STATE_RING) {
06096 p->invitestate = INV_EARLY_MEDIA;
06097 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06098 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06099
06100 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06101 ast_set_flag(&p->flags[0], SIP_RINGING);
06102 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06103 break;
06104 } else {
06105
06106 }
06107 }
06108 res = -1;
06109 break;
06110 case AST_CONTROL_BUSY:
06111 if (ast->_state != AST_STATE_UP) {
06112 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06113 p->invitestate = INV_COMPLETED;
06114 sip_alreadygone(p);
06115 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06116 break;
06117 }
06118 res = -1;
06119 break;
06120 case AST_CONTROL_CONGESTION:
06121 if (ast->_state != AST_STATE_UP) {
06122 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06123 p->invitestate = INV_COMPLETED;
06124 sip_alreadygone(p);
06125 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06126 break;
06127 }
06128 res = -1;
06129 break;
06130 case AST_CONTROL_PROCEEDING:
06131 if ((ast->_state != AST_STATE_UP) &&
06132 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06133 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06134 transmit_response(p, "100 Trying", &p->initreq);
06135 p->invitestate = INV_PROCEEDING;
06136 break;
06137 }
06138 res = -1;
06139 break;
06140 case AST_CONTROL_PROGRESS:
06141 if ((ast->_state != AST_STATE_UP) &&
06142 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06143 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06144 p->invitestate = INV_EARLY_MEDIA;
06145 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06146 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06147 break;
06148 }
06149 res = -1;
06150 break;
06151 case AST_CONTROL_HOLD:
06152 ast_rtp_new_source(p->rtp);
06153 ast_moh_start(ast, data, p->mohinterpret);
06154 break;
06155 case AST_CONTROL_UNHOLD:
06156 ast_rtp_new_source(p->rtp);
06157 ast_moh_stop(ast);
06158 break;
06159 case AST_CONTROL_VIDUPDATE:
06160 if (p->vrtp && !p->novideo) {
06161 transmit_info_with_vidupdate(p);
06162
06163 } else
06164 res = -1;
06165 break;
06166 case AST_CONTROL_T38_PARAMETERS:
06167 if (datalen != sizeof(struct ast_control_t38_parameters)) {
06168 ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);
06169 } else {
06170 const struct ast_control_t38_parameters *parameters = data;
06171 interpret_t38_parameters(p, parameters);
06172 }
06173 break;
06174 case AST_CONTROL_SRCUPDATE:
06175 ast_rtp_new_source(p->rtp);
06176 break;
06177 case -1:
06178 res = -1;
06179 break;
06180 default:
06181 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06182 res = -1;
06183 break;
06184 }
06185 sip_pvt_unlock(p);
06186 return res;
06187 }
06188
06189
06190
06191
06192
06193
06194
06195 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06196 {
06197 struct ast_channel *tmp;
06198 struct ast_variable *v = NULL;
06199 int fmt;
06200 int what;
06201 int video;
06202 int text;
06203 int needvideo = 0;
06204 int needtext = 0;
06205 char buf[SIPBUFSIZE];
06206 char *decoded_exten;
06207
06208 {
06209 const char *my_name;
06210
06211 if (title)
06212 my_name = title;
06213 else if ( (my_name = strchr(i->fromdomain, ':')) )
06214 my_name++;
06215 else
06216 my_name = i->fromdomain;
06217
06218 sip_pvt_unlock(i);
06219
06220 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, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
06221
06222 }
06223 if (!tmp) {
06224 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06225 sip_pvt_lock(i);
06226 return NULL;
06227 }
06228 sip_pvt_lock(i);
06229
06230 tmp->tech = ( ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ? &sip_tech_info : &sip_tech;
06231
06232
06233
06234 if (i->jointcapability) {
06235 what = i->jointcapability;
06236 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06237 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06238 } else if (i->capability) {
06239 what = i->capability;
06240 video = i->capability & AST_FORMAT_VIDEO_MASK;
06241 text = i->capability & AST_FORMAT_TEXT_MASK;
06242 } else {
06243 what = global_capability;
06244 video = global_capability & AST_FORMAT_VIDEO_MASK;
06245 text = global_capability & AST_FORMAT_TEXT_MASK;
06246 }
06247
06248
06249 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06250 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06251 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06252 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06253 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06254 if (i->prefcodec)
06255 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06256
06257
06258 fmt = ast_best_codec(tmp->nativeformats);
06259
06260
06261
06262
06263
06264 if (i->vrtp) {
06265 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06266 needvideo = AST_FORMAT_VIDEO_MASK;
06267 else if (i->prefcodec)
06268 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
06269 else
06270 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06271 }
06272
06273 if (i->trtp) {
06274 if (i->prefcodec)
06275 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
06276 else
06277 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
06278 }
06279
06280 if (needvideo)
06281 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06282 else
06283 ast_debug(3, "This channel will not be able to handle video.\n");
06284
06285 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06286 (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06287 int features = DSP_FEATURE_DIGIT_DETECT;
06288
06289 if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06290 features |= DSP_FEATURE_FAX_DETECT;
06291 }
06292
06293 i->dsp = ast_dsp_new();
06294 ast_dsp_set_features(i->dsp, features);
06295 if (global_relaxdtmf)
06296 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06297 }
06298
06299
06300 if (i->rtp) {
06301 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06302 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06303 }
06304 if (needvideo && i->vrtp) {
06305 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06306 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06307 }
06308 if (needtext && i->trtp)
06309 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06310 if (i->udptl)
06311 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06312
06313 if (state == AST_STATE_RING)
06314 tmp->rings = 1;
06315 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06316 tmp->writeformat = fmt;
06317 tmp->rawwriteformat = fmt;
06318 tmp->readformat = fmt;
06319 tmp->rawreadformat = fmt;
06320 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06321
06322 tmp->callgroup = i->callgroup;
06323 tmp->pickupgroup = i->pickupgroup;
06324 tmp->cid.cid_pres = i->callingpres;
06325 if (!ast_strlen_zero(i->parkinglot))
06326 ast_string_field_set(tmp, parkinglot, i->parkinglot);
06327 if (!ast_strlen_zero(i->accountcode))
06328 ast_string_field_set(tmp, accountcode, i->accountcode);
06329 if (i->amaflags)
06330 tmp->amaflags = i->amaflags;
06331 if (!ast_strlen_zero(i->language))
06332 ast_string_field_set(tmp, language, i->language);
06333 i->owner = tmp;
06334 ast_module_ref(ast_module_info->self);
06335 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06336
06337
06338
06339
06340 decoded_exten = ast_strdupa(i->exten);
06341 ast_uri_decode(decoded_exten);
06342 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06343
06344
06345
06346 tmp->cid.cid_ani = ast_strdup(i->cid_num);
06347 if (!ast_strlen_zero(i->rdnis))
06348 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06349
06350 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06351 tmp->cid.cid_dnid = ast_strdup(i->exten);
06352
06353 tmp->priority = 1;
06354 if (!ast_strlen_zero(i->uri))
06355 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06356 if (!ast_strlen_zero(i->domain))
06357 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06358 if (!ast_strlen_zero(i->callid))
06359 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06360 if (i->rtp)
06361 ast_jb_configure(tmp, &global_jbconf);
06362
06363
06364 for (v = i->chanvars ; v ; v = v->next)
06365 pbx_builtin_setvar_helper(tmp, v->name, v->value);
06366
06367 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06368 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06369 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06370 ast_hangup(tmp);
06371 tmp = NULL;
06372 }
06373
06374 if (i->do_history)
06375 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06376
06377
06378 if (global_callevents)
06379 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06380 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06381 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06382
06383 return tmp;
06384 }
06385
06386
06387 static char *get_body_by_line(const char *line, const char *name, int nameLen)
06388 {
06389 if (!strncasecmp(line, name, nameLen) && line[nameLen] == '=')
06390 return ast_skip_blanks(line + nameLen + 1);
06391
06392 return "";
06393 }
06394
06395
06396
06397
06398
06399 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06400 {
06401 int len = strlen(name);
06402
06403 while (*start < (req->sdp_start + req->sdp_count)) {
06404 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len);
06405 if (r[0] != '\0')
06406 return r;
06407 }
06408
06409
06410 (*start)++;
06411
06412 return "";
06413 }
06414
06415
06416
06417
06418
06419
06420 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06421 {
06422 char type = '\0';
06423 const char *line = NULL;
06424
06425 if (stop > (req->sdp_start + req->sdp_count)) {
06426 stop = req->sdp_start + req->sdp_count;
06427 }
06428
06429 while (*start < stop) {
06430 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06431 if (line[1] == '=') {
06432 type = line[0];
06433 *value = ast_skip_blanks(line + 2);
06434 break;
06435 }
06436 }
06437
06438 return type;
06439 }
06440
06441
06442 static char *get_body(struct sip_request *req, char *name)
06443 {
06444 int x;
06445 int len = strlen(name);
06446 char *r;
06447
06448 for (x = 0; x < req->lines; x++) {
06449 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len);
06450 if (r[0] != '\0')
06451 return r;
06452 }
06453
06454 return "";
06455 }
06456
06457
06458 static const char *find_alias(const char *name, const char *_default)
06459 {
06460
06461 static const struct cfalias {
06462 char * const fullname;
06463 char * const shortname;
06464 } aliases[] = {
06465 { "Content-Type", "c" },
06466 { "Content-Encoding", "e" },
06467 { "From", "f" },
06468 { "Call-ID", "i" },
06469 { "Contact", "m" },
06470 { "Content-Length", "l" },
06471 { "Subject", "s" },
06472 { "To", "t" },
06473 { "Supported", "k" },
06474 { "Refer-To", "r" },
06475 { "Referred-By", "b" },
06476 { "Allow-Events", "u" },
06477 { "Event", "o" },
06478 { "Via", "v" },
06479 { "Accept-Contact", "a" },
06480 { "Reject-Contact", "j" },
06481 { "Request-Disposition", "d" },
06482 { "Session-Expires", "x" },
06483 { "Identity", "y" },
06484 { "Identity-Info", "n" },
06485 };
06486 int x;
06487
06488 for (x = 0; x < ARRAY_LEN(aliases); x++) {
06489 if (!strcasecmp(aliases[x].fullname, name))
06490 return aliases[x].shortname;
06491 }
06492
06493 return _default;
06494 }
06495
06496 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06497 {
06498 int pass;
06499
06500
06501
06502
06503
06504
06505
06506
06507
06508
06509 for (pass = 0; name && pass < 2;pass++) {
06510 int x, len = strlen(name);
06511 for (x = *start; x < req->headers; x++) {
06512 char *header = REQ_OFFSET_TO_STR(req, header[x]);
06513 if (!strncasecmp(header, name, len)) {
06514 char *r = header + len;
06515 if (pedanticsipchecking)
06516 r = ast_skip_blanks(r);
06517
06518 if (*r == ':') {
06519 *start = x+1;
06520 return ast_skip_blanks(r+1);
06521 }
06522 }
06523 }
06524 if (pass == 0)
06525 name = find_alias(name, NULL);
06526 }
06527
06528
06529 return "";
06530 }
06531
06532
06533
06534
06535 static const char *get_header(const struct sip_request *req, const char *name)
06536 {
06537 int start = 0;
06538 return __get_header(req, name, &start);
06539 }
06540
06541
06542 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06543 {
06544
06545 struct ast_frame *f;
06546
06547 if (!p->rtp) {
06548
06549 return &ast_null_frame;
06550 }
06551
06552 switch(ast->fdno) {
06553 case 0:
06554 f = ast_rtp_read(p->rtp);
06555 break;
06556 case 1:
06557 f = ast_rtcp_read(p->rtp);
06558 break;
06559 case 2:
06560 f = ast_rtp_read(p->vrtp);
06561 break;
06562 case 3:
06563 f = ast_rtcp_read(p->vrtp);
06564 break;
06565 case 4:
06566 f = ast_rtp_read(p->trtp);
06567 if (sipdebug_text) {
06568 int i;
06569 unsigned char* arr = f->data.ptr;
06570 for (i=0; i < f->datalen; i++)
06571 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
06572 ast_verbose(" -> ");
06573 for (i=0; i < f->datalen; i++)
06574 ast_verbose("%02X ", arr[i]);
06575 ast_verbose("\n");
06576 }
06577 break;
06578 case 5:
06579 f = ast_udptl_read(p->udptl);
06580 break;
06581 default:
06582 f = &ast_null_frame;
06583 }
06584
06585 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
06586 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
06587 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
06588 return &ast_null_frame;
06589 }
06590
06591
06592 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
06593 return f;
06594
06595 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
06596 if (!(f->subclass & p->jointcapability)) {
06597 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
06598 ast_getformatname(f->subclass), p->owner->name);
06599 return &ast_null_frame;
06600 }
06601 ast_debug(1, "Oooh, format changed to %d %s\n",
06602 f->subclass, ast_getformatname(f->subclass));
06603 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
06604 ast_set_read_format(p->owner, p->owner->readformat);
06605 ast_set_write_format(p->owner, p->owner->writeformat);
06606 }
06607
06608 if (f && ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) && p->dsp) {
06609 f = ast_dsp_process(p->owner, p->dsp, f);
06610 if (f && f->frametype == AST_FRAME_DTMF) {
06611 if (f->subclass == 'f') {
06612 if (option_debug)
06613 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
06614 *faxdetect = 1;
06615
06616 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
06617 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
06618 } else {
06619 ast_dsp_free(p->dsp);
06620 p->dsp = NULL;
06621 }
06622 } else {
06623 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
06624 }
06625 }
06626 }
06627
06628 return f;
06629 }
06630
06631
06632 static struct ast_frame *sip_read(struct ast_channel *ast)
06633 {
06634 struct ast_frame *fr;
06635 struct sip_pvt *p = ast->tech_pvt;
06636 int faxdetected = FALSE;
06637
06638 sip_pvt_lock(p);
06639 fr = sip_rtp_read(ast, p, &faxdetected);
06640 p->lastrtprx = time(NULL);
06641
06642
06643 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) {
06644 ast_channel_lock(ast);
06645 if (strcmp(ast->exten, "fax")) {
06646 const char *target_context = S_OR(ast->macrocontext, ast->context);
06647 ast_channel_unlock(ast);
06648 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
06649 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension\n", ast->name);
06650 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
06651 if (ast_async_goto(ast, target_context, "fax", 1)) {
06652 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
06653 }
06654 fr = &ast_null_frame;
06655 } else {
06656 ast_log(LOG_NOTICE, "Fax detected but no fax extension\n");
06657 }
06658 } else {
06659 ast_channel_unlock(ast);
06660 }
06661 }
06662
06663
06664 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
06665 fr = &ast_null_frame;
06666 }
06667
06668 sip_pvt_unlock(p);
06669
06670 return fr;
06671 }
06672
06673
06674
06675 static char *generate_random_string(char *buf, size_t size)
06676 {
06677 long val[4];
06678 int x;
06679
06680 for (x=0; x<4; x++)
06681 val[x] = ast_random();
06682 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
06683
06684 return buf;
06685 }
06686
06687
06688 static void build_callid_pvt(struct sip_pvt *pvt)
06689 {
06690 char buf[33];
06691
06692 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
06693
06694 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
06695
06696 }
06697
06698
06699 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
06700 {
06701 char buf[33];
06702
06703 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
06704
06705 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
06706 }
06707
06708
06709 static void make_our_tag(char *tagbuf, size_t len)
06710 {
06711 snprintf(tagbuf, len, "as%08lx", ast_random());
06712 }
06713
06714
06715 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
06716 {
06717 struct sip_st_dlg *stp;
06718
06719 if (p->stimer) {
06720 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
06721 return p->stimer;
06722 }
06723
06724 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
06725 return NULL;
06726
06727 p->stimer = stp;
06728
06729 stp->st_schedid = -1;
06730
06731 return p->stimer;
06732 }
06733
06734
06735
06736
06737
06738 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
06739 int useglobal_nat, const int intended_method, struct sip_request *req)
06740 {
06741 struct sip_pvt *p;
06742
06743 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
06744 return NULL;
06745
06746 if (ast_string_field_init(p, 512)) {
06747 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
06748 return NULL;
06749 }
06750
06751 if (req) {
06752 set_socket_transport(&p->socket, req->socket.type);
06753 } else {
06754 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
06755 }
06756
06757 p->socket.fd = -1;
06758 p->method = intended_method;
06759 p->initid = -1;
06760 p->waitid = -1;
06761 p->autokillid = -1;
06762 p->request_queue_sched_id = -1;
06763 p->provisional_keepalive_sched_id = -1;
06764 p->t38id = -1;
06765 p->subscribed = NONE;
06766 p->stateid = -1;
06767 p->sessionversion_remote = -1;
06768 p->session_modify = TRUE;
06769 p->stimer = NULL;
06770 p->prefs = default_prefs;
06771
06772 if (intended_method != SIP_OPTIONS) {
06773 p->timer_t1 = global_t1;
06774 p->timer_b = global_timer_b;
06775 }
06776
06777 if (!sin)
06778 p->ourip = internip;
06779 else {
06780 p->sa = *sin;
06781 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
06782 }
06783
06784
06785 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
06786 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
06787
06788 p->do_history = recordhistory;
06789
06790 p->branch = ast_random();
06791 make_our_tag(p->tag, sizeof(p->tag));
06792 p->ocseq = INITIAL_CSEQ;
06793
06794 if (sip_methods[intended_method].need_rtp) {
06795 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06796
06797 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06798 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06799 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
06800 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06801 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
06802 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
06803 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
06804 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
06805 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
06806 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
06807 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
06808 if (p->chanvars) {
06809 ast_variables_destroy(p->chanvars);
06810 p->chanvars = NULL;
06811 }
06812 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
06813 return NULL;
06814 p->t38_maxdatagram = global_t38_maxdatagram;
06815 }
06816 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
06817 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
06818 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
06819 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
06820 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
06821 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
06822 if (p->vrtp) {
06823 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
06824 ast_rtp_setdtmf(p->vrtp, 0);
06825 ast_rtp_setdtmfcompensate(p->vrtp, 0);
06826 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
06827 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
06828 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
06829 }
06830 if (p->trtp) {
06831 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
06832 ast_rtp_setdtmf(p->trtp, 0);
06833 ast_rtp_setdtmfcompensate(p->trtp, 0);
06834 }
06835 if (p->udptl)
06836 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06837 p->maxcallbitrate = default_maxcallbitrate;
06838 p->autoframing = global_autoframing;
06839 ast_rtp_codec_setpref(p->rtp, &p->prefs);
06840 }
06841
06842 if (useglobal_nat && sin) {
06843
06844 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
06845 p->recv = *sin;
06846 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
06847 }
06848
06849 if (p->method != SIP_REGISTER)
06850 ast_string_field_set(p, fromdomain, default_fromdomain);
06851 build_via(p);
06852 if (!callid)
06853 build_callid_pvt(p);
06854 else
06855 ast_string_field_set(p, callid, callid);
06856
06857 ast_string_field_set(p, mohinterpret, default_mohinterpret);
06858 ast_string_field_set(p, mohsuggest, default_mohsuggest);
06859 p->capability = global_capability;
06860 p->allowtransfer = global_allowtransfer;
06861 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
06862 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
06863 p->noncodeccapability |= AST_RTP_DTMF;
06864 if (p->udptl) {
06865 p->t38_maxdatagram = global_t38_maxdatagram;
06866 set_t38_capabilities(p);
06867 }
06868 ast_string_field_set(p, context, default_context);
06869 ast_string_field_set(p, parkinglot, default_parkinglot);
06870
06871 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
06872
06873
06874
06875 ao2_t_link(dialogs, p, "link pvt into dialogs table");
06876
06877 ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
06878 return p;
06879 }
06880
06881
06882 struct find_call_cb_arg {
06883 enum sipmethod method;
06884 const char *callid;
06885 const char *fromtag;
06886 const char *totag;
06887 const char *tag;
06888 };
06889
06890
06891
06892
06893
06894 static int find_call_cb(void *__pvt, void *__arg, int flags)
06895 {
06896 struct sip_pvt *p = __pvt;
06897 struct find_call_cb_arg *arg = __arg;
06898
06899 int found = FALSE;
06900
06901 if (!ast_strlen_zero(p->callid)) {
06902 if (arg->method == SIP_REGISTER)
06903 found = (!strcmp(p->callid, arg->callid));
06904 else {
06905 found = !strcmp(p->callid, arg->callid);
06906 if (pedanticsipchecking && found) {
06907 found = ast_strlen_zero(arg->tag) || ast_strlen_zero(p->theirtag) || !ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) || !strcmp(p->theirtag, arg->tag);
06908 }
06909 }
06910
06911 ast_debug(5, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
06912
06913
06914 if (pedanticsipchecking && found && arg->method != SIP_RESPONSE) {
06915 if (p->tag[0] == '\0' && arg->totag[0]) {
06916
06917 found = FALSE;
06918 } else if (arg->totag[0]) {
06919 if (strcmp(arg->totag, p->tag)) {
06920 found = FALSE;
06921 }
06922 }
06923 if (!found)
06924 ast_debug(5, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, arg->totag, sip_methods[arg->method].text);
06925 }
06926 }
06927 return found;
06928 }
06929
06930
06931
06932
06933
06934
06935 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
06936 {
06937 struct sip_pvt *p = NULL;
06938 char *tag = "";
06939 char totag[128];
06940 char fromtag[128];
06941 struct find_call_cb_arg arg;
06942 const char *callid = get_header(req, "Call-ID");
06943 const char *from = get_header(req, "From");
06944 const char *to = get_header(req, "To");
06945 const char *cseq = get_header(req, "Cseq");
06946 struct sip_pvt *sip_pvt_ptr;
06947
06948
06949
06950 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
06951 ast_strlen_zero(from) || ast_strlen_zero(cseq))
06952 return NULL;
06953
06954 arg.method = req->method;
06955 arg.callid = callid;
06956 arg.fromtag = fromtag;
06957 arg.totag = totag;
06958 arg.tag = "";
06959
06960 if (pedanticsipchecking) {
06961
06962
06963
06964
06965
06966
06967 if (gettag(req, "To", totag, sizeof(totag)))
06968 req->has_to_tag = 1;
06969 gettag(req, "From", fromtag, sizeof(fromtag));
06970
06971 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
06972
06973 ast_debug(5, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
06974
06975
06976 if (ast_strlen_zero(fromtag)) {
06977 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
06978 return NULL;
06979 }
06980
06981 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
06982 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
06983 return NULL;
06984 }
06985 }
06986
06987 restartsearch:
06988 if (!pedanticsipchecking) {
06989 struct sip_pvt tmp_dialog = {
06990 .callid = callid,
06991 };
06992 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
06993 if (sip_pvt_ptr) {
06994
06995 sip_pvt_lock(sip_pvt_ptr);
06996 return sip_pvt_ptr;
06997 }
06998 } else {
06999 ao2_lock(dialogs);
07000 p = ao2_t_callback(dialogs, 0 , find_call_cb, &arg, "pedantic linear search for dialog");
07001 if (p) {
07002 if (sip_pvt_trylock(p)) {
07003 ao2_unlock(dialogs);
07004 usleep(1);
07005 goto restartsearch;
07006 }
07007 ao2_unlock(dialogs);
07008 return p;
07009 }
07010 ao2_unlock(dialogs);
07011 }
07012
07013
07014 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07015 if (intended_method == SIP_REFER) {
07016
07017 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07018 } else if (intended_method == SIP_NOTIFY) {
07019
07020
07021 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07022 } else {
07023
07024 if ((p = sip_alloc(callid, sin, 1, intended_method, req))) {
07025
07026 sip_pvt_lock(p);
07027 } else {
07028
07029
07030
07031
07032
07033
07034
07035
07036 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07037 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07038 }
07039 }
07040 return p;
07041 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07042
07043 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07044 ast_debug(2, "Got a request with unsupported SIP method.\n");
07045 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07046
07047 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07048 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07049 }
07050
07051
07052 if (intended_method == SIP_RESPONSE)
07053 ast_debug(2, "That's odd... Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
07054
07055 return NULL;
07056 }
07057
07058
07059 static int sip_register(const char *value, int lineno)
07060 {
07061 struct sip_registry *reg;
07062 int portnum = 0;
07063 enum sip_transport transport = SIP_TRANSPORT_UDP;
07064 char buf[256] = "";
07065 char *username = NULL;
07066 char *hostname=NULL, *secret=NULL, *authuser=NULL, *expire=NULL, *tmp=NULL;
07067 char *callback=NULL, *peername=NULL;
07068
07069 if (!value)
07070 return -1;
07071 ast_copy_string(buf, value, sizeof(buf));
07072 tmp = strrchr(buf, '@');
07073
07074
07075 expire = strchr(tmp, '~');
07076 if (expire)
07077 *expire++ = '\0';
07078 callback = strrchr(tmp, '/');
07079 if (callback)
07080 *callback++ = '\0';
07081 if (ast_strlen_zero(callback))
07082 callback = "s";
07083
07084
07085 tmp = strchr(buf, '?');
07086 if (tmp) {
07087 *tmp++ = '\0';
07088 peername = buf;
07089 } else {
07090 tmp = buf;
07091 }
07092
07093 sip_parse_host(tmp, lineno, &username, &portnum, &transport);
07094
07095
07096 hostname = strrchr(username, '@');
07097 if (hostname)
07098 *hostname++ = '\0';
07099 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
07100 ast_log(LOG_WARNING, "Format for registration is [transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07101 return -1;
07102 }
07103
07104 secret = strchr(username, ':');
07105 if (secret) {
07106 *secret++ = '\0';
07107 authuser = strchr(secret, ':');
07108 if (authuser)
07109 *authuser++ = '\0';
07110 }
07111
07112 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07113 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07114 return -1;
07115 }
07116
07117 if (ast_string_field_init(reg, 256)) {
07118 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07119 ast_free(reg);
07120 return -1;
07121 }
07122
07123 ast_atomic_fetchadd_int(®objs, 1);
07124 ASTOBJ_INIT(reg);
07125 ast_string_field_set(reg, callback, callback);
07126 if (!ast_strlen_zero(username))
07127 ast_string_field_set(reg, username, username);
07128 if (hostname)
07129 ast_string_field_set(reg, hostname, hostname);
07130 if (authuser)
07131 ast_string_field_set(reg, authuser, authuser);
07132 if (secret)
07133 ast_string_field_set(reg, secret, secret);
07134 if (peername) {
07135 ast_string_field_set(reg, peername, peername);
07136 }
07137 reg->transport = transport;
07138 reg->expire = -1;
07139 reg->configured_expiry = (expire ? atoi(expire) : default_expiry);
07140 reg->expiry = reg->configured_expiry;
07141 reg->timeout = -1;
07142 reg->refresh = reg->expiry;
07143 reg->portno = portnum;
07144 reg->callid_valid = FALSE;
07145 reg->ocseq = INITIAL_CSEQ;
07146 ASTOBJ_CONTAINER_LINK(®l, reg);
07147 registry_unref(reg, "unref the reg pointer");
07148 return 0;
07149 }
07150
07151
07152
07153 static int lws2sws(char *msgbuf, int len)
07154 {
07155 int h = 0, t = 0;
07156 int lws = 0;
07157
07158 for (; h < len;) {
07159
07160 if (msgbuf[h] == '\r') {
07161 h++;
07162 continue;
07163 }
07164
07165 if (msgbuf[h] == '\n') {
07166
07167 if (h + 1 == len)
07168 break;
07169
07170 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
07171
07172 h++;
07173 continue;
07174 }
07175
07176 msgbuf[t++] = msgbuf[h++];
07177 lws = 0;
07178 continue;
07179 }
07180 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
07181 if (lws) {
07182 h++;
07183 continue;
07184 }
07185 msgbuf[t++] = msgbuf[h++];
07186 lws = 1;
07187 continue;
07188 }
07189 msgbuf[t++] = msgbuf[h++];
07190 if (lws)
07191 lws = 0;
07192 }
07193 msgbuf[t] = '\0';
07194 return t;
07195 }
07196
07197
07198
07199
07200 static int parse_request(struct sip_request *req)
07201 {
07202 char *c = req->data->str;
07203 ptrdiff_t *dst = req->header;
07204 int i = 0, lim = SIP_MAX_HEADERS - 1;
07205 unsigned int skipping_headers = 0;
07206 ptrdiff_t current_header_offset = 0;
07207 char *previous_header = "";
07208
07209 req->header[0] = 0;
07210 req->headers = -1;
07211 for (; *c; c++) {
07212 if (*c == '\r') {
07213 *c = '\0';
07214 } else if (*c == '\n') {
07215 *c = '\0';
07216 current_header_offset = (c + 1) - req->data->str;
07217 previous_header = req->data->str + dst[i];
07218 if (skipping_headers) {
07219
07220
07221
07222 if (ast_strlen_zero(previous_header)) {
07223 skipping_headers = 0;
07224 }
07225 dst[i] = current_header_offset;
07226 continue;
07227 }
07228 if (sipdebug) {
07229 ast_debug(4, "%7s %2d [%3d]: %s\n",
07230 req->headers < 0 ? "Header" : "Body",
07231 i, (int) strlen(previous_header), previous_header);
07232 }
07233 if (ast_strlen_zero(previous_header) && req->headers < 0) {
07234 req->headers = i;
07235 dst = req->line;
07236 i = 0;
07237 lim = SIP_MAX_LINES - 1;
07238 } else {
07239 if (i++ == lim) {
07240
07241
07242
07243 if (req->headers != -1) {
07244 break;
07245 } else {
07246 req->headers = i;
07247 dst = req->line;
07248 i = 0;
07249 lim = SIP_MAX_LINES - 1;
07250 skipping_headers = 1;
07251 }
07252 }
07253 }
07254 dst[i] = current_header_offset;
07255 }
07256 }
07257
07258
07259
07260
07261
07262
07263 previous_header = req->data->str + dst[i];
07264 if ((i < lim) && !ast_strlen_zero(previous_header)) {
07265 if (sipdebug) {
07266 ast_debug(4, "%7s %2d [%3d]: %s\n",
07267 req->headers < 0 ? "Header" : "Body",
07268 i, (int) strlen(previous_header), previous_header );
07269 }
07270 i++;
07271 }
07272
07273
07274 if (req->headers >= 0) {
07275 req->lines = i;
07276 } else {
07277 req->headers = i;
07278 req->lines = 0;
07279
07280 req->line[0] = req->data->used;
07281 }
07282
07283 if (*c) {
07284 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07285 }
07286
07287
07288 return determine_firstline_parts(req);
07289 }
07290
07291
07292
07293
07294
07295
07296
07297
07298
07299 static int find_sdp(struct sip_request *req)
07300 {
07301 const char *content_type;
07302 const char *content_length;
07303 const char *search;
07304 char *boundary;
07305 unsigned int x;
07306 int boundaryisquoted = FALSE;
07307 int found_application_sdp = FALSE;
07308 int found_end_of_headers = FALSE;
07309
07310 content_length = get_header(req, "Content-Length");
07311
07312 if (!ast_strlen_zero(content_length)) {
07313 if (sscanf(content_length, "%30u", &x) != 1) {
07314 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07315 return 0;
07316 }
07317
07318
07319
07320 if (x == 0)
07321 return 0;
07322 }
07323
07324 content_type = get_header(req, "Content-Type");
07325
07326
07327 if (!strncasecmp(content_type, "application/sdp", 15)) {
07328 req->sdp_start = 0;
07329 req->sdp_count = req->lines;
07330 return req->lines ? 1 : 0;
07331 }
07332
07333
07334 if (strncasecmp(content_type, "multipart/mixed", 15))
07335 return 0;
07336
07337
07338 if ((search = strcasestr(content_type, ";boundary=")))
07339 search += 10;
07340 else if ((search = strcasestr(content_type, "; boundary=")))
07341 search += 11;
07342 else
07343 return 0;
07344
07345 if (ast_strlen_zero(search))
07346 return 0;
07347
07348
07349 if (*search == '\"') {
07350 search++;
07351 boundaryisquoted = TRUE;
07352 }
07353
07354
07355
07356 boundary = ast_strdupa(search - 2);
07357 boundary[0] = boundary[1] = '-';
07358
07359 if (boundaryisquoted)
07360 boundary[strlen(boundary) - 1] = '\0';
07361
07362
07363
07364
07365 for (x = 0; x < (req->lines); x++) {
07366 char *line = REQ_OFFSET_TO_STR(req, line[x]);
07367 if (!strncasecmp(line, boundary, strlen(boundary))){
07368 if (found_application_sdp && found_end_of_headers) {
07369 req->sdp_count = (x - 1) - req->sdp_start;
07370 return 1;
07371 }
07372 found_application_sdp = FALSE;
07373 }
07374 if (!strcasecmp(line, "Content-Type: application/sdp"))
07375 found_application_sdp = TRUE;
07376
07377 if (ast_strlen_zero(line)) {
07378 if (found_application_sdp && !found_end_of_headers){
07379 req->sdp_start = x;
07380 found_end_of_headers = TRUE;
07381 }
07382 }
07383 }
07384 if (found_application_sdp && found_end_of_headers) {
07385 req->sdp_count = x - req->sdp_start;
07386 return TRUE;
07387 }
07388 return FALSE;
07389 }
07390
07391 enum media_type {
07392 SDP_AUDIO,
07393 SDP_VIDEO,
07394 SDP_IMAGE,
07395 SDP_TEXT,
07396 };
07397
07398 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
07399 {
07400 const char *m;
07401 const char *c;
07402 int miterator = req->sdp_start;
07403 int citerator = req->sdp_start;
07404 int x = 0;
07405 int numberofports;
07406 int len;
07407 char host[258] = "";
07408 struct ast_hostent audiohp;
07409 struct hostent *hp;
07410
07411 c = get_sdp_iterate(&citerator, req, "c");
07412 if (sscanf(c, "IN IP4 %256s", host) != 1) {
07413 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
07414
07415 }
07416
07417 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
07418 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07419 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
07420 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07421 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
07422
07423
07424
07425
07426 c = get_sdp_iterate(&citerator, req, "c");
07427 if (!ast_strlen_zero(c)) {
07428 sscanf(c, "IN IP4 %256s", host);
07429 }
07430 break;
07431 }
07432 }
07433
07434 if (ast_strlen_zero(host) || x == 0) {
07435 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
07436 return -1;
07437 }
07438
07439 hp = ast_gethostbyname(host, &audiohp);
07440 if (!hp) {
07441 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
07442 return -1;
07443 }
07444
07445 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
07446 sin->sin_port = htons(x);
07447 return 0;
07448 }
07449
07450
07451
07452
07453
07454
07455 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
07456 {
07457
07458 int start = req->sdp_start;
07459 int next = start;
07460 int iterator = start;
07461
07462
07463 char type = '\0';
07464 const char *value = NULL;
07465 const char *m = NULL;
07466 const char *nextm = NULL;
07467 int len = -1;
07468
07469
07470 struct ast_hostent sessionhp;
07471 struct ast_hostent audiohp;
07472 struct ast_hostent videohp;
07473 struct ast_hostent texthp;
07474 struct ast_hostent imagehp;
07475 struct hostent *hp = NULL;
07476 struct hostent *vhp = NULL;
07477 struct hostent *thp = NULL;
07478 struct hostent *ihp = NULL;
07479 int portno = -1;
07480 int vportno = -1;
07481 int tportno = -1;
07482 int udptlportno = -1;
07483 struct sockaddr_in sin;
07484 struct sockaddr_in vsin;
07485 struct sockaddr_in isin;
07486 struct sockaddr_in tsin;
07487
07488
07489 int peercapability = 0, peernoncodeccapability = 0;
07490 int vpeercapability = 0, vpeernoncodeccapability = 0;
07491 int tpeercapability = 0, tpeernoncodeccapability = 0;
07492
07493 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
07494 int newjointcapability;
07495 int newpeercapability;
07496 int newnoncodeccapability;
07497
07498 const char *codecs;
07499 int codec;
07500
07501
07502 int sendonly = -1;
07503 int vsendonly = -1;
07504 int numberofports;
07505 int numberofmediastreams = 0;
07506 int last_rtpmap_codec = 0;
07507 int red_data_pt[10];
07508 int red_num_gen = 0;
07509 char red_fmtp[100] = "empty";
07510 int debug = sip_debug_test_pvt(p);
07511
07512
07513 char buf[SIPBUFSIZE];
07514
07515
07516
07517 if (!p->rtp) {
07518 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
07519 return -1;
07520 }
07521
07522
07523 #ifdef LOW_MEMORY
07524 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
07525 #else
07526 newaudiortp = alloca(ast_rtp_alloc_size());
07527 #endif
07528 memset(newaudiortp, 0, ast_rtp_alloc_size());
07529 ast_rtp_new_init(newaudiortp);
07530 ast_rtp_pt_clear(newaudiortp);
07531
07532 #ifdef LOW_MEMORY
07533 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
07534 #else
07535 newvideortp = alloca(ast_rtp_alloc_size());
07536 #endif
07537 memset(newvideortp, 0, ast_rtp_alloc_size());
07538 ast_rtp_new_init(newvideortp);
07539 ast_rtp_pt_clear(newvideortp);
07540
07541 #ifdef LOW_MEMORY
07542 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
07543 #else
07544 newtextrtp = alloca(ast_rtp_alloc_size());
07545 #endif
07546 memset(newtextrtp, 0, ast_rtp_alloc_size());
07547 ast_rtp_new_init(newtextrtp);
07548 ast_rtp_pt_clear(newtextrtp);
07549
07550
07551 p->lastrtprx = p->lastrtptx = time(NULL);
07552
07553 memset(p->offered_media, 0, sizeof(p->offered_media));
07554
07555
07556
07557 p->novideo = TRUE;
07558 p->notext = TRUE;
07559
07560 if (p->vrtp)
07561 ast_rtp_pt_clear(newvideortp);
07562
07563 if (p->trtp)
07564 ast_rtp_pt_clear(newtextrtp);
07565
07566
07567 nextm = get_sdp_iterate(&next, req, "m");
07568 if (ast_strlen_zero(nextm)) {
07569 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
07570 return -1;
07571 }
07572
07573
07574 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
07575 int processed = FALSE;
07576 switch (type) {
07577 case 'o':
07578
07579
07580
07581 if (!process_sdp_o(value, p))
07582 return (p->session_modify == FALSE) ? 0 : -1;
07583 break;
07584 case 'c':
07585 if (process_sdp_c(value, &sessionhp)) {
07586 processed = TRUE;
07587 hp = &sessionhp.hp;
07588 vhp = hp;
07589 thp = hp;
07590 ihp = hp;
07591 }
07592 break;
07593 case 'a':
07594 if (process_sdp_a_sendonly(value, &sendonly)) {
07595 processed = TRUE;
07596 vsendonly = sendonly;
07597 }
07598 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
07599 processed = TRUE;
07600 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
07601 processed = TRUE;
07602 else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
07603 processed = TRUE;
07604 else if (process_sdp_a_image(value, p))
07605 processed = TRUE;
07606 break;
07607 }
07608
07609 if (option_debug > 2)
07610 ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
07611 }
07612
07613
07614
07615
07616 while (!ast_strlen_zero(nextm)) {
07617 int audio = FALSE;
07618 int video = FALSE;
07619 int image = FALSE;
07620 int text = FALSE;
07621 int x;
07622
07623 numberofports = 1;
07624 len = -1;
07625 start = next;
07626 m = nextm;
07627 iterator = next;
07628 nextm = get_sdp_iterate(&next, req, "m");
07629
07630
07631 if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07632 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
07633 audio = TRUE;
07634 p->offered_media[SDP_AUDIO].offered = TRUE;
07635 numberofmediastreams++;
07636 portno = x;
07637
07638
07639 codecs = m + len;
07640 ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
07641 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07642 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
07643 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07644 return -1;
07645 }
07646 if (debug)
07647 ast_verbose("Found RTP audio format %d\n", codec);
07648
07649 ast_rtp_set_m_type(newaudiortp, codec);
07650 }
07651
07652 } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07653 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
07654 video = TRUE;
07655 p->novideo = FALSE;
07656 p->offered_media[SDP_VIDEO].offered = TRUE;
07657 numberofmediastreams++;
07658 vportno = x;
07659
07660
07661 codecs = m + len;
07662 ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
07663 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07664 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
07665 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07666 return -1;
07667 }
07668 if (debug)
07669 ast_verbose("Found RTP video format %d\n", codec);
07670 ast_rtp_set_m_type(newvideortp, codec);
07671 }
07672
07673 } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07674 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
07675 text = TRUE;
07676 p->notext = FALSE;
07677 p->offered_media[SDP_TEXT].offered = TRUE;
07678 numberofmediastreams++;
07679 tportno = x;
07680
07681
07682 codecs = m + len;
07683 ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
07684 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07685 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
07686 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07687 return -1;
07688 }
07689 if (debug)
07690 ast_verbose("Found RTP text format %d\n", codec);
07691 ast_rtp_set_m_type(newtextrtp, codec);
07692 }
07693
07694 } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
07695 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
07696 image = TRUE;
07697 if (debug)
07698 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
07699 p->offered_media[SDP_IMAGE].offered = TRUE;
07700 udptlportno = x;
07701 numberofmediastreams++;
07702
07703 if (p->t38.state != T38_ENABLED) {
07704 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
07705 }
07706 } else {
07707 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
07708 continue;
07709 }
07710
07711
07712 if (numberofports > 1)
07713 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
07714
07715
07716
07717
07718 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
07719 int processed = FALSE;
07720
07721 switch (type) {
07722 case 'c':
07723 if (audio) {
07724 if (process_sdp_c(value, &audiohp)) {
07725 processed = TRUE;
07726 hp = &audiohp.hp;
07727 }
07728 } else if (video) {
07729 if (process_sdp_c(value, &videohp)) {
07730 processed = TRUE;
07731 vhp = &videohp.hp;
07732 }
07733 } else if (text) {
07734 if (process_sdp_c(value, &texthp)) {
07735 processed = TRUE;
07736 thp = &texthp.hp;
07737 }
07738 } else if (image) {
07739 if (process_sdp_c(value, &imagehp)) {
07740 processed = TRUE;
07741 ihp = &imagehp.hp;
07742 }
07743 }
07744 break;
07745 case 'a':
07746
07747 if (audio) {
07748 if (process_sdp_a_sendonly(value, &sendonly))
07749 processed = TRUE;
07750 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
07751 processed = TRUE;
07752 }
07753
07754 else if (video) {
07755 if (process_sdp_a_sendonly(value, &vsendonly))
07756 processed = TRUE;
07757 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
07758 processed = TRUE;
07759 }
07760
07761 else if (text) {
07762 if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
07763 processed = TRUE;
07764 }
07765
07766 else if (image) {
07767 if (process_sdp_a_image(value, p))
07768 processed = TRUE;
07769 }
07770 break;
07771 }
07772
07773 if (option_debug > 2)
07774 ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
07775 (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
07776 type, value,
07777 (processed == TRUE)? "OK." : "UNSUPPORTED.");
07778 }
07779 }
07780
07781
07782
07783 if (!hp && !vhp && !thp && !ihp) {
07784 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
07785 return -1;
07786 }
07787
07788 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
07789
07790
07791 return -2;
07792
07793 if (numberofmediastreams > 3)
07794
07795 return -3;
07796
07797 if (udptlportno == -1) {
07798 change_t38_state(p, T38_DISABLED);
07799 }
07800
07801
07802 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
07803 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
07804 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
07805
07806 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
07807 newpeercapability = (peercapability | vpeercapability | tpeercapability);
07808 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
07809
07810
07811 if (debug) {
07812
07813 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
07814
07815 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
07816 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
07817 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
07818 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
07819 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
07820 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
07821
07822 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
07823 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
07824 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
07825 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
07826 }
07827 if (!newjointcapability && (portno != -1)) {
07828 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
07829
07830 return -1;
07831 }
07832
07833
07834 if (p->rtp) {
07835 if (portno > 0) {
07836 sin.sin_family = AF_INET;
07837 sin.sin_port = htons(portno);
07838 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
07839 ast_rtp_set_peer(p->rtp, &sin);
07840 if (debug)
07841 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07842
07843
07844 p->jointcapability = newjointcapability;
07845 p->peercapability = newpeercapability;
07846 p->jointnoncodeccapability = newnoncodeccapability;
07847
07848 ast_rtp_pt_copy(p->rtp, newaudiortp);
07849
07850 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
07851 ast_clear_flag(&p->flags[0], SIP_DTMF);
07852 if (newnoncodeccapability & AST_RTP_DTMF) {
07853
07854 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
07855
07856 ast_rtp_setdtmf(p->rtp, 1);
07857 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07858 } else {
07859 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
07860 }
07861 }
07862 } else if (udptlportno > 0) {
07863 if (debug)
07864 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
07865 } else {
07866 ast_rtp_stop(p->rtp);
07867 if (debug)
07868 ast_verbose("Peer doesn't provide audio\n");
07869 }
07870 }
07871
07872
07873 if (p->vrtp) {
07874 if (vportno > 0) {
07875 vsin.sin_family = AF_INET;
07876 vsin.sin_port = htons(vportno);
07877 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
07878 ast_rtp_set_peer(p->vrtp, &vsin);
07879 if (debug)
07880 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
07881 ast_rtp_pt_copy(p->vrtp, newvideortp);
07882 } else {
07883 ast_rtp_stop(p->vrtp);
07884 if (debug)
07885 ast_verbose("Peer doesn't provide video\n");
07886 }
07887 }
07888
07889
07890 if (p->trtp) {
07891 if (tportno > 0) {
07892 tsin.sin_family = AF_INET;
07893 tsin.sin_port = htons(tportno);
07894 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
07895 ast_rtp_set_peer(p->trtp, &tsin);
07896 if (debug)
07897 ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
07898 if ((p->jointcapability & AST_FORMAT_T140RED)) {
07899 p->red = 1;
07900 rtp_red_init(p->trtp, 300, red_data_pt, 2);
07901 } else {
07902 p->red = 0;
07903 }
07904 ast_rtp_pt_copy(p->trtp, newtextrtp);
07905 } else {
07906 ast_rtp_stop(p->trtp);
07907 if (debug)
07908 ast_verbose("Peer doesn't provide T.140\n");
07909 }
07910 }
07911
07912 if (p->udptl) {
07913 if (udptlportno > 0) {
07914 isin.sin_family = AF_INET;
07915 isin.sin_port = htons(udptlportno);
07916 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
07917 struct sockaddr_in remote_address = { 0, };
07918 ast_rtp_get_peer(p->rtp, &remote_address);
07919 if (remote_address.sin_addr.s_addr) {
07920 memcpy(&isin, &remote_address, sizeof(isin));
07921 if (debug) {
07922 ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(isin.sin_addr));
07923 }
07924 }
07925 } else {
07926 memcpy(&isin.sin_addr, ihp->h_addr, sizeof(sin.sin_addr));
07927 }
07928 ast_udptl_set_peer(p->udptl, &isin);
07929 if (debug)
07930 ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
07931
07932
07933 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
07934
07935 ast_udptl_set_far_max_datagram(p->udptl, 0);
07936 }
07937
07938
07939 if ((t38action == SDP_T38_ACCEPT) &&
07940 (p->t38.state == T38_LOCAL_REINVITE)) {
07941 change_t38_state(p, T38_ENABLED);
07942 } else if ((t38action == SDP_T38_INITIATE) &&
07943 p->owner && p->lastinvite) {
07944 change_t38_state(p, T38_PEER_REINVITE);
07945 }
07946 } else {
07947 ast_udptl_stop(p->udptl);
07948 if (debug)
07949 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
07950 }
07951 }
07952
07953 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
07954 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
07955 return 0;
07956 }
07957
07958
07959 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
07960
07961 if (!p->owner)
07962 return 0;
07963
07964 ast_debug(4, "We have an owner, now see if we need to change this call\n");
07965
07966 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
07967 if (debug) {
07968 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
07969 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
07970 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
07971 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
07972 }
07973 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
07974 ast_set_read_format(p->owner, p->owner->readformat);
07975 ast_set_write_format(p->owner, p->owner->writeformat);
07976 }
07977
07978 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
07979 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
07980
07981 ast_queue_frame(p->owner, &ast_null_frame);
07982
07983 append_history(p, "Unhold", "%s", req->data->str);
07984 if (global_callevents)
07985 manager_event(EVENT_FLAG_CALL, "Hold",
07986 "Status: Off\r\n"
07987 "Channel: %s\r\n"
07988 "Uniqueid: %s\r\n",
07989 p->owner->name,
07990 p->owner->uniqueid);
07991 if (global_notifyhold)
07992 sip_peer_hold(p, FALSE);
07993 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
07994 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
07995 int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
07996 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
07997 S_OR(p->mohsuggest, NULL),
07998 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
07999 if (sendonly)
08000 ast_rtp_stop(p->rtp);
08001
08002
08003 ast_queue_frame(p->owner, &ast_null_frame);
08004
08005 append_history(p, "Hold", "%s", req->data->str);
08006 if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08007 manager_event(EVENT_FLAG_CALL, "Hold",
08008 "Status: On\r\n"
08009 "Channel: %s\r\n"
08010 "Uniqueid: %s\r\n",
08011 p->owner->name,
08012 p->owner->uniqueid);
08013 }
08014 if (sendonly == 1)
08015 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08016 else if (sendonly == 2)
08017 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08018 else
08019 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08020 if (global_notifyhold && !already_on_hold)
08021 sip_peer_hold(p, TRUE);
08022 }
08023
08024 return 0;
08025 }
08026
08027 static int process_sdp_o(const char *o, struct sip_pvt *p)
08028 {
08029 char *o_copy;
08030 char *token;
08031 int64_t rua_version;
08032
08033
08034
08035
08036
08037
08038
08039
08040
08041
08042 p->session_modify = TRUE;
08043
08044 if (ast_strlen_zero(o)) {
08045 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08046 return FALSE;
08047 }
08048
08049 o_copy = ast_strdupa(o);
08050 token = strsep(&o_copy, " ");
08051 if (!o_copy) {
08052 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08053 return FALSE;
08054 }
08055 token = strsep(&o_copy, " ");
08056 if (!o_copy) {
08057 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08058 return FALSE;
08059 }
08060 token = strsep(&o_copy, " ");
08061 if (!o_copy) {
08062 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08063 return FALSE;
08064 }
08065 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08066 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08067 return FALSE;
08068 }
08069
08070
08071
08072
08073
08074
08075
08076
08077
08078
08079
08080
08081
08082
08083
08084
08085
08086
08087
08088 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08089 (p->sessionversion_remote < 0) ||
08090 (p->sessionversion_remote < rua_version)) {
08091 p->sessionversion_remote = rua_version;
08092 } else {
08093 if (p->t38.state == T38_LOCAL_REINVITE) {
08094 p->sessionversion_remote = rua_version;
08095 ast_log(LOG_WARNING, "Call %s responded to our T.38 reinvite without changing SDP version; 'ignoresdpversion' should be set for this peer.\n", p->callid);
08096 } else {
08097 p->session_modify = FALSE;
08098 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08099 return FALSE;
08100 }
08101 }
08102
08103 return TRUE;
08104 }
08105
08106 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08107 {
08108 char host[258];
08109 struct hostent *hp;
08110
08111
08112 if (sscanf(c, "IN IP4 %255s", host) != 1) {
08113 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08114 return FALSE;
08115 } else {
08116 if (!(hp = ast_gethostbyname(host, ast_hp))) {
08117 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08118 return FALSE;
08119 }
08120 return TRUE;
08121 }
08122 return FALSE;
08123 }
08124
08125 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08126 {
08127 int found = FALSE;
08128
08129 if (!strcasecmp(a, "sendonly")) {
08130 if (*sendonly == -1)
08131 *sendonly = 1;
08132 found = TRUE;
08133 } else if (!strcasecmp(a, "inactive")) {
08134 if (*sendonly == -1)
08135 *sendonly = 2;
08136 found = TRUE;
08137 } else if (!strcasecmp(a, "sendrecv")) {
08138 if (*sendonly == -1)
08139 *sendonly = 0;
08140 found = TRUE;
08141 }
08142 return found;
08143 }
08144
08145 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08146 {
08147 int found = FALSE;
08148 int codec;
08149 char mimeSubtype[128];
08150 int debug = sip_debug_test_pvt(p);
08151
08152 if (!strncasecmp(a, "ptime", 5)) {
08153 char *tmp = strrchr(a, ':');
08154 long int framing = 0;
08155 if (tmp) {
08156 tmp++;
08157 framing = strtol(tmp, NULL, 10);
08158 if (framing == LONG_MIN || framing == LONG_MAX) {
08159 framing = 0;
08160 ast_debug(1, "Can't read framing from SDP: %s\n", a);
08161 }
08162 }
08163 if (framing && p->autoframing) {
08164 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08165 int codec_n;
08166 int format = 0;
08167 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08168 format = ast_rtp_codec_getformat(codec_n);
08169 if (!format)
08170 continue;
08171 if (option_debug)
08172 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08173 ast_codec_pref_setsize(pref, format, framing);
08174 }
08175 ast_rtp_codec_setpref(p->rtp, pref);
08176 }
08177 found = TRUE;
08178 } else if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
08179
08180 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08181 if (ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
08182 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
08183 if (debug)
08184 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08185
08186 (*last_rtpmap_codec)++;
08187 found = TRUE;
08188 } else {
08189 ast_rtp_unset_m_type(newaudiortp, codec);
08190 if (debug)
08191 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08192 }
08193 } else {
08194 if (debug)
08195 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08196 }
08197 }
08198
08199 return found;
08200 }
08201
08202 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08203 {
08204 int found = FALSE;
08205 int codec;
08206 char mimeSubtype[128];
08207 int debug = sip_debug_test_pvt(p);
08208
08209 if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
08210
08211 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08212
08213 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08214 if (ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
08215 if (debug)
08216 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08217
08218 (*last_rtpmap_codec)++;
08219 found = TRUE;
08220 } else {
08221 ast_rtp_unset_m_type(newvideortp, codec);
08222 if (debug)
08223 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08224 }
08225 }
08226 } else {
08227 if (debug)
08228 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08229 }
08230 }
08231
08232 return found;
08233 }
08234
08235 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec)
08236 {
08237 int found = FALSE;
08238 int codec;
08239 char mimeSubtype[128];
08240 char *red_cp;
08241 int debug = sip_debug_test_pvt(p);
08242
08243 if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
08244
08245 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08246 if (!strncasecmp(mimeSubtype, "T140", 4)) {
08247 if (p->trtp) {
08248
08249 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08250 found = TRUE;
08251 }
08252 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
08253 if (p->trtp) {
08254 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08255 sprintf(red_fmtp, "fmtp:%d ", codec);
08256 if (debug)
08257 ast_verbose("RED submimetype has payload type: %d\n", codec);
08258 found = TRUE;
08259 }
08260 }
08261 } else {
08262 if (debug)
08263 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08264 }
08265 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
08266
08267 red_cp = &red_fmtp[strlen(red_fmtp)];
08268 strncpy(red_fmtp, a, 100);
08269
08270 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08271 red_cp = strtok(red_cp, "/");
08272 while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
08273 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08274 red_cp = strtok(NULL, "/");
08275 }
08276 red_cp = red_fmtp;
08277 found = TRUE;
08278 }
08279
08280 return found;
08281 }
08282
08283 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
08284 {
08285 int found = FALSE;
08286 char s[256];
08287 unsigned int x;
08288
08289 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
08290 ast_debug(3, "MaxBufferSize:%d\n", x);
08291 found = TRUE;
08292 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
08293 ast_debug(3, "T38MaxBitRate: %d\n", x);
08294 switch (x) {
08295 case 14400:
08296 p->t38.their_parms.rate = AST_T38_RATE_14400;
08297 break;
08298 case 12000:
08299 p->t38.their_parms.rate = AST_T38_RATE_12000;
08300 break;
08301 case 9600:
08302 p->t38.their_parms.rate = AST_T38_RATE_9600;
08303 break;
08304 case 7200:
08305 p->t38.their_parms.rate = AST_T38_RATE_7200;
08306 break;
08307 case 4800:
08308 p->t38.their_parms.rate = AST_T38_RATE_4800;
08309 break;
08310 case 2400:
08311 p->t38.their_parms.rate = AST_T38_RATE_2400;
08312 break;
08313 }
08314 found = TRUE;
08315 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
08316 ast_debug(3, "FaxVersion: %u\n", x);
08317 p->t38.their_parms.version = x;
08318 found = TRUE;
08319 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
08320
08321 if (p->t38_maxdatagram > x) {
08322 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
08323 x = p->t38_maxdatagram;
08324 }
08325 ast_debug(3, "FaxMaxDatagram: %u\n", x);
08326 ast_udptl_set_far_max_datagram(p->udptl, x);
08327 found = TRUE;
08328 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
08329 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
08330 ast_debug(3, "FillBitRemoval: %d\n", x);
08331 if (x == 1) {
08332 p->t38.their_parms.fill_bit_removal = TRUE;
08333 }
08334 } else {
08335 ast_debug(3, "FillBitRemoval\n");
08336 p->t38.their_parms.fill_bit_removal = TRUE;
08337 }
08338 found = TRUE;
08339 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
08340 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
08341 ast_debug(3, "Transcoding MMR: %d\n", x);
08342 if (x == 1) {
08343 p->t38.their_parms.transcoding_mmr = TRUE;
08344 }
08345 } else {
08346 ast_debug(3, "Transcoding MMR\n");
08347 p->t38.their_parms.transcoding_mmr = TRUE;
08348 }
08349 found = TRUE;
08350 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
08351 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
08352 ast_debug(3, "Transcoding JBIG: %d\n", x);
08353 if (x == 1) {
08354 p->t38.their_parms.transcoding_jbig = TRUE;
08355 }
08356 } else {
08357 ast_debug(3, "Transcoding JBIG\n");
08358 p->t38.their_parms.transcoding_jbig = TRUE;
08359 }
08360 found = TRUE;
08361 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
08362 ast_debug(3, "RateManagement: %s\n", s);
08363 if (!strcasecmp(s, "localTCF"))
08364 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
08365 else if (!strcasecmp(s, "transferredTCF"))
08366 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
08367 found = TRUE;
08368 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
08369 ast_debug(3, "UDP EC: %s\n", s);
08370 if (!strcasecmp(s, "t38UDPRedundancy")) {
08371 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
08372 } else if (!strcasecmp(s, "t38UDPFEC")) {
08373 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
08374 } else {
08375 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08376 }
08377 found = TRUE;
08378 }
08379
08380 return found;
08381 }
08382
08383
08384 #ifdef LOW_MEMORY
08385 static void ts_ast_rtp_destroy(void *data)
08386 {
08387 struct ast_rtp *tmp = data;
08388 ast_rtp_destroy(tmp);
08389 }
08390 #endif
08391
08392
08393 static int add_header(struct sip_request *req, const char *var, const char *value)
08394 {
08395 if (req->headers == SIP_MAX_HEADERS) {
08396 ast_log(LOG_WARNING, "Out of SIP header space\n");
08397 return -1;
08398 }
08399
08400 if (req->lines) {
08401 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
08402 return -1;
08403 }
08404
08405 if (compactheaders)
08406 var = find_alias(var, var);
08407
08408 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
08409 req->header[req->headers] = req->len;
08410
08411 req->len = req->data->used;
08412 req->headers++;
08413
08414 return 0;
08415 }
08416
08417
08418 static int add_header_contentLength(struct sip_request *req, int len)
08419 {
08420 char clen[10];
08421
08422 snprintf(clen, sizeof(clen), "%d", len);
08423 return add_header(req, "Content-Length", clen);
08424 }
08425
08426
08427 static int add_line(struct sip_request *req, const char *line)
08428 {
08429 if (req->lines == SIP_MAX_LINES) {
08430 ast_log(LOG_WARNING, "Out of SIP line space\n");
08431 return -1;
08432 }
08433 if (!req->lines)
08434
08435 req->len += ast_str_append(&req->data, 0, "\r\n");
08436 req->line[req->lines] = req->len;
08437 ast_str_append(&req->data, 0, "%s", line);
08438 req->len = req->data->used;
08439 req->lines++;
08440 return 0;
08441 }
08442
08443
08444 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
08445 {
08446 const char *tmp = get_header(orig, field);
08447
08448 if (!ast_strlen_zero(tmp))
08449 return add_header(req, field, tmp);
08450 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
08451 return -1;
08452 }
08453
08454
08455 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
08456 {
08457 int start = 0;
08458 int copied = 0;
08459 for (;;) {
08460 const char *tmp = __get_header(orig, field, &start);
08461
08462 if (ast_strlen_zero(tmp))
08463 break;
08464
08465 add_header(req, field, tmp);
08466 copied++;
08467 }
08468 return copied ? 0 : -1;
08469 }
08470
08471
08472
08473
08474
08475
08476
08477
08478
08479 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
08480 {
08481 int copied = 0;
08482 int start = 0;
08483
08484 for (;;) {
08485 char new[512];
08486 const char *oh = __get_header(orig, field, &start);
08487
08488 if (ast_strlen_zero(oh))
08489 break;
08490
08491 if (!copied) {
08492 char leftmost[512], *others, *rport;
08493
08494
08495 ast_copy_string(leftmost, oh, sizeof(leftmost));
08496 others = strchr(leftmost, ',');
08497 if (others)
08498 *others++ = '\0';
08499
08500
08501 rport = strstr(leftmost, ";rport");
08502 if (rport && *(rport+6) == '=')
08503 rport = NULL;
08504
08505
08506 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
08507
08508 char *end;
08509
08510 rport = strstr(leftmost, ";rport");
08511
08512 if (rport) {
08513 end = strchr(rport + 1, ';');
08514 if (end)
08515 memmove(rport, end, strlen(end) + 1);
08516 else
08517 *rport = '\0';
08518 }
08519
08520
08521 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
08522 leftmost, ast_inet_ntoa(p->recv.sin_addr),
08523 ntohs(p->recv.sin_port),
08524 others ? "," : "", others ? others : "");
08525 } else {
08526
08527 snprintf(new, sizeof(new), "%s;received=%s%s%s",
08528 leftmost, ast_inet_ntoa(p->recv.sin_addr),
08529 others ? "," : "", others ? others : "");
08530 }
08531 oh = new;
08532 }
08533 add_header(req, field, oh);
08534 copied++;
08535 }
08536 if (!copied) {
08537 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
08538 return -1;
08539 }
08540 return 0;
08541 }
08542
08543
08544 static void add_route(struct sip_request *req, struct sip_route *route)
08545 {
08546 char r[SIPBUFSIZE*2], *p;
08547 int n, rem = sizeof(r);
08548
08549 if (!route)
08550 return;
08551
08552 p = r;
08553 for (;route ; route = route->next) {
08554 n = strlen(route->hop);
08555 if (rem < n+3)
08556 break;
08557 if (p != r) {
08558 *p++ = ',';
08559 --rem;
08560 }
08561 *p++ = '<';
08562 ast_copy_string(p, route->hop, rem);
08563 p += n;
08564 *p++ = '>';
08565 rem -= (n+2);
08566 }
08567 *p = '\0';
08568 add_header(req, "Route", r);
08569 }
08570
08571
08572 static void set_destination(struct sip_pvt *p, char *uri)
08573 {
08574 char *h, *maddr, hostname[256];
08575 int port, hn;
08576 struct hostent *hp;
08577 struct ast_hostent ahp;
08578 int debug=sip_debug_test_pvt(p);
08579
08580
08581
08582
08583 if (debug)
08584 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
08585
08586
08587 h = strchr(uri, '@');
08588 if (h)
08589 ++h;
08590 else {
08591 h = uri;
08592 if (!strncasecmp(h, "sip:", 4))
08593 h += 4;
08594 else if (!strncasecmp(h, "sips:", 5))
08595 h += 5;
08596 }
08597 hn = strcspn(h, ":;>") + 1;
08598 if (hn > sizeof(hostname))
08599 hn = sizeof(hostname);
08600 ast_copy_string(hostname, h, hn);
08601
08602 h += hn - 1;
08603
08604
08605 if (*h == ':') {
08606
08607 ++h;
08608 port = strtol(h, &h, 10);
08609 }
08610 else
08611 port = STANDARD_SIP_PORT;
08612
08613
08614 maddr = strstr(h, "maddr=");
08615 if (maddr) {
08616 maddr += 6;
08617 hn = strspn(maddr, "0123456789.") + 1;
08618 if (hn > sizeof(hostname))
08619 hn = sizeof(hostname);
08620 ast_copy_string(hostname, maddr, hn);
08621 }
08622
08623 hp = ast_gethostbyname(hostname, &ahp);
08624 if (hp == NULL) {
08625 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
08626 return;
08627 }
08628 p->sa.sin_family = AF_INET;
08629 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
08630 p->sa.sin_port = htons(port);
08631 if (debug)
08632 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
08633 }
08634
08635
08636 static int init_resp(struct sip_request *resp, const char *msg)
08637 {
08638
08639 memset(resp, 0, sizeof(*resp));
08640 resp->method = SIP_RESPONSE;
08641 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
08642 return -1;
08643 resp->header[0] = 0;
08644 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
08645 resp->len = resp->data->used;
08646 resp->headers++;
08647 return 0;
08648 }
08649
08650
08651 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
08652 {
08653
08654 memset(req, 0, sizeof(*req));
08655 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
08656 return -1;
08657 req->method = sipmethod;
08658 req->header[0] = 0;
08659 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
08660 req->len = req->data->used;
08661 req->headers++;
08662 return 0;
08663 }
08664
08665
08666 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
08667
08668
08669
08670
08671
08672
08673
08674
08675
08676
08677
08678
08679
08680
08681
08682 switch (method) {
08683
08684 case SIP_INVITE:
08685 case SIP_UPDATE:
08686 case SIP_SUBSCRIBE:
08687 case SIP_NOTIFY:
08688 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
08689 return 1;
08690 break;
08691
08692
08693 case SIP_REGISTER:
08694 case SIP_OPTIONS:
08695 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
08696 return 1;
08697 break;
08698
08699
08700 case SIP_BYE:
08701 case SIP_PRACK:
08702 case SIP_MESSAGE:
08703 case SIP_PUBLISH:
08704 if (msg[0] == '3' || !strncmp(msg, "485", 3))
08705 return 1;
08706 break;
08707
08708
08709 case SIP_REFER:
08710 if (msg[0] >= '2' && msg[0] <= '6')
08711 return 1;
08712 break;
08713
08714
08715 case SIP_ACK:
08716 case SIP_CANCEL:
08717 case SIP_INFO:
08718 case SIP_PING:
08719 default:
08720 return 0;
08721 }
08722 return 0;
08723 }
08724
08725
08726 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
08727 {
08728 char newto[256];
08729 const char *ot;
08730
08731 init_resp(resp, msg);
08732 copy_via_headers(p, resp, req, "Via");
08733 if (msg[0] == '1' || msg[0] == '2')
08734 copy_all_header(resp, req, "Record-Route");
08735 copy_header(resp, req, "From");
08736 ot = get_header(req, "To");
08737 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
08738
08739
08740 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
08741 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
08742 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
08743 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
08744 else
08745 ast_copy_string(newto, ot, sizeof(newto));
08746 ot = newto;
08747 }
08748 add_header(resp, "To", ot);
08749 copy_header(resp, req, "Call-ID");
08750 copy_header(resp, req, "CSeq");
08751 if (!ast_strlen_zero(global_useragent))
08752 add_header(resp, "Server", global_useragent);
08753 add_header(resp, "Allow", ALLOWED_METHODS);
08754 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
08755
08756
08757 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
08758 char se_hdr[256];
08759 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
08760 strefresher2str(p->stimer->st_ref));
08761 add_header(resp, "Require", "timer");
08762 add_header(resp, "Session-Expires", se_hdr);
08763 }
08764
08765 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
08766
08767
08768 char tmp[256];
08769
08770 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
08771 add_header(resp, "Expires", tmp);
08772 if (p->expiry) {
08773 char contact[SIPBUFSIZE];
08774 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
08775 char *brackets = strchr(contact_uri, '<');
08776 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
08777 add_header(resp, "Contact", contact);
08778 }
08779 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
08780 add_header(resp, "Contact", p->our_contact);
08781 }
08782
08783 if (!ast_strlen_zero(p->url)) {
08784 add_header(resp, "Access-URL", p->url);
08785 ast_string_field_set(p, url, NULL);
08786 }
08787
08788 return 0;
08789 }
08790
08791
08792 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
08793 {
08794 struct sip_request *orig = &p->initreq;
08795 char stripped[80];
08796 char tmp[80];
08797 char newto[256];
08798 const char *c;
08799 const char *ot, *of;
08800 int is_strict = FALSE;
08801 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
08802
08803 memset(req, 0, sizeof(struct sip_request));
08804
08805 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
08806
08807 if (!seqno) {
08808 p->ocseq++;
08809 seqno = p->ocseq;
08810 }
08811
08812
08813 if (sipmethod == SIP_CANCEL) {
08814 p->branch = p->invite_branch;
08815 build_via(p);
08816 } else if (newbranch && (sipmethod == SIP_INVITE)) {
08817 p->branch ^= ast_random();
08818 p->invite_branch = p->branch;
08819 build_via(p);
08820 } else if (newbranch) {
08821 p->branch ^= ast_random();
08822 build_via(p);
08823 }
08824
08825
08826 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
08827 is_strict = TRUE;
08828 if (sipdebug)
08829 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
08830 }
08831
08832 if (sipmethod == SIP_CANCEL)
08833 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
08834 else if (sipmethod == SIP_ACK) {
08835
08836
08837 if (!ast_strlen_zero(p->okcontacturi))
08838 c = is_strict ? p->route->hop : p->okcontacturi;
08839 else
08840 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
08841 } else if (!ast_strlen_zero(p->okcontacturi))
08842 c = is_strict ? p->route->hop : p->okcontacturi;
08843 else if (!ast_strlen_zero(p->uri))
08844 c = p->uri;
08845 else {
08846 char *n;
08847
08848 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
08849 sizeof(stripped));
08850 n = get_in_brackets(stripped);
08851 c = remove_uri_parameters(n);
08852 }
08853 init_req(req, sipmethod, c);
08854
08855 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
08856
08857 add_header(req, "Via", p->via);
08858 if (p->route) {
08859 set_destination(p, p->route->hop);
08860 add_route(req, is_strict ? p->route->next : p->route);
08861 }
08862 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
08863
08864 ot = get_header(orig, "To");
08865 of = get_header(orig, "From");
08866
08867
08868
08869 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
08870
08871
08872 if (is_outbound && !ast_strlen_zero(p->theirtag))
08873 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
08874 else if (!is_outbound)
08875 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
08876 else
08877 snprintf(newto, sizeof(newto), "%s", ot);
08878 ot = newto;
08879 }
08880
08881 if (is_outbound) {
08882 add_header(req, "From", of);
08883 add_header(req, "To", ot);
08884 } else {
08885 add_header(req, "From", ot);
08886 add_header(req, "To", of);
08887 }
08888
08889 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
08890 add_header(req, "Contact", p->our_contact);
08891
08892 copy_header(req, orig, "Call-ID");
08893 add_header(req, "CSeq", tmp);
08894
08895 if (!ast_strlen_zero(global_useragent))
08896 add_header(req, "User-Agent", global_useragent);
08897
08898 if (!ast_strlen_zero(p->rpid))
08899 add_header(req, "Remote-Party-ID", p->rpid);
08900
08901 if (!ast_strlen_zero(p->url)) {
08902 add_header(req, "Access-URL", p->url);
08903 ast_string_field_set(p, url, NULL);
08904 }
08905
08906
08907
08908
08909
08910
08911
08912
08913 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
08914 && sipmethod == SIP_INVITE) {
08915 char se_hdr[256];
08916 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
08917 strefresher2str(p->stimer->st_ref));
08918 add_header(req, "Require", "timer");
08919 add_header(req, "Session-Expires", se_hdr);
08920 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
08921 add_header(req, "Min-SE", se_hdr);
08922 }
08923
08924 return 0;
08925 }
08926
08927
08928 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
08929 {
08930 struct sip_request resp;
08931 int seqno = 0;
08932
08933 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
08934 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
08935 return -1;
08936 }
08937 respprep(&resp, p, msg, req);
08938 add_header_contentLength(&resp, 0);
08939
08940
08941 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
08942 char buf[10];
08943
08944 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
08945 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
08946 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
08947 }
08948 return send_response(p, &resp, reliable, seqno);
08949 }
08950
08951 static int temp_pvt_init(void *data)
08952 {
08953 struct sip_pvt *p = data;
08954
08955 p->do_history = 0;
08956 return ast_string_field_init(p, 512);
08957 }
08958
08959 static void temp_pvt_cleanup(void *data)
08960 {
08961 struct sip_pvt *p = data;
08962
08963 ast_string_field_free_memory(p);
08964
08965 ast_free(data);
08966 }
08967
08968
08969 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)
08970 {
08971 struct sip_pvt *p = NULL;
08972
08973 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
08974 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
08975 return -1;
08976 }
08977
08978
08979
08980
08981
08982
08983
08984
08985
08986 p->method = intended_method;
08987
08988 if (!sin)
08989 p->ourip = internip;
08990 else {
08991 p->sa = *sin;
08992 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
08993 }
08994
08995 p->branch = ast_random();
08996 make_our_tag(p->tag, sizeof(p->tag));
08997 p->ocseq = INITIAL_CSEQ;
08998
08999 if (useglobal_nat && sin) {
09000 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09001 p->recv = *sin;
09002 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09003 }
09004
09005 ast_string_field_set(p, fromdomain, default_fromdomain);
09006 build_via(p);
09007 ast_string_field_set(p, callid, callid);
09008
09009 copy_socket_data(&p->socket, &req->socket);
09010
09011
09012 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09013
09014
09015 ast_string_field_init(p, 0);
09016
09017 return 0;
09018 }
09019
09020
09021 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09022 {
09023 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09024 }
09025
09026
09027 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
09028 {
09029 struct sip_request resp;
09030 respprep(&resp, p, msg, req);
09031 append_date(&resp);
09032 add_header(&resp, "Unsupported", unsupported);
09033 add_header_contentLength(&resp, 0);
09034 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09035 }
09036
09037
09038 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09039 {
09040 struct sip_request resp;
09041 char minse_str[20];
09042
09043 respprep(&resp, p, msg, req);
09044 append_date(&resp);
09045
09046 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09047 add_header(&resp, "Min-SE", minse_str);
09048
09049 add_header_contentLength(&resp, 0);
09050 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09051 }
09052
09053
09054
09055
09056
09057 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09058 {
09059 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09060 }
09061
09062
09063 static void append_date(struct sip_request *req)
09064 {
09065 char tmpdat[256];
09066 struct tm tm;
09067 time_t t = time(NULL);
09068
09069 gmtime_r(&t, &tm);
09070 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09071 add_header(req, "Date", tmpdat);
09072 }
09073
09074
09075 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09076 {
09077 struct sip_request resp;
09078 respprep(&resp, p, msg, req);
09079 append_date(&resp);
09080 add_header_contentLength(&resp, 0);
09081 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09082 }
09083
09084
09085 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09086 {
09087 struct sip_request resp;
09088 respprep(&resp, p, msg, req);
09089 add_header(&resp, "Accept", "application/sdp");
09090 add_header_contentLength(&resp, 0);
09091 return send_response(p, &resp, reliable, 0);
09092 }
09093
09094
09095 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)
09096 {
09097 struct sip_request resp;
09098 char tmp[512];
09099 int seqno = 0;
09100
09101 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09102 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09103 return -1;
09104 }
09105
09106
09107 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
09108 respprep(&resp, p, msg, req);
09109 add_header(&resp, header, tmp);
09110 add_header_contentLength(&resp, 0);
09111 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09112 return send_response(p, &resp, reliable, seqno);
09113 }
09114
09115
09116 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09117 {
09118 int res;
09119
09120 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09121 p->last_provisional = msg;
09122 update_provisional_keepalive(p, with_sdp);
09123 }
09124
09125 return res;
09126 }
09127
09128
09129 static int add_text(struct sip_request *req, const char *text)
09130 {
09131
09132 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09133 add_header_contentLength(req, strlen(text));
09134 add_line(req, text);
09135 return 0;
09136 }
09137
09138
09139
09140
09141
09142 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09143 {
09144 char tmp[256];
09145 int event;
09146 if (mode) {
09147
09148 if (digit == '*')
09149 event = 10;
09150 else if (digit == '#')
09151 event = 11;
09152 else if ((digit >= 'A') && (digit <= 'D'))
09153 event = 12 + digit - 'A';
09154 else
09155 event = atoi(&digit);
09156 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09157 add_header(req, "Content-Type", "application/dtmf");
09158 add_header_contentLength(req, strlen(tmp));
09159 add_line(req, tmp);
09160 } else {
09161
09162 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09163 add_header(req, "Content-Type", "application/dtmf-relay");
09164 add_header_contentLength(req, strlen(tmp));
09165 add_line(req, tmp);
09166 }
09167 return 0;
09168 }
09169
09170
09171
09172 static int add_vidupdate(struct sip_request *req)
09173 {
09174 const char *xml_is_a_huge_waste_of_space =
09175 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09176 " <media_control>\r\n"
09177 " <vc_primitive>\r\n"
09178 " <to_encoder>\r\n"
09179 " <picture_fast_update>\r\n"
09180 " </picture_fast_update>\r\n"
09181 " </to_encoder>\r\n"
09182 " </vc_primitive>\r\n"
09183 " </media_control>\r\n";
09184 add_header(req, "Content-Type", "application/media_control+xml");
09185 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
09186 add_line(req, xml_is_a_huge_waste_of_space);
09187 return 0;
09188 }
09189
09190
09191 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
09192 struct ast_str **m_buf, struct ast_str **a_buf,
09193 int debug, int *min_packet_size)
09194 {
09195 int rtp_code;
09196 struct ast_format_list fmt;
09197
09198
09199 if (debug)
09200 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09201 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09202 return;
09203
09204 if (p->rtp) {
09205 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09206 fmt = ast_codec_pref_getsize(pref, codec);
09207 } else
09208 return;
09209 ast_str_append(m_buf, 0, " %d", rtp_code);
09210 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09211 ast_rtp_lookup_mime_subtype(1, codec,
09212 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09213 sample_rate);
09214 if (codec == AST_FORMAT_G729A) {
09215
09216 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09217 } else if (codec == AST_FORMAT_G723_1) {
09218
09219 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09220 } else if (codec == AST_FORMAT_ILBC) {
09221
09222 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
09223 }
09224
09225 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
09226 *min_packet_size = fmt.cur_ms;
09227
09228
09229 if ((*min_packet_size)==0 && fmt.cur_ms)
09230 *min_packet_size = fmt.cur_ms;
09231 }
09232
09233
09234
09235 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
09236 struct ast_str **m_buf, struct ast_str **a_buf,
09237 int debug, int *min_packet_size)
09238 {
09239 int rtp_code;
09240
09241 if (!p->vrtp)
09242 return;
09243
09244 if (debug)
09245 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09246
09247 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
09248 return;
09249
09250 ast_str_append(m_buf, 0, " %d", rtp_code);
09251 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09252 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
09253
09254 }
09255
09256
09257 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
09258 struct ast_str **m_buf, struct ast_str **a_buf,
09259 int debug, int *min_packet_size)
09260 {
09261 int rtp_code;
09262
09263 if (!p->trtp)
09264 return;
09265
09266 if (debug)
09267 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09268
09269 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
09270 return;
09271
09272 ast_str_append(m_buf, 0, " %d", rtp_code);
09273 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09274 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
09275
09276
09277 if (codec == AST_FORMAT_T140RED) {
09278 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
09279 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09280 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09281 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
09282
09283 }
09284 }
09285
09286
09287
09288 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
09289 {
09290 switch (rate) {
09291 case AST_T38_RATE_2400:
09292 return 2400;
09293 case AST_T38_RATE_4800:
09294 return 4800;
09295 case AST_T38_RATE_7200:
09296 return 7200;
09297 case AST_T38_RATE_9600:
09298 return 9600;
09299 case AST_T38_RATE_12000:
09300 return 12000;
09301 case AST_T38_RATE_14400:
09302 return 14400;
09303 default:
09304 return 0;
09305 }
09306 }
09307
09308
09309 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
09310 struct ast_str **m_buf, struct ast_str **a_buf,
09311 int debug)
09312 {
09313 int rtp_code;
09314
09315 if (debug)
09316 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
09317 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
09318 return;
09319
09320 ast_str_append(m_buf, 0, " %d", rtp_code);
09321 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09322 ast_rtp_lookup_mime_subtype(0, format, 0),
09323 sample_rate);
09324 if (format == AST_RTP_DTMF)
09325 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
09326 }
09327
09328
09329
09330
09331 static void get_our_media_address(struct sip_pvt *p, int needvideo,
09332 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
09333 struct sockaddr_in *dest, struct sockaddr_in *vdest)
09334 {
09335
09336 ast_rtp_get_us(p->rtp, sin);
09337 if (p->vrtp)
09338 ast_rtp_get_us(p->vrtp, vsin);
09339 if (p->trtp)
09340 ast_rtp_get_us(p->trtp, tsin);
09341
09342
09343
09344 if (p->redirip.sin_addr.s_addr) {
09345 dest->sin_port = p->redirip.sin_port;
09346 dest->sin_addr = p->redirip.sin_addr;
09347 } else {
09348 dest->sin_addr = p->ourip.sin_addr;
09349 dest->sin_port = sin->sin_port;
09350 }
09351 if (needvideo) {
09352
09353 if (p->vredirip.sin_addr.s_addr) {
09354 vdest->sin_addr = p->vredirip.sin_addr;
09355 vdest->sin_port = p->vredirip.sin_port;
09356 } else {
09357 vdest->sin_addr = p->ourip.sin_addr;
09358 vdest->sin_port = vsin->sin_port;
09359 }
09360 }
09361
09362 }
09363
09364
09365
09366
09367
09368
09369 #define SDP_SAMPLE_RATE(x) 8000
09370
09371
09372
09373
09374
09375
09376
09377 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
09378 {
09379 int len = 0;
09380 int alreadysent = 0;
09381
09382 struct sockaddr_in sin;
09383 struct sockaddr_in vsin;
09384 struct sockaddr_in tsin;
09385 struct sockaddr_in dest;
09386 struct sockaddr_in udptlsin;
09387 struct sockaddr_in vdest = { 0, };
09388 struct sockaddr_in tdest = { 0, };
09389 struct sockaddr_in udptldest = { 0, };
09390
09391
09392 char *version = "v=0\r\n";
09393 char subject[256];
09394 char owner[256];
09395 char connection[256];
09396 char *session_time = "t=0 0\r\n";
09397 char bandwidth[256] = "";
09398 char *hold = "";
09399 struct ast_str *m_audio = ast_str_alloca(256);
09400 struct ast_str *m_video = ast_str_alloca(256);
09401 struct ast_str *m_text = ast_str_alloca(256);
09402 struct ast_str *m_modem = ast_str_alloca(256);
09403 struct ast_str *a_audio = ast_str_alloca(1024);
09404 struct ast_str *a_video = ast_str_alloca(1024);
09405 struct ast_str *a_text = ast_str_alloca(1024);
09406 struct ast_str *a_modem = ast_str_alloca(1024);
09407
09408 int x;
09409 int capability = 0;
09410 int needaudio = FALSE;
09411 int needvideo = FALSE;
09412 int needtext = FALSE;
09413 int debug = sip_debug_test_pvt(p);
09414 int min_audio_packet_size = 0;
09415 int min_video_packet_size = 0;
09416 int min_text_packet_size = 0;
09417
09418 char codecbuf[SIPBUFSIZE];
09419 char buf[SIPBUFSIZE];
09420 char dummy_answer[256];
09421
09422
09423 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
09424
09425 if (!p->rtp) {
09426 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
09427 return AST_FAILURE;
09428 }
09429
09430
09431
09432
09433 if (!p->sessionid) {
09434 p->sessionid = (int)ast_random();
09435 p->sessionversion = p->sessionid;
09436 } else {
09437 if (oldsdp == FALSE)
09438 p->sessionversion++;
09439 }
09440
09441
09442 if (add_audio && (p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
09443 if (p->vrtp) {
09444 needvideo = TRUE;
09445 ast_debug(2, "This call needs video offers!\n");
09446 } else
09447 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
09448 }
09449
09450 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
09451
09452 snprintf(owner, sizeof(owner), "o=%s %d %d IN IP4 %s\r\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner, p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
09453 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
09454
09455 if (add_audio) {
09456 capability = p->jointcapability;
09457
09458
09459 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
09460 p->novideo ? "True" : "False", p->notext ? "True" : "False");
09461 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
09462
09463
09464 if (capability & AST_FORMAT_AUDIO_MASK)
09465 needaudio = TRUE;
09466
09467 if (debug)
09468 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
09469
09470
09471
09472 if (needvideo) {
09473 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
09474
09475
09476 if (p->maxcallbitrate)
09477 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
09478 if (debug)
09479 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));
09480 }
09481
09482
09483 if((capability & AST_FORMAT_TEXT_MASK) && !p->notext) {
09484 if (sipdebug_text)
09485 ast_verbose("We think we can do text\n");
09486 if (p->trtp) {
09487 if (sipdebug_text)
09488 ast_verbose("And we have a text rtp object\n");
09489 needtext = TRUE;
09490 ast_debug(2, "This call needs text offers! \n");
09491 } else
09492 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
09493 }
09494
09495
09496
09497 if (needtext) {
09498 if (sipdebug_text)
09499 ast_verbose("Lets set up the text sdp\n");
09500
09501 if (p->tredirip.sin_addr.s_addr) {
09502 tdest.sin_addr = p->tredirip.sin_addr;
09503 tdest.sin_port = p->tredirip.sin_port;
09504 } else {
09505 tdest.sin_addr = p->ourip.sin_addr;
09506 tdest.sin_port = tsin.sin_port;
09507 }
09508 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
09509
09510 if (debug)
09511 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
09512
09513 }
09514
09515
09516
09517
09518
09519
09520 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
09521
09522 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
09523 hold = "a=recvonly\r\n";
09524 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
09525 hold = "a=inactive\r\n";
09526 else
09527 hold = "a=sendrecv\r\n";
09528
09529
09530
09531
09532
09533
09534
09535
09536
09537
09538 if (capability & p->prefcodec) {
09539 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
09540
09541 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
09542 &m_audio, &a_audio,
09543 debug, &min_audio_packet_size);
09544 alreadysent |= codec;
09545 }
09546
09547
09548 for (x = 0; x < 32; x++) {
09549 int codec;
09550
09551 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
09552 break;
09553
09554 if (!(capability & codec))
09555 continue;
09556
09557 if (alreadysent & codec)
09558 continue;
09559
09560 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
09561 &m_audio, &a_audio,
09562 debug, &min_audio_packet_size);
09563 alreadysent |= codec;
09564 }
09565
09566
09567 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
09568 if (!(capability & x))
09569 continue;
09570
09571 if (alreadysent & x)
09572 continue;
09573
09574 if (x & AST_FORMAT_AUDIO_MASK)
09575 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
09576 &m_audio, &a_audio, debug, &min_audio_packet_size);
09577 else if (x & AST_FORMAT_VIDEO_MASK)
09578 add_vcodec_to_sdp(p, x, 90000,
09579 &m_video, &a_video, debug, &min_video_packet_size);
09580 else if (x & AST_FORMAT_TEXT_MASK)
09581 add_tcodec_to_sdp(p, x, 1000,
09582 &m_text, &a_text, debug, &min_text_packet_size);
09583 }
09584
09585
09586 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
09587 if (!(p->jointnoncodeccapability & x))
09588 continue;
09589
09590 add_noncodec_to_sdp(p, x, 8000, &m_audio, &a_audio, debug);
09591 }
09592
09593 ast_debug(3, "-- Done with adding codecs to SDP\n");
09594
09595 if (!p->owner || !ast_internal_timing_enabled(p->owner))
09596 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
09597
09598 if (min_audio_packet_size)
09599 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
09600
09601
09602 if (min_video_packet_size)
09603 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
09604
09605
09606 if (min_text_packet_size)
09607 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
09608 }
09609
09610 if (add_t38) {
09611 ast_udptl_get_us(p->udptl, &udptlsin);
09612
09613
09614 if (p->udptlredirip.sin_addr.s_addr) {
09615 udptldest.sin_port = p->udptlredirip.sin_port;
09616 udptldest.sin_addr = p->udptlredirip.sin_addr;
09617 } else {
09618 udptldest.sin_addr = p->ourip.sin_addr;
09619 udptldest.sin_port = udptlsin.sin_port;
09620 }
09621
09622 if (debug)
09623 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
09624
09625
09626
09627
09628 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
09629
09630 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
09631 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
09632 if (p->t38.our_parms.fill_bit_removal) {
09633 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
09634 }
09635 if (p->t38.our_parms.transcoding_mmr) {
09636 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
09637 }
09638 if (p->t38.our_parms.transcoding_jbig) {
09639 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
09640 }
09641 switch (p->t38.our_parms.rate_management) {
09642 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
09643 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
09644 break;
09645 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
09646 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
09647 break;
09648 }
09649 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
09650 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
09651 case UDPTL_ERROR_CORRECTION_NONE:
09652 break;
09653 case UDPTL_ERROR_CORRECTION_FEC:
09654 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
09655 break;
09656 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
09657 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
09658 break;
09659 }
09660 }
09661
09662 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
09663 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
09664 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
09665 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
09666
09667 if (needaudio)
09668 ast_str_append(&m_audio, 0, "\r\n");
09669 if (needvideo)
09670 ast_str_append(&m_video, 0, "\r\n");
09671 if (needtext)
09672 ast_str_append(&m_text, 0, "\r\n");
09673
09674 len = strlen(version) + strlen(subject) + strlen(owner) +
09675 strlen(connection) + strlen(session_time);
09676 if (needaudio)
09677 len += m_audio->used + a_audio->used + strlen(hold);
09678 if (needvideo)
09679 len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
09680 if (needtext)
09681 len += m_text->used + a_text->used + strlen(hold);
09682 if (add_t38)
09683 len += m_modem->used + a_modem->used;
09684
09685 add_header(resp, "Content-Type", "application/sdp");
09686 add_header_contentLength(resp, len);
09687 add_line(resp, version);
09688 add_line(resp, owner);
09689 add_line(resp, subject);
09690 add_line(resp, connection);
09691 if (needvideo)
09692 add_line(resp, bandwidth);
09693 add_line(resp, session_time);
09694 if (needaudio) {
09695 add_line(resp, m_audio->str);
09696 add_line(resp, a_audio->str);
09697 add_line(resp, hold);
09698 } else if (p->offered_media[SDP_AUDIO].offered) {
09699 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
09700 add_line(resp, dummy_answer);
09701 }
09702 if (needvideo) {
09703 add_line(resp, m_video->str);
09704 add_line(resp, a_video->str);
09705 add_line(resp, hold);
09706 } else if (p->offered_media[SDP_VIDEO].offered) {
09707 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
09708 add_line(resp, dummy_answer);
09709 }
09710 if (needtext) {
09711 add_line(resp, m_text->str);
09712 add_line(resp, a_text->str);
09713 add_line(resp, hold);
09714 } else if (p->offered_media[SDP_TEXT].offered) {
09715 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
09716 add_line(resp, dummy_answer);
09717 }
09718 if (add_t38) {
09719 add_line(resp, m_modem->str);
09720 add_line(resp, a_modem->str);
09721 } else if (p->offered_media[SDP_IMAGE].offered) {
09722 add_line(resp, "m=image 0 udptl t38\r\n");
09723 }
09724
09725
09726 p->lastrtprx = p->lastrtptx = time(NULL);
09727
09728 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
09729
09730 return AST_SUCCESS;
09731 }
09732
09733
09734 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
09735 {
09736 struct sip_request resp;
09737 int seqno;
09738
09739 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
09740 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
09741 return -1;
09742 }
09743 respprep(&resp, p, msg, req);
09744 if (p->udptl) {
09745 add_sdp(&resp, p, 0, 0, 1);
09746 } else
09747 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
09748 if (retrans && !p->pendinginvite)
09749 p->pendinginvite = seqno;
09750 return send_response(p, &resp, retrans, seqno);
09751 }
09752
09753
09754 static void copy_request(struct sip_request *dst, const struct sip_request *src)
09755 {
09756 struct ast_str *duplicate = dst->data;
09757
09758
09759 memcpy(dst, src, sizeof(*dst));
09760 dst->data = duplicate;
09761
09762
09763
09764
09765
09766
09767
09768 if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
09769 return;
09770 else if (dst->data->len < src->data->used + 1)
09771 ast_str_make_space(&dst->data, src->data->used + 1);
09772
09773 memcpy(dst->data->str, src->data->str, src->data->used + 1);
09774 dst->data->used = src->data->used;
09775 }
09776
09777
09778
09779
09780 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
09781 {
09782 struct sip_request resp;
09783 int seqno;
09784 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
09785 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
09786 return -1;
09787 }
09788 respprep(&resp, p, msg, req);
09789 if (p->rtp) {
09790 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
09791 ast_debug(1, "Setting framing from config on incoming call\n");
09792 ast_rtp_codec_setpref(p->rtp, &p->prefs);
09793 }
09794 try_suggested_sip_codec(p);
09795 if (p->t38.state == T38_ENABLED) {
09796 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
09797 } else {
09798 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
09799 }
09800 } else
09801 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
09802 if (reliable && !p->pendinginvite)
09803 p->pendinginvite = seqno;
09804 return send_response(p, &resp, reliable, seqno);
09805 }
09806
09807
09808 static int determine_firstline_parts(struct sip_request *req)
09809 {
09810 char *e = ast_skip_blanks(req->data->str);
09811 char *local_rlPart1;
09812
09813 if (!*e)
09814 return -1;
09815 req->rlPart1 = e - req->data->str;
09816 local_rlPart1 = e;
09817 e = ast_skip_nonblanks(e);
09818 if (*e)
09819 *e++ = '\0';
09820
09821 e = ast_skip_blanks(e);
09822 if ( !*e )
09823 return -1;
09824 ast_trim_blanks(e);
09825
09826 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
09827 if (strlen(e) < 3)
09828 return -1;
09829 req->rlPart2 = e - req->data->str;
09830 } else {
09831 if ( *e == '<' ) {
09832 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
09833 e++;
09834 if (!*e)
09835 return -1;
09836 }
09837 req->rlPart2 = e - req->data->str;
09838 e = ast_skip_nonblanks(e);
09839 if (*e)
09840 *e++ = '\0';
09841 e = ast_skip_blanks(e);
09842 if (strcasecmp(e, "SIP/2.0") ) {
09843 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
09844 return -1;
09845 }
09846 }
09847 return 1;
09848 }
09849
09850
09851
09852
09853
09854
09855
09856
09857
09858
09859
09860
09861
09862
09863 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
09864 {
09865 struct sip_request req;
09866
09867 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
09868
09869 add_header(&req, "Allow", ALLOWED_METHODS);
09870 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
09871 if (sipdebug) {
09872 if (oldsdp == TRUE)
09873 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
09874 else
09875 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
09876 }
09877
09878 if (p->do_history)
09879 append_history(p, "ReInv", "Re-invite sent");
09880 memset(p->offered_media, 0, sizeof(p->offered_media));
09881
09882 if (t38version)
09883 add_sdp(&req, p, oldsdp, FALSE, TRUE);
09884 else
09885 add_sdp(&req, p, oldsdp, TRUE, FALSE);
09886
09887
09888 initialize_initreq(p, &req);
09889 p->lastinvite = p->ocseq;
09890 ast_set_flag(&p->flags[0], SIP_OUTGOING);
09891
09892 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
09893 }
09894
09895
09896 static char *remove_uri_parameters(char *uri)
09897 {
09898 char *atsign;
09899 atsign = strchr(uri, '@');
09900 if (!atsign)
09901 atsign = uri;
09902 atsign = strchr(atsign, ';');
09903 if (atsign)
09904 *atsign = '\0';
09905 return uri;
09906 }
09907
09908
09909 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
09910 {
09911 char stripped[SIPBUFSIZE];
09912 char *c;
09913
09914 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
09915 c = get_in_brackets(stripped);
09916
09917 c = remove_uri_parameters(c);
09918 if (!ast_strlen_zero(c))
09919 ast_string_field_set(p, uri, c);
09920
09921 }
09922
09923
09924 static void build_contact(struct sip_pvt *p)
09925 {
09926 int ourport = ntohs(p->ourip.sin_port);
09927
09928 if (!sip_standard_port(p->socket.type, ourport)) {
09929 if (p->socket.type == SIP_TRANSPORT_UDP)
09930 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
09931 else
09932 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
09933 } else {
09934 if (p->socket.type == SIP_TRANSPORT_UDP)
09935 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
09936 else
09937 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
09938 }
09939 }
09940
09941
09942 static void build_rpid(struct sip_pvt *p)
09943 {
09944 int send_pres_tags = TRUE;
09945 const char *privacy=NULL;
09946 const char *screen=NULL;
09947 char buf[256];
09948 const char *clid = default_callerid;
09949 const char *clin = NULL;
09950 const char *fromdomain;
09951
09952 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
09953 return;
09954
09955 if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
09956 clid = p->owner->cid.cid_num;
09957 if (p->owner && p->owner->cid.cid_name)
09958 clin = p->owner->cid.cid_name;
09959 if (ast_strlen_zero(clin))
09960 clin = clid;
09961
09962 switch (p->callingpres) {
09963 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
09964 privacy = "off";
09965 screen = "no";
09966 break;
09967 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
09968 privacy = "off";
09969 screen = "yes";
09970 break;
09971 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
09972 privacy = "off";
09973 screen = "no";
09974 break;
09975 case AST_PRES_ALLOWED_NETWORK_NUMBER:
09976 privacy = "off";
09977 screen = "yes";
09978 break;
09979 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
09980 privacy = "full";
09981 screen = "no";
09982 break;
09983 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
09984 privacy = "full";
09985 screen = "yes";
09986 break;
09987 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
09988 privacy = "full";
09989 screen = "no";
09990 break;
09991 case AST_PRES_PROHIB_NETWORK_NUMBER:
09992 privacy = "full";
09993 screen = "yes";
09994 break;
09995 case AST_PRES_NUMBER_NOT_AVAILABLE:
09996 send_pres_tags = FALSE;
09997 break;
09998 default:
09999 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10000 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10001 privacy = "full";
10002 else
10003 privacy = "off";
10004 screen = "no";
10005 break;
10006 }
10007
10008 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10009
10010 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10011 if (send_pres_tags)
10012 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10013 ast_string_field_set(p, rpid, buf);
10014
10015 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10016 S_OR(p->fromuser, clid),
10017 fromdomain, p->tag);
10018 }
10019
10020
10021 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10022 {
10023 struct ast_str *invite = ast_str_alloca(256);
10024 char from[256];
10025 char to[256];
10026 char tmp_n[SIPBUFSIZE/2];
10027 char tmp_l[SIPBUFSIZE/2];
10028 const char *l = NULL;
10029 const char *n = NULL;
10030 const char *d = NULL;
10031 const char *urioptions = "";
10032 int ourport;
10033
10034 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10035 const char *s = p->username;
10036
10037
10038
10039
10040
10041
10042 if (*s == '+')
10043 s++;
10044 for (; *s; s++) {
10045 if (!strchr(AST_DIGIT_ANYNUM, *s) )
10046 break;
10047 }
10048
10049 if (!*s)
10050 urioptions = ";user=phone";
10051 }
10052
10053
10054 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10055
10056 d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10057 if (p->owner) {
10058 l = p->owner->cid.cid_num;
10059 n = p->owner->cid.cid_name;
10060 }
10061
10062 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10063 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10064 l = CALLERID_UNKNOWN;
10065 n = l;
10066 d = FROMDOMAIN_INVALID;
10067 }
10068 if (ast_strlen_zero(l))
10069 l = default_callerid;
10070 if (ast_strlen_zero(n))
10071 n = l;
10072
10073 if (!ast_strlen_zero(p->fromuser))
10074 l = p->fromuser;
10075 else
10076 ast_string_field_set(p, fromuser, l);
10077
10078
10079 if (!ast_strlen_zero(p->fromname))
10080 n = p->fromname;
10081 else
10082 ast_string_field_set(p, fromname, n);
10083
10084 if (pedanticsipchecking) {
10085 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10086 n = tmp_n;
10087 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10088 l = tmp_l;
10089 }
10090
10091 ourport = ntohs(p->ourip.sin_port);
10092 if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10093 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10094 else
10095 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10096
10097
10098 if (!ast_strlen_zero(p->fullcontact)) {
10099
10100 ast_str_append(&invite, 0, "%s", p->fullcontact);
10101 } else {
10102
10103 ast_str_append(&invite, 0, "sip:");
10104 if (!ast_strlen_zero(p->username)) {
10105 n = p->username;
10106 if (pedanticsipchecking) {
10107 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10108 n = tmp_n;
10109 }
10110 ast_str_append(&invite, 0, "%s@", n);
10111 }
10112 ast_str_append(&invite, 0, "%s", p->tohost);
10113 if (p->portinuri)
10114 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10115 ast_str_append(&invite, 0, "%s", urioptions);
10116 }
10117
10118
10119 if (p->options && !ast_strlen_zero(p->options->uri_options))
10120 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10121
10122
10123
10124
10125 ast_string_field_set(p, uri, invite->str);
10126
10127 if (!ast_strlen_zero(p->todnid)) {
10128
10129 if (!strchr(p->todnid, '@')) {
10130
10131 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10132 } else {
10133 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10134 }
10135 } else {
10136 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
10137
10138 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (!strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10139 } else if (p->options && p->options->vxml_url) {
10140
10141 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10142 } else
10143 snprintf(to, sizeof(to), "<%s>", p->uri);
10144 }
10145
10146 init_req(req, sipmethod, p->uri);
10147
10148 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10149
10150 add_header(req, "Via", p->via);
10151 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10152
10153
10154
10155
10156 add_route(req, p->route);
10157
10158
10159 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10160 build_rpid(p);
10161 add_header(req, "From", p->rpid_from);
10162 } else
10163 add_header(req, "From", from);
10164 add_header(req, "To", to);
10165 ast_string_field_set(p, exten, l);
10166 build_contact(p);
10167 add_header(req, "Contact", p->our_contact);
10168 add_header(req, "Call-ID", p->callid);
10169 add_header(req, "CSeq", tmp_n);
10170 if (!ast_strlen_zero(global_useragent))
10171 add_header(req, "User-Agent", global_useragent);
10172 if (!ast_strlen_zero(p->rpid))
10173 add_header(req, "Remote-Party-ID", p->rpid);
10174 }
10175
10176
10177
10178
10179
10180
10181
10182
10183 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10184 {
10185 struct sip_request req;
10186 struct ast_variable *var;
10187
10188 req.method = sipmethod;
10189 if (init) {
10190 p->branch ^= ast_random();
10191 p->invite_branch = p->branch;
10192 build_via(p);
10193 }
10194 if (init > 1)
10195 initreqprep(&req, p, sipmethod);
10196 else
10197
10198 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10199
10200 if (p->options && p->options->auth)
10201 add_header(&req, p->options->authheader, p->options->auth);
10202 append_date(&req);
10203 if (sipmethod == SIP_REFER) {
10204 if (p->refer) {
10205 char buf[SIPBUFSIZE];
10206 if (!ast_strlen_zero(p->refer->refer_to))
10207 add_header(&req, "Refer-To", p->refer->refer_to);
10208 if (!ast_strlen_zero(p->refer->referred_by)) {
10209 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10210 add_header(&req, "Referred-By", buf);
10211 }
10212 }
10213 }
10214
10215
10216 if (p->options && !ast_strlen_zero(p->options->replaces)) {
10217 add_header(&req, "Replaces", p->options->replaces);
10218 add_header(&req, "Require", "replaces");
10219 }
10220
10221
10222 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
10223 char i2astr[10];
10224
10225 if (!p->stimer->st_interval)
10226 p->stimer->st_interval = st_get_se(p, TRUE);
10227
10228 p->stimer->st_active = TRUE;
10229
10230 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
10231 add_header(&req, "Session-Expires", i2astr);
10232 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
10233 add_header(&req, "Min-SE", i2astr);
10234 }
10235
10236 add_header(&req, "Allow", ALLOWED_METHODS);
10237 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10238
10239 if(p->notify_headers) {
10240 char buf[512];
10241 for (var = p->notify_headers; var; var = var->next) {
10242 ast_copy_string(buf, var->value, sizeof(buf));
10243 add_header(&req, var->name, ast_unescape_semicolon(buf));
10244 }
10245 }
10246 if (p->options && p->options->addsipheaders && p->owner) {
10247 struct ast_channel *chan = p->owner;
10248 struct varshead *headp;
10249
10250 ast_channel_lock(chan);
10251
10252 headp = &chan->varshead;
10253
10254 if (!headp)
10255 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
10256 else {
10257 const struct ast_var_t *current;
10258 AST_LIST_TRAVERSE(headp, current, entries) {
10259
10260 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
10261 char *content, *end;
10262 const char *header = ast_var_value(current);
10263 char *headdup = ast_strdupa(header);
10264
10265
10266 if (*headdup == '"')
10267 headdup++;
10268 if ((content = strchr(headdup, ':'))) {
10269 *content++ = '\0';
10270 content = ast_skip_blanks(content);
10271
10272 end = content + strlen(content) -1;
10273 if (*end == '"')
10274 *end = '\0';
10275
10276 add_header(&req, headdup, content);
10277 if (sipdebug)
10278 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
10279 }
10280 }
10281 }
10282 }
10283
10284 ast_channel_unlock(chan);
10285 }
10286 if (sdp) {
10287 memset(p->offered_media, 0, sizeof(p->offered_media));
10288 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
10289 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
10290 add_sdp(&req, p, FALSE, FALSE, TRUE);
10291 } else if (p->rtp)
10292 add_sdp(&req, p, FALSE, TRUE, FALSE);
10293 } else {
10294 if (!p->notify_headers) {
10295 add_header_contentLength(&req, 0);
10296 }
10297 }
10298
10299 if (!p->initreq.headers || init > 2)
10300 initialize_initreq(p, &req);
10301 p->lastinvite = p->ocseq;
10302 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
10303 }
10304
10305
10306 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
10307 {
10308 struct ast_str *tmp = ast_str_alloca(4000);
10309 char from[256], to[256];
10310 char *c, *mfrom, *mto;
10311 struct sip_request req;
10312 char hint[AST_MAX_EXTENSION];
10313 char *statestring = "terminated";
10314 const struct cfsubscription_types *subscriptiontype;
10315 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
10316 char *pidfstate = "--";
10317 char *pidfnote= "Ready";
10318
10319 memset(from, 0, sizeof(from));
10320 memset(to, 0, sizeof(to));
10321
10322 switch (state) {
10323 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
10324 statestring = (global_notifyringing) ? "early" : "confirmed";
10325 local_state = NOTIFY_INUSE;
10326 pidfstate = "busy";
10327 pidfnote = "Ringing";
10328 break;
10329 case AST_EXTENSION_RINGING:
10330 statestring = "early";
10331 local_state = NOTIFY_INUSE;
10332 pidfstate = "busy";
10333 pidfnote = "Ringing";
10334 break;
10335 case AST_EXTENSION_INUSE:
10336 statestring = "confirmed";
10337 local_state = NOTIFY_INUSE;
10338 pidfstate = "busy";
10339 pidfnote = "On the phone";
10340 break;
10341 case AST_EXTENSION_BUSY:
10342 statestring = "confirmed";
10343 local_state = NOTIFY_CLOSED;
10344 pidfstate = "busy";
10345 pidfnote = "On the phone";
10346 break;
10347 case AST_EXTENSION_UNAVAILABLE:
10348 statestring = "terminated";
10349 local_state = NOTIFY_CLOSED;
10350 pidfstate = "away";
10351 pidfnote = "Unavailable";
10352 break;
10353 case AST_EXTENSION_ONHOLD:
10354 statestring = "confirmed";
10355 local_state = NOTIFY_CLOSED;
10356 pidfstate = "busy";
10357 pidfnote = "On hold";
10358 break;
10359 case AST_EXTENSION_NOT_INUSE:
10360 default:
10361
10362 break;
10363 }
10364
10365 subscriptiontype = find_subscription_type(p->subscribed);
10366
10367
10368 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
10369 char *hint2 = hint, *individual_hint = NULL;
10370 int hint_count = 0, unavailable_count = 0;
10371
10372 while ((individual_hint = strsep(&hint2, "&"))) {
10373 hint_count++;
10374
10375 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
10376 unavailable_count++;
10377 }
10378
10379
10380
10381
10382 if (hint_count > 0 && hint_count == unavailable_count) {
10383 local_state = NOTIFY_CLOSED;
10384 pidfstate = "away";
10385 pidfnote = "Not online";
10386 }
10387 }
10388
10389 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
10390 c = get_in_brackets(from);
10391 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
10392 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
10393 return -1;
10394 }
10395
10396 mfrom = remove_uri_parameters(c);
10397
10398 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
10399 c = get_in_brackets(to);
10400 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
10401 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
10402 return -1;
10403 }
10404 mto = remove_uri_parameters(c);
10405
10406 reqprep(&req, p, SIP_NOTIFY, 0, 1);
10407
10408
10409 add_header(&req, "Event", subscriptiontype->event);
10410 add_header(&req, "Content-Type", subscriptiontype->mediatype);
10411 switch(state) {
10412 case AST_EXTENSION_DEACTIVATED:
10413 if (timeout)
10414 add_header(&req, "Subscription-State", "terminated;reason=timeout");
10415 else {
10416 add_header(&req, "Subscription-State", "terminated;reason=probation");
10417 add_header(&req, "Retry-After", "60");
10418 }
10419 break;
10420 case AST_EXTENSION_REMOVED:
10421 add_header(&req, "Subscription-State", "terminated;reason=noresource");
10422 break;
10423 default:
10424 if (p->expiry)
10425 add_header(&req, "Subscription-State", "active");
10426 else
10427 add_header(&req, "Subscription-State", "terminated;reason=timeout");
10428 }
10429 switch (p->subscribed) {
10430 case XPIDF_XML:
10431 case CPIM_PIDF_XML:
10432 ast_str_append(&tmp, 0,
10433 "<?xml version=\"1.0\"?>\n"
10434 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
10435 "<presence>\n");
10436 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
10437 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
10438 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
10439 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
10440 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
10441 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
10442 break;
10443 case PIDF_XML:
10444 ast_str_append(&tmp, 0,
10445 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
10446 "<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);
10447 ast_str_append(&tmp, 0, "<pp:person><status>\n");
10448 if (pidfstate[0] != '-')
10449 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
10450 ast_str_append(&tmp, 0, "</status></pp:person>\n");
10451 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote);
10452 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten);
10453 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
10454 if (pidfstate[0] == 'b')
10455 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
10456 else
10457 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
10458 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
10459 break;
10460 case DIALOG_INFO_XML:
10461 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
10462 ast_str_append(&tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
10463 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
10464 ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
10465 else
10466 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
10467 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
10468 if (state == AST_EXTENSION_ONHOLD) {
10469 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
10470 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
10471 "</target>\n</local>\n", mto);
10472 }
10473 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
10474 break;
10475 case NONE:
10476 default:
10477 break;
10478 }
10479
10480 add_header_contentLength(&req, tmp->used);
10481 add_line(&req, tmp->str);
10482
10483 p->pendinginvite = p->ocseq;
10484
10485 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10486 }
10487
10488
10489
10490
10491
10492
10493
10494 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
10495 {
10496 struct sip_request req;
10497 struct ast_str *out = ast_str_alloca(500);
10498 int ourport = ntohs(p->ourip.sin_port);
10499 const char *exten = S_OR(vmexten, default_vmexten);
10500
10501 initreqprep(&req, p, SIP_NOTIFY);
10502 add_header(&req, "Event", "message-summary");
10503 add_header(&req, "Content-Type", default_notifymime);
10504 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
10505
10506 if (!ast_strlen_zero(p->fromdomain)) {
10507 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
10508 } else if (!sip_standard_port(p->socket.type, ourport)) {
10509 if (p->socket.type == SIP_TRANSPORT_UDP) {
10510 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
10511 } else {
10512 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
10513 }
10514 } else {
10515 if (p->socket.type == SIP_TRANSPORT_UDP) {
10516 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
10517 } else {
10518 ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
10519 }
10520 }
10521
10522
10523
10524 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
10525 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
10526
10527 if (p->subscribed) {
10528 if (p->expiry)
10529 add_header(&req, "Subscription-State", "active");
10530 else
10531 add_header(&req, "Subscription-State", "terminated;reason=timeout");
10532 }
10533
10534 add_header_contentLength(&req, out->used);
10535 add_line(&req, out->str);
10536
10537 if (!p->initreq.headers)
10538 initialize_initreq(p, &req);
10539 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10540 }
10541
10542
10543 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
10544 {
10545 struct sip_request req;
10546 char tmp[SIPBUFSIZE/2];
10547
10548 reqprep(&req, p, SIP_NOTIFY, 0, 1);
10549 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
10550 add_header(&req, "Event", tmp);
10551 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
10552 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
10553 add_header(&req, "Allow", ALLOWED_METHODS);
10554 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10555
10556 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
10557 add_header_contentLength(&req, strlen(tmp));
10558 add_line(&req, tmp);
10559
10560 if (!p->initreq.headers)
10561 initialize_initreq(p, &req);
10562
10563 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10564 }
10565
10566
10567 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
10568 struct sip_request req;
10569 struct ast_variable *var, *newvar;
10570
10571 initreqprep(&req, p, SIP_NOTIFY);
10572
10573
10574 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
10575 add_header(&req, newvar->name, newvar->value);
10576 for (var = vars; var; var = var->next) {
10577 char buf[512];
10578 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
10579 ast_copy_string(buf, var->value, sizeof(buf));
10580 add_header(&req, var->name, ast_unescape_semicolon(buf));
10581 newvar->next = ast_variable_new(var->name, var->value, "");
10582 newvar = newvar->next;
10583 }
10584
10585 if (!p->initreq.headers) {
10586 initialize_initreq(p, &req);
10587 }
10588
10589 return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
10590 }
10591
10592 static int manager_sipnotify(struct mansession *s, const struct message *m)
10593 {
10594 const char *channame = astman_get_header(m, "Channel");
10595 struct ast_variable *vars = astman_get_variables(m);
10596 struct sip_pvt *p;
10597
10598 if (ast_strlen_zero(channame)) {
10599 astman_send_error(s, m, "SIPNotify requires a channel name");
10600 return 0;
10601 }
10602
10603 if (!strncasecmp(channame, "sip/", 4)) {
10604 channame += 4;
10605 }
10606
10607 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
10608 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
10609 return 0;
10610 }
10611
10612 if (create_addr(p, channame, NULL, 0)) {
10613
10614 dialog_unlink_all(p, TRUE, TRUE);
10615 dialog_unref(p, "unref dialog inside for loop" );
10616
10617 astman_send_error(s, m, "Could not create address");
10618 return 0;
10619 }
10620
10621
10622 ast_set_flag(&p->flags[0], SIP_OUTGOING);
10623
10624
10625 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10626 build_via(p);
10627 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
10628 build_callid_pvt(p);
10629 ao2_t_link(dialogs, p, "Linking in new name");
10630 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
10631 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
10632
10633 if (!transmit_notify_custom(p, vars)) {
10634 astman_send_ack(s, m, "Notify Sent");
10635 } else {
10636 astman_send_error(s, m, "Unable to send notify");
10637 }
10638 ast_variables_destroy(vars);
10639 return 0;
10640 }
10641
10642 static char mandescr_sipnotify[] =
10643 "Description: Sends a SIP Notify event\n"
10644 "All parameters for this event must be specified in the body of this request\n"
10645 "via multiple Variable: name=value sequences.\n"
10646 "Variables: \n"
10647 " *Channel: <peername> Peer to receive the notify. Required.\n"
10648 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
10649 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
10650
10651 static const struct _map_x_s regstatestrings[] = {
10652 { REG_STATE_FAILED, "Failed" },
10653 { REG_STATE_UNREGISTERED, "Unregistered"},
10654 { REG_STATE_REGSENT, "Request Sent"},
10655 { REG_STATE_AUTHSENT, "Auth. Sent"},
10656 { REG_STATE_REGISTERED, "Registered"},
10657 { REG_STATE_REJECTED, "Rejected"},
10658 { REG_STATE_TIMEOUT, "Timeout"},
10659 { REG_STATE_NOAUTH, "No Authentication"},
10660 { -1, NULL }
10661 };
10662
10663
10664 static const char *regstate2str(enum sipregistrystate regstate)
10665 {
10666 return map_x_s(regstatestrings, regstate, "Unknown");
10667 }
10668
10669
10670
10671
10672
10673
10674
10675 static int sip_reregister(const void *data)
10676 {
10677
10678 struct sip_registry *r= (struct sip_registry *) data;
10679
10680
10681 if (!r)
10682 return 0;
10683
10684 if (r->call && r->call->do_history)
10685 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
10686
10687
10688 if (sipdebug)
10689 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
10690
10691 r->expire = -1;
10692 r->expiry = r->configured_expiry;
10693 __sip_do_register(r);
10694 registry_unref(r, "unref the re-register scheduled event");
10695 return 0;
10696 }
10697
10698
10699 static int __sip_do_register(struct sip_registry *r)
10700 {
10701 int res;
10702
10703 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
10704 return res;
10705 }
10706
10707
10708
10709
10710
10711
10712
10713 static int sip_reg_timeout(const void *data)
10714 {
10715
10716
10717 struct sip_registry *r = (struct sip_registry *)data;
10718 struct sip_pvt *p;
10719 int res;
10720
10721
10722 if (!r)
10723 return 0;
10724
10725 if (r->dnsmgr) {
10726
10727 ast_dnsmgr_refresh(r->dnsmgr);
10728 }
10729
10730 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
10731
10732
10733
10734
10735 if (r->call) {
10736
10737
10738 p = r->call;
10739 sip_pvt_lock(p);
10740 p->needdestroy = 1;
10741
10742 __sip_pretend_ack(p);
10743 sip_pvt_unlock(p);
10744
10745
10746
10747 if (p->registry)
10748 p->registry = registry_unref(p->registry, "p->registry unreffed");
10749 r->call = dialog_unref(r->call, "unrefing r->call");
10750 }
10751
10752 r->timeout = -1;
10753 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
10754
10755
10756
10757 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
10758 r->regstate = REG_STATE_FAILED;
10759 } else {
10760 r->regstate = REG_STATE_UNREGISTERED;
10761 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
10762 }
10763 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
10764 registry_unref(r, "unreffing registry_unref r");
10765 return 0;
10766 }
10767
10768
10769
10770
10771 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
10772 {
10773 struct sip_request req;
10774 char from[256];
10775 char to[256];
10776 char tmp[80];
10777 char addr[80];
10778 struct sip_pvt *p;
10779 struct sip_peer *peer = NULL;
10780 int res;
10781 char *fromdomain;
10782
10783
10784 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
10785 if (r) {
10786 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
10787 }
10788 return 0;
10789 }
10790
10791 if (r->dnsmgr == NULL) {
10792 char transport[MAXHOSTNAMELEN];
10793 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
10794 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport));
10795 ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, global_srvlookup ? transport : NULL);
10796 if (peer) {
10797 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
10798 }
10799 }
10800
10801 if (r->call) {
10802 if (!auth) {
10803 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
10804 return 0;
10805 } else {
10806 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
10807 make_our_tag(p->tag, sizeof(p->tag));
10808 ast_string_field_set(p, theirtag, NULL);
10809 }
10810 } else {
10811
10812 if (!r->callid_valid) {
10813 build_callid_registry(r, internip.sin_addr, default_fromdomain);
10814 r->callid_valid = TRUE;
10815 }
10816
10817 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
10818 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
10819 return 0;
10820 }
10821
10822 if (p->do_history)
10823 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
10824
10825 if (!ast_strlen_zero(r->peername)) {
10826 if (!(peer = find_peer(r->peername, NULL, 1, FINDPEERS, FALSE, 0))) {
10827 ast_log(LOG_WARNING, "Could not find peer %s in transmit_register\n", r->peername);
10828 } else {
10829 p->peerauth = peer->auth;
10830 }
10831 }
10832 ref_proxy(p, obproxy_get(p, peer));
10833 if (peer) {
10834 unref_peer(peer, "transmit_registration: from find_peer operation");
10835 }
10836
10837 if (!r->us.sin_port && r->portno)
10838 r->us.sin_port = htons(r->portno);
10839
10840
10841 if (create_addr(p, r->hostname, &r->us, 0)) {
10842
10843
10844 dialog_unlink_all(p, TRUE, TRUE);
10845 p = dialog_unref(p, "unref dialog after unlink_all");
10846 if (r->timeout > -1) {
10847 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
10848 registry_unref(_data, "del for REPLACE of registry ptr"),
10849 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
10850 registry_addref(r,"add for REPLACE registry ptr"));
10851 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
10852 } else {
10853 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
10854 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);
10855 }
10856 r->regattempts++;
10857 return 0;
10858 }
10859
10860
10861 ast_string_field_set(r, callid, p->callid);
10862 if (!r->dnsmgr && r->portno) {
10863 p->sa.sin_port = htons(r->portno);
10864 p->recv.sin_port = htons(r->portno);
10865 } else {
10866 r->portno = ntohs(p->sa.sin_port);
10867 }
10868 ast_set_flag(&p->flags[0], SIP_OUTGOING);
10869 r->call = dialog_ref(p, "copying dialog into registry r->call");
10870 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
10871 if (!ast_strlen_zero(r->secret))
10872 ast_string_field_set(p, peersecret, r->secret);
10873 if (!ast_strlen_zero(r->md5secret))
10874 ast_string_field_set(p, peermd5secret, r->md5secret);
10875
10876
10877 if (!ast_strlen_zero(r->authuser)) {
10878 ast_string_field_set(p, peername, r->authuser);
10879 ast_string_field_set(p, authname, r->authuser);
10880 } else if (!ast_strlen_zero(r->username)) {
10881 ast_string_field_set(p, peername, r->username);
10882 ast_string_field_set(p, authname, r->username);
10883 ast_string_field_set(p, fromuser, r->username);
10884 }
10885 if (!ast_strlen_zero(r->username))
10886 ast_string_field_set(p, username, r->username);
10887
10888 if (!ast_strlen_zero(r->callback))
10889 ast_string_field_set(p, exten, r->callback);
10890
10891
10892 set_socket_transport(&p->socket, r->transport);
10893 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
10894 p->socket.port = sip_tcp_desc.local_address.sin_port;
10895 }
10896
10897
10898
10899
10900
10901
10902 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10903 build_contact(p);
10904 }
10905
10906
10907 if (auth == NULL) {
10908 if (r->timeout > -1)
10909 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
10910 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
10911 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
10912 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
10913 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
10914 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
10915 }
10916
10917 if ((fromdomain = strchr(r->username, '@'))) {
10918
10919 fromdomain++ ;
10920
10921 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
10922 if (!ast_strlen_zero(p->theirtag))
10923 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
10924 else
10925 snprintf(to, sizeof(to), "<sip:%s>", r->username);
10926
10927
10928
10929 if (ast_strlen_zero(p->fromdomain)) {
10930 ast_string_field_set(p, fromdomain, fromdomain);
10931 }
10932 } else {
10933 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
10934 if (!ast_strlen_zero(p->theirtag))
10935 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
10936 else
10937 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
10938 }
10939
10940
10941
10942 if (!ast_strlen_zero(p->fromdomain)) {
10943 if (r->portno && r->portno != STANDARD_SIP_PORT)
10944 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
10945 else
10946 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
10947 } else {
10948 if (r->portno && r->portno != STANDARD_SIP_PORT)
10949 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
10950 else
10951 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
10952 }
10953 ast_string_field_set(p, uri, addr);
10954
10955 p->branch ^= ast_random();
10956
10957 init_req(&req, sipmethod, addr);
10958
10959
10960 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
10961 p->ocseq = r->ocseq;
10962
10963 build_via(p);
10964 add_header(&req, "Via", p->via);
10965 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10966 add_header(&req, "From", from);
10967 add_header(&req, "To", to);
10968 add_header(&req, "Call-ID", p->callid);
10969 add_header(&req, "CSeq", tmp);
10970 if (!ast_strlen_zero(global_useragent))
10971 add_header(&req, "User-Agent", global_useragent);
10972
10973
10974 if (auth)
10975 add_header(&req, authheader, auth);
10976 else if (!ast_strlen_zero(r->nonce)) {
10977 char digest[1024];
10978
10979
10980
10981
10982
10983
10984 if (sipdebug)
10985 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
10986 ast_string_field_set(p, realm, r->realm);
10987 ast_string_field_set(p, nonce, r->nonce);
10988 ast_string_field_set(p, domain, r->domain);
10989 ast_string_field_set(p, opaque, r->opaque);
10990 ast_string_field_set(p, qop, r->qop);
10991 p->noncecount = ++r->noncecount;
10992
10993 memset(digest, 0, sizeof(digest));
10994 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
10995 add_header(&req, "Authorization", digest);
10996 else
10997 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
10998
10999 }
11000
11001 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11002 add_header(&req, "Expires", tmp);
11003 add_header(&req, "Contact", p->our_contact);
11004 add_header_contentLength(&req, 0);
11005
11006 initialize_initreq(p, &req);
11007 if (sip_debug_test_pvt(p)) {
11008 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11009 }
11010 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11011 r->regattempts++;
11012 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11013 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11014 dialog_unref(p, "p is finished here at the end of transmit_register");
11015 return res;
11016 }
11017
11018
11019 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11020 {
11021 struct sip_request req;
11022
11023 reqprep(&req, p, SIP_MESSAGE, 0, 1);
11024 add_text(&req, text);
11025 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11026 }
11027
11028
11029 static int sip_refer_allocate(struct sip_pvt *p)
11030 {
11031 p->refer = ast_calloc(1, sizeof(struct sip_refer));
11032 return p->refer ? 1 : 0;
11033 }
11034
11035
11036
11037
11038
11039
11040 static int transmit_refer(struct sip_pvt *p, const char *dest)
11041 {
11042 struct sip_request req = {
11043 .headers = 0,
11044 };
11045 char from[256];
11046 const char *of;
11047 char *c;
11048 char referto[256];
11049 char *ttag, *ftag;
11050 char *theirtag = ast_strdupa(p->theirtag);
11051
11052 if (sipdebug)
11053 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11054
11055
11056 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11057 of = get_header(&p->initreq, "To");
11058 ttag = theirtag;
11059 ftag = p->tag;
11060 } else {
11061 of = get_header(&p->initreq, "From");
11062 ftag = theirtag;
11063 ttag = p->tag;
11064 }
11065
11066 ast_copy_string(from, of, sizeof(from));
11067 of = get_in_brackets(from);
11068 ast_string_field_set(p, from, of);
11069 if (!strncasecmp(of, "sip:", 4))
11070 of += 4;
11071 else if (!strncasecmp(of, "sips:", 5))
11072 of += 5;
11073 else
11074 ast_log(LOG_NOTICE, "From address missing 'sip(s):', using it anyway\n");
11075
11076 if ((c = strchr(dest, '@')))
11077 c = NULL;
11078 else if ((c = strchr(of, '@')))
11079 *c++ = '\0';
11080 if (c)
11081 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
11082 else
11083 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
11084
11085
11086 sip_refer_allocate(p);
11087 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
11088 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
11089 p->refer->status = REFER_SENT;
11090
11091 reqprep(&req, p, SIP_REFER, 0, 1);
11092
11093 add_header(&req, "Refer-To", referto);
11094 add_header(&req, "Allow", ALLOWED_METHODS);
11095 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11096 if (!ast_strlen_zero(p->our_contact))
11097 add_header(&req, "Referred-By", p->our_contact);
11098
11099 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109 }
11110
11111
11112
11113 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
11114 {
11115 struct sip_request req;
11116
11117 reqprep(&req, p, SIP_INFO, 0, 1);
11118 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
11119 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11120 }
11121
11122
11123 static int transmit_info_with_vidupdate(struct sip_pvt *p)
11124 {
11125 struct sip_request req;
11126
11127 reqprep(&req, p, SIP_INFO, 0, 1);
11128 add_vidupdate(&req);
11129 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11130 }
11131
11132
11133
11134
11135 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11136 {
11137 struct sip_request resp;
11138
11139 if (sipmethod == SIP_ACK)
11140 p->invitestate = INV_CONFIRMED;
11141
11142 reqprep(&resp, p, sipmethod, seqno, newbranch);
11143 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
11144 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
11145
11146 add_header_contentLength(&resp, 0);
11147 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
11148 }
11149
11150
11151 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
11152 {
11153 if (code == WWW_AUTH) {
11154 *header = "WWW-Authenticate";
11155 *respheader = "Authorization";
11156 } else if (code == PROXY_AUTH) {
11157 *header = "Proxy-Authenticate";
11158 *respheader = "Proxy-Authorization";
11159 } else {
11160 ast_verbose("-- wrong response code %d\n", code);
11161 *header = *respheader = "Invalid";
11162 }
11163 }
11164
11165
11166 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11167 {
11168 struct sip_request resp;
11169
11170 reqprep(&resp, p, sipmethod, seqno, newbranch);
11171 if (!ast_strlen_zero(p->realm)) {
11172 char digest[1024];
11173
11174 memset(digest, 0, sizeof(digest));
11175 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
11176 char *dummy, *response;
11177 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
11178 auth_headers(code, &dummy, &response);
11179 add_header(&resp, response, digest);
11180 } else
11181 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
11182 }
11183
11184
11185 if (sipmethod == SIP_BYE) {
11186 char buf[10];
11187
11188 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
11189 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
11190 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
11191 }
11192
11193 add_header_contentLength(&resp, 0);
11194 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
11195 }
11196
11197
11198 static void destroy_association(struct sip_peer *peer)
11199 {
11200 int realtimeregs = ast_check_realtime("sipregs");
11201 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
11202
11203 if (!sip_cfg.ignore_regexpire) {
11204 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
11205 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
11206 } else {
11207 ast_db_del("SIP/Registry", peer->name);
11208 }
11209 }
11210 }
11211
11212 static void set_socket_transport(struct sip_socket *socket, int transport)
11213 {
11214
11215 if (socket->type != transport) {
11216 socket->fd = -1;
11217 socket->type = transport;
11218 if (socket->tcptls_session) {
11219 ao2_ref(socket->tcptls_session, -1);
11220 socket->tcptls_session = NULL;
11221 }
11222 }
11223 }
11224
11225
11226 static int expire_register(const void *data)
11227 {
11228 struct sip_peer *peer = (struct sip_peer *)data;
11229
11230 if (!peer)
11231 return 0;
11232
11233 peer->expire = -1;
11234 peer->portinuri = 0;
11235 memset(&peer->addr, 0, sizeof(peer->addr));
11236
11237 destroy_association(peer);
11238 set_socket_transport(&peer->socket, peer->default_outbound_transport);
11239
11240 if (peer->socket.tcptls_session) {
11241 ao2_ref(peer->socket.tcptls_session, -1);
11242 peer->socket.tcptls_session = NULL;
11243 }
11244
11245 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
11246 register_peer_exten(peer, FALSE);
11247 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
11248
11249
11250
11251
11252 if (peer->is_realtime)
11253 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
11254
11255 if (peer->selfdestruct ||
11256 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
11257 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
11258 if (peer->addr.sin_addr.s_addr) {
11259 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
11260 }
11261 }
11262
11263 unref_peer(peer, "removing peer ref for expire_register");
11264
11265 return 0;
11266 }
11267
11268
11269 static int sip_poke_peer_s(const void *data)
11270 {
11271 struct sip_peer *peer = (struct sip_peer *)data;
11272
11273 peer->pokeexpire = -1;
11274
11275 sip_poke_peer(peer, 0);
11276
11277 unref_peer(peer, "removing poke peer ref");
11278
11279 return 0;
11280 }
11281
11282
11283 static void reg_source_db(struct sip_peer *peer)
11284 {
11285 char data[256];
11286 struct in_addr in;
11287 int expire;
11288 int port;
11289 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
11290
11291 if (peer->rt_fromcontact)
11292 return;
11293 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
11294 return;
11295
11296 scan = data;
11297 addr = strsep(&scan, ":");
11298 port_str = strsep(&scan, ":");
11299 expiry_str = strsep(&scan, ":");
11300 username = strsep(&scan, ":");
11301 contact = scan;
11302
11303 if (!inet_aton(addr, &in))
11304 return;
11305
11306 if (port_str)
11307 port = atoi(port_str);
11308 else
11309 return;
11310
11311 if (expiry_str)
11312 expire = atoi(expiry_str);
11313 else
11314 return;
11315
11316 if (username)
11317 ast_copy_string(peer->username, username, sizeof(peer->username));
11318 if (contact)
11319 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
11320
11321 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
11322 peer->name, peer->username, ast_inet_ntoa(in), port, expire);
11323
11324 memset(&peer->addr, 0, sizeof(peer->addr));
11325 peer->addr.sin_family = AF_INET;
11326 peer->addr.sin_addr = in;
11327 peer->addr.sin_port = htons(port);
11328 if (sipsock < 0) {
11329
11330 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
11331 unref_peer(_data, "removing poke peer ref"),
11332 unref_peer(peer, "removing poke peer ref"),
11333 ref_peer(peer, "adding poke peer ref"));
11334 } else {
11335 sip_poke_peer(peer, 0);
11336 }
11337 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
11338 unref_peer(_data, "remove registration ref"),
11339 unref_peer(peer, "remove registration ref"),
11340 ref_peer(peer, "add registration ref"));
11341 register_peer_exten(peer, TRUE);
11342 }
11343
11344
11345 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
11346 {
11347 char contact[SIPBUFSIZE];
11348 char *c;
11349
11350
11351 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
11352 c = get_in_brackets(contact);
11353
11354
11355 ast_string_field_set(pvt, fullcontact, c);
11356
11357
11358 ast_string_field_set(pvt, okcontacturi, c);
11359
11360
11361
11362 return TRUE;
11363 }
11364
11365 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
11366 {
11367 struct hostent *hp;
11368 struct ast_hostent ahp;
11369 int port = STANDARD_SIP_PORT;
11370 char *host, *pt, *transport;
11371 char contact_buf[256];
11372 char *contact;
11373
11374
11375 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
11376 contact = contact_buf;
11377
11378
11379
11380
11381
11382
11383
11384
11385 if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
11386 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
11387 }
11388
11389
11390 if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
11391 port = port_str2int(pt, STANDARD_TLS_PORT);
11392 } else {
11393 port = port_str2int(pt, STANDARD_SIP_PORT);
11394 }
11395
11396
11397
11398 hp = ast_gethostbyname(host, &ahp);
11399 if (!hp) {
11400 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
11401 return -1;
11402 }
11403 sin->sin_family = AF_INET;
11404 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
11405 sin->sin_port = htons(port);
11406
11407 return 0;
11408 }
11409
11410
11411 static int set_address_from_contact(struct sip_pvt *pvt)
11412 {
11413 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
11414
11415
11416 pvt->sa = pvt->recv;
11417 return 0;
11418 }
11419
11420 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
11421 }
11422
11423
11424 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
11425 {
11426 char contact[SIPBUFSIZE];
11427 char data[SIPBUFSIZE];
11428 const char *expires = get_header(req, "Expires");
11429 int expire = atoi(expires);
11430 char *curi, *host, *pt, *transport;
11431 int port;
11432 int transport_type;
11433 const char *useragent;
11434 struct hostent *hp;
11435 struct ast_hostent ahp;
11436 struct sockaddr_in oldsin, testsin;
11437
11438
11439 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
11440
11441 if (ast_strlen_zero(expires)) {
11442 char *s = strcasestr(contact, ";expires=");
11443 if (s) {
11444 expires = strsep(&s, ";");
11445 if (sscanf(expires + 9, "%30d", &expire) != 1)
11446 expire = default_expiry;
11447 } else {
11448
11449 expire = default_expiry;
11450 }
11451 }
11452
11453 copy_socket_data(&pvt->socket, &req->socket);
11454
11455
11456 curi = contact;
11457 if (strchr(contact, '<') == NULL)
11458 strsep(&curi, ";");
11459 curi = get_in_brackets(contact);
11460
11461
11462
11463
11464
11465 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
11466
11467 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
11468 pvt->expiry = ast_sched_when(sched, peer->expire);
11469 return PARSE_REGISTER_QUERY;
11470 } else if (!strcasecmp(curi, "*") || !expire) {
11471
11472 memset(&peer->addr, 0, sizeof(peer->addr));
11473 set_socket_transport(&peer->socket, peer->default_outbound_transport);
11474
11475 AST_SCHED_DEL_UNREF(sched, peer->expire,
11476 unref_peer(peer, "remove register expire ref"));
11477
11478 destroy_association(peer);
11479
11480 register_peer_exten(peer, FALSE);
11481 peer->fullcontact[0] = '\0';
11482 peer->useragent[0] = '\0';
11483 peer->sipoptions = 0;
11484 peer->lastms = 0;
11485 peer->portinuri = 0;
11486 pvt->expiry = 0;
11487
11488 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
11489
11490 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
11491 return PARSE_REGISTER_UPDATE;
11492 }
11493
11494
11495 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
11496
11497
11498 ast_string_field_build(pvt, our_contact, "<%s>", curi);
11499
11500
11501 if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
11502 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
11503 }
11504
11505
11506
11507 peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
11508
11509
11510 if ((transport_type = get_transport_str2enum(transport))) {
11511
11512
11513
11514
11515 port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
11516 } else {
11517 port = port_str2int(pt, STANDARD_SIP_PORT);
11518 transport_type = pvt->socket.type;
11519 }
11520
11521
11522
11523
11524 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
11525 set_socket_transport(&peer->socket, transport_type);
11526 }
11527
11528 oldsin = peer->addr;
11529
11530
11531 if (peer->addr.sin_addr.s_addr) {
11532 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
11533 }
11534
11535
11536
11537 hp = ast_gethostbyname(host, &ahp);
11538 if (!hp) {
11539 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
11540 *peer->fullcontact = '\0';
11541 ast_string_field_set(pvt, our_contact, "");
11542 return PARSE_REGISTER_FAILED;
11543 }
11544 memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
11545 if ( ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
11546 ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
11547 ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
11548 *peer->fullcontact = '\0';
11549 ast_string_field_set(pvt, our_contact, "");
11550 return PARSE_REGISTER_DENIED;
11551 }
11552
11553 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
11554 peer->addr.sin_family = AF_INET;
11555 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
11556 peer->addr.sin_port = htons(port);
11557 } else {
11558
11559
11560 peer->addr = pvt->recv;
11561 }
11562
11563
11564
11565
11566 if ((peer->socket.type == pvt->socket.type) &&
11567 (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
11568 (peer->addr.sin_port == pvt->recv.sin_port)){
11569
11570 copy_socket_data(&peer->socket, &pvt->socket);
11571 }
11572
11573
11574 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
11575
11576
11577 peer->sipoptions = pvt->sipoptions;
11578
11579 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
11580 ast_copy_string(peer->username, curi, sizeof(peer->username));
11581
11582 AST_SCHED_DEL_UNREF(sched, peer->expire,
11583 unref_peer(peer, "remove register expire ref"));
11584
11585 if (expire > max_expiry)
11586 expire = max_expiry;
11587 if (expire < min_expiry)
11588 expire = min_expiry;
11589 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
11590 peer->expire = -1;
11591 } else {
11592 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
11593 ref_peer(peer, "add registration ref"));
11594 if (peer->expire == -1) {
11595 unref_peer(peer, "remote registration ref");
11596 }
11597 }
11598 pvt->expiry = expire;
11599 snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expire, peer->username, peer->fullcontact);
11600
11601
11602
11603
11604 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
11605 ast_db_put("SIP/Registry", peer->name, data);
11606 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
11607
11608
11609 if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
11610 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
11611 }
11612 sip_poke_peer(peer, 0);
11613 register_peer_exten(peer, 1);
11614
11615
11616 useragent = get_header(req, "User-Agent");
11617 if (strcasecmp(useragent, peer->useragent)) {
11618 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
11619 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
11620 }
11621 return PARSE_REGISTER_UPDATE;
11622 }
11623
11624
11625 static void free_old_route(struct sip_route *route)
11626 {
11627 struct sip_route *next;
11628
11629 while (route) {
11630 next = route->next;
11631 ast_free(route);
11632 route = next;
11633 }
11634 }
11635
11636
11637 static void list_route(struct sip_route *route)
11638 {
11639 if (!route)
11640 ast_verbose("list_route: no route\n");
11641 else {
11642 for (;route; route = route->next)
11643 ast_verbose("list_route: hop: <%s>\n", route->hop);
11644 }
11645 }
11646
11647
11648 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
11649 {
11650 struct sip_route *thishop, *head, *tail;
11651 int start = 0;
11652 int len;
11653 const char *rr, *contact, *c;
11654
11655
11656 if (p->route && p->route_persistant) {
11657 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
11658 return;
11659 }
11660
11661 if (p->route) {
11662 free_old_route(p->route);
11663 p->route = NULL;
11664 }
11665
11666
11667 p->route_persistant = 1;
11668
11669
11670
11671
11672
11673
11674 head = NULL;
11675 tail = head;
11676
11677 for (;;) {
11678
11679 rr = __get_header(req, "Record-Route", &start);
11680 if (*rr == '\0')
11681 break;
11682 for (; (rr = strchr(rr, '<')) ; rr += len) {
11683 ++rr;
11684 len = strcspn(rr, ">") + 1;
11685
11686 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
11687
11688 ast_copy_string(thishop->hop, rr, len);
11689 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
11690
11691 if (backwards) {
11692
11693 thishop->next = head;
11694 head = thishop;
11695
11696 if (!tail)
11697 tail = thishop;
11698 } else {
11699 thishop->next = NULL;
11700
11701 if (tail)
11702 tail->next = thishop;
11703 else
11704 head = thishop;
11705 tail = thishop;
11706 }
11707 }
11708 }
11709 }
11710
11711
11712 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
11713
11714
11715 contact = get_header(req, "Contact");
11716 if (!ast_strlen_zero(contact)) {
11717 ast_debug(2, "build_route: Contact hop: %s\n", contact);
11718
11719 c = strchr(contact, '<');
11720 if (c) {
11721
11722 ++c;
11723 len = strcspn(c, ">") + 1;
11724 } else {
11725
11726 c = contact;
11727 len = strlen(contact) + 1;
11728 }
11729 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
11730
11731 ast_copy_string(thishop->hop, c, len);
11732 thishop->next = NULL;
11733
11734 if (tail)
11735 tail->next = thishop;
11736 else
11737 head = thishop;
11738 }
11739 }
11740 }
11741
11742
11743 p->route = head;
11744
11745
11746 if (sip_debug_test_pvt(p))
11747 list_route(p->route);
11748 }
11749
11750
11751
11752
11753
11754
11755
11756 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
11757 {
11758 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
11759 ast_string_field_build(p, randdata, "%08lx", ast_random());
11760 p->stalenonce = 0;
11761 }
11762 }
11763
11764 AST_THREADSTORAGE(check_auth_buf);
11765 #define CHECK_AUTH_BUF_INITLEN 256
11766
11767
11768
11769
11770
11771
11772 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
11773 const char *secret, const char *md5secret, int sipmethod,
11774 char *uri, enum xmittype reliable, int ignore)
11775 {
11776 const char *response;
11777 char *reqheader, *respheader;
11778 const char *authtoken;
11779 char a1_hash[256];
11780 char resp_hash[256]="";
11781 char *c;
11782 int wrongnonce = FALSE;
11783 int good_response;
11784 const char *usednonce = p->randdata;
11785 struct ast_str *buf;
11786 int res;
11787
11788
11789 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
11790 struct x {
11791 const char *key;
11792 const char *s;
11793 } *i, keys[] = {
11794 [K_RESP] = { "response=", "" },
11795 [K_URI] = { "uri=", "" },
11796 [K_USER] = { "username=", "" },
11797 [K_NONCE] = { "nonce=", "" },
11798 [K_LAST] = { NULL, NULL}
11799 };
11800
11801
11802 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
11803 return AUTH_SUCCESSFUL;
11804
11805
11806
11807 response = "401 Unauthorized";
11808
11809
11810
11811
11812
11813 auth_headers(WWW_AUTH, &respheader, &reqheader);
11814
11815 authtoken = get_header(req, reqheader);
11816 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
11817
11818
11819 if (!reliable) {
11820
11821
11822 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
11823
11824 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11825 }
11826 return AUTH_CHALLENGE_SENT;
11827 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
11828
11829 set_nonce_randdata(p, 1);
11830 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
11831
11832 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11833 return AUTH_CHALLENGE_SENT;
11834 }
11835
11836
11837
11838
11839
11840
11841 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
11842 return AUTH_SECRET_FAILED;
11843
11844
11845 res = ast_str_set(&buf, 0, "%s", authtoken);
11846
11847 if (res == AST_DYNSTR_BUILD_FAILED)
11848 return AUTH_SECRET_FAILED;
11849
11850 c = buf->str;
11851
11852 while(c && *(c = ast_skip_blanks(c)) ) {
11853 for (i = keys; i->key != NULL; i++) {
11854 const char *separator = ",";
11855
11856 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11857 continue;
11858
11859 c += strlen(i->key);
11860 if (*c == '"') {
11861 c++;
11862 separator = "\"";
11863 }
11864 i->s = c;
11865 strsep(&c, separator);
11866 break;
11867 }
11868 if (i->key == NULL)
11869 strsep(&c, " ,");
11870 }
11871
11872
11873 if (strcmp(username, keys[K_USER].s)) {
11874 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
11875 username, keys[K_USER].s);
11876
11877 return AUTH_USERNAME_MISMATCH;
11878 }
11879
11880
11881
11882 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
11883 wrongnonce = TRUE;
11884 usednonce = keys[K_NONCE].s;
11885 } else {
11886 p->stalenonce = 1;
11887 }
11888
11889 if (!ast_strlen_zero(md5secret))
11890 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11891 else {
11892 char a1[256];
11893 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
11894 ast_md5_hash(a1_hash, a1);
11895 }
11896
11897
11898 {
11899 char a2[256];
11900 char a2_hash[256];
11901 char resp[256];
11902
11903 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
11904 S_OR(keys[K_URI].s, uri));
11905 ast_md5_hash(a2_hash, a2);
11906 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
11907 ast_md5_hash(resp_hash, resp);
11908 }
11909
11910 good_response = keys[K_RESP].s &&
11911 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
11912 if (wrongnonce) {
11913 if (good_response) {
11914 if (sipdebug)
11915 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
11916
11917 set_nonce_randdata(p, 0);
11918 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
11919 } else {
11920
11921 if (!req->ignore) {
11922 if (sipdebug)
11923 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
11924 set_nonce_randdata(p, 1);
11925 } else {
11926 if (sipdebug)
11927 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
11928 }
11929 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
11930 }
11931
11932
11933 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11934 return AUTH_CHALLENGE_SENT;
11935 }
11936 if (good_response) {
11937 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
11938 return AUTH_SUCCESSFUL;
11939 }
11940
11941
11942
11943
11944
11945
11946 return AUTH_SECRET_FAILED;
11947 }
11948
11949
11950 static void sip_peer_hold(struct sip_pvt *p, int hold)
11951 {
11952 struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
11953
11954 if (!peer)
11955 return;
11956
11957
11958 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
11959
11960
11961 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
11962 unref_peer(peer, "sip_peer_hold: from find_peer operation");
11963
11964 return;
11965 }
11966
11967
11968 static void mwi_event_cb(const struct ast_event *event, void *userdata)
11969 {
11970 struct sip_peer *peer = userdata;
11971
11972 ao2_lock(peer);
11973 sip_send_mwi_to_peer(peer, event, 0);
11974 ao2_unlock(peer);
11975 }
11976
11977
11978
11979
11980 static int cb_extensionstate(char *context, char* exten, int state, void *data)
11981 {
11982 struct sip_pvt *p = data;
11983
11984 sip_pvt_lock(p);
11985
11986 switch(state) {
11987 case AST_EXTENSION_DEACTIVATED:
11988 case AST_EXTENSION_REMOVED:
11989 if (p->autokillid > -1 && sip_cancel_destroy(p))
11990 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
11991 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11992 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
11993 p->stateid = -1;
11994 p->subscribed = NONE;
11995 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
11996 break;
11997 default:
11998 p->laststate = state;
11999 break;
12000 }
12001 if (p->subscribed != NONE) {
12002 if (!p->pendinginvite) {
12003 transmit_state_notify(p, state, 1, FALSE);
12004 } else {
12005
12006
12007 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12008 }
12009 }
12010 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12011 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12012
12013 sip_pvt_unlock(p);
12014
12015 return 0;
12016 }
12017
12018
12019
12020
12021 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12022 {
12023
12024
12025 const char *response = "407 Proxy Authentication Required";
12026 const char *reqheader = "Proxy-Authorization";
12027 const char *respheader = "Proxy-Authenticate";
12028 const char *authtoken;
12029 struct ast_str *buf;
12030 char *c;
12031
12032
12033 enum keys { K_NONCE, K_LAST };
12034 struct x {
12035 const char *key;
12036 const char *s;
12037 } *i, keys[] = {
12038 [K_NONCE] = { "nonce=", "" },
12039 [K_LAST] = { NULL, NULL}
12040 };
12041
12042 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12043 response = "401 Unauthorized";
12044 reqheader = "Authorization";
12045 respheader = "WWW-Authenticate";
12046 }
12047 authtoken = get_header(req, reqheader);
12048 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12049
12050
12051 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12052
12053 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12054 return;
12055 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12056
12057 set_nonce_randdata(p, 1);
12058 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12059
12060 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12061 return;
12062 }
12063
12064 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12065 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12066 return;
12067 }
12068
12069
12070 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12071 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12072 return;
12073 }
12074
12075 c = buf->str;
12076
12077 while (c && *(c = ast_skip_blanks(c))) {
12078 for (i = keys; i->key != NULL; i++) {
12079 const char *separator = ",";
12080
12081 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
12082 continue;
12083 }
12084
12085 c += strlen(i->key);
12086 if (*c == '"') {
12087 c++;
12088 separator = "\"";
12089 }
12090 i->s = c;
12091 strsep(&c, separator);
12092 break;
12093 }
12094 if (i->key == NULL) {
12095 strsep(&c, " ,");
12096 }
12097 }
12098
12099
12100 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
12101 if (!req->ignore) {
12102 set_nonce_randdata(p, 1);
12103 }
12104 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12105
12106
12107 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12108 } else {
12109 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12110 }
12111 }
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124 static char *terminate_uri(char *uri)
12125 {
12126 char *t = uri;
12127 while (*t && *t > ' ' && *t != ';')
12128 t++;
12129 *t = '\0';
12130 return uri;
12131 }
12132
12133
12134
12135
12136
12137
12138 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
12139 struct sip_request *req, char *uri)
12140 {
12141 enum check_auth_result res = AUTH_NOT_FOUND;
12142 struct sip_peer *peer;
12143 char tmp[256];
12144 char *name, *c;
12145 char *domain;
12146
12147 terminate_uri(uri);
12148
12149 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
12150 if (pedanticsipchecking)
12151 ast_uri_decode(tmp);
12152
12153 c = get_in_brackets(tmp);
12154 c = remove_uri_parameters(c);
12155
12156 if (!strncasecmp(c, "sip:", 4)) {
12157 name = c + 4;
12158 } else if (!strncasecmp(c, "sips:", 5)) {
12159 name = c + 5;
12160 } else {
12161 name = c;
12162 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
12163 }
12164
12165
12166
12167
12168
12169 if ((c = strchr(name, '@'))) {
12170 *c++ = '\0';
12171 domain = c;
12172 if ((c = strchr(domain, ':')))
12173 *c = '\0';
12174 if (!AST_LIST_EMPTY(&domain_list)) {
12175 if (!check_sip_domain(domain, NULL, 0)) {
12176 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
12177 return AUTH_UNKNOWN_DOMAIN;
12178 }
12179 }
12180 }
12181 c = strchr(name, ';');
12182 if (c)
12183 *c = '\0';
12184
12185 ast_string_field_set(p, exten, name);
12186 build_contact(p);
12187 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
12188 if (!(peer && ast_apply_ha(peer->ha, sin))) {
12189
12190 if (peer) {
12191 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
12192 peer = NULL;
12193 res = AUTH_ACL_FAILED;
12194 } else
12195 res = AUTH_NOT_FOUND;
12196 }
12197
12198 if (peer) {
12199
12200 if (p->rtp) {
12201 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
12202 p->autoframing = peer->autoframing;
12203 }
12204 if (!peer->host_dynamic) {
12205 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
12206 res = AUTH_PEER_NOT_DYNAMIC;
12207 } else {
12208 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
12209 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
12210 transmit_response(p, "100 Trying", req);
12211 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
12212 if (sip_cancel_destroy(p))
12213 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12214
12215 if (check_request_transport(peer, req)) {
12216 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12217 transmit_response_with_date(p, "403 Forbidden", req);
12218 res = AUTH_BAD_TRANSPORT;
12219 } else {
12220
12221
12222
12223 switch (parse_register_contact(p, peer, req)) {
12224 case PARSE_REGISTER_DENIED:
12225 transmit_response_with_date(p, "603 Denied", req);
12226 peer->lastmsgssent = -1;
12227 res = 0;
12228 break;
12229 case PARSE_REGISTER_FAILED:
12230 ast_log(LOG_WARNING, "Failed to parse contact info\n");
12231 transmit_response_with_date(p, "400 Bad Request", req);
12232 peer->lastmsgssent = -1;
12233 res = 0;
12234 break;
12235 case PARSE_REGISTER_QUERY:
12236 ast_string_field_set(p, fullcontact, peer->fullcontact);
12237 transmit_response_with_date(p, "200 OK", req);
12238 peer->lastmsgssent = -1;
12239 res = 0;
12240 break;
12241 case PARSE_REGISTER_UPDATE:
12242 ast_string_field_set(p, fullcontact, peer->fullcontact);
12243 update_peer(peer, p->expiry);
12244
12245 transmit_response_with_date(p, "200 OK", req);
12246 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
12247 peer->lastmsgssent = -1;
12248 res = 0;
12249 break;
12250 }
12251 }
12252
12253 }
12254 }
12255 }
12256 if (!peer && autocreatepeer) {
12257
12258 peer = temp_peer(name);
12259 if (peer) {
12260 ao2_t_link(peers, peer, "link peer into peer table");
12261 if (peer->addr.sin_addr.s_addr) {
12262 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
12263 }
12264
12265 if (sip_cancel_destroy(p))
12266 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12267 switch (parse_register_contact(p, peer, req)) {
12268 case PARSE_REGISTER_DENIED:
12269 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
12270 peer->lastmsgssent = -1;
12271 res = 0;
12272 break;
12273 case PARSE_REGISTER_FAILED:
12274 ast_log(LOG_WARNING, "Failed to parse contact info\n");
12275 transmit_response_with_date(p, "400 Bad Request", req);
12276 peer->lastmsgssent = -1;
12277 res = 0;
12278 break;
12279 case PARSE_REGISTER_QUERY:
12280 ast_string_field_set(p, fullcontact, peer->fullcontact);
12281 transmit_response_with_date(p, "200 OK", req);
12282 peer->lastmsgssent = -1;
12283 res = 0;
12284 break;
12285 case PARSE_REGISTER_UPDATE:
12286 ast_string_field_set(p, fullcontact, peer->fullcontact);
12287
12288 transmit_response_with_date(p, "200 OK", req);
12289 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
12290 peer->lastmsgssent = -1;
12291 res = 0;
12292 break;
12293 }
12294 }
12295 }
12296 if (!peer && global_alwaysauthreject) {
12297
12298
12299
12300 transmit_response(p, "100 Trying", req);
12301
12302 sched_yield();
12303 }
12304 if (!res) {
12305 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12306 }
12307 if (res < 0) {
12308 switch (res) {
12309 case AUTH_SECRET_FAILED:
12310
12311 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12312 if (global_authfailureevents)
12313 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_SECRET_FAILED\r\nAddress: %s\r\nPort: %d\r\n",
12314 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
12315 break;
12316 case AUTH_USERNAME_MISMATCH:
12317
12318
12319
12320
12321 case AUTH_NOT_FOUND:
12322 case AUTH_PEER_NOT_DYNAMIC:
12323 case AUTH_ACL_FAILED:
12324 if (global_alwaysauthreject) {
12325 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
12326 } else {
12327
12328 if (res == AUTH_PEER_NOT_DYNAMIC) {
12329 transmit_response(p, "403 Forbidden", &p->initreq);
12330 if (global_authfailureevents)
12331 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_PEER_NOT_DYNAMIC\r\nAddress: %s\r\nPort: %d\r\n",
12332 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
12333 }
12334 else
12335 transmit_response(p, "404 Not found", &p->initreq);
12336 if (global_authfailureevents)
12337 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: %s\r\nAddress: %s\r\nPort: %d\r\n",
12338 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND", name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
12339 }
12340 break;
12341 case AUTH_BAD_TRANSPORT:
12342 default:
12343 break;
12344 }
12345 }
12346 if (peer)
12347 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
12348
12349 return res;
12350 }
12351
12352
12353 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
12354
12355 if (!strcmp(reason, "unknown")) {
12356 ast_string_field_set(p, redircause, "UNKNOWN");
12357 } else if (!strcmp(reason, "user-busy")) {
12358 ast_string_field_set(p, redircause, "BUSY");
12359 } else if (!strcmp(reason, "no-answer")) {
12360 ast_string_field_set(p, redircause, "NOANSWER");
12361 } else if (!strcmp(reason, "unavailable")) {
12362 ast_string_field_set(p, redircause, "UNREACHABLE");
12363 } else if (!strcmp(reason, "unconditional")) {
12364 ast_string_field_set(p, redircause, "UNCONDITIONAL");
12365 } else if (!strcmp(reason, "time-of-day")) {
12366 ast_string_field_set(p, redircause, "UNKNOWN");
12367 } else if (!strcmp(reason, "do-not-disturb")) {
12368 ast_string_field_set(p, redircause, "UNKNOWN");
12369 } else if (!strcmp(reason, "deflection")) {
12370 ast_string_field_set(p, redircause, "UNKNOWN");
12371 } else if (!strcmp(reason, "follow-me")) {
12372 ast_string_field_set(p, redircause, "UNKNOWN");
12373 } else if (!strcmp(reason, "out-of-service")) {
12374 ast_string_field_set(p, redircause, "UNREACHABLE");
12375 } else if (!strcmp(reason, "away")) {
12376 ast_string_field_set(p, redircause, "UNREACHABLE");
12377 } else {
12378 ast_string_field_set(p, redircause, "UNKNOWN");
12379 }
12380 }
12381
12382
12383 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
12384 {
12385 char tmp[256], *exten, *rexten, *rdomain;
12386 char *params, *reason = NULL;
12387 struct sip_request *req;
12388
12389 req = oreq ? oreq : &p->initreq;
12390
12391 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
12392 if (ast_strlen_zero(tmp))
12393 return 0;
12394
12395 params = strchr(tmp, ';');
12396
12397 exten = get_in_brackets(tmp);
12398 if (!strncasecmp(exten, "sip:", 4)) {
12399 exten += 4;
12400 } else if (!strncasecmp(exten, "sips:", 5)) {
12401 exten += 5;
12402 } else {
12403 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
12404 return -1;
12405 }
12406
12407
12408 if (params) {
12409 *params = '\0';
12410 params++;
12411 while (*params == ';' || *params == ' ')
12412 params++;
12413
12414 if ((reason = strcasestr(params, "reason="))) {
12415 reason+=7;
12416
12417 if (*reason == '"')
12418 ast_strip_quoted(reason, "\"", "\"");
12419 if (!ast_strlen_zero(reason)) {
12420 sip_set_redirstr(p, reason);
12421 if (p->owner) {
12422 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
12423 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
12424 }
12425 }
12426 }
12427 }
12428
12429 rdomain = exten;
12430 rexten = strsep(&rdomain, "@");
12431 if (p->owner)
12432 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
12433
12434 if (sip_debug_test_pvt(p))
12435 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
12436
12437 ast_string_field_set(p, rdnis, rexten);
12438
12439 return 0;
12440 }
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
12451 {
12452 char tmp[256] = "", *uri, *a;
12453 char tmpf[256] = "", *from = NULL;
12454 struct sip_request *req;
12455 char *colon;
12456 char *decoded_uri;
12457
12458 req = oreq;
12459 if (!req)
12460 req = &p->initreq;
12461
12462
12463 if (req->rlPart2)
12464 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
12465
12466 if (pedanticsipchecking)
12467 ast_uri_decode(tmp);
12468
12469 uri = get_in_brackets(tmp);
12470
12471 if (!strncasecmp(uri, "sip:", 4)) {
12472 uri += 4;
12473 } else if (!strncasecmp(uri, "sips:", 5)) {
12474 uri += 5;
12475 } else {
12476 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
12477 return -1;
12478 }
12479
12480
12481
12482
12483
12484 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
12485 if (!ast_strlen_zero(tmpf)) {
12486 if (pedanticsipchecking)
12487 ast_uri_decode(tmpf);
12488 from = get_in_brackets(tmpf);
12489 }
12490
12491 if (!ast_strlen_zero(from)) {
12492 if (!strncasecmp(from, "sip:", 4)) {
12493 from += 4;
12494 } else if (!strncasecmp(from, "sips:", 5)) {
12495 from += 5;
12496 } else {
12497 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
12498 return -1;
12499 }
12500 if ((a = strchr(from, '@')))
12501 *a++ = '\0';
12502 else
12503 a = from;
12504 from = strsep(&from, ";");
12505 a = strsep(&a, ";");
12506 ast_string_field_set(p, fromdomain, a);
12507 }
12508
12509
12510
12511
12512 if ((a = strchr(uri, '@'))) {
12513 *a++ = '\0';
12514 } else {
12515 a = uri;
12516 uri = "s";
12517 }
12518 colon = strchr(a, ':');
12519 if (colon)
12520 *colon = '\0';
12521
12522 uri = strsep(&uri, ";");
12523 a = strsep(&a, ";");
12524
12525 ast_string_field_set(p, domain, a);
12526
12527 if (!AST_LIST_EMPTY(&domain_list)) {
12528 char domain_context[AST_MAX_EXTENSION];
12529
12530 domain_context[0] = '\0';
12531 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
12532 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
12533 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
12534 return -2;
12535 }
12536 }
12537
12538 if (!ast_strlen_zero(domain_context))
12539 ast_string_field_set(p, context, domain_context);
12540 }
12541
12542
12543 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
12544 ast_string_field_set(p, context, p->subscribecontext);
12545
12546 if (sip_debug_test_pvt(p))
12547 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
12548
12549
12550 if (req->method == SIP_SUBSCRIBE) {
12551 char hint[AST_MAX_EXTENSION];
12552 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
12553 } else {
12554 decoded_uri = ast_strdupa(uri);
12555 ast_uri_decode(decoded_uri);
12556
12557
12558
12559
12560
12561 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
12562 !strcmp(decoded_uri, ast_pickup_ext())) {
12563 if (!oreq)
12564 ast_string_field_set(p, exten, decoded_uri);
12565 return 0;
12566 }
12567 }
12568
12569
12570 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
12571 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
12572 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
12573 return 1;
12574 }
12575
12576 return -1;
12577 }
12578
12579
12580
12581
12582 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
12583 {
12584 struct sip_pvt *sip_pvt_ptr;
12585 struct sip_pvt tmp_dialog = {
12586 .callid = callid,
12587 };
12588
12589 if (totag)
12590 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
12591
12592
12593
12594 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
12595 if (sip_pvt_ptr) {
12596
12597 sip_pvt_lock(sip_pvt_ptr);
12598 if (pedanticsipchecking) {
12599 unsigned char frommismatch = 0, tomismatch = 0;
12600
12601 if (ast_strlen_zero(fromtag)) {
12602 sip_pvt_unlock(sip_pvt_ptr);
12603 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
12604 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
12605 return NULL;
12606 }
12607
12608 if (ast_strlen_zero(totag)) {
12609 sip_pvt_unlock(sip_pvt_ptr);
12610 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
12611 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
12612 return NULL;
12613 }
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
12629 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
12630 if (frommismatch || tomismatch) {
12631 sip_pvt_unlock(sip_pvt_ptr);
12632 if (frommismatch) {
12633 ast_debug(4, "Matched %s call for callid=%s - But the pedantic check rejected the match; their tag is %s Our tag is %s\n",
12634 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
12635 fromtag, sip_pvt_ptr->theirtag);
12636 }
12637 if (tomismatch) {
12638 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
12639 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
12640 totag, sip_pvt_ptr->tag);
12641 }
12642 return NULL;
12643 }
12644 }
12645
12646 if (totag)
12647 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
12648 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
12649 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
12650
12651
12652 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
12653 sip_pvt_unlock(sip_pvt_ptr);
12654 usleep(1);
12655 sip_pvt_lock(sip_pvt_ptr);
12656 }
12657 }
12658
12659 return sip_pvt_ptr;
12660 }
12661
12662
12663
12664 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
12665 {
12666
12667 const char *p_referred_by = NULL;
12668 char *h_refer_to = NULL;
12669 char *h_referred_by = NULL;
12670 char *refer_to;
12671 const char *p_refer_to;
12672 char *referred_by_uri = NULL;
12673 char *ptr;
12674 struct sip_request *req = NULL;
12675 const char *transfer_context = NULL;
12676 struct sip_refer *referdata;
12677
12678
12679 req = outgoing_req;
12680 referdata = transferer->refer;
12681
12682 if (!req)
12683 req = &transferer->initreq;
12684
12685 p_refer_to = get_header(req, "Refer-To");
12686 if (ast_strlen_zero(p_refer_to)) {
12687 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
12688 return -2;
12689 }
12690 h_refer_to = ast_strdupa(p_refer_to);
12691 refer_to = get_in_brackets(h_refer_to);
12692 if (pedanticsipchecking)
12693 ast_uri_decode(refer_to);
12694
12695 if (!strncasecmp(refer_to, "sip:", 4)) {
12696 refer_to += 4;
12697 } else if (!strncasecmp(refer_to, "sips:", 5)) {
12698 refer_to += 5;
12699 } else {
12700 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
12701 return -3;
12702 }
12703
12704
12705 p_referred_by = get_header(req, "Referred-By");
12706
12707
12708 if (transferer->owner) {
12709 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
12710 if (peer) {
12711 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
12712 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
12713 }
12714 }
12715
12716 if (!ast_strlen_zero(p_referred_by)) {
12717 char *lessthan;
12718 h_referred_by = ast_strdupa(p_referred_by);
12719 if (pedanticsipchecking)
12720 ast_uri_decode(h_referred_by);
12721
12722
12723 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
12724 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
12725 *(lessthan - 1) = '\0';
12726 }
12727
12728 referred_by_uri = get_in_brackets(h_referred_by);
12729 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
12730 referred_by_uri += 4;
12731 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
12732 referred_by_uri += 5;
12733 } else {
12734 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
12735 referred_by_uri = NULL;
12736 }
12737 }
12738
12739
12740 if ((ptr = strcasestr(refer_to, "replaces="))) {
12741 char *to = NULL, *from = NULL;
12742
12743
12744 referdata->attendedtransfer = 1;
12745 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
12746 ast_uri_decode(referdata->replaces_callid);
12747 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
12748 *ptr++ = '\0';
12749 }
12750
12751 if (ptr) {
12752
12753 to = strcasestr(ptr, "to-tag=");
12754 from = strcasestr(ptr, "from-tag=");
12755 }
12756
12757
12758 if (to) {
12759 ptr = to + 7;
12760 if ((to = strchr(ptr, '&')))
12761 *to = '\0';
12762 if ((to = strchr(ptr, ';')))
12763 *to = '\0';
12764 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
12765 }
12766
12767 if (from) {
12768 ptr = from + 9;
12769 if ((to = strchr(ptr, '&')))
12770 *to = '\0';
12771 if ((to = strchr(ptr, ';')))
12772 *to = '\0';
12773 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
12774 }
12775
12776 if (!pedanticsipchecking)
12777 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
12778 else
12779 ast_debug(2, "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>" );
12780 }
12781
12782 if ((ptr = strchr(refer_to, '@'))) {
12783 char *urioption = NULL, *domain;
12784 *ptr++ = '\0';
12785
12786 if ((urioption = strchr(ptr, ';')))
12787 *urioption++ = '\0';
12788
12789 domain = ptr;
12790 if ((ptr = strchr(domain, ':')))
12791 *ptr = '\0';
12792
12793
12794 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
12795 if (urioption)
12796 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
12797 }
12798
12799 if ((ptr = strchr(refer_to, ';')))
12800 *ptr = '\0';
12801 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
12802
12803 if (referred_by_uri) {
12804 if ((ptr = strchr(referred_by_uri, ';')))
12805 *ptr = '\0';
12806 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
12807 } else {
12808 referdata->referred_by[0] = '\0';
12809 }
12810
12811
12812 if (transferer->owner)
12813 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
12814
12815
12816 if (ast_strlen_zero(transfer_context)) {
12817 transfer_context = S_OR(transferer->owner->macrocontext,
12818 S_OR(transferer->context, default_context));
12819 }
12820
12821 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
12822
12823
12824 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
12825 if (sip_debug_test_pvt(transferer)) {
12826 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
12827 }
12828
12829 return 0;
12830 }
12831 if (sip_debug_test_pvt(transferer))
12832 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
12833
12834
12835 return -1;
12836 }
12837
12838
12839
12840 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
12841 {
12842 char tmp[256] = "", *c, *a;
12843 struct sip_request *req = oreq ? oreq : &p->initreq;
12844 struct sip_refer *referdata = NULL;
12845 const char *transfer_context = NULL;
12846
12847 if (!p->refer && !sip_refer_allocate(p))
12848 return -1;
12849
12850 referdata = p->refer;
12851
12852 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
12853 c = get_in_brackets(tmp);
12854
12855 if (pedanticsipchecking)
12856 ast_uri_decode(c);
12857
12858 if (!strncasecmp(c, "sip:", 4)) {
12859 c += 4;
12860 } else if (!strncasecmp(c, "sips:", 5)) {
12861 c += 5;
12862 } else {
12863 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
12864 return -1;
12865 }
12866
12867 if ((a = strchr(c, ';')))
12868 *a = '\0';
12869
12870 if ((a = strchr(c, '@'))) {
12871 *a++ = '\0';
12872 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
12873 }
12874
12875 if (sip_debug_test_pvt(p))
12876 ast_verbose("Looking for %s in %s\n", c, p->context);
12877
12878 if (p->owner)
12879 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
12880
12881
12882 if (ast_strlen_zero(transfer_context)) {
12883 transfer_context = S_OR(p->owner->macrocontext,
12884 S_OR(p->context, default_context));
12885 }
12886 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
12887
12888 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
12889 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
12890 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
12891 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
12892 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
12893
12894 ast_string_field_set(p, context, transfer_context);
12895 return 0;
12896 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
12897 return 1;
12898 }
12899
12900 return -1;
12901 }
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
12914 {
12915 char via[256];
12916 char *cur, *opts;
12917
12918 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
12919
12920
12921 opts = strchr(via, ',');
12922 if (opts)
12923 *opts = '\0';
12924
12925
12926 opts = strchr(via, ';');
12927 if (!opts)
12928 return;
12929 *opts++ = '\0';
12930 while ( (cur = strsep(&opts, ";")) ) {
12931 if (!strncmp(cur, "rport=", 6)) {
12932 int port = strtol(cur+6, NULL, 10);
12933
12934 p->ourip.sin_port = ntohs(port);
12935 } else if (!strncmp(cur, "received=", 9)) {
12936 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
12937 ;
12938 }
12939 }
12940 }
12941
12942
12943 static void check_via(struct sip_pvt *p, struct sip_request *req)
12944 {
12945 char via[512];
12946 char *c, *pt, *maddr;
12947 struct hostent *hp;
12948 struct ast_hostent ahp;
12949
12950 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
12951
12952
12953 c = strchr(via, ',');
12954 if (c)
12955 *c = '\0';
12956
12957
12958 c = strstr(via, ";rport");
12959 if (c && (c[6] != '='))
12960 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
12961
12962
12963 maddr = strstr(via, "maddr=");
12964 if (maddr) {
12965 maddr += 6;
12966 c = maddr + strspn(maddr, "0123456789.");
12967 *c = '\0';
12968 }
12969
12970 c = strchr(via, ';');
12971 if (c)
12972 *c = '\0';
12973
12974 c = strchr(via, ' ');
12975 if (c) {
12976 *c = '\0';
12977 c = ast_skip_blanks(c+1);
12978 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
12979 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
12980 return;
12981 }
12982 pt = strchr(c, ':');
12983 if (pt)
12984 *pt++ = '\0';
12985
12986 if (maddr)
12987 c = maddr;
12988 hp = ast_gethostbyname(c, &ahp);
12989 if (!hp) {
12990 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
12991 return;
12992 }
12993 memset(&p->sa, 0, sizeof(p->sa));
12994 p->sa.sin_family = AF_INET;
12995 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
12996 p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
12997
12998 if (sip_debug_test_pvt(p)) {
12999 const struct sockaddr_in *dst = sip_real_dst(p);
13000 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13001 }
13002 }
13003 }
13004
13005
13006 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13007 {
13008 const char *end = strchr(input, '<');
13009 const char *tmp = strchr(input, '"');
13010 int bytes = 0;
13011 int maxbytes = outputsize - 1;
13012
13013 if (!end || end == input)
13014 return NULL;
13015
13016 end--;
13017
13018 if (tmp && tmp <= end) {
13019
13020
13021
13022 end = strchr(tmp+1, '"');
13023 if (!end)
13024 return NULL;
13025 bytes = (int) (end - tmp);
13026
13027 if (bytes > maxbytes)
13028 bytes = maxbytes;
13029 ast_copy_string(output, tmp + 1, bytes);
13030 } else {
13031
13032
13033 input = ast_skip_blanks(input);
13034
13035 while(*end && *end < 33 && end > input)
13036 end--;
13037 if (end >= input) {
13038 bytes = (int) (end - input) + 2;
13039
13040 if (bytes > maxbytes)
13041 bytes = maxbytes;
13042 ast_copy_string(output, input, bytes);
13043 } else
13044 return NULL;
13045 }
13046 return output;
13047 }
13048
13049
13050
13051
13052
13053 static int get_rpid_num(const char *input, char *output, int maxlen)
13054 {
13055 char *start;
13056 char *end;
13057
13058 start = strchr(input, ':');
13059 if (!start) {
13060 output[0] = '\0';
13061 return 0;
13062 }
13063 start++;
13064
13065
13066 ast_copy_string(output, start, maxlen);
13067 output[maxlen-1] = '\0';
13068
13069 end = strchr(output, '@');
13070 if (end)
13071 *end = '\0';
13072 else
13073 output[0] = '\0';
13074 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
13075 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
13076
13077 return 0;
13078 }
13079
13080
13081
13082
13083 static struct ast_variable *copy_vars(struct ast_variable *src)
13084 {
13085 struct ast_variable *res = NULL, *tmp, *v = NULL;
13086
13087 for (v = src ; v ; v = v->next) {
13088 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
13089 tmp->next = res;
13090 res = tmp;
13091 }
13092 }
13093 return res;
13094 }
13095
13096
13097 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
13098 {
13099
13100 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
13101 char *tmp = ast_strdupa(rpid_num);
13102 if (!ast_strlen_zero(calleridname))
13103 ast_string_field_set(p, cid_name, calleridname);
13104 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13105 ast_shrink_phone_number(tmp);
13106 ast_string_field_set(p, cid_num, tmp);
13107 }
13108 }
13109
13110
13111 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
13112 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
13113 struct sip_peer **authpeer,
13114 enum xmittype reliable,
13115 char *rpid_num, char *calleridname, char *uri2)
13116 {
13117 enum check_auth_result res;
13118 int debug=sip_debug_test_addr(sin);
13119 struct sip_peer *peer;
13120
13121 if (sipmethod == SIP_SUBSCRIBE) {
13122
13123
13124
13125 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
13126 } else {
13127
13128 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
13129
13130
13131 if (!peer) {
13132 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
13133 }
13134 }
13135
13136 if (!peer) {
13137 if (debug)
13138 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
13139 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
13140 return AUTH_DONT_KNOW;
13141 }
13142 if (!ast_apply_ha(peer->ha, sin)) {
13143 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
13144 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
13145 return AUTH_ACL_FAILED;
13146 }
13147 if (debug)
13148 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
13149 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
13150
13151
13152
13153 if (p->rtp) {
13154 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13155 p->autoframing = peer->autoframing;
13156 }
13157
13158
13159 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
13160 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
13161
13162 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
13163 p->t38_maxdatagram = peer->t38_maxdatagram;
13164 set_t38_capabilities(p);
13165 }
13166
13167
13168
13169 if (p->sipoptions)
13170 peer->sipoptions = p->sipoptions;
13171
13172 replace_cid(p, rpid_num, calleridname);
13173 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
13174
13175 ast_string_field_set(p, peersecret, peer->secret);
13176 ast_string_field_set(p, peermd5secret, peer->md5secret);
13177 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
13178 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
13179 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
13180 ast_string_field_set(p, parkinglot, peer->parkinglot);
13181 if (peer->callingpres)
13182 p->callingpres = peer->callingpres;
13183 if (peer->maxms && peer->lastms)
13184 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
13185 else
13186 p->timer_t1 = peer->timer_t1;
13187
13188
13189 if (peer->timer_b)
13190 p->timer_b = peer->timer_b;
13191 else
13192 p->timer_b = 64 * p->timer_t1;
13193
13194 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
13195
13196 ast_string_field_set(p, peersecret, NULL);
13197 ast_string_field_set(p, peermd5secret, NULL);
13198 }
13199 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
13200 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
13201 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
13202
13203 if (peer->call_limit)
13204 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
13205 ast_string_field_set(p, peername, peer->name);
13206 ast_string_field_set(p, authname, peer->name);
13207
13208 if (sipmethod == SIP_INVITE) {
13209
13210 p->chanvars = copy_vars(peer->chanvars);
13211 }
13212
13213 if (authpeer) {
13214 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
13215 (*authpeer) = peer;
13216 }
13217
13218 if (!ast_strlen_zero(peer->username)) {
13219 ast_string_field_set(p, username, peer->username);
13220
13221
13222 ast_string_field_set(p, authname, peer->username);
13223 }
13224 if (!ast_strlen_zero(peer->cid_num)) {
13225 char *tmp = ast_strdupa(peer->cid_num);
13226 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13227 ast_shrink_phone_number(tmp);
13228 ast_string_field_set(p, cid_num, tmp);
13229 }
13230 if (!ast_strlen_zero(peer->cid_name))
13231 ast_string_field_set(p, cid_name, peer->cid_name);
13232 ast_string_field_set(p, fullcontact, peer->fullcontact);
13233 if (!ast_strlen_zero(peer->context))
13234 ast_string_field_set(p, context, peer->context);
13235 ast_string_field_set(p, peersecret, peer->secret);
13236 ast_string_field_set(p, peermd5secret, peer->md5secret);
13237 ast_string_field_set(p, language, peer->language);
13238 ast_string_field_set(p, accountcode, peer->accountcode);
13239 p->amaflags = peer->amaflags;
13240 p->callgroup = peer->callgroup;
13241 p->pickupgroup = peer->pickupgroup;
13242 p->capability = peer->capability;
13243 p->prefs = peer->prefs;
13244 p->jointcapability = peer->capability;
13245 if (p->peercapability)
13246 p->jointcapability &= p->peercapability;
13247 p->maxcallbitrate = peer->maxcallbitrate;
13248 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
13249 (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
13250 !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
13251 p->vrtp) {
13252 ast_rtp_destroy(p->vrtp);
13253 p->vrtp = NULL;
13254 }
13255 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
13256 ast_rtp_destroy(p->trtp);
13257 p->trtp = NULL;
13258 }
13259 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
13260 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
13261 p->noncodeccapability |= AST_RTP_DTMF;
13262 else
13263 p->noncodeccapability &= ~AST_RTP_DTMF;
13264 p->jointnoncodeccapability = p->noncodeccapability;
13265 }
13266 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
13267 return res;
13268 }
13269
13270
13271
13272
13273
13274
13275
13276 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
13277 int sipmethod, char *uri, enum xmittype reliable,
13278 struct sockaddr_in *sin, struct sip_peer **authpeer)
13279 {
13280 char from[256];
13281 char *dummy;
13282 char *domain;
13283 char *of;
13284 char rpid_num[50];
13285 const char *rpid;
13286 enum check_auth_result res;
13287 char calleridname[50];
13288 char *uri2 = ast_strdupa(uri);
13289
13290 terminate_uri(uri2);
13291
13292 ast_copy_string(from, get_header(req, "From"), sizeof(from));
13293 if (pedanticsipchecking)
13294 ast_uri_decode(from);
13295
13296 memset(calleridname, 0, sizeof(calleridname));
13297 get_calleridname(from, calleridname, sizeof(calleridname));
13298 if (calleridname[0])
13299 ast_string_field_set(p, cid_name, calleridname);
13300
13301 rpid = get_header(req, "Remote-Party-ID");
13302 memset(rpid_num, 0, sizeof(rpid_num));
13303 if (!ast_strlen_zero(rpid))
13304 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
13305
13306 of = get_in_brackets(from);
13307 if (ast_strlen_zero(p->exten)) {
13308 char *t = uri2;
13309 if (!strncasecmp(t, "sip:", 4))
13310 t+= 4;
13311 else if (!strncasecmp(t, "sips:", 5))
13312 t += 5;
13313 ast_string_field_set(p, exten, t);
13314 t = strchr(p->exten, '@');
13315 if (t)
13316 *t = '\0';
13317 if (ast_strlen_zero(p->our_contact))
13318 build_contact(p);
13319 }
13320
13321 ast_string_field_set(p, from, of);
13322
13323
13324
13325 if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
13326 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
13327 }
13328
13329 if (ast_strlen_zero(of)) {
13330
13331
13332
13333
13334
13335
13336 of = domain;
13337 } else {
13338 char *tmp = ast_strdupa(of);
13339
13340
13341
13342 tmp = strsep(&tmp, ";");
13343 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13344 ast_shrink_phone_number(tmp);
13345 ast_string_field_set(p, cid_num, tmp);
13346 }
13347
13348 if (global_match_auth_username) {
13349
13350
13351
13352
13353
13354
13355
13356
13357 const char *hdr = get_header(req, "Authorization");
13358 if (ast_strlen_zero(hdr))
13359 hdr = get_header(req, "Proxy-Authorization");
13360
13361 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
13362 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
13363 of = from;
13364 of = strsep(&of, "\"");
13365 }
13366 }
13367
13368 res = check_peer_ok(p, of, req, sipmethod, sin,
13369 authpeer, reliable, rpid_num, calleridname, uri2);
13370 if (res != AUTH_DONT_KNOW)
13371 return res;
13372
13373
13374 if (global_allowguest) {
13375 replace_cid(p, rpid_num, calleridname);
13376 res = AUTH_SUCCESSFUL;
13377 } else if (global_alwaysauthreject)
13378 res = AUTH_FAKE_AUTH;
13379 else
13380 res = AUTH_SECRET_FAILED;
13381
13382
13383 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
13384 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
13385 }
13386
13387 return res;
13388 }
13389
13390
13391
13392
13393 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
13394 {
13395 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
13396 }
13397
13398
13399 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
13400 {
13401 int x;
13402 int y;
13403
13404 buf[0] = '\0';
13405
13406 y = len - strlen(buf) - 5;
13407 if (y < 0)
13408 y = 0;
13409 for (x = 0; x < req->lines; x++) {
13410 char *line = REQ_OFFSET_TO_STR(req, line[x]);
13411 strncat(buf, line, y);
13412 y -= strlen(line) + 1;
13413 if (y < 0)
13414 y = 0;
13415 if (y != 0 && addnewline)
13416 strcat(buf, "\n");
13417 }
13418 return 0;
13419 }
13420
13421
13422
13423
13424
13425 static void receive_message(struct sip_pvt *p, struct sip_request *req)
13426 {
13427 char buf[1400];
13428 struct ast_frame f;
13429 const char *content_type = get_header(req, "Content-Type");
13430
13431 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
13432 transmit_response(p, "415 Unsupported Media Type", req);
13433 if (!p->owner)
13434 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13435 return;
13436 }
13437
13438 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
13439 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
13440 transmit_response(p, "202 Accepted", req);
13441 if (!p->owner)
13442 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13443 return;
13444 }
13445
13446 if (p->owner) {
13447 if (sip_debug_test_pvt(p))
13448 ast_verbose("SIP Text message received: '%s'\n", buf);
13449 memset(&f, 0, sizeof(f));
13450 f.frametype = AST_FRAME_TEXT;
13451 f.subclass = 0;
13452 f.offset = 0;
13453 f.data.ptr = buf;
13454 f.datalen = strlen(buf);
13455 ast_queue_frame(p->owner, &f);
13456 transmit_response(p, "202 Accepted", req);
13457 return;
13458 }
13459
13460
13461 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);
13462 transmit_response(p, "405 Method Not Allowed", req);
13463 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13464 return;
13465 }
13466
13467
13468 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13469 {
13470 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
13471 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
13472 char ilimits[40];
13473 char iused[40];
13474 int showall = FALSE;
13475 struct ao2_iterator i;
13476 struct sip_peer *peer;
13477
13478 switch (cmd) {
13479 case CLI_INIT:
13480 e->command = "sip show inuse";
13481 e->usage =
13482 "Usage: sip show inuse [all]\n"
13483 " List all SIP devices usage counters and limits.\n"
13484 " Add option \"all\" to show all devices, not only those with a limit.\n";
13485 return NULL;
13486 case CLI_GENERATE:
13487 return NULL;
13488 }
13489
13490 if (a->argc < 3)
13491 return CLI_SHOWUSAGE;
13492
13493 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
13494 showall = TRUE;
13495
13496 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
13497
13498 i = ao2_iterator_init(peers, 0);
13499 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
13500 ao2_lock(peer);
13501 if (peer->call_limit)
13502 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
13503 else
13504 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
13505 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
13506 if (showall || peer->call_limit)
13507 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
13508 ao2_unlock(peer);
13509 unref_peer(peer, "toss iterator pointer");
13510 }
13511 ao2_iterator_destroy(&i);
13512
13513 return CLI_SUCCESS;
13514 #undef FORMAT
13515 #undef FORMAT2
13516 }
13517
13518
13519
13520 static char *transfermode2str(enum transfermodes mode)
13521 {
13522 if (mode == TRANSFER_OPENFORALL)
13523 return "open";
13524 else if (mode == TRANSFER_CLOSED)
13525 return "closed";
13526 return "strict";
13527 }
13528
13529 static struct _map_x_s natmodes[] = {
13530 { SIP_NAT_NEVER, "No"},
13531 { SIP_NAT_ROUTE, "Route"},
13532 { SIP_NAT_ALWAYS, "Always"},
13533 { SIP_NAT_RFC3581, "RFC3581"},
13534 { -1, NULL},
13535 };
13536
13537
13538 static const char *nat2str(int nat)
13539 {
13540 return map_x_s(natmodes, nat, "Unknown");
13541 }
13542
13543 #ifdef NOTUSED
13544
13545
13546
13547
13548 static struct _map_x_s natcfgmodes[] = {
13549 { SIP_NAT_NEVER, "never"},
13550 { SIP_NAT_ROUTE, "route"},
13551 { SIP_NAT_ALWAYS, "yes"},
13552 { SIP_NAT_RFC3581, "no"},
13553 { -1, NULL},
13554 };
13555
13556
13557 static const char *nat2strconfig(int nat)
13558 {
13559 return map_x_s(natcfgmodes, nat, "Unknown");
13560 }
13561 #endif
13562
13563
13564
13565
13566
13567
13568
13569 static struct _map_x_s stmodes[] = {
13570 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
13571 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
13572 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
13573 { -1, NULL},
13574 };
13575
13576 static const char *stmode2str(enum st_mode m)
13577 {
13578 return map_x_s(stmodes, m, "Unknown");
13579 }
13580
13581 static enum st_mode str2stmode(const char *s)
13582 {
13583 return map_s_x(stmodes, s, -1);
13584 }
13585
13586
13587 static struct _map_x_s strefreshers[] = {
13588 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
13589 { SESSION_TIMER_REFRESHER_UAC, "uac"},
13590 { SESSION_TIMER_REFRESHER_UAS, "uas"},
13591 { -1, NULL},
13592 };
13593
13594 static const char *strefresher2str(enum st_refresher r)
13595 {
13596 return map_x_s(strefreshers, r, "Unknown");
13597 }
13598
13599 static enum st_refresher str2strefresher(const char *s)
13600 {
13601 return map_s_x(strefreshers, s, -1);
13602 }
13603
13604
13605 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
13606 {
13607 int res = 0;
13608 if (peer->maxms) {
13609 if (peer->lastms < 0) {
13610 ast_copy_string(status, "UNREACHABLE", statuslen);
13611 } else if (peer->lastms > peer->maxms) {
13612 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
13613 res = 1;
13614 } else if (peer->lastms) {
13615 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
13616 res = 1;
13617 } else {
13618 ast_copy_string(status, "UNKNOWN", statuslen);
13619 }
13620 } else {
13621 ast_copy_string(status, "Unmonitored", statuslen);
13622
13623 res = -1;
13624 }
13625 return res;
13626 }
13627
13628
13629
13630
13631
13632
13633 static const char *cli_yesno(int x)
13634 {
13635 return x ? "Yes" : "No";
13636 }
13637
13638
13639 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13640 {
13641 struct sip_threadinfo *th;
13642 struct ao2_iterator i;
13643
13644 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
13645 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
13646
13647 switch (cmd) {
13648 case CLI_INIT:
13649 e->command = "sip show tcp";
13650 e->usage =
13651 "Usage: sip show tcp\n"
13652 " Lists all active TCP/TLS sessions.\n";
13653 return NULL;
13654 case CLI_GENERATE:
13655 return NULL;
13656 }
13657
13658 if (a->argc != 3)
13659 return CLI_SHOWUSAGE;
13660
13661 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
13662 i = ao2_iterator_init(threadt, 0);
13663 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
13664 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr),
13665 ntohs(th->tcptls_session->remote_address.sin_port),
13666 get_transport(th->type),
13667 (th->tcptls_session->client ? "Client" : "Server"));
13668 ao2_t_ref(th, -1, "decrement ref from iterator");
13669 }
13670 ao2_iterator_destroy(&i);
13671 return CLI_SUCCESS;
13672 #undef FORMAT
13673 #undef FORMAT2
13674 }
13675
13676
13677 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13678 {
13679 regex_t regexbuf;
13680 int havepattern = FALSE;
13681 struct ao2_iterator user_iter;
13682 struct sip_peer *user;
13683
13684 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
13685
13686 switch (cmd) {
13687 case CLI_INIT:
13688 e->command = "sip show users";
13689 e->usage =
13690 "Usage: sip show users [like <pattern>]\n"
13691 " Lists all known SIP users.\n"
13692 " Optional regular expression pattern is used to filter the user list.\n";
13693 return NULL;
13694 case CLI_GENERATE:
13695 return NULL;
13696 }
13697
13698 switch (a->argc) {
13699 case 5:
13700 if (!strcasecmp(a->argv[3], "like")) {
13701 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
13702 return CLI_SHOWUSAGE;
13703 havepattern = TRUE;
13704 } else
13705 return CLI_SHOWUSAGE;
13706 case 3:
13707 break;
13708 default:
13709 return CLI_SHOWUSAGE;
13710 }
13711
13712 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
13713
13714 user_iter = ao2_iterator_init(peers, 0);
13715 while ((user = ao2_iterator_next(&user_iter))) {
13716 ao2_lock(user);
13717 if (!(user->type & SIP_TYPE_USER)) {
13718 ao2_unlock(user);
13719 unref_peer(user, "sip show users");
13720 continue;
13721 }
13722
13723 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
13724 ao2_unlock(user);
13725 unref_peer(user, "sip show users");
13726 continue;
13727 }
13728
13729 ast_cli(a->fd, FORMAT, user->name,
13730 user->secret,
13731 user->accountcode,
13732 user->context,
13733 cli_yesno(user->ha != NULL),
13734 nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
13735 ao2_unlock(user);
13736 unref_peer(user, "sip show users");
13737 }
13738 ao2_iterator_destroy(&user_iter);
13739
13740 if (havepattern)
13741 regfree(®exbuf);
13742
13743 return CLI_SUCCESS;
13744 #undef FORMAT
13745 }
13746
13747
13748 static char mandescr_show_registry[] =
13749 "Description: Lists all registration requests and status\n"
13750 "Registrations will follow as separate events. followed by a final event called\n"
13751 "RegistrationsComplete.\n"
13752 "Variables: \n"
13753 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
13754
13755
13756 static int manager_show_registry(struct mansession *s, const struct message *m)
13757 {
13758 const char *id = astman_get_header(m, "ActionID");
13759 char idtext[256] = "";
13760 int total = 0;
13761
13762 if (!ast_strlen_zero(id))
13763 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13764
13765 astman_send_listack(s, m, "Registrations will follow", "start");
13766
13767 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
13768 ASTOBJ_RDLOCK(iterator);
13769 astman_append(s,
13770 "Event: RegistryEntry\r\n"
13771 "%s"
13772 "Host: %s\r\n"
13773 "Port: %d\r\n"
13774 "Username: %s\r\n"
13775 "Refresh: %d\r\n"
13776 "State: %s\r\n"
13777 "RegistrationTime: %ld\r\n"
13778 "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
13779 iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
13780 ASTOBJ_UNLOCK(iterator);
13781 total++;
13782 } while(0));
13783
13784 astman_append(s,
13785 "Event: RegistrationsComplete\r\n"
13786 "EventList: Complete\r\n"
13787 "ListItems: %d\r\n"
13788 "%s"
13789 "\r\n", total, idtext);
13790
13791 return 0;
13792 }
13793
13794 static char mandescr_show_peers[] =
13795 "Description: Lists SIP peers in text format with details on current status.\n"
13796 "Peerlist will follow as separate events, followed by a final event called\n"
13797 "PeerlistComplete.\n"
13798 "Variables: \n"
13799 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
13800
13801
13802
13803 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
13804 {
13805 const char *id = astman_get_header(m, "ActionID");
13806 const char *a[] = {"sip", "show", "peers"};
13807 char idtext[256] = "";
13808 int total = 0;
13809
13810 if (!ast_strlen_zero(id))
13811 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13812
13813 astman_send_listack(s, m, "Peer status list will follow", "start");
13814
13815 _sip_show_peers(-1, &total, s, m, 3, a);
13816
13817 astman_append(s,
13818 "Event: PeerlistComplete\r\n"
13819 "EventList: Complete\r\n"
13820 "ListItems: %d\r\n"
13821 "%s"
13822 "\r\n", total, idtext);
13823 return 0;
13824 }
13825
13826
13827 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13828 {
13829 switch (cmd) {
13830 case CLI_INIT:
13831 e->command = "sip show peers";
13832 e->usage =
13833 "Usage: sip show peers [like <pattern>]\n"
13834 " Lists all known SIP peers.\n"
13835 " Optional regular expression pattern is used to filter the peer list.\n";
13836 return NULL;
13837 case CLI_GENERATE:
13838 return NULL;
13839 }
13840
13841 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
13842 }
13843
13844 int peercomparefunc(const void *a, const void *b);
13845
13846 int peercomparefunc(const void *a, const void *b)
13847 {
13848 struct sip_peer **ap = (struct sip_peer **)a;
13849 struct sip_peer **bp = (struct sip_peer **)b;
13850 return strcmp((*ap)->name, (*bp)->name);
13851 }
13852
13853
13854
13855 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
13856 {
13857 regex_t regexbuf;
13858 int havepattern = FALSE;
13859 struct sip_peer *peer;
13860 struct ao2_iterator i;
13861
13862
13863 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
13864 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
13865
13866 char name[256];
13867 int total_peers = 0;
13868 int peers_mon_online = 0;
13869 int peers_mon_offline = 0;
13870 int peers_unmon_offline = 0;
13871 int peers_unmon_online = 0;
13872 const char *id;
13873 char idtext[256] = "";
13874 int realtimepeers;
13875 int objcount = ao2_container_count(peers);
13876 struct sip_peer **peerarray;
13877 int k;
13878
13879
13880 realtimepeers = ast_check_realtime("sippeers");
13881 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
13882
13883 if (s) {
13884 id = astman_get_header(m, "ActionID");
13885 if (!ast_strlen_zero(id))
13886 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13887 }
13888
13889 switch (argc) {
13890 case 5:
13891 if (!strcasecmp(argv[3], "like")) {
13892 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
13893 return CLI_SHOWUSAGE;
13894 havepattern = TRUE;
13895 } else
13896 return CLI_SHOWUSAGE;
13897 case 3:
13898 break;
13899 default:
13900 return CLI_SHOWUSAGE;
13901 }
13902
13903 if (!s)
13904 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
13905
13906
13907 i = ao2_iterator_init(peers, 0);
13908 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
13909 ao2_lock(peer);
13910
13911 if (!(peer->type & SIP_TYPE_PEER)) {
13912 ao2_unlock(peer);
13913 unref_peer(peer, "unref peer because it's actually a user");
13914 continue;
13915 }
13916
13917 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
13918 objcount--;
13919 ao2_unlock(peer);
13920 unref_peer(peer, "toss iterator peer ptr before continue");
13921 continue;
13922 }
13923
13924 peerarray[total_peers++] = peer;
13925 ao2_unlock(peer);
13926 }
13927 ao2_iterator_destroy(&i);
13928
13929 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
13930
13931 for(k=0; k < total_peers; k++) {
13932 char status[20] = "";
13933 char srch[2000];
13934 char pstatus;
13935 peer = peerarray[k];
13936
13937 ao2_lock(peer);
13938 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
13939 ao2_unlock(peer);
13940 unref_peer(peer, "toss iterator peer ptr before continue");
13941 continue;
13942 }
13943
13944 if (!ast_strlen_zero(peer->username) && !s)
13945 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
13946 else
13947 ast_copy_string(name, peer->name, sizeof(name));
13948
13949 pstatus = peer_status(peer, status, sizeof(status));
13950 if (pstatus == 1)
13951 peers_mon_online++;
13952 else if (pstatus == 0)
13953 peers_mon_offline++;
13954 else {
13955 if (peer->addr.sin_port == 0)
13956 peers_unmon_offline++;
13957 else
13958 peers_unmon_online++;
13959 }
13960
13961 snprintf(srch, sizeof(srch), FORMAT, name,
13962 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13963 peer->host_dynamic ? " D " : " ",
13964 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
13965 peer->ha ? " A " : " ",
13966 ntohs(peer->addr.sin_port), status,
13967 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13968
13969 if (!s) {
13970 ast_cli(fd, FORMAT, name,
13971 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13972 peer->host_dynamic ? " D " : " ",
13973 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
13974 peer->ha ? " A " : " ",
13975
13976 ntohs(peer->addr.sin_port), status,
13977 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13978 } else {
13979
13980 astman_append(s,
13981 "Event: PeerEntry\r\n%s"
13982 "Channeltype: SIP\r\n"
13983 "ObjectName: %s\r\n"
13984 "ChanObjectType: peer\r\n"
13985 "IPaddress: %s\r\n"
13986 "IPport: %d\r\n"
13987 "Dynamic: %s\r\n"
13988 "Natsupport: %s\r\n"
13989 "VideoSupport: %s\r\n"
13990 "TextSupport: %s\r\n"
13991 "ACL: %s\r\n"
13992 "Status: %s\r\n"
13993 "RealtimeDevice: %s\r\n\r\n",
13994 idtext,
13995 peer->name,
13996 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
13997 ntohs(peer->addr.sin_port),
13998 peer->host_dynamic ? "yes" : "no",
13999 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
14000 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
14001 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
14002 peer->ha ? "yes" : "no",
14003 status,
14004 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14005 }
14006 ao2_unlock(peer);
14007 unref_peer(peer, "toss iterator peer ptr");
14008 }
14009
14010 if (!s)
14011 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14012 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14013
14014 if (havepattern)
14015 regfree(®exbuf);
14016
14017 if (total)
14018 *total = total_peers;
14019
14020 ast_free(peerarray);
14021
14022 return CLI_SUCCESS;
14023 #undef FORMAT
14024 #undef FORMAT2
14025 }
14026
14027 static int peer_dump_func(void *userobj, void *arg, int flags)
14028 {
14029 struct sip_peer *peer = userobj;
14030 int refc = ao2_t_ref(userobj, 0, "");
14031 int *fd = arg;
14032
14033 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
14034 peer->name, 0, refc);
14035 return 0;
14036 }
14037
14038 static int dialog_dump_func(void *userobj, void *arg, int flags)
14039 {
14040 struct sip_pvt *pvt = userobj;
14041 int refc = ao2_t_ref(userobj, 0, "");
14042 int *fd = arg;
14043
14044 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
14045 pvt->callid, 0, refc);
14046 return 0;
14047 }
14048
14049
14050
14051 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14052 {
14053 char tmp[256];
14054
14055 switch (cmd) {
14056 case CLI_INIT:
14057 e->command = "sip show objects";
14058 e->usage =
14059 "Usage: sip show objects\n"
14060 " Lists status of known SIP objects\n";
14061 return NULL;
14062 case CLI_GENERATE:
14063 return NULL;
14064 }
14065
14066 if (a->argc != 3)
14067 return CLI_SHOWUSAGE;
14068 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
14069 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
14070 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
14071 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
14072 ast_cli(a->fd, "-= Dialog objects:\n\n");
14073 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
14074 return CLI_SUCCESS;
14075 }
14076
14077 static void print_group(int fd, ast_group_t group, int crlf)
14078 {
14079 char buf[256];
14080 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
14081 }
14082
14083
14084 static struct _map_x_s dtmfstr[] = {
14085 { SIP_DTMF_RFC2833, "rfc2833" },
14086 { SIP_DTMF_INFO, "info" },
14087 { SIP_DTMF_SHORTINFO, "shortinfo" },
14088 { SIP_DTMF_INBAND, "inband" },
14089 { SIP_DTMF_AUTO, "auto" },
14090 { -1, NULL },
14091 };
14092
14093
14094 static const char *dtmfmode2str(int mode)
14095 {
14096 return map_x_s(dtmfstr, mode, "<error>");
14097 }
14098
14099
14100 static int str2dtmfmode(const char *str)
14101 {
14102 return map_s_x(dtmfstr, str, -1);
14103 }
14104
14105 static struct _map_x_s insecurestr[] = {
14106 { SIP_INSECURE_PORT, "port" },
14107 { SIP_INSECURE_INVITE, "invite" },
14108 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
14109 { 0, "no" },
14110 { -1, NULL },
14111 };
14112
14113
14114 static const char *insecure2str(int mode)
14115 {
14116 return map_x_s(insecurestr, mode, "<error>");
14117 }
14118
14119
14120
14121
14122 static void cleanup_stale_contexts(char *new, char *old)
14123 {
14124 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
14125
14126 while ((oldcontext = strsep(&old, "&"))) {
14127 stalecontext = '\0';
14128 ast_copy_string(newlist, new, sizeof(newlist));
14129 stringp = newlist;
14130 while ((newcontext = strsep(&stringp, "&"))) {
14131 if (!strcmp(newcontext, oldcontext)) {
14132
14133 stalecontext = '\0';
14134 break;
14135 } else if (strcmp(newcontext, oldcontext)) {
14136 stalecontext = oldcontext;
14137 }
14138
14139 }
14140 if (stalecontext)
14141 ast_context_destroy(ast_context_find(stalecontext), "SIP");
14142 }
14143 }
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
14154 {
14155 struct sip_pvt *dialog = dialogobj;
14156 time_t *t = arg;
14157
14158
14159
14160 if (sip_pvt_trylock(dialog)) {
14161
14162
14163
14164
14165
14166
14167 ao2_unlock(dialogs);
14168 usleep(1);
14169 ao2_lock(dialogs);
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180 return 0;
14181 }
14182
14183
14184 check_rtp_timeout(dialog, *t);
14185
14186
14187
14188
14189 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
14190
14191 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
14192 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
14193 sip_pvt_unlock(dialog);
14194 return 0;
14195 }
14196
14197 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
14198 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
14199 sip_pvt_unlock(dialog);
14200 return 0;
14201 }
14202
14203 sip_pvt_unlock(dialog);
14204
14205
14206 dialog_unlink_all(dialog, TRUE, FALSE);
14207 return 0;
14208 }
14209
14210 sip_pvt_unlock(dialog);
14211
14212 return 0;
14213 }
14214
14215
14216
14217 static int peer_is_marked(void *peerobj, void *arg, int flags)
14218 {
14219 struct sip_peer *peer = peerobj;
14220 return peer->the_mark ? CMP_MATCH : 0;
14221 }
14222
14223
14224
14225 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14226 {
14227 struct sip_peer *peer, *pi;
14228 int prunepeer = FALSE;
14229 int multi = FALSE;
14230 char *name = NULL;
14231 regex_t regexbuf;
14232 struct ao2_iterator i;
14233
14234 if (cmd == CLI_INIT) {
14235 e->command = "sip prune realtime [peer|all] [all|like]";
14236 e->usage =
14237 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
14238 " Prunes object(s) from the cache.\n"
14239 " Optional regular expression pattern is used to filter the objects.\n";
14240 return NULL;
14241 } else if (cmd == CLI_GENERATE) {
14242 if (a->pos == 4) {
14243 if (strcasestr(a->line, "realtime peer"))
14244 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
14245 }
14246 return NULL;
14247 }
14248 switch (a->argc) {
14249 case 4:
14250 name = a->argv[3];
14251
14252 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
14253 return CLI_SHOWUSAGE;
14254 prunepeer = TRUE;
14255 if (!strcasecmp(name, "all")) {
14256 multi = TRUE;
14257 name = NULL;
14258 }
14259
14260 break;
14261 case 5:
14262
14263 name = a->argv[4];
14264 if (!strcasecmp(a->argv[3], "peer"))
14265 prunepeer = TRUE;
14266 else if (!strcasecmp(a->argv[3], "like")) {
14267 prunepeer = TRUE;
14268 multi = TRUE;
14269 } else
14270 return CLI_SHOWUSAGE;
14271 if (!strcasecmp(a->argv[4], "like"))
14272 return CLI_SHOWUSAGE;
14273 if (!multi && !strcasecmp(a->argv[4], "all")) {
14274 multi = TRUE;
14275 name = NULL;
14276 }
14277 break;
14278 case 6:
14279 name = a->argv[5];
14280 multi = TRUE;
14281
14282 if (strcasecmp(a->argv[4], "like"))
14283 return CLI_SHOWUSAGE;
14284 if (!strcasecmp(a->argv[3], "peer")) {
14285 prunepeer = TRUE;
14286 } else
14287 return CLI_SHOWUSAGE;
14288 break;
14289 default:
14290 return CLI_SHOWUSAGE;
14291 }
14292
14293 if (multi && name) {
14294 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
14295 return CLI_SHOWUSAGE;
14296 }
14297
14298 if (multi) {
14299 if (prunepeer) {
14300 int pruned = 0;
14301
14302 i = ao2_iterator_init(peers, 0);
14303 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14304 ao2_lock(pi);
14305 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
14306 unref_peer(pi, "toss iterator peer ptr before continue");
14307 ao2_unlock(pi);
14308 continue;
14309 };
14310 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14311 pi->the_mark = 1;
14312 pruned++;
14313 }
14314 ao2_unlock(pi);
14315 unref_peer(pi, "toss iterator peer ptr");
14316 }
14317 ao2_iterator_destroy(&i);
14318 if (pruned) {
14319 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, 0,
14320 "initiating callback to remove marked peers");
14321 ast_cli(a->fd, "%d peers pruned.\n", pruned);
14322 } else
14323 ast_cli(a->fd, "No peers found to prune.\n");
14324 }
14325 } else {
14326 if (prunepeer) {
14327 struct sip_peer tmp;
14328 ast_copy_string(tmp.name, name, sizeof(tmp.name));
14329 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
14330 if (peer->addr.sin_addr.s_addr) {
14331 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
14332 }
14333 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14334 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
14335
14336 ao2_t_link(peers, peer, "link peer into peer table");
14337 if (peer->addr.sin_addr.s_addr) {
14338 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
14339 }
14340
14341 } else
14342 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
14343 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
14344 } else
14345 ast_cli(a->fd, "Peer '%s' not found.\n", name);
14346 }
14347 }
14348
14349 return CLI_SUCCESS;
14350 }
14351
14352
14353 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
14354 {
14355 int x, codec;
14356
14357 for(x = 0; x < 32 ; x++) {
14358 codec = ast_codec_pref_index(pref, x);
14359 if (!codec)
14360 break;
14361 ast_cli(fd, "%s", ast_getformatname(codec));
14362 ast_cli(fd, ":%d", pref->framing[x]);
14363 if (x < 31 && ast_codec_pref_index(pref, x + 1))
14364 ast_cli(fd, ",");
14365 }
14366 if (!x)
14367 ast_cli(fd, "none");
14368 }
14369
14370
14371 static const char *domain_mode_to_text(const enum domain_mode mode)
14372 {
14373 switch (mode) {
14374 case SIP_DOMAIN_AUTO:
14375 return "[Automatic]";
14376 case SIP_DOMAIN_CONFIG:
14377 return "[Configured]";
14378 }
14379
14380 return "";
14381 }
14382
14383
14384 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14385 {
14386 struct domain *d;
14387 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
14388
14389 switch (cmd) {
14390 case CLI_INIT:
14391 e->command = "sip show domains";
14392 e->usage =
14393 "Usage: sip show domains\n"
14394 " Lists all configured SIP local domains.\n"
14395 " Asterisk only responds to SIP messages to local domains.\n";
14396 return NULL;
14397 case CLI_GENERATE:
14398 return NULL;
14399 }
14400
14401 if (AST_LIST_EMPTY(&domain_list)) {
14402 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
14403 return CLI_SUCCESS;
14404 } else {
14405 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
14406 AST_LIST_LOCK(&domain_list);
14407 AST_LIST_TRAVERSE(&domain_list, d, list)
14408 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
14409 domain_mode_to_text(d->mode));
14410 AST_LIST_UNLOCK(&domain_list);
14411 ast_cli(a->fd, "\n");
14412 return CLI_SUCCESS;
14413 }
14414 }
14415 #undef FORMAT
14416
14417 static char mandescr_show_peer[] =
14418 "Description: Show one SIP peer with details on current status.\n"
14419 "Variables: \n"
14420 " Peer: <name> The peer name you want to check.\n"
14421 " ActionID: <id> Optional action ID for this AMI transaction.\n";
14422
14423
14424 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
14425 {
14426 const char *a[4];
14427 const char *peer;
14428
14429 peer = astman_get_header(m, "Peer");
14430 if (ast_strlen_zero(peer)) {
14431 astman_send_error(s, m, "Peer: <name> missing.");
14432 return 0;
14433 }
14434 a[0] = "sip";
14435 a[1] = "show";
14436 a[2] = "peer";
14437 a[3] = peer;
14438
14439 _sip_show_peer(1, -1, s, m, 4, a);
14440 astman_append(s, "\r\n\r\n" );
14441 return 0;
14442 }
14443
14444
14445 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14446 {
14447 switch (cmd) {
14448 case CLI_INIT:
14449 e->command = "sip show peer";
14450 e->usage =
14451 "Usage: sip show peer <name> [load]\n"
14452 " Shows all details on one SIP peer and the current status.\n"
14453 " Option \"load\" forces lookup of peer in realtime storage.\n";
14454 return NULL;
14455 case CLI_GENERATE:
14456 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
14457 }
14458 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
14459 }
14460
14461
14462 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
14463 {
14464 struct sip_peer *peer;
14465 int load_realtime;
14466
14467 if (argc < 4)
14468 return CLI_SHOWUSAGE;
14469
14470 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
14471 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
14472 sip_poke_peer(peer, 1);
14473 unref_peer(peer, "qualify: done with peer");
14474 } else if (type == 0) {
14475 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
14476 } else {
14477 astman_send_error(s, m, "Peer not found");
14478 }
14479 return CLI_SUCCESS;
14480 }
14481
14482
14483 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
14484 {
14485 const char *a[4];
14486 const char *peer;
14487
14488 peer = astman_get_header(m, "Peer");
14489 if (ast_strlen_zero(peer)) {
14490 astman_send_error(s, m, "Peer: <name> missing.");
14491 return 0;
14492 }
14493 a[0] = "sip";
14494 a[1] = "qualify";
14495 a[2] = "peer";
14496 a[3] = peer;
14497
14498 _sip_qualify_peer(1, -1, s, m, 4, a);
14499 astman_append(s, "\r\n\r\n" );
14500 return 0;
14501 }
14502
14503
14504 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14505 {
14506 switch (cmd) {
14507 case CLI_INIT:
14508 e->command = "sip qualify peer";
14509 e->usage =
14510 "Usage: sip qualify peer <name> [load]\n"
14511 " Requests a response from one SIP peer and the current status.\n"
14512 " Option \"load\" forces lookup of peer in realtime storage.\n";
14513 return NULL;
14514 case CLI_GENERATE:
14515 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
14516 }
14517 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
14518 }
14519
14520
14521 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
14522 {
14523 struct sip_mailbox *mailbox;
14524
14525 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
14526 ast_str_append(mailbox_str, 0, "%s%s%s%s",
14527 mailbox->mailbox,
14528 ast_strlen_zero(mailbox->context) ? "" : "@",
14529 S_OR(mailbox->context, ""),
14530 AST_LIST_NEXT(mailbox, entry) ? "," : "");
14531 }
14532 }
14533
14534 static struct _map_x_s faxecmodes[] = {
14535 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
14536 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
14537 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
14538 { -1, NULL},
14539 };
14540
14541 static const char *faxec2str(int faxec)
14542 {
14543 return map_x_s(faxecmodes, faxec, "Unknown");
14544 }
14545
14546
14547 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
14548 {
14549 char status[30] = "";
14550 char cbuf[256];
14551 struct sip_peer *peer;
14552 char codec_buf[512];
14553 struct ast_codec_pref *pref;
14554 struct ast_variable *v;
14555 struct sip_auth *auth;
14556 int x = 0, codec = 0, load_realtime;
14557 int realtimepeers;
14558
14559 realtimepeers = ast_check_realtime("sippeers");
14560
14561 if (argc < 4)
14562 return CLI_SHOWUSAGE;
14563
14564 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
14565 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
14566
14567 if (s) {
14568 if (peer) {
14569 const char *id = astman_get_header(m, "ActionID");
14570
14571 astman_append(s, "Response: Success\r\n");
14572 if (!ast_strlen_zero(id))
14573 astman_append(s, "ActionID: %s\r\n", id);
14574 } else {
14575 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
14576 astman_send_error(s, m, cbuf);
14577 return CLI_SUCCESS;
14578 }
14579 }
14580 if (peer && type==0 ) {
14581 struct ast_str *mailbox_str = ast_str_alloca(512);
14582 ast_cli(fd, "\n\n");
14583 ast_cli(fd, " * Name : %s\n", peer->name);
14584 if (realtimepeers) {
14585 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
14586 }
14587 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
14588 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
14589 for (auth = peer->auth; auth; auth = auth->next) {
14590 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
14591 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
14592 }
14593 ast_cli(fd, " Context : %s\n", peer->context);
14594 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
14595 ast_cli(fd, " Language : %s\n", peer->language);
14596 if (!ast_strlen_zero(peer->accountcode))
14597 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
14598 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
14599 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
14600 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
14601 if (!ast_strlen_zero(peer->fromuser))
14602 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
14603 if (!ast_strlen_zero(peer->fromdomain))
14604 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
14605 ast_cli(fd, " Callgroup : ");
14606 print_group(fd, peer->callgroup, 0);
14607 ast_cli(fd, " Pickupgroup : ");
14608 print_group(fd, peer->pickupgroup, 0);
14609 peer_mailboxes_to_str(&mailbox_str, peer);
14610 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
14611 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
14612 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
14613 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
14614 if (peer->busy_level)
14615 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
14616 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
14617 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
14618 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
14619 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
14620 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
14621 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
14622 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
14623 ast_cli(fd, " T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
14624 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
14625 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
14626 ast_cli(fd, " CanReinvite : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)));
14627 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
14628 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
14629 ast_cli(fd, " Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
14630 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
14631 ast_cli(fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14632 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
14633 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
14634 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
14635 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
14636 if (peer->outboundproxy)
14637 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
14638 peer->outboundproxy->force ? "(forced)" : "");
14639
14640
14641 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
14642 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
14643 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
14644 ast_cli(fd, " ToHost : %s\n", peer->tohost);
14645 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));
14646 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
14647 ast_cli(fd, " Transport : %s\n", get_transport(peer->socket.type));
14648 if (!ast_strlen_zero(global_regcontext))
14649 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
14650 ast_cli(fd, " Def. Username: %s\n", peer->username);
14651 ast_cli(fd, " SIP Options : ");
14652 if (peer->sipoptions) {
14653 int lastoption = -1;
14654 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
14655 if (sip_options[x].id != lastoption) {
14656 if (peer->sipoptions & sip_options[x].id)
14657 ast_cli(fd, "%s ", sip_options[x].text);
14658 lastoption = x;
14659 }
14660 }
14661 } else
14662 ast_cli(fd, "(none)");
14663
14664 ast_cli(fd, "\n");
14665 ast_cli(fd, " Codecs : ");
14666 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
14667 ast_cli(fd, "%s\n", codec_buf);
14668 ast_cli(fd, " Codec Order : (");
14669 print_codec_to_cli(fd, &peer->prefs);
14670 ast_cli(fd, ")\n");
14671
14672 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
14673 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
14674 ast_cli(fd, " Status : ");
14675 peer_status(peer, status, sizeof(status));
14676 ast_cli(fd, "%s\n", status);
14677 ast_cli(fd, " Useragent : %s\n", peer->useragent);
14678 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
14679 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
14680 if (peer->chanvars) {
14681 ast_cli(fd, " Variables :\n");
14682 for (v = peer->chanvars ; v ; v = v->next)
14683 ast_cli(fd, " %s = %s\n", v->name, v->value);
14684 }
14685
14686 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
14687 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
14688 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
14689 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
14690 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
14691 ast_cli(fd, "\n");
14692 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
14693 } else if (peer && type == 1) {
14694 char buffer[256];
14695 struct ast_str *mailbox_str = ast_str_alloca(512);
14696 astman_append(s, "Channeltype: SIP\r\n");
14697 astman_append(s, "ObjectName: %s\r\n", peer->name);
14698 astman_append(s, "ChanObjectType: peer\r\n");
14699 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
14700 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
14701 astman_append(s, "Context: %s\r\n", peer->context);
14702 astman_append(s, "Language: %s\r\n", peer->language);
14703 if (!ast_strlen_zero(peer->accountcode))
14704 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
14705 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
14706 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
14707 if (!ast_strlen_zero(peer->fromuser))
14708 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
14709 if (!ast_strlen_zero(peer->fromdomain))
14710 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
14711 astman_append(s, "Callgroup: ");
14712 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
14713 astman_append(s, "Pickupgroup: ");
14714 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
14715 peer_mailboxes_to_str(&mailbox_str, peer);
14716 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
14717 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
14718 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
14719 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
14720 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
14721 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
14722 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
14723 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
14724 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
14725 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
14726 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
14727 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
14728 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
14729 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
14730 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
14731 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
14732 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
14733 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
14734 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
14735 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
14736 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
14737 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
14738 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
14739 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
14740
14741
14742 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
14743 astman_append(s, "ToHost: %s\r\n", peer->tohost);
14744 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));
14745 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));
14746 astman_append(s, "Default-Username: %s\r\n", peer->username);
14747 if (!ast_strlen_zero(global_regcontext))
14748 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
14749 astman_append(s, "Codecs: ");
14750 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
14751 astman_append(s, "%s\r\n", codec_buf);
14752 astman_append(s, "CodecOrder: ");
14753 pref = &peer->prefs;
14754 for(x = 0; x < 32 ; x++) {
14755 codec = ast_codec_pref_index(pref, x);
14756 if (!codec)
14757 break;
14758 astman_append(s, "%s", ast_getformatname(codec));
14759 if (x < 31 && ast_codec_pref_index(pref, x+1))
14760 astman_append(s, ",");
14761 }
14762
14763 astman_append(s, "\r\n");
14764 astman_append(s, "Status: ");
14765 peer_status(peer, status, sizeof(status));
14766 astman_append(s, "%s\r\n", status);
14767 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
14768 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
14769 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
14770 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
14771 if (peer->chanvars) {
14772 for (v = peer->chanvars ; v ; v = v->next) {
14773 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
14774 }
14775 }
14776
14777 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
14778
14779 } else {
14780 ast_cli(fd, "Peer %s not found.\n", argv[3]);
14781 ast_cli(fd, "\n");
14782 }
14783
14784 return CLI_SUCCESS;
14785 }
14786
14787
14788 static char *complete_sip_user(const char *word, int state)
14789 {
14790 char *result = NULL;
14791 int wordlen = strlen(word);
14792 int which = 0;
14793 struct ao2_iterator user_iter;
14794 struct sip_peer *user;
14795
14796 user_iter = ao2_iterator_init(peers, 0);
14797 while ((user = ao2_iterator_next(&user_iter))) {
14798 ao2_lock(user);
14799 if (!(user->type & SIP_TYPE_USER)) {
14800 ao2_unlock(user);
14801 unref_peer(user, "complete sip user");
14802 continue;
14803 }
14804
14805 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
14806 result = ast_strdup(user->name);
14807 }
14808 ao2_unlock(user);
14809 unref_peer(user, "complete sip user");
14810 }
14811 ao2_iterator_destroy(&user_iter);
14812 return result;
14813 }
14814
14815 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
14816 {
14817 if (pos == 3)
14818 return complete_sip_user(word, state);
14819
14820 return NULL;
14821 }
14822
14823
14824 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14825 {
14826 char cbuf[256];
14827 struct sip_peer *user;
14828 struct ast_variable *v;
14829 int load_realtime;
14830
14831 switch (cmd) {
14832 case CLI_INIT:
14833 e->command = "sip show user";
14834 e->usage =
14835 "Usage: sip show user <name> [load]\n"
14836 " Shows all details on one SIP user and the current status.\n"
14837 " Option \"load\" forces lookup of peer in realtime storage.\n";
14838 return NULL;
14839 case CLI_GENERATE:
14840 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
14841 }
14842
14843 if (a->argc < 4)
14844 return CLI_SHOWUSAGE;
14845
14846
14847 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
14848
14849 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
14850 ao2_lock(user);
14851 ast_cli(a->fd, "\n\n");
14852 ast_cli(a->fd, " * Name : %s\n", user->name);
14853 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
14854 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
14855 ast_cli(a->fd, " Context : %s\n", user->context);
14856 ast_cli(a->fd, " Language : %s\n", user->language);
14857 if (!ast_strlen_zero(user->accountcode))
14858 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
14859 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
14860 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
14861 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
14862 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
14863 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
14864 ast_cli(a->fd, " Callgroup : ");
14865 print_group(a->fd, user->callgroup, 0);
14866 ast_cli(a->fd, " Pickupgroup : ");
14867 print_group(a->fd, user->pickupgroup, 0);
14868 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
14869 ast_cli(a->fd, " ACL : %s\n", cli_yesno(user->ha != NULL));
14870 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
14871 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
14872 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
14873 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
14874 ast_cli(a->fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&user->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14875
14876 ast_cli(a->fd, " Codec Order : (");
14877 print_codec_to_cli(a->fd, &user->prefs);
14878 ast_cli(a->fd, ")\n");
14879
14880 ast_cli(a->fd, " Auto-Framing: %s \n", cli_yesno(user->autoframing));
14881 if (user->chanvars) {
14882 ast_cli(a->fd, " Variables :\n");
14883 for (v = user->chanvars ; v ; v = v->next)
14884 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
14885 }
14886
14887 ast_cli(a->fd, "\n");
14888
14889 ao2_unlock(user);
14890 unref_peer(user, "sip show user");
14891 } else {
14892 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
14893 ast_cli(a->fd, "\n");
14894 }
14895
14896 return CLI_SUCCESS;
14897 }
14898
14899
14900 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14901 {
14902 struct ast_str *cbuf;
14903 struct ast_cb_names cbnames = {9, { "retrans_pkt",
14904 "__sip_autodestruct",
14905 "expire_register",
14906 "auto_congest",
14907 "sip_reg_timeout",
14908 "sip_poke_peer_s",
14909 "sip_poke_noanswer",
14910 "sip_reregister",
14911 "sip_reinvite_retry"},
14912 { retrans_pkt,
14913 __sip_autodestruct,
14914 expire_register,
14915 auto_congest,
14916 sip_reg_timeout,
14917 sip_poke_peer_s,
14918 sip_poke_noanswer,
14919 sip_reregister,
14920 sip_reinvite_retry}};
14921
14922 switch (cmd) {
14923 case CLI_INIT:
14924 e->command = "sip show sched";
14925 e->usage =
14926 "Usage: sip show sched\n"
14927 " Shows stats on what's in the sched queue at the moment\n";
14928 return NULL;
14929 case CLI_GENERATE:
14930 return NULL;
14931 }
14932
14933 cbuf = ast_str_alloca(2048);
14934
14935 ast_cli(a->fd, "\n");
14936 ast_sched_report(sched, &cbuf, &cbnames);
14937 ast_cli(a->fd, "%s", cbuf->str);
14938
14939 return CLI_SUCCESS;
14940 }
14941
14942
14943 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14944 {
14945 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
14946 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
14947 char host[80];
14948 char tmpdat[256];
14949 struct ast_tm tm;
14950 int counter = 0;
14951
14952 switch (cmd) {
14953 case CLI_INIT:
14954 e->command = "sip show registry";
14955 e->usage =
14956 "Usage: sip show registry\n"
14957 " Lists all registration requests and status.\n";
14958 return NULL;
14959 case CLI_GENERATE:
14960 return NULL;
14961 }
14962
14963 if (a->argc != 3)
14964 return CLI_SHOWUSAGE;
14965 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
14966
14967 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
14968 ASTOBJ_RDLOCK(iterator);
14969 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
14970 if (iterator->regtime.tv_sec) {
14971 ast_localtime(&iterator->regtime, &tm, NULL);
14972 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
14973 } else
14974 tmpdat[0] = '\0';
14975 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
14976 ASTOBJ_UNLOCK(iterator);
14977 counter++;
14978 } while(0));
14979 ast_cli(a->fd, "%d SIP registrations.\n", counter);
14980 return CLI_SUCCESS;
14981 #undef FORMAT
14982 #undef FORMAT2
14983 }
14984
14985
14986
14987
14988
14989 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14990 {
14991 struct sip_peer *peer;
14992 int load_realtime = 0;
14993
14994 switch (cmd) {
14995 case CLI_INIT:
14996 e->command = "sip unregister";
14997 e->usage =
14998 "Usage: sip unregister <peer>\n"
14999 " Unregister (force expiration) a SIP peer from the registry\n";
15000 return NULL;
15001 case CLI_GENERATE:
15002 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15003 }
15004
15005 if (a->argc != 3)
15006 return CLI_SHOWUSAGE;
15007
15008 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15009 if (peer->expire > 0) {
15010 AST_SCHED_DEL_UNREF(sched, peer->expire,
15011 unref_peer(peer, "remove register expire ref"));
15012 expire_register(ref_peer(peer, "ref for expire_register"));
15013 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15014 } else {
15015 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15016 }
15017 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15018 } else {
15019 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15020 }
15021
15022 return CLI_SUCCESS;
15023 }
15024
15025
15026 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15027 {
15028 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s (%-2.2s) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
15029 #define FORMAT "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%-2.2u%%) %-6.6u %-10.10u%-1.1s %-10.10u (%-2.2u%%) %-6.6u\n"
15030 struct sip_pvt *cur = __cur;
15031 unsigned int rxcount;
15032 unsigned int txcount;
15033 char durbuf[10];
15034 int duration;
15035 int durh, durm, durs;
15036 struct ast_channel *c = cur->owner;
15037 struct __show_chan_arg *arg = __arg;
15038 int fd = arg->fd;
15039
15040
15041 if (cur->subscribed != NONE)
15042 return 0;
15043
15044 if (!cur->rtp) {
15045 if (sipdebug)
15046 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n", ast_inet_ntoa(cur->sa.sin_addr), cur->callid, invitestate2string[cur->invitestate].desc, "-- No RTP active");
15047 return 0;
15048 }
15049 rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
15050 txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
15051
15052
15053 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
15054 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
15055 durh = duration / 3600;
15056 durm = (duration % 3600) / 60;
15057 durs = duration % 60;
15058 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
15059 } else {
15060 durbuf[0] = '\0';
15061 }
15062
15063 ast_cli(fd, FORMAT,
15064 ast_inet_ntoa(cur->sa.sin_addr),
15065 cur->callid,
15066 durbuf,
15067 rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
15068 rxcount > (unsigned int) 100000 ? "K":" ",
15069 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS),
15070 rxcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) / rxcount * 100) : 0,
15071 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
15072 txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
15073 txcount > (unsigned int) 100000 ? "K":" ",
15074 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS),
15075 txcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS)/ txcount * 100) : 0,
15076 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
15077 );
15078 arg->numchans++;
15079
15080 return 0;
15081 }
15082
15083
15084 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15085 {
15086 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15087
15088 switch (cmd) {
15089 case CLI_INIT:
15090 e->command = "sip show channelstats";
15091 e->usage =
15092 "Usage: sip show channelstats\n"
15093 " Lists all currently active SIP channel's RTCP statistics.\n"
15094 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
15095 return NULL;
15096 case CLI_GENERATE:
15097 return NULL;
15098 }
15099
15100 if (a->argc != 3)
15101 return CLI_SHOWUSAGE;
15102
15103 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "%", "Jitter", "Send: Pack", "Lost", "Jitter");
15104
15105 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
15106 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
15107 return CLI_SUCCESS;
15108 }
15109 #undef FORMAT
15110 #undef FORMAT2
15111
15112
15113 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15114 {
15115 int realtimepeers;
15116 int realtimeregs;
15117 char codec_buf[SIPBUFSIZE];
15118 const char *msg;
15119
15120 switch (cmd) {
15121 case CLI_INIT:
15122 e->command = "sip show settings";
15123 e->usage =
15124 "Usage: sip show settings\n"
15125 " Provides detailed list of the configuration of the SIP channel.\n";
15126 return NULL;
15127 case CLI_GENERATE:
15128 return NULL;
15129 }
15130
15131
15132 realtimepeers = ast_check_realtime("sippeers");
15133 realtimeregs = ast_check_realtime("sipregs");
15134
15135 if (a->argc != 3)
15136 return CLI_SHOWUSAGE;
15137 ast_cli(a->fd, "\n\nGlobal Settings:\n");
15138 ast_cli(a->fd, "----------------\n");
15139 ast_cli(a->fd, " UDP SIP Port: %d\n", ntohs(bindaddr.sin_port));
15140 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
15141 ast_cli(a->fd, " TCP SIP Port: ");
15142 if (sip_tcp_desc.local_address.sin_family == AF_INET) {
15143 ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
15144 ast_cli(a->fd, " TCP Bindaddress: %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
15145 } else {
15146 ast_cli(a->fd, "Disabled\n");
15147 }
15148 ast_cli(a->fd, " TLS SIP Port: ");
15149 if (default_tls_cfg.enabled != FALSE) {
15150 ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
15151 ast_cli(a->fd, " TLS Bindaddress: %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
15152 } else {
15153 ast_cli(a->fd, "Disabled\n");
15154 }
15155 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
15156 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
15157 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(autocreatepeer));
15158 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15159 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
15160 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(global_allowguest));
15161 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15162 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15163 ast_cli(a->fd, " Allow promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
15164 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
15165 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
15166 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
15167 ast_cli(a->fd, " Our auth realm %s\n", global_realm);
15168 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(allow_external_domains));
15169 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
15170 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(global_alwaysauthreject));
15171 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(global_directrtpsetup));
15172 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
15173 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
15174 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
15175 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
15176 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(global_regextenonqualify));
15177 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
15178 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
15179 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
15180 ast_cli(a->fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
15181 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
15182
15183 ast_cli(a->fd, " T.38 support: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
15184 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
15185 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
15186
15187 if (!realtimepeers && !realtimeregs)
15188 ast_cli(a->fd, " SIP realtime: Disabled\n" );
15189 else
15190 ast_cli(a->fd, " SIP realtime: Enabled\n" );
15191 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
15192 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
15193 ast_cli(a->fd, "---------------------------\n");
15194 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
15195 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
15196 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
15197 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
15198 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
15199 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
15200 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
15201 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
15202 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
15203 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
15204 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
15205 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
15206 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
15207 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
15208
15209 ast_cli(a->fd, "\nNetwork Settings:\n");
15210 ast_cli(a->fd, "---------------------------\n");
15211
15212 if (localaddr == NULL)
15213 msg = "Disabled, no localnet list";
15214 else if (externip.sin_addr.s_addr == 0)
15215 msg = "Disabled, externip is 0.0.0.0";
15216 else if (stunaddr.sin_addr.s_addr != 0)
15217 msg = "Enabled using STUN";
15218 else if (!ast_strlen_zero(externhost))
15219 msg = "Enabled using externhost";
15220 else
15221 msg = "Enabled using externip";
15222 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
15223 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
15224 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
15225 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
15226 ast_cli(a->fd, " Internal IP: %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
15227 {
15228 struct ast_ha *d;
15229 const char *prefix = "Localnet:";
15230 char buf[INET_ADDRSTRLEN];
15231
15232 for (d = localaddr; d ; prefix = "", d = d->next) {
15233 ast_cli(a->fd, " %-24s%s/%s\n",
15234 prefix, ast_inet_ntoa(d->netaddr),
15235 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
15236 }
15237 }
15238 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
15239
15240 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
15241 ast_cli(a->fd, "---------------------------\n");
15242 ast_cli(a->fd, " Codecs: ");
15243 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
15244 ast_cli(a->fd, "%s\n", codec_buf);
15245 ast_cli(a->fd, " Codec Order: ");
15246 print_codec_to_cli(a->fd, &default_prefs);
15247 ast_cli(a->fd, "\n");
15248 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
15249 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
15250 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(compactheaders));
15251 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
15252 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
15253 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
15254 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
15255 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(global_srvlookup));
15256 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(pedanticsipchecking));
15257 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
15258 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
15259 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
15260 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
15261 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
15262 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(global_notifyringing));
15263 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(global_notifyhold));
15264 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
15265 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
15266 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
15267 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(global_outboundproxy.name) ? "<not set>" : global_outboundproxy.name,
15268 global_outboundproxy.force ? "(forced)" : "");
15269 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
15270 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
15271 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
15272 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
15273 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
15274 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
15275 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
15276 ast_cli(a->fd, " No premature media: %s\n", global_prematuremediafilter ? "Yes" : "No");
15277
15278 ast_cli(a->fd, "\nDefault Settings:\n");
15279 ast_cli(a->fd, "-----------------\n");
15280 ast_cli(a->fd, " Context: %s\n", default_context);
15281 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
15282 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
15283 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
15284 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
15285 ast_cli(a->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" );
15286 ast_cli(a->fd, " Language: %s\n", default_language);
15287 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
15288 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
15289 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
15290
15291
15292 if (realtimepeers || realtimeregs) {
15293 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
15294 ast_cli(a->fd, "----------------------\n");
15295 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
15296 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
15297 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
15298 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
15299 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
15300 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
15301 ast_cli(a->fd, " Auto Clear: %d\n", global_rtautoclear);
15302 }
15303 ast_cli(a->fd, "\n----\n");
15304 return CLI_SUCCESS;
15305 }
15306
15307
15308 static const char *subscription_type2str(enum subscriptiontype subtype)
15309 {
15310 int i;
15311
15312 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
15313 if (subscription_types[i].type == subtype) {
15314 return subscription_types[i].text;
15315 }
15316 }
15317 return subscription_types[0].text;
15318 }
15319
15320
15321 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
15322 {
15323 int i;
15324
15325 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
15326 if (subscription_types[i].type == subtype) {
15327 return &subscription_types[i];
15328 }
15329 }
15330 return &subscription_types[0];
15331 }
15332
15333
15334
15335
15336
15337
15338
15339
15340 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
15341 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
15342 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
15343 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
15344
15345
15346 static int show_channels_cb(void *__cur, void *__arg, int flags)
15347 {
15348 struct sip_pvt *cur = __cur;
15349 struct __show_chan_arg *arg = __arg;
15350 const struct sockaddr_in *dst = sip_real_dst(cur);
15351
15352
15353 if (cur->subscribed == NONE && !arg->subscriptions) {
15354
15355 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
15356 char formatbuf[SIPBUFSIZE/2];
15357
15358 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
15359 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
15360 cur->callid,
15361 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
15362 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
15363 cur->needdestroy ? "(d)" : "",
15364 cur->lastmsg ,
15365 referstatus
15366 );
15367 arg->numchans++;
15368 }
15369 if (cur->subscribed != NONE && arg->subscriptions) {
15370 struct ast_str *mailbox_str = ast_str_alloca(512);
15371 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
15372 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
15373 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
15374 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
15375 cur->callid,
15376
15377 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
15378 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
15379 subscription_type2str(cur->subscribed),
15380 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
15381 cur->expiry
15382 );
15383 arg->numchans++;
15384 }
15385 return 0;
15386 }
15387
15388
15389
15390
15391
15392
15393 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15394 {
15395 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15396
15397
15398 if (cmd == CLI_INIT) {
15399 e->command = "sip show {channels|subscriptions}";
15400 e->usage =
15401 "Usage: sip show channels\n"
15402 " Lists all currently active SIP calls (dialogs).\n"
15403 "Usage: sip show subscriptions\n"
15404 " Lists active SIP subscriptions.\n";
15405 return NULL;
15406 } else if (cmd == CLI_GENERATE)
15407 return NULL;
15408
15409 if (a->argc != e->args)
15410 return CLI_SHOWUSAGE;
15411 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
15412 if (!arg.subscriptions)
15413 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
15414 else
15415 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
15416
15417
15418 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
15419
15420
15421 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
15422 (arg.subscriptions ? "subscription" : "dialog"),
15423 ESS(arg.numchans));
15424 return CLI_SUCCESS;
15425 #undef FORMAT
15426 #undef FORMAT2
15427 #undef FORMAT3
15428 }
15429
15430
15431
15432
15433
15434
15435 static char *complete_sipch(const char *line, const char *word, int pos, int state)
15436 {
15437 int which=0;
15438 struct sip_pvt *cur;
15439 char *c = NULL;
15440 int wordlen = strlen(word);
15441 struct ao2_iterator i;
15442
15443 if (pos != 3) {
15444 return NULL;
15445 }
15446
15447 i = ao2_iterator_init(dialogs, 0);
15448 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
15449 sip_pvt_lock(cur);
15450 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
15451 c = ast_strdup(cur->callid);
15452 sip_pvt_unlock(cur);
15453 dialog_unref(cur, "drop ref in iterator loop break");
15454 break;
15455 }
15456 sip_pvt_unlock(cur);
15457 dialog_unref(cur, "drop ref in iterator loop");
15458 }
15459 ao2_iterator_destroy(&i);
15460 return c;
15461 }
15462
15463
15464
15465 static char *complete_sip_peer(const char *word, int state, int flags2)
15466 {
15467 char *result = NULL;
15468 int wordlen = strlen(word);
15469 int which = 0;
15470 struct ao2_iterator i = ao2_iterator_init(peers, 0);
15471 struct sip_peer *peer;
15472
15473 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15474
15475 if (!strncasecmp(word, peer->name, wordlen) &&
15476 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
15477 ++which > state)
15478 result = ast_strdup(peer->name);
15479 unref_peer(peer, "toss iterator peer ptr before break");
15480 if (result) {
15481 break;
15482 }
15483 }
15484 ao2_iterator_destroy(&i);
15485 return result;
15486 }
15487
15488
15489 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
15490 {
15491 char *result = NULL;
15492 int wordlen = strlen(word);
15493 int which = 0;
15494 struct ao2_iterator i;
15495 struct sip_peer *peer;
15496
15497 i = ao2_iterator_init(peers, 0);
15498 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15499 if (!strncasecmp(word, peer->name, wordlen) &&
15500 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
15501 ++which > state && peer->expire > 0)
15502 result = ast_strdup(peer->name);
15503 if (result) {
15504 unref_peer(peer, "toss iterator peer ptr before break");
15505 break;
15506 }
15507 unref_peer(peer, "toss iterator peer ptr");
15508 }
15509 ao2_iterator_destroy(&i);
15510 return result;
15511 }
15512
15513
15514 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
15515 {
15516 if (pos == 3)
15517 return complete_sipch(line, word, pos, state);
15518
15519 return NULL;
15520 }
15521
15522
15523 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
15524 {
15525 if (pos == 3) {
15526 return complete_sip_peer(word, state, 0);
15527 }
15528
15529 return NULL;
15530 }
15531
15532
15533 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
15534 {
15535 if (pos == 2)
15536 return complete_sip_registered_peer(word, state, 0);
15537
15538 return NULL;
15539 }
15540
15541
15542 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
15543 {
15544 char *c = NULL;
15545
15546 if (pos == 2) {
15547 int which = 0;
15548 char *cat = NULL;
15549 int wordlen = strlen(word);
15550
15551
15552
15553 if (!notify_types)
15554 return NULL;
15555
15556 while ( (cat = ast_category_browse(notify_types, cat)) ) {
15557 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
15558 c = ast_strdup(cat);
15559 break;
15560 }
15561 }
15562 return c;
15563 }
15564
15565 if (pos > 2)
15566 return complete_sip_peer(word, state, 0);
15567
15568 return NULL;
15569 }
15570
15571
15572 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15573 {
15574 struct sip_pvt *cur;
15575 size_t len;
15576 int found = 0;
15577 struct ao2_iterator i;
15578
15579 switch (cmd) {
15580 case CLI_INIT:
15581 e->command = "sip show channel";
15582 e->usage =
15583 "Usage: sip show channel <call-id>\n"
15584 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
15585 return NULL;
15586 case CLI_GENERATE:
15587 return complete_sipch(a->line, a->word, a->pos, a->n);
15588 }
15589
15590 if (a->argc != 4)
15591 return CLI_SHOWUSAGE;
15592 len = strlen(a->argv[3]);
15593
15594 i = ao2_iterator_init(dialogs, 0);
15595 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
15596 sip_pvt_lock(cur);
15597
15598 if (!strncasecmp(cur->callid, a->argv[3], len)) {
15599 char formatbuf[SIPBUFSIZE/2];
15600 ast_cli(a->fd, "\n");
15601 if (cur->subscribed != NONE)
15602 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
15603 else
15604 ast_cli(a->fd, " * SIP Call\n");
15605 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
15606 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
15607 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
15608 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
15609 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
15610 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
15611 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
15612 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
15613 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
15614 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
15615 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
15616 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
15617 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
15618 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
15619 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
15620 ast_cli(a->fd, " Audio IP: %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip.sin_addr), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
15621 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
15622 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
15623 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
15624 if (!ast_strlen_zero(cur->username))
15625 ast_cli(a->fd, " Username: %s\n", cur->username);
15626 if (!ast_strlen_zero(cur->peername))
15627 ast_cli(a->fd, " Peername: %s\n", cur->peername);
15628 if (!ast_strlen_zero(cur->uri))
15629 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
15630 if (!ast_strlen_zero(cur->cid_num))
15631 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
15632 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
15633 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
15634 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
15635 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
15636 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
15637 ast_cli(a->fd, " SIP Options: ");
15638 if (cur->sipoptions) {
15639 int x;
15640 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15641 if (cur->sipoptions & sip_options[x].id)
15642 ast_cli(a->fd, "%s ", sip_options[x].text);
15643 }
15644 ast_cli(a->fd, "\n");
15645 } else
15646 ast_cli(a->fd, "(none)\n");
15647
15648 if (!cur->stimer)
15649 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
15650 else {
15651 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
15652 if (cur->stimer->st_active == TRUE) {
15653 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
15654 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
15655 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
15656 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
15657 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
15658 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
15659 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
15660 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
15661 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
15662 }
15663 }
15664
15665 ast_cli(a->fd, "\n\n");
15666
15667 found++;
15668 }
15669
15670 sip_pvt_unlock(cur);
15671
15672 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
15673 }
15674 ao2_iterator_destroy(&i);
15675
15676 if (!found)
15677 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
15678
15679 return CLI_SUCCESS;
15680 }
15681
15682
15683 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15684 {
15685 struct sip_pvt *cur;
15686 size_t len;
15687 int found = 0;
15688 struct ao2_iterator i;
15689
15690 switch (cmd) {
15691 case CLI_INIT:
15692 e->command = "sip show history";
15693 e->usage =
15694 "Usage: sip show history <call-id>\n"
15695 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
15696 return NULL;
15697 case CLI_GENERATE:
15698 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
15699 }
15700
15701 if (a->argc != 4)
15702 return CLI_SHOWUSAGE;
15703
15704 if (!recordhistory)
15705 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
15706
15707 len = strlen(a->argv[3]);
15708
15709 i = ao2_iterator_init(dialogs, 0);
15710 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
15711 sip_pvt_lock(cur);
15712 if (!strncasecmp(cur->callid, a->argv[3], len)) {
15713 struct sip_history *hist;
15714 int x = 0;
15715
15716 ast_cli(a->fd, "\n");
15717 if (cur->subscribed != NONE)
15718 ast_cli(a->fd, " * Subscription\n");
15719 else
15720 ast_cli(a->fd, " * SIP Call\n");
15721 if (cur->history)
15722 AST_LIST_TRAVERSE(cur->history, hist, list)
15723 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
15724 if (x == 0)
15725 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
15726 found++;
15727 }
15728 sip_pvt_unlock(cur);
15729 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
15730 }
15731 ao2_iterator_destroy(&i);
15732
15733 if (!found)
15734 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
15735
15736 return CLI_SUCCESS;
15737 }
15738
15739
15740 static void sip_dump_history(struct sip_pvt *dialog)
15741 {
15742 int x = 0;
15743 struct sip_history *hist;
15744 static int errmsg = 0;
15745
15746 if (!dialog)
15747 return;
15748
15749 if (!option_debug && !sipdebug) {
15750 if (!errmsg) {
15751 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
15752 errmsg = 1;
15753 }
15754 return;
15755 }
15756
15757 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
15758 if (dialog->subscribed)
15759 ast_debug(1, " * Subscription\n");
15760 else
15761 ast_debug(1, " * SIP Call\n");
15762 if (dialog->history)
15763 AST_LIST_TRAVERSE(dialog->history, hist, list)
15764 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
15765 if (!x)
15766 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
15767 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
15768 }
15769
15770
15771
15772 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
15773 {
15774 char buf[1024];
15775 unsigned int event;
15776 const char *c = get_header(req, "Content-Type");
15777
15778
15779 if (!strcasecmp(c, "application/dtmf-relay") ||
15780 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
15781 unsigned int duration = 0;
15782
15783 if (!p->owner) {
15784 transmit_response(p, "481 Call leg/transaction does not exist", req);
15785 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15786 return;
15787 }
15788
15789
15790 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
15791 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
15792 transmit_response(p, "200 OK", req);
15793 return;
15794 } else {
15795 ast_copy_string(buf, c, sizeof(buf));
15796 }
15797
15798 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
15799 duration = atoi(c);
15800 if (!duration)
15801 duration = 100;
15802
15803
15804 if (ast_strlen_zero(buf)) {
15805 transmit_response(p, "200 OK", req);
15806 return;
15807 }
15808
15809 if (buf[0] == '*')
15810 event = 10;
15811 else if (buf[0] == '#')
15812 event = 11;
15813 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
15814 event = 12 + buf[0] - 'A';
15815 else if (buf[0] == '!')
15816 event = 16;
15817 else
15818 event = atoi(buf);
15819 if (event == 16) {
15820
15821 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
15822 ast_queue_frame(p->owner, &f);
15823 if (sipdebug)
15824 ast_verbose("* DTMF-relay event received: FLASH\n");
15825 } else {
15826
15827 struct ast_frame f = { AST_FRAME_DTMF, };
15828 if (event < 10) {
15829 f.subclass = '0' + event;
15830 } else if (event < 11) {
15831 f.subclass = '*';
15832 } else if (event < 12) {
15833 f.subclass = '#';
15834 } else if (event < 16) {
15835 f.subclass = 'A' + (event - 12);
15836 }
15837 f.len = duration;
15838 ast_queue_frame(p->owner, &f);
15839 if (sipdebug)
15840 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
15841 }
15842 transmit_response(p, "200 OK", req);
15843 return;
15844 } else if (!strcasecmp(c, "application/dtmf")) {
15845
15846 unsigned int duration = 0;
15847
15848 if (!p->owner) {
15849 transmit_response(p, "481 Call leg/transaction does not exist", req);
15850 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15851 return;
15852 }
15853
15854 get_msg_text(buf, sizeof(buf), req, TRUE);
15855 duration = 100;
15856
15857 if (ast_strlen_zero(buf)) {
15858 transmit_response(p, "200 OK", req);
15859 return;
15860 }
15861 event = atoi(buf);
15862 if (event == 16) {
15863
15864 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
15865 ast_queue_frame(p->owner, &f);
15866 if (sipdebug)
15867 ast_verbose("* DTMF-relay event received: FLASH\n");
15868 } else {
15869
15870 struct ast_frame f = { AST_FRAME_DTMF, };
15871 if (event < 10) {
15872 f.subclass = '0' + event;
15873 } else if (event < 11) {
15874 f.subclass = '*';
15875 } else if (event < 12) {
15876 f.subclass = '#';
15877 } else if (event < 16) {
15878 f.subclass = 'A' + (event - 12);
15879 }
15880 f.len = duration;
15881 ast_queue_frame(p->owner, &f);
15882 if (sipdebug)
15883 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
15884 }
15885 transmit_response(p, "200 OK", req);
15886 return;
15887
15888 } else if (!strcasecmp(c, "application/media_control+xml")) {
15889
15890 if (p->owner)
15891 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
15892 transmit_response(p, "200 OK", req);
15893 return;
15894 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
15895
15896 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
15897 if (p->owner && p->owner->cdr)
15898 ast_cdr_setuserfield(p->owner, c);
15899 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
15900 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
15901 transmit_response(p, "200 OK", req);
15902 } else {
15903 transmit_response(p, "403 Forbidden", req);
15904 }
15905 return;
15906 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
15907
15908
15909
15910
15911
15912
15913
15914 struct ast_call_feature *feat;
15915 int j;
15916 struct ast_frame f = { AST_FRAME_DTMF, };
15917
15918 ast_rdlock_call_features();
15919 feat = ast_find_call_feature("automon");
15920 if (!feat || ast_strlen_zero(feat->exten)) {
15921 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
15922
15923 transmit_response(p, "403 Forbidden", req);
15924 ast_unlock_call_features();
15925 return;
15926 }
15927
15928 f.len = 100;
15929 for (j=0; j < strlen(feat->exten); j++) {
15930 f.subclass = feat->exten[j];
15931 ast_queue_frame(p->owner, &f);
15932 if (sipdebug)
15933 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
15934 }
15935 ast_unlock_call_features();
15936
15937 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
15938 transmit_response(p, "200 OK", req);
15939 return;
15940 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
15941
15942 transmit_response(p, "200 OK", req);
15943 return;
15944 }
15945
15946
15947
15948
15949 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
15950 transmit_response(p, "415 Unsupported media type", req);
15951 return;
15952 }
15953
15954
15955 static char *sip_do_debug_ip(int fd, char *arg)
15956 {
15957 struct hostent *hp;
15958 struct ast_hostent ahp;
15959 int port = 0;
15960 char *p;
15961
15962 p = arg;
15963 strsep(&p, ":");
15964 if (p)
15965 port = atoi(p);
15966 hp = ast_gethostbyname(arg, &ahp);
15967 if (hp == NULL)
15968 return CLI_SHOWUSAGE;
15969
15970 debugaddr.sin_family = AF_INET;
15971 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
15972 debugaddr.sin_port = htons(port);
15973 if (port == 0)
15974 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
15975 else
15976 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
15977
15978 sipdebug |= sip_debug_console;
15979
15980 return CLI_SUCCESS;
15981 }
15982
15983
15984 static char *sip_do_debug_peer(int fd, char *arg)
15985 {
15986 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
15987 if (!peer)
15988 ast_cli(fd, "No such peer '%s'\n", arg);
15989 else if (peer->addr.sin_addr.s_addr == 0)
15990 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
15991 else {
15992 debugaddr.sin_family = AF_INET;
15993 debugaddr.sin_addr = peer->addr.sin_addr;
15994 debugaddr.sin_port = peer->addr.sin_port;
15995 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
15996 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
15997 sipdebug |= sip_debug_console;
15998 }
15999 if (peer)
16000 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16001 return CLI_SUCCESS;
16002 }
16003
16004
16005 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16006 {
16007 int oldsipdebug = sipdebug & sip_debug_console;
16008 char *what;
16009
16010 if (cmd == CLI_INIT) {
16011 e->command = "sip set debug {on|off|ip|peer}";
16012 e->usage =
16013 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
16014 " Globally disables dumping of SIP packets,\n"
16015 " or enables it either globally or for a (single)\n"
16016 " IP address or registered peer.\n";
16017 return NULL;
16018 } else if (cmd == CLI_GENERATE) {
16019 if (a->pos == 4 && strcasestr(a->line, " peer"))
16020 return complete_sip_peer(a->word, a->n, 0);
16021 return NULL;
16022 }
16023
16024 what = a->argv[e->args-1];
16025 if (a->argc == e->args) {
16026 if (!strcasecmp(what, "on")) {
16027 sipdebug |= sip_debug_console;
16028 sipdebug_text = 1;
16029 memset(&debugaddr, 0, sizeof(debugaddr));
16030 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
16031 return CLI_SUCCESS;
16032 } else if (!strcasecmp(what, "off")) {
16033 sipdebug &= ~sip_debug_console;
16034 sipdebug_text = 0;
16035 ast_cli(a->fd, "SIP Debugging Disabled\n");
16036 return CLI_SUCCESS;
16037 }
16038 } else if (a->argc == e->args +1) {
16039 if (!strcasecmp(what, "ip"))
16040 return sip_do_debug_ip(a->fd, a->argv[e->args]);
16041 else if (!strcasecmp(what, "peer"))
16042 return sip_do_debug_peer(a->fd, a->argv[e->args]);
16043 }
16044 return CLI_SHOWUSAGE;
16045 }
16046
16047
16048 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16049 {
16050 struct ast_variable *varlist;
16051 int i;
16052
16053 switch (cmd) {
16054 case CLI_INIT:
16055 e->command = "sip notify";
16056 e->usage =
16057 "Usage: sip notify <type> <peer> [<peer>...]\n"
16058 " Send a NOTIFY message to a SIP peer or peers\n"
16059 " Message types are defined in sip_notify.conf\n";
16060 return NULL;
16061 case CLI_GENERATE:
16062 return complete_sipnotify(a->line, a->word, a->pos, a->n);
16063 }
16064
16065 if (a->argc < 4)
16066 return CLI_SHOWUSAGE;
16067
16068 if (!notify_types) {
16069 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
16070 return CLI_FAILURE;
16071 }
16072
16073 varlist = ast_variable_browse(notify_types, a->argv[2]);
16074
16075 if (!varlist) {
16076 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
16077 return CLI_FAILURE;
16078 }
16079
16080 for (i = 3; i < a->argc; i++) {
16081 struct sip_pvt *p;
16082
16083 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
16084 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
16085 return CLI_FAILURE;
16086 }
16087
16088 if (create_addr(p, a->argv[i], NULL, 1)) {
16089
16090 dialog_unlink_all(p, TRUE, TRUE);
16091 dialog_unref(p, "unref dialog inside for loop" );
16092
16093 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
16094 continue;
16095 }
16096
16097
16098 ast_set_flag(&p->flags[0], SIP_OUTGOING);
16099
16100
16101 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
16102 build_via(p);
16103 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
16104 build_callid_pvt(p);
16105 ao2_t_link(dialogs, p, "Linking in new name");
16106 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
16107 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
16108 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
16109 transmit_notify_custom(p, varlist);
16110 }
16111
16112 return CLI_SUCCESS;
16113 }
16114
16115
16116 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16117 {
16118 switch (cmd) {
16119 case CLI_INIT:
16120 e->command = "sip history [off]";
16121 e->usage =
16122 "Usage: sip history [off]\n"
16123 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
16124 " Use 'sip show history' to view the history of a call number.\n";
16125 return NULL;
16126 case CLI_GENERATE:
16127 return NULL;
16128 }
16129
16130 if (a->argc < 2 || a->argc > 3) {
16131 return CLI_SHOWUSAGE;
16132 }
16133 if (a->argc == 2) {
16134 recordhistory = TRUE;
16135 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
16136 } else {
16137 if (strncasecmp(a->argv[2], "off", 3))
16138 return CLI_SHOWUSAGE;
16139 recordhistory = FALSE;
16140 ast_cli(a->fd, "SIP History Recording Disabled\n");
16141 }
16142 return CLI_SUCCESS;
16143 }
16144
16145
16146 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16147 {
16148 switch (cmd) {
16149 case CLI_INIT:
16150 e->command = "sip set history {on|off}";
16151 e->usage =
16152 "Usage: sip set history {on|off}\n"
16153 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
16154 " Use 'sip show history' to view the history of a call number.\n";
16155 return NULL;
16156 case CLI_GENERATE:
16157 return NULL;
16158 }
16159
16160 if (a->argc != e->args)
16161 return CLI_SHOWUSAGE;
16162
16163 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
16164 recordhistory = TRUE;
16165 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
16166 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
16167 recordhistory = FALSE;
16168 ast_cli(a->fd, "SIP History Recording Disabled\n");
16169 } else {
16170 return CLI_SHOWUSAGE;
16171 }
16172 return CLI_SUCCESS;
16173 }
16174
16175
16176 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
16177 {
16178 char *header, *respheader;
16179 char digest[1024];
16180
16181 p->authtries++;
16182 auth_headers(code, &header, &respheader);
16183 memset(digest, 0, sizeof(digest));
16184 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
16185
16186
16187 if (sip_debug_test_pvt(p) && p->registry)
16188 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
16189
16190 return -1;
16191 }
16192 if (p->do_history)
16193 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
16194 if (sip_debug_test_pvt(p) && p->registry)
16195 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
16196 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
16197 }
16198
16199
16200 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
16201 {
16202 char *header, *respheader;
16203 char digest[1024];
16204
16205 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
16206 return -2;
16207
16208 p->authtries++;
16209 auth_headers(code, &header, &respheader);
16210 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
16211 memset(digest, 0, sizeof(digest));
16212 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
16213
16214 return -1;
16215 }
16216
16217 p->options->auth = digest;
16218 p->options->authheader = respheader;
16219 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
16220 }
16221
16222
16223
16224
16225
16226 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
16227 {
16228 char tmp[512];
16229 char *c;
16230 char oldnonce[256];
16231
16232
16233 const struct x {
16234 const char *key;
16235 const ast_string_field *field;
16236 } *i, keys[] = {
16237 { "realm=", &p->realm },
16238 { "nonce=", &p->nonce },
16239 { "opaque=", &p->opaque },
16240 { "qop=", &p->qop },
16241 { "domain=", &p->domain },
16242 { NULL, 0 },
16243 };
16244
16245 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
16246 if (ast_strlen_zero(tmp))
16247 return -1;
16248 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
16249 ast_log(LOG_WARNING, "missing Digest.\n");
16250 return -1;
16251 }
16252 c = tmp + strlen("Digest ");
16253 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
16254 while (c && *(c = ast_skip_blanks(c))) {
16255 for (i = keys; i->key != NULL; i++) {
16256 char *src, *separator;
16257 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
16258 continue;
16259
16260 c += strlen(i->key);
16261 if (*c == '"') {
16262 src = ++c;
16263 separator = "\"";
16264 } else {
16265 src = c;
16266 separator = ",";
16267 }
16268 strsep(&c, separator);
16269 ast_string_field_ptr_set(p, i->field, src);
16270 break;
16271 }
16272 if (i->key == NULL)
16273 strsep(&c, ",");
16274 }
16275
16276 if (strcmp(p->nonce, oldnonce))
16277 p->noncecount = 0;
16278
16279
16280 if (p->registry) {
16281 struct sip_registry *r = p->registry;
16282
16283 if (strcmp(r->nonce, p->nonce)) {
16284 ast_string_field_set(r, realm, p->realm);
16285 ast_string_field_set(r, nonce, p->nonce);
16286 ast_string_field_set(r, domain, p->domain);
16287 ast_string_field_set(r, opaque, p->opaque);
16288 ast_string_field_set(r, qop, p->qop);
16289 r->noncecount = 0;
16290 }
16291 }
16292 return build_reply_digest(p, sipmethod, digest, digest_len);
16293 }
16294
16295
16296
16297
16298
16299
16300 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
16301 {
16302 char a1[256];
16303 char a2[256];
16304 char a1_hash[256];
16305 char a2_hash[256];
16306 char resp[256];
16307 char resp_hash[256];
16308 char uri[256];
16309 char opaque[256] = "";
16310 char cnonce[80];
16311 const char *username;
16312 const char *secret;
16313 const char *md5secret;
16314 struct sip_auth *auth = NULL;
16315
16316 if (!ast_strlen_zero(p->domain))
16317 ast_copy_string(uri, p->domain, sizeof(uri));
16318 else if (!ast_strlen_zero(p->uri))
16319 ast_copy_string(uri, p->uri, sizeof(uri));
16320 else
16321 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
16322
16323 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
16324
16325
16326 if(!(auth = find_realm_authentication(p->peerauth, p->realm)))
16327 auth = find_realm_authentication(authl, p->realm);
16328
16329 if (auth) {
16330 ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
16331 username = auth->username;
16332 secret = auth->secret;
16333 md5secret = auth->md5secret;
16334 if (sipdebug)
16335 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
16336 } else {
16337
16338 username = p->authname;
16339 secret = p->peersecret;
16340 md5secret = p->peermd5secret;
16341 }
16342 if (ast_strlen_zero(username))
16343 return -1;
16344
16345
16346 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
16347 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
16348 if (!ast_strlen_zero(md5secret))
16349 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
16350 else
16351 ast_md5_hash(a1_hash, a1);
16352 ast_md5_hash(a2_hash, a2);
16353
16354 p->noncecount++;
16355 if (!ast_strlen_zero(p->qop))
16356 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
16357 else
16358 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
16359 ast_md5_hash(resp_hash, resp);
16360
16361
16362 if (!ast_strlen_zero(p->opaque)) {
16363 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
16364 }
16365
16366
16367 if (!ast_strlen_zero(p->qop))
16368 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
16369 else
16370 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
16371
16372 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
16373
16374 return 0;
16375 }
16376
16377
16378 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
16379 {
16380 struct sip_pvt *p;
16381 const char *content = NULL;
16382 AST_DECLARE_APP_ARGS(args,
16383 AST_APP_ARG(header);
16384 AST_APP_ARG(number);
16385 );
16386 int i, number, start = 0;
16387
16388 if (ast_strlen_zero(data)) {
16389 ast_log(LOG_WARNING, "This function requires a header name.\n");
16390 return -1;
16391 }
16392
16393 ast_channel_lock(chan);
16394 if (!IS_SIP_TECH(chan->tech)) {
16395 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
16396 ast_channel_unlock(chan);
16397 return -1;
16398 }
16399
16400 AST_STANDARD_APP_ARGS(args, data);
16401 if (!args.number) {
16402 number = 1;
16403 } else {
16404 sscanf(args.number, "%30d", &number);
16405 if (number < 1)
16406 number = 1;
16407 }
16408
16409 p = chan->tech_pvt;
16410
16411
16412 if (!p) {
16413 ast_channel_unlock(chan);
16414 return -1;
16415 }
16416
16417 for (i = 0; i < number; i++)
16418 content = __get_header(&p->initreq, args.header, &start);
16419
16420 if (ast_strlen_zero(content)) {
16421 ast_channel_unlock(chan);
16422 return -1;
16423 }
16424
16425 ast_copy_string(buf, content, len);
16426 ast_channel_unlock(chan);
16427
16428 return 0;
16429 }
16430
16431 static struct ast_custom_function sip_header_function = {
16432 .name = "SIP_HEADER",
16433 .synopsis = "Gets the specified SIP header",
16434 .syntax = "SIP_HEADER(<name>[,<number>])",
16435 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
16436 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
16437 "that name to retrieve. Headers start at offset 1.\n",
16438 .read = func_header_read,
16439 };
16440
16441
16442 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
16443 {
16444 if (ast_strlen_zero(data)) {
16445 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
16446 return -1;
16447 }
16448 if (check_sip_domain(data, NULL, 0))
16449 ast_copy_string(buf, data, len);
16450 else
16451 buf[0] = '\0';
16452 return 0;
16453 }
16454
16455 static struct ast_custom_function checksipdomain_function = {
16456 .name = "CHECKSIPDOMAIN",
16457 .synopsis = "Checks if domain is a local domain",
16458 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
16459 .read = func_check_sipdomain,
16460 .desc = "This function checks if the domain in the argument is configured\n"
16461 "as a local SIP domain that this Asterisk server is configured to handle.\n"
16462 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
16463 "Check the domain= configuration in sip.conf\n",
16464 };
16465
16466
16467 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
16468 {
16469 struct sip_peer *peer;
16470 char *colname;
16471
16472 if ((colname = strchr(data, ':'))) {
16473 static int deprecation_warning = 0;
16474 *colname++ = '\0';
16475 if (deprecation_warning++ % 10 == 0)
16476 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
16477 } else if ((colname = strchr(data, ',')))
16478 *colname++ = '\0';
16479 else
16480 colname = "ip";
16481
16482 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
16483 return -1;
16484
16485 if (!strcasecmp(colname, "ip")) {
16486 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
16487 } else if (!strcasecmp(colname, "port")) {
16488 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
16489 } else if (!strcasecmp(colname, "status")) {
16490 peer_status(peer, buf, len);
16491 } else if (!strcasecmp(colname, "language")) {
16492 ast_copy_string(buf, peer->language, len);
16493 } else if (!strcasecmp(colname, "regexten")) {
16494 ast_copy_string(buf, peer->regexten, len);
16495 } else if (!strcasecmp(colname, "limit")) {
16496 snprintf(buf, len, "%d", peer->call_limit);
16497 } else if (!strcasecmp(colname, "busylevel")) {
16498 snprintf(buf, len, "%d", peer->busy_level);
16499 } else if (!strcasecmp(colname, "curcalls")) {
16500 snprintf(buf, len, "%d", peer->inUse);
16501 } else if (!strcasecmp(colname, "accountcode")) {
16502 ast_copy_string(buf, peer->accountcode, len);
16503 } else if (!strcasecmp(colname, "callgroup")) {
16504 ast_print_group(buf, len, peer->callgroup);
16505 } else if (!strcasecmp(colname, "pickupgroup")) {
16506 ast_print_group(buf, len, peer->pickupgroup);
16507 } else if (!strcasecmp(colname, "useragent")) {
16508 ast_copy_string(buf, peer->useragent, len);
16509 } else if (!strcasecmp(colname, "mailbox")) {
16510 struct ast_str *mailbox_str = ast_str_alloca(512);
16511 peer_mailboxes_to_str(&mailbox_str, peer);
16512 ast_copy_string(buf, mailbox_str->str, len);
16513 } else if (!strcasecmp(colname, "context")) {
16514 ast_copy_string(buf, peer->context, len);
16515 } else if (!strcasecmp(colname, "expire")) {
16516 snprintf(buf, len, "%d", peer->expire);
16517 } else if (!strcasecmp(colname, "dynamic")) {
16518 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
16519 } else if (!strcasecmp(colname, "callerid_name")) {
16520 ast_copy_string(buf, peer->cid_name, len);
16521 } else if (!strcasecmp(colname, "callerid_num")) {
16522 ast_copy_string(buf, peer->cid_num, len);
16523 } else if (!strcasecmp(colname, "codecs")) {
16524 ast_getformatname_multiple(buf, len -1, peer->capability);
16525 } else if (!strncasecmp(colname, "chanvar[", 8)) {
16526 char *chanvar=colname + 8;
16527 struct ast_variable *v;
16528
16529 chanvar = strsep(&chanvar, "]");
16530 for (v = peer->chanvars ; v ; v = v->next)
16531 if (!strcasecmp(v->name, chanvar))
16532 ast_copy_string(buf, v->value, len);
16533 } else if (!strncasecmp(colname, "codec[", 6)) {
16534 char *codecnum;
16535 int codec = 0;
16536
16537 codecnum = colname + 6;
16538 codecnum = strsep(&codecnum, "]");
16539 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
16540 ast_copy_string(buf, ast_getformatname(codec), len);
16541 } else {
16542 buf[0] = '\0';
16543 }
16544 } else {
16545 buf[0] = '\0';
16546 }
16547
16548 unref_peer(peer, "unref_peer from function_sippeer, just before return");
16549
16550 return 0;
16551 }
16552
16553
16554 struct ast_custom_function sippeer_function = {
16555 .name = "SIPPEER",
16556 .synopsis = "Gets SIP peer information",
16557 .syntax = "SIPPEER(<peername>[,item])",
16558 .read = function_sippeer,
16559 .desc = "Valid items are:\n"
16560 "- ip (default) The IP address.\n"
16561 "- port The port number\n"
16562 "- mailbox The configured mailbox.\n"
16563 "- context The configured context.\n"
16564 "- expire The epoch time of the next expire.\n"
16565 "- dynamic Is it dynamic? (yes/no).\n"
16566 "- callerid_name The configured Caller ID name.\n"
16567 "- callerid_num The configured Caller ID number.\n"
16568 "- callgroup The configured Callgroup.\n"
16569 "- pickupgroup The configured Pickupgroup.\n"
16570 "- codecs The configured codecs.\n"
16571 "- status Status (if qualify=yes).\n"
16572 "- regexten Registration extension\n"
16573 "- limit Call limit (call-limit)\n"
16574 "- busylevel Configured call level for signalling busy\n"
16575 "- curcalls Current amount of calls \n"
16576 " Only available if call-limit is set\n"
16577 "- language Default language for peer\n"
16578 "- accountcode Account code for this peer\n"
16579 "- useragent Current user agent id for peer\n"
16580 "- chanvar[name] A channel variable configured with setvar for this peer.\n"
16581 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
16582 "\n"
16583 };
16584
16585
16586 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
16587 {
16588 struct sip_pvt *p;
16589 static int deprecated = 0;
16590
16591 *buf = 0;
16592
16593 if (!data) {
16594 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
16595 return -1;
16596 }
16597
16598 ast_channel_lock(chan);
16599 if (!IS_SIP_TECH(chan->tech)) {
16600 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
16601 ast_channel_unlock(chan);
16602 return -1;
16603 }
16604
16605 if (deprecated++ % 20 == 0) {
16606
16607 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
16608 }
16609
16610 p = chan->tech_pvt;
16611
16612
16613 if (!p) {
16614 ast_channel_unlock(chan);
16615 return -1;
16616 }
16617
16618 if (!strcasecmp(data, "peerip")) {
16619 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
16620 } else if (!strcasecmp(data, "recvip")) {
16621 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
16622 } else if (!strcasecmp(data, "from")) {
16623 ast_copy_string(buf, p->from, len);
16624 } else if (!strcasecmp(data, "uri")) {
16625 ast_copy_string(buf, p->uri, len);
16626 } else if (!strcasecmp(data, "useragent")) {
16627 ast_copy_string(buf, p->useragent, len);
16628 } else if (!strcasecmp(data, "peername")) {
16629 ast_copy_string(buf, p->peername, len);
16630 } else if (!strcasecmp(data, "t38passthrough")) {
16631 if (p->t38.state == T38_DISABLED)
16632 ast_copy_string(buf, "0", sizeof("0"));
16633 else
16634 ast_copy_string(buf, "1", sizeof("1"));
16635 } else {
16636 ast_channel_unlock(chan);
16637 return -1;
16638 }
16639 ast_channel_unlock(chan);
16640
16641 return 0;
16642 }
16643
16644
16645 static struct ast_custom_function sipchaninfo_function = {
16646 .name = "SIPCHANINFO",
16647 .synopsis = "Gets the specified SIP parameter from the current channel",
16648 .syntax = "SIPCHANINFO(item)",
16649 .read = function_sipchaninfo_read,
16650 .desc = "Valid items are:\n"
16651 "- peerip The IP address of the peer.\n"
16652 "- recvip The source IP address of the peer.\n"
16653 "- from The URI from the From: header.\n"
16654 "- uri The URI from the Contact: header.\n"
16655 "- useragent The useragent.\n"
16656 "- peername The name of the peer.\n"
16657 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
16658 };
16659
16660
16661 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
16662 {
16663 char tmp[SIPBUFSIZE];
16664 char *s, *e, *t, *trans;
16665 char *domain;
16666 enum sip_transport transport = SIP_TRANSPORT_UDP;
16667
16668 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
16669 if ((t = strchr(tmp, ',')))
16670 *t = '\0';
16671
16672 s = get_in_brackets(tmp);
16673 if ((trans = strcasestr(s, ";transport="))) do {
16674 trans += 11;
16675
16676 if ((e = strchr(trans, ';')))
16677 *e = '\0';
16678
16679 if (!strncasecmp(trans, "tcp", 3))
16680 transport = SIP_TRANSPORT_TCP;
16681 else if (!strncasecmp(trans, "tls", 3))
16682 transport = SIP_TRANSPORT_TLS;
16683 else {
16684 if (strncasecmp(trans, "udp", 3))
16685 ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
16686 transport = SIP_TRANSPORT_UDP;
16687 }
16688 } while(0);
16689 s = remove_uri_parameters(s);
16690
16691 if (p->socket.tcptls_session) {
16692 ao2_ref(p->socket.tcptls_session, -1);
16693 p->socket.tcptls_session = NULL;
16694 }
16695
16696 set_socket_transport(&p->socket, transport);
16697
16698 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
16699 char *host = NULL;
16700 if (!strncasecmp(s, "sip:", 4))
16701 s += 4;
16702 else if (!strncasecmp(s, "sips:", 5))
16703 s += 5;
16704 e = strchr(s, '/');
16705 if (e)
16706 *e = '\0';
16707 if ((host = strchr(s, '@'))) {
16708 *host++ = '\0';
16709 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
16710 if (p->owner)
16711 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
16712 } else {
16713 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
16714 if (p->owner)
16715 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
16716 }
16717 } else {
16718 e = strchr(tmp, '@');
16719 if (e) {
16720 *e++ = '\0';
16721 domain = e;
16722 } else {
16723
16724 domain = tmp;
16725 }
16726 e = strchr(tmp, '/');
16727 if (e)
16728 *e = '\0';
16729
16730 if (!strncasecmp(s, "sip:", 4))
16731 s += 4;
16732 else if (!strncasecmp(s, "sips:", 5))
16733 s += 5;
16734 e = strchr(s, ';');
16735 if (e)
16736 *e = '\0';
16737 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
16738 if (p->owner) {
16739 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
16740 ast_string_field_set(p->owner, call_forward, s);
16741 }
16742 }
16743 }
16744
16745
16746 static void check_pendings(struct sip_pvt *p)
16747 {
16748 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16749
16750 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
16751 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
16752
16753
16754 else {
16755
16756
16757 if (p->pendinginvite)
16758 return;
16759
16760
16761 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
16762 }
16763 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
16764 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16765 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
16766
16767 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
16768 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
16769 } else {
16770 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
16771
16772 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
16773 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
16774 }
16775 }
16776 }
16777
16778
16779
16780
16781
16782 static int sip_reinvite_retry(const void *data)
16783 {
16784 struct sip_pvt *p = (struct sip_pvt *) data;
16785
16786 sip_pvt_lock(p);
16787 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16788 p->waitid = -1;
16789 check_pendings(p);
16790 sip_pvt_unlock(p);
16791 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
16792 return 0;
16793 }
16794
16795
16796
16797 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16798 {
16799 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
16800 int res = 0;
16801 int xmitres = 0;
16802 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
16803 char *p_hdrval;
16804 int rtn;
16805
16806 if (reinvite)
16807 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
16808 else
16809 ast_debug(4, "SIP response %d to standard invite\n", resp);
16810
16811 if (p->alreadygone) {
16812 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
16813 return;
16814 }
16815
16816
16817
16818 AST_SCHED_DEL_UNREF(sched, p->initid, dialog_unref(p, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
16819
16820
16821
16822
16823 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
16824 resp = 183;
16825
16826
16827 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
16828 p->invitestate = INV_PROCEEDING;
16829
16830
16831 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
16832 p->invitestate = INV_COMPLETED;
16833
16834
16835 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
16836 p->pendinginvite = 0;
16837
16838 switch (resp) {
16839 case 100:
16840 case 101:
16841 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
16842 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16843 check_pendings(p);
16844 break;
16845
16846 case 180:
16847 case 182:
16848 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
16849 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16850 if (!req->ignore && p->owner) {
16851 ast_queue_control(p->owner, AST_CONTROL_RINGING);
16852 if (p->owner->_state != AST_STATE_UP) {
16853 ast_setstate(p->owner, AST_STATE_RINGING);
16854 }
16855 }
16856 if (find_sdp(req)) {
16857 if (p->invitestate != INV_CANCELLED)
16858 p->invitestate = INV_EARLY_MEDIA;
16859 res = process_sdp(p, req, SDP_T38_NONE);
16860 if (!req->ignore && p->owner) {
16861
16862 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16863 }
16864 }
16865 check_pendings(p);
16866 break;
16867
16868 case 183:
16869 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
16870 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16871 if (find_sdp(req)) {
16872 if (p->invitestate != INV_CANCELLED)
16873 p->invitestate = INV_EARLY_MEDIA;
16874 res = process_sdp(p, req, SDP_T38_NONE);
16875 if (!req->ignore && p->owner) {
16876
16877 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16878 }
16879 } else {
16880
16881
16882
16883
16884 if (!req->ignore && p->owner) {
16885 ast_queue_control(p->owner, AST_CONTROL_RINGING);
16886 }
16887 }
16888 check_pendings(p);
16889 break;
16890
16891 case 200:
16892 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
16893 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16894 p->authtries = 0;
16895 if (find_sdp(req)) {
16896 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
16897 if (!reinvite)
16898
16899
16900 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
16901 }
16902
16903
16904
16905
16906 if (outgoing) {
16907 update_call_counter(p, DEC_CALL_RINGING);
16908 parse_ok_contact(p, req);
16909
16910 if (!reinvite)
16911 build_route(p, req, 1);
16912
16913 if(set_address_from_contact(p)) {
16914
16915
16916 if (!p->route && !req->ignore)
16917 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
16918 }
16919
16920 }
16921
16922 if (!req->ignore && p->owner) {
16923 if (!reinvite) {
16924 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
16925 if (global_callevents)
16926 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
16927 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
16928 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
16929 } else {
16930 ast_queue_frame(p->owner, &ast_null_frame);
16931 }
16932 } else {
16933
16934
16935
16936 if (!req->ignore)
16937 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
16938 }
16939
16940
16941 if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
16942 p_hdrval = (char*)get_header(req, "Session-Expires");
16943 if (!ast_strlen_zero(p_hdrval)) {
16944
16945 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
16946 int tmp_st_interval = 0;
16947 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
16948 if (rtn != 0) {
16949 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
16950 }
16951 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
16952 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
16953 p->stimer->st_ref = tmp_st_ref;
16954 }
16955 if (tmp_st_interval) {
16956 p->stimer->st_interval = tmp_st_interval;
16957 }
16958 p->stimer->st_active = TRUE;
16959 p->stimer->st_active_peer_ua = TRUE;
16960 start_session_timer(p);
16961 } else {
16962
16963 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
16964 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
16965 p->stimer->st_active_peer_ua = FALSE;
16966 start_session_timer(p);
16967 }
16968 }
16969 }
16970
16971
16972
16973 p->invitestate = INV_TERMINATED;
16974 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
16975 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
16976 check_pendings(p);
16977 break;
16978
16979 case 407:
16980 case 401:
16981
16982 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16983 if (p->options)
16984 p->options->auth_type = resp;
16985
16986
16987 ast_string_field_set(p, theirtag, NULL);
16988 if (!req->ignore) {
16989 if (p->authtries < MAX_AUTHTRIES)
16990 p->invitestate = INV_CALLING;
16991 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
16992 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
16993 p->needdestroy = 1;
16994 sip_alreadygone(p);
16995 if (p->owner)
16996 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16997 }
16998 }
16999 break;
17000
17001 case 403:
17002
17003 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17004 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17005 if (!req->ignore && p->owner)
17006 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17007 p->needdestroy = 1;
17008 sip_alreadygone(p);
17009 break;
17010
17011 case 404:
17012 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17013 if (p->owner && !req->ignore)
17014 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17015 sip_alreadygone(p);
17016 break;
17017
17018 case 408:
17019 case 481:
17020
17021 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17022 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17023 if (p->owner)
17024 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17025 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17026 break;
17027
17028 case 422:
17029 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17030 ast_string_field_set(p, theirtag, NULL);
17031 proc_422_rsp(p, req);
17032 break;
17033
17034 case 487:
17035
17036
17037
17038 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17039 if (p->owner && !req->ignore) {
17040 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17041 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17042 } else if (!req->ignore) {
17043 update_call_counter(p, DEC_CALL_LIMIT);
17044 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17045 p->needdestroy = 1;
17046 sip_alreadygone(p);
17047 }
17048 break;
17049 case 415:
17050 case 488:
17051 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17052 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17053 change_t38_state(p, T38_DISABLED);
17054
17055 ast_rtp_set_rtptimers_onhold(p->rtp);
17056
17057
17058 transmit_reinvite_with_sdp(p, FALSE, FALSE);
17059 } else {
17060
17061 if (p->owner && !req->ignore)
17062 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17063 p->needdestroy = 1;
17064
17065 if (!reinvite)
17066 sip_alreadygone(p);
17067 }
17068 break;
17069 case 491:
17070 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17071 if (p->owner && !req->ignore) {
17072 if (p->owner->_state != AST_STATE_UP) {
17073 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17074 p->needdestroy = 1;
17075 } else {
17076
17077
17078
17079 int wait;
17080
17081
17082 if (p->outgoing_call) {
17083 wait = 2100 + ast_random() % 2000;
17084 } else {
17085 wait = ast_random() % 2000;
17086 }
17087 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, dialog_ref(p, "passing dialog ptr into sched structure based on waitid for sip_reinvite_retry."));
17088 ast_log(LOG_WARNING, "just did sched_add waitid(%d) for sip_reinvite_retry for dialog %s in handle_response_invite\n", p->waitid, p->callid);
17089 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
17090 }
17091 }
17092 break;
17093
17094 case 501:
17095 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17096 if (p->owner)
17097 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17098 break;
17099 }
17100 if (xmitres == XMIT_ERROR)
17101 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
17102 }
17103
17104
17105
17106
17107 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17108 {
17109 switch (resp) {
17110 case 200:
17111
17112 if (p->owner) {
17113 if (!p->refer) {
17114 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
17115 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
17116 } else {
17117 ast_debug(4, "Got OK on REFER Notify message\n");
17118 }
17119 } else {
17120 if (p->subscribed == NONE) {
17121 ast_debug(4, "Got 200 accepted on NOTIFY\n");
17122 p->needdestroy = 1;
17123 }
17124 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17125
17126 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17127 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17128 }
17129 }
17130 break;
17131 case 401:
17132 case 407:
17133 if (!p->notify_headers) {
17134 break;
17135 }
17136 ast_string_field_set(p, theirtag, NULL);
17137 if (ast_strlen_zero(p->authname)) {
17138 ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s:%d but we have no matching peer or realm auth!\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
17139 p->needdestroy = 1;
17140 }
17141 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
17142 ast_log(LOG_NOTICE, "Failed to authenticate on NOTYFY to '%s'\n", get_header(&p->initreq, "From"));
17143 p->needdestroy = 1;
17144 }
17145 break;
17146 }
17147 }
17148
17149
17150
17151
17152 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17153 {
17154
17155 if (!p->refer)
17156 return;
17157
17158 switch (resp) {
17159 case 202:
17160
17161
17162 p->refer->status = REFER_ACCEPTED;
17163
17164 ast_debug(3, "Got 202 accepted on transfer\n");
17165
17166 break;
17167
17168 case 401:
17169 case 407:
17170 if (ast_strlen_zero(p->authname)) {
17171 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
17172 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
17173 p->needdestroy = 1;
17174 }
17175 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
17176 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
17177 p->refer->status = REFER_NOAUTH;
17178 p->needdestroy = 1;
17179 }
17180 break;
17181 case 481:
17182
17183
17184
17185
17186 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
17187 if (p->owner)
17188 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17189 p->needdestroy = 1;
17190 break;
17191
17192 case 500:
17193 case 501:
17194
17195
17196 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
17197 p->needdestroy = 1;
17198 p->refer->status = REFER_FAILED;
17199 break;
17200 case 603:
17201 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
17202 p->refer->status = REFER_FAILED;
17203 p->needdestroy = 1;
17204 break;
17205 }
17206 }
17207
17208
17209 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17210 {
17211 int expires, expires_ms;
17212 struct sip_registry *r;
17213 r=p->registry;
17214
17215 switch (resp) {
17216 case 401:
17217 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
17218 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
17219 p->needdestroy = 1;
17220 }
17221 break;
17222 case 403:
17223 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
17224 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
17225 r->regstate = REG_STATE_NOAUTH;
17226 p->needdestroy = 1;
17227 break;
17228 case 404:
17229 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
17230 p->needdestroy = 1;
17231 if (r->call)
17232 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
17233 r->regstate = REG_STATE_REJECTED;
17234 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
17235 break;
17236 case 407:
17237 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
17238 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
17239 p->needdestroy = 1;
17240 }
17241 break;
17242 case 408:
17243
17244 if (r) {
17245 r->regattempts = 0;
17246 } else {
17247 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
17248 }
17249 break;
17250 case 423:
17251 r->expiry = atoi(get_header(req, "Min-Expires"));
17252 ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
17253 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
17254 if (r->call) {
17255 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
17256 p->needdestroy = 1;
17257 }
17258 if (r->expiry > max_expiry) {
17259 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
17260 r->expiry = r->configured_expiry;
17261 r->regstate = REG_STATE_REJECTED;
17262 } else {
17263 r->regstate = REG_STATE_UNREGISTERED;
17264 transmit_register(r, SIP_REGISTER, NULL, NULL);
17265 }
17266 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
17267 break;
17268 case 479:
17269 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
17270 p->needdestroy = 1;
17271 if (r->call)
17272 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
17273 r->regstate = REG_STATE_REJECTED;
17274 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
17275 break;
17276 case 200:
17277 if (!r) {
17278 ast_log(LOG_WARNING, "Got 200 OK on REGISTER, but there isn't a registry entry for '%s' (we probably already got the OK)\n", S_OR(p->peername, p->username));
17279 p->needdestroy = 1;
17280 return 0;
17281 }
17282
17283 r->regstate = REG_STATE_REGISTERED;
17284 r->regtime = ast_tvnow();
17285 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
17286 r->regattempts = 0;
17287 ast_debug(1, "Registration successful\n");
17288 if (r->timeout > -1) {
17289 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
17290 }
17291 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
17292 if (r->call)
17293 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
17294 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
17295
17296 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17297
17298
17299
17300
17301
17302
17303 expires = 0;
17304
17305
17306 if (!ast_strlen_zero(get_header(req, "Contact"))) {
17307 const char *contact = NULL;
17308 const char *tmptmp = NULL;
17309 int start = 0;
17310 for(;;) {
17311 contact = __get_header(req, "Contact", &start);
17312
17313 if(!ast_strlen_zero(contact)) {
17314 if( (tmptmp=strstr(contact, p->our_contact))) {
17315 contact=tmptmp;
17316 break;
17317 }
17318 } else
17319 break;
17320 }
17321 tmptmp = strcasestr(contact, "expires=");
17322 if (tmptmp) {
17323 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
17324 expires = 0;
17325 }
17326
17327 }
17328 if (!expires)
17329 expires=atoi(get_header(req, "expires"));
17330 if (!expires)
17331 expires=default_expiry;
17332
17333 expires_ms = expires * 1000;
17334 if (expires <= EXPIRY_GUARD_LIMIT)
17335 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
17336 else
17337 expires_ms -= EXPIRY_GUARD_SECS * 1000;
17338 if (sipdebug)
17339 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
17340
17341 r->refresh= (int) expires_ms / 1000;
17342
17343
17344 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
17345 registry_unref(_data,"unref in REPLACE del fail"),
17346 registry_unref(r,"unref in REPLACE add fail"),
17347 registry_addref(r,"The Addition side of REPLACE"));
17348 }
17349 return 1;
17350 }
17351
17352
17353 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
17354 {
17355 struct sip_peer *peer = p->relatedpeer ;
17356 int statechanged, is_reachable, was_reachable;
17357 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
17358
17359
17360
17361
17362
17363
17364 if (pingtime < 1)
17365 pingtime = 1;
17366
17367
17368
17369
17370
17371 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
17372 is_reachable = pingtime <= peer->maxms;
17373 statechanged = peer->lastms == 0
17374 || was_reachable != is_reachable;
17375
17376 peer->lastms = pingtime;
17377 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
17378 if (statechanged) {
17379 const char *s = is_reachable ? "Reachable" : "Lagged";
17380 char str_lastms[20];
17381 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
17382
17383 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
17384 peer->name, s, pingtime, peer->maxms);
17385 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
17386 if (sip_cfg.peer_rtupdate) {
17387 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
17388 }
17389 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17390 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
17391 peer->name, s, pingtime);
17392 if (is_reachable && global_regextenonqualify)
17393 register_peer_exten(peer, TRUE);
17394 }
17395
17396 p->needdestroy = 1;
17397
17398
17399 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
17400 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
17401 sip_poke_peer_s, peer,
17402 unref_peer(_data, "removing poke peer ref"),
17403 unref_peer(peer, "removing poke peer ref"),
17404 ref_peer(peer, "adding poke peer ref"));
17405 }
17406
17407
17408 static void stop_media_flows(struct sip_pvt *p)
17409 {
17410
17411 if (p->rtp)
17412 ast_rtp_stop(p->rtp);
17413 if (p->vrtp)
17414 ast_rtp_stop(p->vrtp);
17415 if (p->trtp)
17416 ast_rtp_stop(p->trtp);
17417 if (p->udptl)
17418 ast_udptl_stop(p->udptl);
17419 }
17420
17421
17422
17423 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17424 {
17425 struct ast_channel *owner;
17426 int sipmethod;
17427 int res = 1;
17428 const char *c = get_header(req, "Cseq");
17429
17430 char *c_copy = ast_strdupa(c);
17431
17432 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
17433
17434 if (!msg)
17435 msg = "";
17436
17437 sipmethod = find_sip_method(msg);
17438
17439 owner = p->owner;
17440 if (owner)
17441 owner->hangupcause = hangup_sip2cause(resp);
17442
17443 if (p->socket.type == SIP_TRANSPORT_UDP) {
17444 int ack_res;
17445
17446
17447 if ((resp >= 100) && (resp <= 199)) {
17448 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
17449 } else {
17450 ack_res = __sip_ack(p, seqno, 0, sipmethod);
17451 }
17452
17453 if (ack_res == FALSE) {
17454 append_history(p, "Ignore", "Ignoring this retransmit\n");
17455 return;
17456 }
17457 }
17458
17459
17460 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
17461 p->pendinginvite = 0;
17462
17463
17464 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
17465 char tag[128];
17466
17467 gettag(req, "To", tag, sizeof(tag));
17468 ast_string_field_set(p, theirtag, tag);
17469 }
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
17486 p->needdestroy = 1;
17487 return;
17488 }
17489
17490 if (p->relatedpeer && p->method == SIP_OPTIONS) {
17491
17492
17493
17494 if (resp != 100)
17495 handle_response_peerpoke(p, resp, req);
17496 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
17497 switch(resp) {
17498 case 100:
17499 case 101:
17500 if (sipmethod == SIP_INVITE)
17501 handle_response_invite(p, resp, rest, req, seqno);
17502 break;
17503 case 183:
17504 if (sipmethod == SIP_INVITE)
17505 handle_response_invite(p, resp, rest, req, seqno);
17506 break;
17507 case 180:
17508 if (sipmethod == SIP_INVITE)
17509 handle_response_invite(p, resp, rest, req, seqno);
17510 break;
17511 case 182:
17512 if (sipmethod == SIP_INVITE)
17513 handle_response_invite(p, resp, rest, req, seqno);
17514 break;
17515 case 200:
17516 p->authtries = 0;
17517 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
17518
17519
17520
17521 } else if (sipmethod == SIP_INVITE) {
17522 handle_response_invite(p, resp, rest, req, seqno);
17523 } else if (sipmethod == SIP_NOTIFY) {
17524 handle_response_notify(p, resp, rest, req, seqno);
17525 } else if (sipmethod == SIP_REGISTER)
17526 res = handle_response_register(p, resp, rest, req, seqno);
17527 else if (sipmethod == SIP_BYE) {
17528 p->needdestroy = 1;
17529 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17530 } else if (sipmethod == SIP_SUBSCRIBE) {
17531 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17532 }
17533 break;
17534 case 202:
17535 if (sipmethod == SIP_REFER)
17536 handle_response_refer(p, resp, rest, req, seqno);
17537 break;
17538 case 401:
17539 case 407:
17540 if (sipmethod == SIP_INVITE)
17541 handle_response_invite(p, resp, rest, req, seqno);
17542 else if (sipmethod == SIP_NOTIFY)
17543 handle_response_notify(p, resp, rest, req, seqno);
17544 else if (sipmethod == SIP_REFER)
17545 handle_response_refer(p, resp, rest, req, seqno);
17546 else if (p->registry && sipmethod == SIP_REGISTER)
17547 res = handle_response_register(p, resp, rest, req, seqno);
17548 else if (sipmethod == SIP_BYE) {
17549 if (p->options)
17550 p->options->auth_type = resp;
17551 if (ast_strlen_zero(p->authname)) {
17552 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
17553 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
17554 p->needdestroy = 1;
17555 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
17556 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
17557 p->needdestroy = 1;
17558 }
17559 } else {
17560 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
17561 p->needdestroy = 1;
17562 }
17563 break;
17564 case 403:
17565 if (sipmethod == SIP_INVITE)
17566 handle_response_invite(p, resp, rest, req, seqno);
17567 else if (p->registry && sipmethod == SIP_REGISTER)
17568 res = handle_response_register(p, resp, rest, req, seqno);
17569 else {
17570 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
17571 p->needdestroy = 1;
17572 }
17573 break;
17574 case 404:
17575 if (p->registry && sipmethod == SIP_REGISTER)
17576 res = handle_response_register(p, resp, rest, req, seqno);
17577 else if (sipmethod == SIP_INVITE)
17578 handle_response_invite(p, resp, rest, req, seqno);
17579 else if (owner)
17580 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17581 break;
17582 case 423:
17583 if (sipmethod == SIP_REGISTER)
17584 res = handle_response_register(p, resp, rest, req, seqno);
17585 break;
17586 case 408:
17587 if (sipmethod == SIP_INVITE)
17588 handle_response_invite(p, resp, rest, req, seqno);
17589 else if (sipmethod == SIP_REGISTER)
17590 res = handle_response_register(p, resp, rest, req, seqno);
17591 else if (sipmethod == SIP_BYE) {
17592 p->needdestroy = 1;
17593 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
17594 } else {
17595 if (owner)
17596 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17597 p->needdestroy = 1;
17598 }
17599 break;
17600
17601 case 422:
17602 if (sipmethod == SIP_INVITE) {
17603 handle_response_invite(p, resp, rest, req, seqno);
17604 }
17605 break;
17606
17607 case 481:
17608 if (sipmethod == SIP_INVITE) {
17609 handle_response_invite(p, resp, rest, req, seqno);
17610 } else if (sipmethod == SIP_REFER) {
17611 handle_response_refer(p, resp, rest, req, seqno);
17612 } else if (sipmethod == SIP_BYE) {
17613
17614
17615 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17616 } else if (sipmethod == SIP_CANCEL) {
17617
17618
17619 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17620 } else {
17621 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17622
17623 }
17624 break;
17625 case 487:
17626 if (sipmethod == SIP_INVITE)
17627 handle_response_invite(p, resp, rest, req, seqno);
17628 break;
17629 case 415:
17630 case 488:
17631 if (sipmethod == SIP_INVITE)
17632 handle_response_invite(p, resp, rest, req, seqno);
17633 break;
17634 case 491:
17635 if (sipmethod == SIP_INVITE)
17636 handle_response_invite(p, resp, rest, req, seqno);
17637 else {
17638 ast_debug(1, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
17639 p->needdestroy = 1;
17640 }
17641 break;
17642 case 501:
17643 if (sipmethod == SIP_INVITE)
17644 handle_response_invite(p, resp, rest, req, seqno);
17645 else if (sipmethod == SIP_REFER)
17646 handle_response_refer(p, resp, rest, req, seqno);
17647 else
17648 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
17649 break;
17650 case 603:
17651 if (sipmethod == SIP_REFER) {
17652 handle_response_refer(p, resp, rest, req, seqno);
17653 break;
17654 }
17655
17656 default:
17657 if ((resp >= 300) && (resp < 700)) {
17658
17659 if ((resp != 487))
17660 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
17661
17662 if (sipmethod == SIP_INVITE)
17663 stop_media_flows(p);
17664
17665
17666 switch(resp) {
17667 case 300:
17668 case 301:
17669 case 302:
17670 case 305:
17671 parse_moved_contact(p, req);
17672
17673 case 486:
17674 case 600:
17675 case 603:
17676 if (p->owner)
17677 ast_queue_control(p->owner, AST_CONTROL_BUSY);
17678 break;
17679 case 482:
17680
17681
17682
17683
17684 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
17685 if (p->owner)
17686 ast_string_field_build(p->owner, call_forward,
17687 "Local/%s@%s", p->username, p->context);
17688
17689 case 480:
17690 case 404:
17691 case 410:
17692 case 400:
17693 case 500:
17694 if (sipmethod == SIP_REFER) {
17695 handle_response_refer(p, resp, rest, req, seqno);
17696 break;
17697 }
17698
17699 case 502:
17700 case 503:
17701 case 504:
17702 if (owner)
17703 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17704 break;
17705 default:
17706
17707 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
17708 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
17709 break;
17710 }
17711
17712 if (sipmethod == SIP_INVITE)
17713 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17714 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
17715 sip_alreadygone(p);
17716 if (!p->owner)
17717 p->needdestroy = 1;
17718 } else if ((resp >= 100) && (resp < 200)) {
17719 if (sipmethod == SIP_INVITE) {
17720 if (!req->ignore && sip_cancel_destroy(p))
17721 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17722 if (find_sdp(req))
17723 process_sdp(p, req, SDP_T38_NONE);
17724 if (p->owner) {
17725
17726 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17727 }
17728 }
17729 } else
17730 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));
17731 }
17732 } else {
17733
17734
17735 if (req->debug)
17736 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
17737
17738 if (sipmethod == SIP_INVITE && resp == 200) {
17739
17740
17741 char tag[128];
17742
17743 gettag(req, "To", tag, sizeof(tag));
17744 ast_string_field_set(p, theirtag, tag);
17745 }
17746
17747 switch(resp) {
17748 case 200:
17749 if (sipmethod == SIP_INVITE) {
17750 handle_response_invite(p, resp, rest, req, seqno);
17751 } else if (sipmethod == SIP_CANCEL) {
17752 ast_debug(1, "Got 200 OK on CANCEL\n");
17753
17754
17755 } else if (sipmethod == SIP_NOTIFY) {
17756
17757 if (p->owner) {
17758 if (p->refer) {
17759 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
17760 } else
17761 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
17762
17763 } else {
17764 if (!p->subscribed && !p->refer)
17765 p->needdestroy = 1;
17766 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17767
17768 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17769 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17770 }
17771 }
17772 } else if (sipmethod == SIP_BYE)
17773 p->needdestroy = 1;
17774 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
17775
17776
17777 ;
17778 else if (sipmethod == SIP_BYE)
17779
17780 p->needdestroy = 1;
17781 break;
17782 case 202:
17783 if (sipmethod == SIP_REFER)
17784 handle_response_refer(p, resp, rest, req, seqno);
17785 break;
17786 case 401:
17787 case 407:
17788 if (sipmethod == SIP_REFER)
17789 handle_response_refer(p, resp, rest, req, seqno);
17790 else if (sipmethod == SIP_INVITE)
17791 handle_response_invite(p, resp, rest, req, seqno);
17792 else if (sipmethod == SIP_BYE) {
17793 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
17794 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
17795 p->needdestroy = 1;
17796 }
17797 }
17798 break;
17799 case 481:
17800 if (sipmethod == SIP_INVITE) {
17801
17802 handle_response_invite(p, resp, rest, req, seqno);
17803 } else if (sipmethod == SIP_BYE) {
17804 p->needdestroy = 1;
17805 } else if (sipdebug) {
17806 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
17807 }
17808 break;
17809 case 501:
17810 if (sipmethod == SIP_INVITE)
17811 handle_response_invite(p, resp, rest, req, seqno);
17812 else if (sipmethod == SIP_REFER)
17813 handle_response_refer(p, resp, rest, req, seqno);
17814 break;
17815 case 603:
17816 if (sipmethod == SIP_REFER) {
17817 handle_response_refer(p, resp, rest, req, seqno);
17818 break;
17819 }
17820
17821 default:
17822 if ((resp >= 100) && (resp < 200)) {
17823 if (sipmethod == SIP_INVITE) {
17824 if (!req->ignore && sip_cancel_destroy(p))
17825 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17826 }
17827 }
17828 if ((resp >= 300) && (resp < 700)) {
17829 if ((resp != 487))
17830 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
17831 switch(resp) {
17832 case 415:
17833 case 488:
17834 case 603:
17835 case 500:
17836 case 502:
17837 case 503:
17838 case 504:
17839
17840
17841 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
17842 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17843 break;
17844 }
17845 }
17846 break;
17847 }
17848 }
17849 }
17850
17851
17852
17853
17854
17855
17856
17857 static void *sip_park_thread(void *stuff)
17858 {
17859 struct ast_channel *transferee, *transferer;
17860 struct sip_dual *d;
17861 struct sip_request req = {0,};
17862 int ext;
17863 int res;
17864
17865 d = stuff;
17866 transferee = d->chan1;
17867 transferer = d->chan2;
17868 copy_request(&req, &d->req);
17869
17870 if (!transferee || !transferer) {
17871 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
17872 if (d->req.data)
17873 ast_free(d->req.data);
17874 free(d);
17875 return NULL;
17876 }
17877 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
17878
17879 ast_channel_lock(transferee);
17880 if (ast_do_masquerade(transferee)) {
17881 ast_log(LOG_WARNING, "Masquerade failed.\n");
17882 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
17883 ast_channel_unlock(transferee);
17884 if (d->req.data)
17885 ast_free(d->req.data);
17886 free(d);
17887 return NULL;
17888 }
17889 ast_channel_unlock(transferee);
17890
17891 res = ast_park_call(transferee, transferer, 0, &ext);
17892
17893
17894 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
17895 if (!res) {
17896 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
17897 } else {
17898
17899 sprintf(buf, "Call parked on extension '%d'", ext);
17900 transmit_message_with_text(transferer->tech_pvt, buf);
17901 }
17902 #endif
17903
17904
17905
17906 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
17907 if (!res) {
17908
17909 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
17910 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
17911 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
17912 ast_hangup(transferer);
17913 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
17914 } else {
17915 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
17916 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
17917 ast_debug(1, "SIP Call parked failed \n");
17918
17919 }
17920 if (d->req.data)
17921 ast_free(d->req.data);
17922 free(d);
17923 return NULL;
17924 }
17925
17926
17927
17928
17929 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
17930 {
17931 struct sip_dual *d;
17932 struct ast_channel *transferee, *transferer;
17933
17934 pthread_t th;
17935
17936 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
17937 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
17938 if ((!transferer) || (!transferee)) {
17939 if (transferee) {
17940 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17941 ast_hangup(transferee);
17942 }
17943 if (transferer) {
17944 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17945 ast_hangup(transferer);
17946 }
17947 return -1;
17948 }
17949
17950
17951 transferee->readformat = chan1->readformat;
17952 transferee->writeformat = chan1->writeformat;
17953
17954
17955 ast_channel_masquerade(transferee, chan1);
17956
17957
17958 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
17959 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
17960 transferee->priority = chan1->priority;
17961
17962
17963
17964
17965
17966 transferer->readformat = chan2->readformat;
17967 transferer->writeformat = chan2->writeformat;
17968 if (!ast_strlen_zero(chan2->parkinglot))
17969 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
17970
17971
17972
17973
17974 while (ast_channel_trylock(chan2)) {
17975 struct sip_pvt *pvt = chan2->tech_pvt;
17976 sip_pvt_unlock(pvt);
17977 usleep(1);
17978 sip_pvt_lock(pvt);
17979 }
17980 ast_channel_masquerade(transferer, chan2);
17981 ast_channel_unlock(chan2);
17982
17983
17984 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
17985 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
17986 transferer->priority = chan2->priority;
17987
17988 ast_channel_lock(transferer);
17989 if (ast_do_masquerade(transferer)) {
17990 ast_log(LOG_WARNING, "Masquerade failed :(\n");
17991 ast_channel_unlock(transferer);
17992 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17993 ast_hangup(transferer);
17994 return -1;
17995 }
17996 ast_channel_unlock(transferer);
17997 if (!transferer || !transferee) {
17998 if (!transferer) {
17999 ast_debug(1, "No transferer channel, giving up parking\n");
18000 }
18001 if (!transferee) {
18002 ast_debug(1, "No transferee channel, giving up parking\n");
18003 }
18004 return -1;
18005 }
18006 if ((d = ast_calloc(1, sizeof(*d)))) {
18007
18008
18009 copy_request(&d->req, req);
18010 d->chan1 = transferee;
18011 d->chan2 = transferer;
18012 d->seqno = seqno;
18013 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
18014
18015 if (d->req.data)
18016 ast_free(d->req.data);
18017 ast_free(d);
18018
18019 return 0;
18020 }
18021 }
18022 return -1;
18023 }
18024
18025
18026
18027
18028 static void ast_quiet_chan(struct ast_channel *chan)
18029 {
18030 if (chan && chan->_state == AST_STATE_UP) {
18031 if (ast_test_flag(chan, AST_FLAG_MOH))
18032 ast_moh_stop(chan);
18033 else if (chan->generatordata)
18034 ast_deactivate_generator(chan);
18035 }
18036 }
18037
18038
18039
18040 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
18041 {
18042 int res = 0;
18043 struct ast_channel *peera = NULL,
18044 *peerb = NULL,
18045 *peerc = NULL,
18046 *peerd = NULL;
18047
18048
18049
18050
18051 ast_debug(4, "Sip transfer:--------------------\n");
18052 if (transferer->chan1)
18053 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
18054 else
18055 ast_debug(4, "-- No transferer first channel - odd??? \n");
18056 if (target->chan1)
18057 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
18058 else
18059 ast_debug(4, "-- No target first channel ---\n");
18060 if (transferer->chan2)
18061 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
18062 else
18063 ast_debug(4, "-- No bridged call to transferee\n");
18064 if (target->chan2)
18065 ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
18066 else
18067 ast_debug(4, "-- No target second channel ---\n");
18068 ast_debug(4, "-- END Sip transfer:--------------------\n");
18069 if (transferer->chan2) {
18070 peera = transferer->chan1;
18071 peerb = target->chan1;
18072 peerc = transferer->chan2;
18073 peerd = target->chan2;
18074 ast_debug(3, "SIP transfer: Four channels to handle\n");
18075 } else if (target->chan2) {
18076 peera = target->chan1;
18077 peerb = transferer->chan1;
18078 peerc = target->chan2;
18079 peerd = transferer->chan2;
18080 ast_debug(3, "SIP transfer: Three channels to handle\n");
18081 }
18082
18083 if (peera && peerb && peerc && (peerb != peerc)) {
18084 ast_quiet_chan(peera);
18085 ast_quiet_chan(peerb);
18086 ast_quiet_chan(peerc);
18087 if (peerd)
18088 ast_quiet_chan(peerd);
18089
18090 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
18091 if (ast_channel_masquerade(peerb, peerc)) {
18092 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
18093 res = -1;
18094 } else
18095 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
18096 return res;
18097 } else {
18098 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
18099 if (transferer->chan1)
18100 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
18101 if (target->chan1)
18102 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
18103 return -1;
18104 }
18105 return 0;
18106 }
18107
18108
18109
18110
18111
18112
18113 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
18114 {
18115 const char *thetag;
18116
18117 if (!tagbuf)
18118 return NULL;
18119 tagbuf[0] = '\0';
18120 thetag = get_header(req, header);
18121 thetag = strcasestr(thetag, ";tag=");
18122 if (thetag) {
18123 thetag += 5;
18124 ast_copy_string(tagbuf, thetag, tagbufsize);
18125 return strsep(&tagbuf, ";");
18126 }
18127 return NULL;
18128 }
18129
18130
18131 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
18132 {
18133
18134
18135 int res = 0;
18136 const char *event = get_header(req, "Event");
18137 char *eventid = NULL;
18138 char *sep;
18139
18140 if( (sep = strchr(event, ';')) ) {
18141 *sep++ = '\0';
18142 eventid = sep;
18143 }
18144
18145 if (sipdebug)
18146 ast_debug(2, "Got NOTIFY Event: %s\n", event);
18147
18148 if (strcmp(event, "refer")) {
18149
18150
18151 transmit_response(p, "489 Bad event", req);
18152 res = -1;
18153 } else {
18154
18155
18156
18157
18158
18159 char buf[1024];
18160 char *cmd, *code;
18161 int respcode;
18162 int success = TRUE;
18163
18164
18165
18166
18167
18168
18169
18170
18171 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
18172
18173 transmit_response(p, "400 Bad request", req);
18174 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18175 return -1;
18176 }
18177
18178
18179 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
18180 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
18181 transmit_response(p, "400 Bad request", req);
18182 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18183 return -1;
18184 }
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
18207 cmd = ast_skip_blanks(buf);
18208 code = cmd;
18209
18210 while(*code && (*code > 32)) {
18211 code++;
18212 }
18213 *code++ = '\0';
18214 code = ast_skip_blanks(code);
18215 sep = code;
18216 sep++;
18217 while(*sep && (*sep > 32)) {
18218 sep++;
18219 }
18220 *sep++ = '\0';
18221 respcode = atoi(code);
18222 switch (respcode) {
18223 case 100:
18224 case 101:
18225
18226 break;
18227 case 183:
18228
18229 break;
18230 case 200:
18231
18232 break;
18233 case 301:
18234 case 302:
18235
18236 success = FALSE;
18237 break;
18238 case 503:
18239
18240 success = FALSE;
18241 break;
18242 case 603:
18243
18244 success = FALSE;
18245 break;
18246 }
18247 if (!success) {
18248 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
18249 }
18250
18251
18252 transmit_response(p, "200 OK", req);
18253 };
18254
18255 if (!p->lastinvite)
18256 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18257
18258 return res;
18259 }
18260
18261
18262
18263
18264 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
18265 {
18266 int res;
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278 if (p->lastinvite) {
18279
18280 transmit_response_with_allow(p, "200 OK", req, 0);
18281 return 0;
18282 }
18283
18284 res = get_destination(p, req);
18285 build_contact(p);
18286
18287 if (ast_strlen_zero(p->context))
18288 ast_string_field_set(p, context, default_context);
18289
18290 if (ast_shutting_down())
18291 transmit_response_with_allow(p, "503 Unavailable", req, 0);
18292 else if (res < 0)
18293 transmit_response_with_allow(p, "404 Not Found", req, 0);
18294 else
18295 transmit_response_with_allow(p, "200 OK", req, 0);
18296
18297
18298
18299 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18300
18301 return res;
18302 }
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
18314 {
18315 int earlyreplace = 0;
18316 int oneleggedreplace = 0;
18317 struct ast_channel *c = p->owner;
18318 struct ast_channel *replacecall = p->refer->refer_call->owner;
18319 struct ast_channel *targetcall;
18320
18321 struct ast_channel *test;
18322
18323
18324 if (replacecall->_state == AST_STATE_RING)
18325 earlyreplace = 1;
18326
18327
18328 if (!(targetcall = ast_bridged_channel(replacecall))) {
18329
18330 if (!earlyreplace) {
18331 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
18332 oneleggedreplace = 1;
18333 }
18334 }
18335 if (targetcall && targetcall->_state == AST_STATE_RINGING)
18336 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
18337
18338 if (targetcall)
18339 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
18340 else
18341 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
18342
18343 if (req->ignore) {
18344 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
18345
18346
18347
18348 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
18349
18350 if (c) {
18351 *nounlock = 1;
18352 ast_channel_unlock(c);
18353 }
18354 ast_channel_unlock(replacecall);
18355 sip_pvt_unlock(p->refer->refer_call);
18356 return 1;
18357 }
18358 if (!c) {
18359
18360 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
18361 transmit_response_reliable(p, "503 Service Unavailable", req);
18362 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
18363 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18364 ast_channel_unlock(replacecall);
18365 sip_pvt_unlock(p->refer->refer_call);
18366 return 1;
18367 }
18368 append_history(p, "Xfer", "INVITE/Replace received");
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380 transmit_response(p, "100 Trying", req);
18381 ast_setstate(c, AST_STATE_RING);
18382
18383
18384
18385
18386
18387 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
18388
18389 ast_setstate(c, AST_STATE_UP);
18390
18391
18392 ast_quiet_chan(replacecall);
18393 ast_quiet_chan(targetcall);
18394 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
18395
18396
18397 if (! earlyreplace && ! oneleggedreplace )
18398 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
18399
18400
18401 if(ast_channel_masquerade(replacecall, c))
18402 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
18403 else
18404 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
18405
18406
18407 if (ast_do_masquerade(replacecall)) {
18408 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
18409 }
18410
18411 if (earlyreplace || oneleggedreplace ) {
18412 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18413 }
18414
18415 ast_setstate(c, AST_STATE_DOWN);
18416 ast_debug(4, "After transfer:----------------------------\n");
18417 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
18418 if (replacecall)
18419 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
18420 if (p->owner) {
18421 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
18422 test = ast_bridged_channel(p->owner);
18423 if (test)
18424 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
18425 else
18426 ast_debug(4, " -- No call bridged to C->owner \n");
18427 } else
18428 ast_debug(4, " -- No channel yet \n");
18429 ast_debug(4, "End After transfer:----------------------------\n");
18430
18431
18432 ast_channel_unlock(replacecall);
18433 ast_channel_unlock(c);
18434 sip_pvt_unlock(p->refer->refer_call);
18435 sip_pvt_unlock(p);
18436 *nounlock = 1;
18437
18438
18439 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
18440 ast_hangup(c);
18441 sip_pvt_lock(p);
18442
18443 return 0;
18444 }
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462 static int sip_uri_params_cmp(const char *input1, const char *input2)
18463 {
18464 char *params1 = NULL;
18465 char *params2 = NULL;
18466 char *pos1;
18467 char *pos2;
18468 int zerolength1 = 0;
18469 int zerolength2 = 0;
18470 int maddrmatch = 0;
18471 int ttlmatch = 0;
18472 int usermatch = 0;
18473 int methodmatch = 0;
18474
18475 if (ast_strlen_zero(input1)) {
18476 zerolength1 = 1;
18477 } else {
18478 params1 = ast_strdupa(input1);
18479 }
18480 if (ast_strlen_zero(input2)) {
18481 zerolength2 = 1;
18482 } else {
18483 params2 = ast_strdupa(input2);
18484 }
18485
18486
18487
18488
18489 if (zerolength1 && zerolength2) {
18490 return 0;
18491 }
18492
18493 pos1 = params1;
18494 while (!ast_strlen_zero(pos1)) {
18495 char *name1 = pos1;
18496 char *value1 = strchr(pos1, '=');
18497 char *semicolon1 = strchr(pos1, ';');
18498 int matched = 0;
18499 if (semicolon1) {
18500 *semicolon1++ = '\0';
18501 }
18502 if (!value1) {
18503 goto fail;
18504 }
18505 *value1++ = '\0';
18506
18507
18508
18509
18510
18511 pos2 = ast_strdupa(params2);
18512 while (!ast_strlen_zero(pos2)) {
18513 char *name2 = pos2;
18514 char *value2 = strchr(pos2, '=');
18515 char *semicolon2 = strchr(pos2, ';');
18516 if (semicolon2) {
18517 *semicolon2++ = '\0';
18518 }
18519 if (!value2) {
18520 goto fail;
18521 }
18522 *value2++ = '\0';
18523 if (!strcasecmp(name1, name2)) {
18524 if (strcasecmp(value1, value2)) {
18525 goto fail;
18526 } else {
18527 matched = 1;
18528 break;
18529 }
18530 }
18531 pos2 = semicolon2;
18532 }
18533
18534 if (!strcasecmp(name1, "maddr")) {
18535 if (matched) {
18536 maddrmatch = 1;
18537 } else {
18538 goto fail;
18539 }
18540 } else if (!strcasecmp(name1, "ttl")) {
18541 if (matched) {
18542 ttlmatch = 1;
18543 } else {
18544 goto fail;
18545 }
18546 } else if (!strcasecmp(name1, "user")) {
18547 if (matched) {
18548 usermatch = 1;
18549 } else {
18550 goto fail;
18551 }
18552 } else if (!strcasecmp(name1, "method")) {
18553 if (matched) {
18554 methodmatch = 1;
18555 } else {
18556 goto fail;
18557 }
18558 }
18559 pos1 = semicolon1;
18560 }
18561
18562
18563
18564
18565
18566 pos2 = params2;
18567 while (!ast_strlen_zero(pos2)) {
18568 char *name2 = pos2;
18569 char *value2 = strchr(pos2, '=');
18570 char *semicolon2 = strchr(pos2, ';');
18571 if (semicolon2) {
18572 *semicolon2++ = '\0';
18573 }
18574 if (!value2) {
18575 goto fail;
18576 }
18577 *value2++ = '\0';
18578 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
18579 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
18580 (!strcasecmp(name2, "user") && !usermatch) ||
18581 (!strcasecmp(name2, "method") && !methodmatch)) {
18582 goto fail;
18583 }
18584 }
18585 return 0;
18586
18587 fail:
18588 return 1;
18589 }
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602 static int sip_uri_headers_cmp(const char *input1, const char *input2)
18603 {
18604 char *headers1 = NULL;
18605 char *headers2 = NULL;
18606 int zerolength1 = 0;
18607 int zerolength2 = 0;
18608 int different = 0;
18609 char *header1;
18610
18611 if (ast_strlen_zero(input1)) {
18612 zerolength1 = 1;
18613 } else {
18614 headers1 = ast_strdupa(input1);
18615 }
18616
18617 if (ast_strlen_zero(input2)) {
18618 zerolength2 = 1;
18619 } else {
18620 headers2 = ast_strdupa(input2);
18621 }
18622
18623 if ((zerolength1 && !zerolength2) ||
18624 (zerolength2 && !zerolength1))
18625 return 1;
18626
18627 if (zerolength1 && zerolength2)
18628 return 0;
18629
18630
18631
18632
18633
18634 if (strlen(headers1) != strlen(headers2)) {
18635 return 1;
18636 }
18637
18638 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
18639 if (!strcasestr(headers2, header1)) {
18640 different = 1;
18641 break;
18642 }
18643 }
18644
18645 return different;
18646 }
18647
18648 static int sip_uri_cmp(const char *input1, const char *input2)
18649 {
18650 char *uri1 = ast_strdupa(input1);
18651 char *uri2 = ast_strdupa(input2);
18652 char *host1;
18653 char *host2;
18654 char *params1;
18655 char *params2;
18656 char *headers1;
18657 char *headers2;
18658
18659
18660
18661
18662 strsep(&uri1, ":");
18663 strsep(&uri2, ":");
18664
18665 if ((host1 = strchr(uri1, '@'))) {
18666 *host1++ = '\0';
18667 }
18668 if ((host2 = strchr(uri2, '@'))) {
18669 *host2++ = '\0';
18670 }
18671
18672
18673
18674
18675 if ((host1 && !host2) ||
18676 (host2 && !host1) ||
18677 (host1 && host2 && strcmp(uri1, uri2))) {
18678 return 1;
18679 }
18680
18681 if (!host1)
18682 host1 = uri1;
18683 if (!host2)
18684 host2 = uri2;
18685
18686
18687
18688
18689
18690 if ((params1 = strchr(host1, ';'))) {
18691 *params1++ = '\0';
18692 }
18693 if ((params2 = strchr(host2, ';'))) {
18694 *params2++ = '\0';
18695 }
18696
18697
18698
18699
18700 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
18701 *headers1++ = '\0';
18702 }
18703 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
18704 *headers2++ = '\0';
18705 }
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717 if (strcasecmp(host1, host2)) {
18718 return 1;
18719 }
18720
18721
18722 if (sip_uri_headers_cmp(headers1, headers2)) {
18723 return 1;
18724 }
18725
18726
18727 return sip_uri_params_cmp(params1, params2);
18728 }
18729
18730
18731 static int sip_t38_abort(const void *data)
18732 {
18733 struct sip_pvt *p = (struct sip_pvt *) data;
18734
18735 change_t38_state(p, T38_DISABLED);
18736 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
18737 p->t38id = -1;
18738 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
18739
18740 return 0;
18741 }
18742
18743
18744
18745
18746
18747
18748
18749 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock)
18750 {
18751 int res = 1;
18752 int gotdest;
18753 const char *p_replaces;
18754 char *replace_id = NULL;
18755 const char *required;
18756 unsigned int required_profile = 0;
18757 struct ast_channel *c = NULL;
18758 int reinvite = 0;
18759 int rtn;
18760
18761 const char *p_uac_se_hdr;
18762 const char *p_uac_min_se;
18763 int uac_max_se = -1;
18764 int uac_min_se = -1;
18765 int st_active = FALSE;
18766 int st_interval = 0;
18767 enum st_refresher st_ref;
18768 int dlg_min_se = -1;
18769 st_ref = SESSION_TIMER_REFRESHER_AUTO;
18770
18771
18772 if (!p->sipoptions) {
18773 const char *supported = get_header(req, "Supported");
18774 if (!ast_strlen_zero(supported))
18775 parse_sip_options(p, supported);
18776 }
18777
18778
18779 required = get_header(req, "Require");
18780 if (!ast_strlen_zero(required)) {
18781 required_profile = parse_sip_options(NULL, required);
18782 if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
18783
18784 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
18785 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
18786 p->invitestate = INV_COMPLETED;
18787 if (!p->lastinvite)
18788 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18789 return -1;
18790 }
18791 }
18792
18793
18794
18795 p->sipoptions |= required_profile;
18796 p->reqsipoptions = required_profile;
18797
18798
18799 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
18800
18801
18802
18803
18804
18805 int different;
18806 char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
18807 char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
18808 if (pedanticsipchecking)
18809 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
18810 else
18811 different = strcmp(initial_rlPart2, this_rlPart2);
18812 if (!different) {
18813 transmit_response(p, "482 Loop Detected", req);
18814 p->invitestate = INV_COMPLETED;
18815 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18816 return 0;
18817 } else {
18818
18819
18820
18821
18822
18823
18824
18825 char *uri = ast_strdupa(this_rlPart2);
18826 char *at = strchr(uri, '@');
18827 char *peerorhost;
18828 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
18829 transmit_response(p, "100 Trying", req);
18830 if (at) {
18831 *at = '\0';
18832 }
18833
18834 if ((peerorhost = strchr(uri, ':'))) {
18835 *peerorhost++ = '\0';
18836 }
18837 ast_string_field_set(p, theirtag, NULL);
18838
18839
18840 ast_string_field_set(p->owner, call_forward, peerorhost);
18841 ast_queue_control(p->owner, AST_CONTROL_BUSY);
18842 return 0;
18843 }
18844 }
18845
18846 if (!req->ignore && p->pendinginvite) {
18847 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858 __sip_ack(p, p->pendinginvite, 1, 0);
18859 } else {
18860
18861 p->glareinvite = seqno;
18862 if (p->rtp && find_sdp(req)) {
18863 struct sockaddr_in sin;
18864 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
18865 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
18866 } else {
18867 ast_rtp_set_alt_peer(p->rtp, &sin);
18868 }
18869 if (p->vrtp) {
18870 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
18871 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
18872 } else {
18873 ast_rtp_set_alt_peer(p->vrtp, &sin);
18874 }
18875 }
18876 }
18877 transmit_response_reliable(p, "491 Request Pending", req);
18878 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
18879
18880 return 0;
18881 }
18882 }
18883
18884 p_replaces = get_header(req, "Replaces");
18885 if (!ast_strlen_zero(p_replaces)) {
18886
18887 char *ptr;
18888 char *fromtag = NULL;
18889 char *totag = NULL;
18890 char *start, *to;
18891 int error = 0;
18892
18893 if (p->owner) {
18894 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
18895 transmit_response_reliable(p, "400 Bad request", req);
18896
18897 return -1;
18898 }
18899
18900 if (sipdebug)
18901 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
18902
18903 replace_id = ast_strdupa(p_replaces);
18904 ast_uri_decode(replace_id);
18905
18906 if (!p->refer && !sip_refer_allocate(p)) {
18907 transmit_response_reliable(p, "500 Server Internal Error", req);
18908 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
18909 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18910 p->invitestate = INV_COMPLETED;
18911 return -1;
18912 }
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923 replace_id = ast_skip_blanks(replace_id);
18924
18925 start = replace_id;
18926 while ( (ptr = strsep(&start, ";")) ) {
18927 ptr = ast_skip_blanks(ptr);
18928 if ( (to = strcasestr(ptr, "to-tag=") ) )
18929 totag = to + 7;
18930 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
18931 fromtag = to + 9;
18932 fromtag = strsep(&fromtag, "&");
18933 }
18934 }
18935
18936 if (sipdebug)
18937 ast_debug(4, "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>");
18938
18939
18940
18941
18942
18943 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
18944 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
18945 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
18946 error = 1;
18947 }
18948
18949
18950
18951
18952
18953
18954
18955 if (p->refer->refer_call == p) {
18956 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
18957 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
18958 transmit_response_reliable(p, "400 Bad request", req);
18959 error = 1;
18960 }
18961
18962 if (!error && !p->refer->refer_call->owner) {
18963
18964 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
18965
18966 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
18967 error = 1;
18968 }
18969
18970 if (!error && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
18971 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
18972 transmit_response_reliable(p, "603 Declined (Replaces)", req);
18973 error = 1;
18974 }
18975
18976 if (error) {
18977 append_history(p, "Xfer", "INVITE/Replace Failed.");
18978 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18979 sip_pvt_unlock(p);
18980 if (p->refer->refer_call) {
18981 sip_pvt_unlock(p->refer->refer_call);
18982 if (p->refer->refer_call->owner) {
18983 ast_channel_unlock(p->refer->refer_call->owner);
18984 }
18985 }
18986 p->invitestate = INV_COMPLETED;
18987 return -1;
18988 }
18989 }
18990
18991
18992
18993
18994 if (!req->ignore) {
18995 int newcall = (p->initreq.headers ? TRUE : FALSE);
18996
18997 if (sip_cancel_destroy(p))
18998 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18999
19000 p->pendinginvite = seqno;
19001 check_via(p, req);
19002
19003 copy_request(&p->initreq, req);
19004 if (sipdebug)
19005 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19006 if (!p->owner) {
19007 if (debug)
19008 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
19009 if (newcall)
19010 append_history(p, "Invite", "New call: %s", p->callid);
19011 parse_ok_contact(p, req);
19012 } else {
19013 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
19014
19015 if (find_sdp(req)) {
19016 if (process_sdp(p, req, SDP_T38_INITIATE)) {
19017 transmit_response_reliable(p, "488 Not acceptable here", req);
19018 if (!p->lastinvite)
19019 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19020 return -1;
19021 }
19022 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
19023 } else {
19024 p->jointcapability = p->capability;
19025 ast_debug(1, "Hm.... No sdp for the moment\n");
19026 }
19027 if (p->do_history)
19028 append_history(p, "ReInv", "Re-invite received");
19029 }
19030 } else if (debug)
19031 ast_verbose("Ignoring this INVITE request\n");
19032
19033
19034 if (!p->lastinvite && !req->ignore && !p->owner) {
19035
19036
19037 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
19038 if (res == AUTH_CHALLENGE_SENT) {
19039 p->invitestate = INV_COMPLETED;
19040 return 0;
19041 }
19042 if (res < 0) {
19043 if (res == AUTH_FAKE_AUTH) {
19044 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
19045 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
19046 } else {
19047 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
19048 transmit_response_reliable(p, "403 Forbidden", req);
19049 }
19050 p->invitestate = INV_COMPLETED;
19051 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19052 ast_string_field_set(p, theirtag, NULL);
19053 return 0;
19054 }
19055
19056
19057 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl && (p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
19058 p->t38_maxdatagram = global_t38_maxdatagram;
19059 set_t38_capabilities(p);
19060 }
19061
19062
19063 if (find_sdp(req)) {
19064 if (process_sdp(p, req, SDP_T38_INITIATE)) {
19065
19066 transmit_response_reliable(p, "488 Not acceptable here", req);
19067 p->invitestate = INV_COMPLETED;
19068 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19069 ast_debug(1, "No compatible codecs for this SIP call.\n");
19070 return -1;
19071 }
19072 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
19073 if (p->rtp) {
19074 ast_rtp_set_constantssrc(p->rtp);
19075 }
19076 if (p->vrtp) {
19077 ast_rtp_set_constantssrc(p->vrtp);
19078 }
19079 }
19080 } else {
19081 p->jointcapability = p->capability;
19082 ast_debug(2, "No SDP in Invite, third party call control\n");
19083 }
19084
19085
19086
19087 if (p->owner)
19088 ast_queue_frame(p->owner, &ast_null_frame);
19089
19090
19091
19092 if (ast_strlen_zero(p->context))
19093 ast_string_field_set(p, context, default_context);
19094
19095
19096
19097 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
19098 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
19099 if (res < 0) {
19100 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
19101 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
19102 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19103 p->invitestate = INV_COMPLETED;
19104 }
19105 return 0;
19106 }
19107 gotdest = get_destination(p, NULL);
19108 get_rdnis(p, NULL);
19109 extract_uri(p, req);
19110 build_contact(p);
19111
19112 if (p->rtp) {
19113 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
19114 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
19115 }
19116
19117 if (!replace_id && gotdest) {
19118 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
19119 transmit_response_reliable(p, "484 Address Incomplete", req);
19120 else {
19121 char *decoded_exten = ast_strdupa(p->exten);
19122
19123 transmit_response_reliable(p, "404 Not Found", req);
19124 ast_uri_decode(decoded_exten);
19125 ast_log(LOG_NOTICE, "Call from '%s' to extension"
19126 " '%s' rejected because extension not found.\n",
19127 S_OR(p->username, p->peername), decoded_exten);
19128 }
19129 p->invitestate = INV_COMPLETED;
19130 update_call_counter(p, DEC_CALL_LIMIT);
19131 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19132 return 0;
19133 } else {
19134
19135
19136
19137 if (ast_strlen_zero(p->exten))
19138 ast_string_field_set(p, exten, "s");
19139
19140
19141 make_our_tag(p->tag, sizeof(p->tag));
19142
19143 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
19144 *recount = 1;
19145
19146
19147 build_route(p, req, 0);
19148
19149 if (c) {
19150
19151 ast_channel_lock(c);
19152 }
19153 }
19154 } else {
19155 if (sipdebug) {
19156 if (!req->ignore)
19157 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
19158 else
19159 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
19160 }
19161 if (!req->ignore)
19162 reinvite = 1;
19163 c = p->owner;
19164 }
19165
19166
19167 if (p->sipoptions & SIP_OPT_TIMER) {
19168
19169
19170 ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
19171
19172
19173 if (!p->stimer)
19174 sip_st_alloc(p);
19175
19176
19177 p_uac_se_hdr = get_header(req, "Session-Expires");
19178 if (!ast_strlen_zero(p_uac_se_hdr)) {
19179 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
19180 if (rtn != 0) {
19181 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
19182 p->invitestate = INV_COMPLETED;
19183 if (!p->lastinvite) {
19184 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19185 }
19186 return -1;
19187 }
19188 }
19189
19190
19191 p_uac_min_se = get_header(req, "Min-SE");
19192 if (!ast_strlen_zero(p_uac_min_se)) {
19193 rtn = parse_minse(p_uac_min_se, &uac_min_se);
19194 if (rtn != 0) {
19195 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
19196 p->invitestate = INV_COMPLETED;
19197 if (!p->lastinvite) {
19198 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19199 }
19200 return -1;
19201 }
19202 }
19203
19204 dlg_min_se = st_get_se(p, FALSE);
19205 switch (st_get_mode(p)) {
19206 case SESSION_TIMER_MODE_ACCEPT:
19207 case SESSION_TIMER_MODE_ORIGINATE:
19208 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
19209 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
19210 p->invitestate = INV_COMPLETED;
19211 if (!p->lastinvite) {
19212 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19213 }
19214 return -1;
19215 }
19216
19217 p->stimer->st_active_peer_ua = TRUE;
19218 st_active = TRUE;
19219 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
19220 st_ref = st_get_refresher(p);
19221 }
19222
19223 if (uac_max_se > 0) {
19224 int dlg_max_se = st_get_se(p, TRUE);
19225 if (dlg_max_se >= uac_min_se) {
19226 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
19227 } else {
19228 st_interval = uac_max_se;
19229 }
19230 } else {
19231
19232 st_interval = global_max_se;
19233 }
19234 break;
19235
19236 case SESSION_TIMER_MODE_REFUSE:
19237 if (p->reqsipoptions & SIP_OPT_TIMER) {
19238 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
19239 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
19240 p->invitestate = INV_COMPLETED;
19241 if (!p->lastinvite) {
19242 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19243 }
19244 return -1;
19245 }
19246 break;
19247
19248 default:
19249 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
19250 break;
19251 }
19252 } else {
19253
19254
19255
19256 switch (st_get_mode(p)) {
19257 case SESSION_TIMER_MODE_ORIGINATE:
19258 st_active = TRUE;
19259 st_interval = st_get_se(p, TRUE);
19260 st_ref = SESSION_TIMER_REFRESHER_UAS;
19261 p->stimer->st_active_peer_ua = FALSE;
19262 break;
19263
19264 default:
19265 break;
19266 }
19267 }
19268
19269 if (reinvite == 0) {
19270
19271 if (st_active == TRUE) {
19272 p->stimer->st_active = TRUE;
19273 p->stimer->st_interval = st_interval;
19274 p->stimer->st_ref = st_ref;
19275 start_session_timer(p);
19276 }
19277 } else {
19278 if (p->stimer->st_active == TRUE) {
19279
19280
19281
19282 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
19283
19284
19285 if (st_interval > 0) {
19286 p->stimer->st_interval = st_interval;
19287 p->stimer->st_ref = st_ref;
19288 }
19289
19290 restart_session_timer(p);
19291 if (p->stimer->st_expirys > 0) {
19292 p->stimer->st_expirys--;
19293 }
19294 }
19295 }
19296
19297 if (!req->ignore && p)
19298 p->lastinvite = seqno;
19299
19300 if (replace_id) {
19301
19302 if (sipdebug)
19303 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
19304 return handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
19305 }
19306
19307
19308 if (c) {
19309 enum ast_channel_state c_state = c->_state;
19310
19311 if (c_state != AST_STATE_UP && reinvite &&
19312 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322 c_state = AST_STATE_UP;
19323 }
19324
19325 switch(c_state) {
19326 case AST_STATE_DOWN:
19327 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
19328 transmit_provisional_response(p, "100 Trying", req, 0);
19329 p->invitestate = INV_PROCEEDING;
19330 ast_setstate(c, AST_STATE_RING);
19331 if (strcmp(p->exten, ast_pickup_ext())) {
19332 enum ast_pbx_result result;
19333
19334 result = ast_pbx_start(c);
19335
19336 switch(result) {
19337 case AST_PBX_FAILED:
19338 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
19339 p->invitestate = INV_COMPLETED;
19340 transmit_response_reliable(p, "503 Unavailable", req);
19341 break;
19342 case AST_PBX_CALL_LIMIT:
19343 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
19344 p->invitestate = INV_COMPLETED;
19345 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
19346 break;
19347 case AST_PBX_SUCCESS:
19348
19349 break;
19350 }
19351
19352 if (result) {
19353
19354
19355 ast_channel_unlock(c);
19356 sip_pvt_unlock(p);
19357 ast_hangup(c);
19358 sip_pvt_lock(p);
19359 c = NULL;
19360 }
19361 } else {
19362 ast_channel_unlock(c);
19363 *nounlock = 1;
19364 if (ast_pickup_call(c)) {
19365 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
19366 transmit_response_reliable(p, "503 Unavailable", req);
19367 sip_alreadygone(p);
19368
19369 sip_pvt_unlock(p);
19370 c->hangupcause = AST_CAUSE_CALL_REJECTED;
19371 } else {
19372 sip_pvt_unlock(p);
19373 ast_setstate(c, AST_STATE_DOWN);
19374 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19375 }
19376 p->invitestate = INV_COMPLETED;
19377 ast_hangup(c);
19378 sip_pvt_lock(p);
19379 c = NULL;
19380 }
19381 break;
19382 case AST_STATE_RING:
19383 transmit_provisional_response(p, "100 Trying", req, 0);
19384 p->invitestate = INV_PROCEEDING;
19385 break;
19386 case AST_STATE_RINGING:
19387 transmit_provisional_response(p, "180 Ringing", req, 0);
19388 p->invitestate = INV_PROCEEDING;
19389 break;
19390 case AST_STATE_UP:
19391 ast_debug(2, "%s: This call is UP.... \n", c->name);
19392
19393 transmit_response(p, "100 Trying", req);
19394
19395 if (p->t38.state == T38_PEER_REINVITE) {
19396 p->t38id = ast_sched_add(sched, 5000, sip_t38_abort, dialog_ref(p, "passing dialog ptr into sched structure based on t38id for sip_t38_abort."));
19397 } else if (p->t38.state == T38_ENABLED) {
19398 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19399 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
19400 } else if (p->t38.state == T38_DISABLED) {
19401
19402 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19403 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
19404 }
19405
19406 p->invitestate = INV_TERMINATED;
19407 break;
19408 default:
19409 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
19410 transmit_response(p, "100 Trying", req);
19411 break;
19412 }
19413 } else {
19414 if (p && (p->autokillid == -1)) {
19415 const char *msg;
19416
19417 if (!p->jointcapability)
19418 msg = "488 Not Acceptable Here (codec error)";
19419 else {
19420 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
19421 msg = "503 Unavailable";
19422 }
19423 transmit_response_reliable(p, msg, req);
19424 p->invitestate = INV_COMPLETED;
19425 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19426 }
19427 }
19428 return res;
19429 }
19430
19431
19432
19433 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
19434 {
19435 struct sip_dual target;
19436
19437 int res = 0;
19438 struct sip_pvt *targetcall_pvt;
19439
19440
19441 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
19442 transferer->refer->replaces_callid_fromtag))) {
19443 if (transferer->refer->localtransfer) {
19444
19445 transmit_response(transferer, "202 Accepted", req);
19446
19447
19448 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
19449 append_history(transferer, "Xfer", "Refer failed");
19450 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
19451 transferer->refer->status = REFER_FAILED;
19452 return -1;
19453 }
19454
19455 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
19456 return 0;
19457 }
19458
19459
19460 transmit_response(transferer, "202 Accepted", req);
19461 append_history(transferer, "Xfer", "Refer accepted");
19462 if (!targetcall_pvt->owner) {
19463 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
19464
19465 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
19466 append_history(transferer, "Xfer", "Refer failed");
19467 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
19468 transferer->refer->status = REFER_FAILED;
19469 sip_pvt_unlock(targetcall_pvt);
19470 if (targetcall_pvt)
19471 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
19472 return -1;
19473 }
19474
19475
19476 target.chan1 = targetcall_pvt->owner;
19477 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
19478
19479 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
19480
19481 if (target.chan2)
19482 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
19483 else if (target.chan1->_state != AST_STATE_RING)
19484 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
19485 else
19486 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
19487 }
19488
19489
19490 if (sipdebug) {
19491 if (current->chan2)
19492 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
19493 else
19494 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
19495 }
19496
19497 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19498
19499
19500 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Attended\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\n",
19501 transferer->owner->name,
19502 transferer->owner->uniqueid,
19503 transferer->callid,
19504 target.chan1->name,
19505 target.chan1->uniqueid);
19506 res = attempt_transfer(current, &target);
19507 sip_pvt_unlock(targetcall_pvt);
19508 if (res) {
19509
19510 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
19511 append_history(transferer, "Xfer", "Refer failed");
19512 if (targetcall_pvt->owner)
19513 ast_channel_unlock(targetcall_pvt->owner);
19514 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19515 } else {
19516
19517
19518
19519 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
19520 append_history(transferer, "Xfer", "Refer succeeded");
19521 transferer->refer->status = REFER_200OK;
19522 if (targetcall_pvt->owner) {
19523 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
19524 ast_channel_unlock(targetcall_pvt->owner);
19525 }
19526 }
19527 if (targetcall_pvt)
19528 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
19529 return 1;
19530 }
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
19597 {
19598 struct sip_dual current;
19599
19600
19601 int res = 0;
19602 current.req.data = NULL;
19603
19604 if (req->debug)
19605 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");
19606
19607 if (!p->owner) {
19608
19609
19610 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
19611 transmit_response(p, "603 Declined (No dialog)", req);
19612 if (!req->ignore) {
19613 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
19614 sip_alreadygone(p);
19615 p->needdestroy = 1;
19616 }
19617 return 0;
19618 }
19619
19620
19621
19622 if (p->allowtransfer == TRANSFER_CLOSED ) {
19623
19624 transmit_response(p, "603 Declined (policy)", req);
19625 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
19626
19627 return 0;
19628 }
19629
19630 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
19631
19632 transmit_response(p, "491 Request pending", req);
19633 append_history(p, "Xfer", "Refer failed. Request pending.");
19634 return 0;
19635 }
19636
19637
19638 if (!p->refer && !sip_refer_allocate(p)) {
19639 transmit_response(p, "500 Internal Server Error", req);
19640 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
19641 return -3;
19642 }
19643
19644 res = get_refer_info(p, req);
19645
19646 p->refer->status = REFER_SENT;
19647
19648 if (res != 0) {
19649 switch (res) {
19650 case -2:
19651 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
19652 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
19653 if (req->debug)
19654 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
19655 break;
19656 case -3:
19657 transmit_response(p, "603 Declined (Non sip: uri)", req);
19658 append_history(p, "Xfer", "Refer failed. Non SIP uri");
19659 if (req->debug)
19660 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
19661 break;
19662 default:
19663
19664 transmit_response(p, "202 Accepted", req);
19665 append_history(p, "Xfer", "Refer failed. Bad extension.");
19666 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
19667 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19668 if (req->debug)
19669 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
19670 break;
19671 }
19672 return 0;
19673 }
19674 if (ast_strlen_zero(p->context))
19675 ast_string_field_set(p, context, default_context);
19676
19677
19678 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
19679 p->refer->localtransfer = 1;
19680 if (sipdebug)
19681 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
19682 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
19683
19684 p->refer->localtransfer = 1;
19685 } else if (sipdebug)
19686 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
19687
19688
19689
19690 if (req->ignore)
19691 return res;
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719 current.chan1 = p->owner;
19720
19721
19722 current.chan2 = ast_bridged_channel(current.chan1);
19723
19724 if (sipdebug)
19725 ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");
19726
19727 if (!current.chan2 && !p->refer->attendedtransfer) {
19728
19729
19730
19731 if (sipdebug)
19732 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
19733 p->refer->status = REFER_FAILED;
19734 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
19735 transmit_response(p, "603 Declined", req);
19736 return -1;
19737 }
19738
19739 if (current.chan2) {
19740 if (sipdebug)
19741 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
19742
19743 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
19744 }
19745
19746 ast_set_flag(&p->flags[0], SIP_GOTREFER);
19747
19748
19749 if (p->refer->attendedtransfer) {
19750 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
19751 return res;
19752
19753 if (sipdebug)
19754 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
19755
19756 }
19757
19758
19759
19760 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
19761
19762 *nounlock = 1;
19763 ast_channel_unlock(current.chan1);
19764 copy_request(¤t.req, req);
19765 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19766 p->refer->status = REFER_200OK;
19767 append_history(p, "Xfer", "REFER to call parking.");
19768 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransfer2Parking: Yes\r\n",
19769 current.chan1->name,
19770 current.chan1->uniqueid,
19771 p->callid,
19772 current.chan2->name,
19773 current.chan2->uniqueid,
19774 p->refer->refer_to);
19775 if (sipdebug)
19776 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
19777 sip_park(current.chan2, current.chan1, req, seqno);
19778 return res;
19779 }
19780
19781
19782 transmit_response(p, "202 Accepted", req);
19783
19784 if (current.chan1 && current.chan2) {
19785 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
19786 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
19787 }
19788 if (current.chan2) {
19789 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
19790 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
19791 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
19792
19793 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
19794
19795 if (p->refer->referred_by)
19796 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
19797 }
19798
19799 if (!ast_strlen_zero(p->refer->replaces_callid)) {
19800 char tempheader[SIPBUFSIZE];
19801 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
19802 p->refer->replaces_callid_totag ? ";to-tag=" : "",
19803 p->refer->replaces_callid_totag,
19804 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
19805 p->refer->replaces_callid_fromtag);
19806 if (current.chan2)
19807 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
19808 }
19809
19810
19811 *nounlock = 1;
19812 ast_channel_unlock(current.chan1);
19813
19814
19815
19816
19817 if (!p->refer->attendedtransfer)
19818 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
19819
19820
19821
19822
19823
19824 if (!current.chan2) {
19825
19826
19827
19828
19829
19830
19831
19832 p->refer->status = REFER_FAILED;
19833 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
19834 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19835 append_history(p, "Xfer", "Refer failed (only bridged calls).");
19836 return -1;
19837 }
19838 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19839
19840
19841
19842
19843 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
19844
19845 if (!res) {
19846 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransferContext: %s\r\n",
19847 current.chan1->name,
19848 current.chan1->uniqueid,
19849 p->callid,
19850 current.chan2->name,
19851 current.chan2->uniqueid,
19852 p->refer->refer_to, p->refer->refer_to_context);
19853
19854 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
19855 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
19856 if (p->refer->localtransfer)
19857 p->refer->status = REFER_200OK;
19858 if (p->owner)
19859 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19860 append_history(p, "Xfer", "Refer succeeded.");
19861 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19862
19863
19864 res = 0;
19865 } else {
19866 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19867 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
19868 append_history(p, "Xfer", "Refer failed.");
19869
19870 p->refer->status = REFER_FAILED;
19871 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
19872 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19873 res = -1;
19874 }
19875 return res;
19876 }
19877
19878
19879 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
19880 {
19881
19882 check_via(p, req);
19883 sip_alreadygone(p);
19884
19885
19886
19887
19888
19889
19890 if (p->invitestate == INV_TERMINATED)
19891 __sip_pretend_ack(p);
19892 else
19893 p->invitestate = INV_CANCELLED;
19894
19895 if (p->owner && p->owner->_state == AST_STATE_UP) {
19896
19897 transmit_response(p, "200 OK", req);
19898 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
19899 return 0;
19900 }
19901
19902 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
19903 update_call_counter(p, DEC_CALL_LIMIT);
19904
19905 stop_media_flows(p);
19906 if (p->owner)
19907 ast_queue_hangup(p->owner);
19908 else
19909 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19910 if (p->initreq.len > 0) {
19911 struct sip_pkt *pkt, *prev_pkt;
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
19924 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
19925 AST_SCHED_DEL(sched, pkt->retransid);
19926 UNLINK(pkt, p->packets, prev_pkt);
19927 ast_free(pkt);
19928 break;
19929 }
19930 }
19931 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
19932 transmit_response(p, "200 OK", req);
19933 return 1;
19934 } else {
19935 transmit_response(p, "481 Call Leg Does Not Exist", req);
19936 return 0;
19937 }
19938 }
19939
19940 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
19941 {
19942 struct sip_pvt *p = chan->tech_pvt;
19943 char *all = "", *parse = ast_strdupa(preparse);
19944 int res = 0;
19945 AST_DECLARE_APP_ARGS(args,
19946 AST_APP_ARG(param);
19947 AST_APP_ARG(type);
19948 AST_APP_ARG(field);
19949 );
19950 AST_STANDARD_APP_ARGS(args, parse);
19951
19952
19953 if (!IS_SIP_TECH(chan->tech)) {
19954 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
19955 return 0;
19956 }
19957
19958 memset(buf, 0, buflen);
19959
19960 if (p == NULL) {
19961 return -1;
19962 }
19963
19964 if (!strcasecmp(args.param, "peerip")) {
19965 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
19966 } else if (!strcasecmp(args.param, "recvip")) {
19967 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
19968 } else if (!strcasecmp(args.param, "from")) {
19969 ast_copy_string(buf, p->from, buflen);
19970 } else if (!strcasecmp(args.param, "uri")) {
19971 ast_copy_string(buf, p->uri, buflen);
19972 } else if (!strcasecmp(args.param, "useragent")) {
19973 ast_copy_string(buf, p->useragent, buflen);
19974 } else if (!strcasecmp(args.param, "peername")) {
19975 ast_copy_string(buf, p->peername, buflen);
19976 } else if (!strcasecmp(args.param, "t38passthrough")) {
19977 ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
19978 } else if (!strcasecmp(args.param, "rtpdest")) {
19979 struct sockaddr_in sin;
19980
19981 if (ast_strlen_zero(args.type))
19982 args.type = "audio";
19983
19984 if (!strcasecmp(args.type, "audio"))
19985 ast_rtp_get_peer(p->rtp, &sin);
19986 else if (!strcasecmp(args.type, "video"))
19987 ast_rtp_get_peer(p->vrtp, &sin);
19988 else if (!strcasecmp(args.type, "text"))
19989 ast_rtp_get_peer(p->trtp, &sin);
19990 else
19991 return -1;
19992
19993 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
19994 } else if (!strcasecmp(args.param, "rtpqos")) {
19995 struct ast_rtp_quality qos;
19996 struct ast_rtp *rtp = p->rtp;
19997
19998 memset(&qos, 0, sizeof(qos));
19999
20000 if (ast_strlen_zero(args.type))
20001 args.type = "audio";
20002 if (ast_strlen_zero(args.field))
20003 args.field = "all";
20004
20005 if (!strcasecmp(args.type, "AUDIO")) {
20006 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
20007 } else if (!strcasecmp(args.type, "VIDEO")) {
20008 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
20009 } else if (!strcasecmp(args.type, "TEXT")) {
20010 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
20011 } else {
20012 return -1;
20013 }
20014
20015 if (!strcasecmp(args.field, "local_ssrc"))
20016 snprintf(buf, buflen, "%u", qos.local_ssrc);
20017 else if (!strcasecmp(args.field, "local_lostpackets"))
20018 snprintf(buf, buflen, "%u", qos.local_lostpackets);
20019 else if (!strcasecmp(args.field, "local_jitter"))
20020 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
20021 else if (!strcasecmp(args.field, "local_count"))
20022 snprintf(buf, buflen, "%u", qos.local_count);
20023 else if (!strcasecmp(args.field, "remote_ssrc"))
20024 snprintf(buf, buflen, "%u", qos.remote_ssrc);
20025 else if (!strcasecmp(args.field, "remote_lostpackets"))
20026 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
20027 else if (!strcasecmp(args.field, "remote_jitter"))
20028 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
20029 else if (!strcasecmp(args.field, "remote_count"))
20030 snprintf(buf, buflen, "%u", qos.remote_count);
20031 else if (!strcasecmp(args.field, "rtt"))
20032 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
20033 else if (!strcasecmp(args.field, "all"))
20034 ast_copy_string(buf, all, buflen);
20035 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
20036 ;
20037 else {
20038 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
20039 return -1;
20040 }
20041 } else {
20042 res = -1;
20043 }
20044 return res;
20045 }
20046
20047
20048 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
20049 {
20050 struct ast_channel *c=NULL;
20051 int res;
20052 struct ast_channel *bridged_to;
20053
20054
20055 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
20056 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
20057 }
20058
20059 __sip_pretend_ack(p);
20060
20061 p->invitestate = INV_TERMINATED;
20062
20063 copy_request(&p->initreq, req);
20064 if (sipdebug)
20065 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20066 check_via(p, req);
20067 sip_alreadygone(p);
20068
20069
20070 if (p->do_history || p->owner) {
20071 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
20072 char *videoqos, *textqos;
20073
20074
20075
20076
20077 while (bridge && ast_channel_trylock(bridge)) {
20078 ast_channel_unlock(p->owner);
20079 do {
20080
20081 sip_pvt_unlock(p);
20082 usleep(1);
20083 sip_pvt_lock(p);
20084 } while (p->owner && ast_channel_trylock(p->owner));
20085 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
20086 }
20087
20088 if (p->rtp) {
20089 if (p->do_history) {
20090 char *audioqos,
20091 *audioqos_jitter,
20092 *audioqos_loss,
20093 *audioqos_rtt;
20094
20095 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
20096 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
20097 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
20098 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
20099
20100 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
20101 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
20102 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
20103 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
20104 }
20105
20106 if (p->owner) {
20107 ast_rtp_set_vars(p->owner, p->rtp);
20108 }
20109 }
20110
20111 if (bridge) {
20112 struct sip_pvt *q = bridge->tech_pvt;
20113
20114 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
20115 ast_rtp_set_vars(bridge, q->rtp);
20116 ast_channel_unlock(bridge);
20117 }
20118
20119 if (p->vrtp) {
20120 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
20121 if (p->do_history)
20122 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
20123 if (p->owner)
20124 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
20125 }
20126
20127 if (p->trtp) {
20128 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
20129 if (p->do_history)
20130 append_history(p, "RTCPtext", "Quality:%s", textqos);
20131 if (p->owner)
20132 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
20133 }
20134 }
20135
20136 stop_media_flows(p);
20137 stop_session_timer(p);
20138
20139 if (!ast_strlen_zero(get_header(req, "Also"))) {
20140 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
20141 ast_inet_ntoa(p->recv.sin_addr));
20142 if (ast_strlen_zero(p->context))
20143 ast_string_field_set(p, context, default_context);
20144 res = get_also_info(p, req);
20145 if (!res) {
20146 c = p->owner;
20147 if (c) {
20148 bridged_to = ast_bridged_channel(c);
20149 if (bridged_to) {
20150
20151 ast_queue_control(c, AST_CONTROL_UNHOLD);
20152 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
20153 } else
20154 ast_queue_hangup(p->owner);
20155 }
20156 } else {
20157 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
20158 if (p->owner)
20159 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
20160 }
20161 } else if (p->owner) {
20162 ast_queue_hangup(p->owner);
20163 ast_debug(3, "Received bye, issuing owner hangup\n");
20164 } else {
20165 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20166 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
20167 }
20168 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20169 transmit_response(p, "200 OK", req);
20170
20171 return 1;
20172 }
20173
20174
20175 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
20176 {
20177 if (!req->ignore) {
20178 if (req->debug)
20179 ast_verbose("Receiving message!\n");
20180 receive_message(p, req);
20181 } else
20182 transmit_response(p, "202 Accepted", req);
20183 return 1;
20184 }
20185
20186 static void add_peer_mwi_subs(struct sip_peer *peer)
20187 {
20188 struct sip_mailbox *mailbox;
20189
20190 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
20191 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
20192 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
20193 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
20194 AST_EVENT_IE_END);
20195 }
20196 }
20197
20198
20199 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
20200 {
20201 int gotdest = 0;
20202 int res = 0;
20203 int firststate = AST_EXTENSION_REMOVED;
20204 struct sip_peer *authpeer = NULL;
20205 const char *eventheader = get_header(req, "Event");
20206 const char *acceptheader = get_header(req, "Accept");
20207 int resubscribe = (p->subscribed != NONE);
20208 char *temp, *event;
20209 struct ao2_iterator i;
20210
20211 if (p->initreq.headers) {
20212
20213 if (p->initreq.method != SIP_SUBSCRIBE) {
20214
20215
20216 transmit_response(p, "403 Forbidden (within dialog)", req);
20217
20218 ast_debug(1, "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);
20219 return 0;
20220 } else if (req->debug) {
20221 if (resubscribe)
20222 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
20223 else
20224 ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
20225 }
20226 }
20227
20228
20229
20230
20231 if (!global_allowsubscribe) {
20232 transmit_response(p, "403 Forbidden (policy)", req);
20233 p->needdestroy = 1;
20234 return 0;
20235 }
20236
20237 if (!req->ignore && !resubscribe) {
20238 const char *to = get_header(req, "To");
20239 char totag[128];
20240
20241
20242 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
20243 if (req->debug)
20244 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
20245 transmit_response(p, "481 Subscription does not exist", req);
20246 p->needdestroy = 1;
20247 return 0;
20248 }
20249
20250
20251 if (req->debug)
20252 ast_verbose("Creating new subscription\n");
20253
20254 copy_request(&p->initreq, req);
20255 if (sipdebug)
20256 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20257 check_via(p, req);
20258 build_route(p, req, 0);
20259 } else if (req->debug && req->ignore)
20260 ast_verbose("Ignoring this SUBSCRIBE request\n");
20261
20262
20263 if (ast_strlen_zero(eventheader)) {
20264 transmit_response(p, "489 Bad Event", req);
20265 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
20266 p->needdestroy = 1;
20267 return 0;
20268 }
20269
20270 if ( (strchr(eventheader, ';'))) {
20271 event = ast_strdupa(eventheader);
20272 temp = strchr(event, ';');
20273 *temp = '\0';
20274
20275 } else
20276 event = (char *) eventheader;
20277
20278
20279 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
20280
20281 if (res == AUTH_CHALLENGE_SENT)
20282 return 0;
20283 if (res < 0) {
20284 if (res == AUTH_FAKE_AUTH) {
20285 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20286 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
20287 } else {
20288 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
20289 transmit_response_reliable(p, "403 Forbidden", req);
20290 }
20291 p->needdestroy = 1;
20292 return 0;
20293 }
20294
20295
20296
20297
20298
20299
20300
20301 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
20302 transmit_response(p, "403 Forbidden (policy)", req);
20303 p->needdestroy = 1;
20304 if (authpeer)
20305 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
20306 return 0;
20307 }
20308
20309 if (strcmp(event, "message-summary")) {
20310
20311 gotdest = get_destination(p, NULL);
20312 }
20313
20314
20315 parse_ok_contact(p, req);
20316
20317 build_contact(p);
20318 if (gotdest) {
20319 transmit_response(p, "404 Not Found", req);
20320 p->needdestroy = 1;
20321 if (authpeer)
20322 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
20323 return 0;
20324 }
20325
20326
20327 if (ast_strlen_zero(p->tag))
20328 make_our_tag(p->tag, sizeof(p->tag));
20329
20330 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
20331 unsigned int pidf_xml;
20332
20333 if (authpeer)
20334 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
20335
20336
20337
20338 pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
20339
20340
20341
20342 if (pidf_xml && strstr(p->useragent, "Polycom")) {
20343 p->subscribed = XPIDF_XML;
20344 } else if (pidf_xml) {
20345 p->subscribed = PIDF_XML;
20346 } else if (strstr(acceptheader, "application/dialog-info+xml")) {
20347 p->subscribed = DIALOG_INFO_XML;
20348
20349 } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
20350 p->subscribed = CPIM_PIDF_XML;
20351 } else if (strstr(acceptheader, "application/xpidf+xml")) {
20352 p->subscribed = XPIDF_XML;
20353 } else if (ast_strlen_zero(acceptheader)) {
20354 if (p->subscribed == NONE) {
20355 transmit_response(p, "489 Bad Event", req);
20356
20357 ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
20358 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
20359 p->needdestroy = 1;
20360 return 0;
20361 }
20362
20363
20364 } else {
20365
20366 char mybuf[200];
20367 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
20368 transmit_response(p, mybuf, req);
20369
20370 ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
20371 acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
20372 p->needdestroy = 1;
20373 return 0;
20374 }
20375 } else if (!strcmp(event, "message-summary")) {
20376 if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
20377
20378 transmit_response(p, "406 Not Acceptable", req);
20379 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
20380 p->needdestroy = 1;
20381 if (authpeer)
20382 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
20383 return 0;
20384 }
20385
20386
20387
20388
20389
20390 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
20391 transmit_response(p, "404 Not found (no mailbox)", req);
20392 p->needdestroy = 1;
20393 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
20394 if (authpeer)
20395 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
20396 return 0;
20397 }
20398
20399 p->subscribed = MWI_NOTIFICATION;
20400 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
20401 add_peer_mwi_subs(authpeer);
20402 }
20403 if (authpeer->mwipvt && authpeer->mwipvt != p) {
20404
20405 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
20406 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
20407
20408 }
20409 if (authpeer->mwipvt)
20410 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
20411 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
20412 if (p->relatedpeer)
20413 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
20414 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
20415
20416 } else {
20417 transmit_response(p, "489 Bad Event", req);
20418 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
20419 p->needdestroy = 1;
20420 if (authpeer)
20421 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
20422 return 0;
20423 }
20424
20425
20426 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
20427 if (p->stateid > -1) {
20428 ast_extension_state_del(p->stateid, cb_extensionstate);
20429
20430 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
20431 }
20432 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
20433 }
20434
20435 if (!req->ignore && p)
20436 p->lastinvite = seqno;
20437 if (p && !p->needdestroy) {
20438 p->expiry = atoi(get_header(req, "Expires"));
20439
20440
20441 if (p->expiry > max_expiry)
20442 p->expiry = max_expiry;
20443 if (p->expiry < min_expiry && p->expiry > 0)
20444 p->expiry = min_expiry;
20445
20446 if (sipdebug) {
20447 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
20448 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
20449 else
20450 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
20451 }
20452 if (p->autokillid > -1 && sip_cancel_destroy(p))
20453 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20454 if (p->expiry > 0)
20455 sip_scheddestroy(p, (p->expiry + 10) * 1000);
20456
20457 if (p->subscribed == MWI_NOTIFICATION) {
20458 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20459 transmit_response(p, "200 OK", req);
20460 if (p->relatedpeer) {
20461 ao2_lock(p->relatedpeer);
20462 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
20463 ao2_unlock(p->relatedpeer);
20464 }
20465 } else {
20466 struct sip_pvt *p_old;
20467
20468 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
20469
20470 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));
20471 transmit_response(p, "404 Not found", req);
20472 p->needdestroy = 1;
20473 return 0;
20474 }
20475 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20476 transmit_response(p, "200 OK", req);
20477 transmit_state_notify(p, firststate, 1, FALSE);
20478 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
20479
20480 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
20481
20482
20483
20484
20485
20486
20487 i = ao2_iterator_init(dialogs, 0);
20488 while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
20489 if (p_old == p) {
20490 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
20491 continue;
20492 }
20493 if (p_old->initreq.method != SIP_SUBSCRIBE) {
20494 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
20495 continue;
20496 }
20497 if (p_old->subscribed == NONE) {
20498 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
20499 continue;
20500 }
20501 sip_pvt_lock(p_old);
20502 if (!strcmp(p_old->username, p->username)) {
20503 if (!strcmp(p_old->exten, p->exten) &&
20504 !strcmp(p_old->context, p->context)) {
20505 p_old->needdestroy = 1;
20506 sip_pvt_unlock(p_old);
20507 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
20508 break;
20509 }
20510 }
20511 sip_pvt_unlock(p_old);
20512 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
20513 }
20514 ao2_iterator_destroy(&i);
20515 }
20516 if (!p->expiry)
20517 p->needdestroy = 1;
20518 }
20519 return 1;
20520 }
20521
20522
20523 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
20524 {
20525 enum check_auth_result res;
20526
20527
20528 copy_request(&p->initreq, req);
20529 if (sipdebug)
20530 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20531 check_via(p, req);
20532 if ((res = register_verify(p, sin, req, e)) < 0) {
20533 const char *reason;
20534
20535 switch (res) {
20536 case AUTH_SECRET_FAILED:
20537 reason = "Wrong password";
20538 break;
20539 case AUTH_USERNAME_MISMATCH:
20540 reason = "Username/auth name mismatch";
20541 break;
20542 case AUTH_NOT_FOUND:
20543 reason = "No matching peer found";
20544 break;
20545 case AUTH_UNKNOWN_DOMAIN:
20546 reason = "Not a local domain";
20547 break;
20548 case AUTH_PEER_NOT_DYNAMIC:
20549 reason = "Peer is not supposed to register";
20550 break;
20551 case AUTH_ACL_FAILED:
20552 reason = "Device does not match ACL";
20553 break;
20554 case AUTH_BAD_TRANSPORT:
20555 reason = "Device not configured to use this transport type";
20556 break;
20557 default:
20558 reason = "Unknown failure";
20559 break;
20560 }
20561 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
20562 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
20563 reason);
20564 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
20565 } else
20566 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
20567
20568 if (res < 1) {
20569
20570
20571 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20572 }
20573 return res;
20574 }
20575
20576
20577
20578
20579 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
20580 {
20581
20582
20583 const char *cmd;
20584 const char *cseq;
20585 const char *useragent;
20586 int seqno;
20587 int len;
20588 int respid;
20589 int res = 0;
20590 int debug = sip_debug_test_pvt(p);
20591 char *e;
20592 int error = 0;
20593 int oldmethod = p->method;
20594 int acked = 0;
20595
20596
20597 cseq = get_header(req, "Cseq");
20598 cmd = REQ_OFFSET_TO_STR(req, header[0]);
20599
20600
20601 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
20602 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
20603 error = 1;
20604 }
20605 if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
20606 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
20607 error = 1;
20608 }
20609 if (error) {
20610 if (!p->initreq.headers)
20611 p->needdestroy = 1;
20612 return -1;
20613 }
20614
20615
20616 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
20617 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
20618
20619
20620 useragent = get_header(req, "User-Agent");
20621 if (!ast_strlen_zero(useragent))
20622 ast_string_field_set(p, useragent, useragent);
20623
20624
20625 if (req->method == SIP_RESPONSE) {
20626
20627
20628
20629
20630
20631
20632 if (ast_strlen_zero(e)) {
20633 return 0;
20634 }
20635 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
20636 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
20637 return 0;
20638 }
20639 if (respid <= 0) {
20640 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
20641 return 0;
20642 }
20643 if (p->ocseq && (p->ocseq < seqno)) {
20644 if (option_debug)
20645 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
20646 return -1;
20647 } else {
20648 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
20649 extract_uri(p, req);
20650 }
20651 handle_response(p, respid, e + len, req, seqno);
20652 }
20653 return 0;
20654 }
20655
20656
20657
20658
20659
20660 p->method = req->method;
20661 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
20662
20663 if (p->icseq && (p->icseq > seqno) ) {
20664 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
20665 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
20666 } else {
20667 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
20668 if (req->method != SIP_ACK)
20669 transmit_response(p, "503 Server error", req);
20670 return -1;
20671 }
20672 } else if (p->icseq &&
20673 p->icseq == seqno &&
20674 req->method != SIP_ACK &&
20675 (p->method != SIP_CANCEL || p->alreadygone)) {
20676
20677
20678
20679 req->ignore = 1;
20680 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
20681 }
20682
20683 if (seqno >= p->icseq)
20684
20685
20686
20687 p->icseq = seqno;
20688
20689
20690 if (ast_strlen_zero(p->theirtag)) {
20691 char tag[128];
20692
20693 gettag(req, "From", tag, sizeof(tag));
20694 ast_string_field_set(p, theirtag, tag);
20695 }
20696 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
20697
20698 if (pedanticsipchecking) {
20699
20700
20701
20702
20703 if (!p->initreq.headers && req->has_to_tag) {
20704
20705 if (!req->ignore && req->method == SIP_INVITE) {
20706 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
20707
20708 } else if (req->method != SIP_ACK) {
20709 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
20710 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20711 } else {
20712 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
20713 }
20714 return res;
20715 }
20716 }
20717
20718 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
20719 transmit_response(p, "400 Bad request", req);
20720 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20721 return -1;
20722 }
20723
20724
20725 switch (p->method) {
20726 case SIP_OPTIONS:
20727 res = handle_request_options(p, req);
20728 break;
20729 case SIP_INVITE:
20730 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
20731 break;
20732 case SIP_REFER:
20733 res = handle_request_refer(p, req, debug, seqno, nounlock);
20734 break;
20735 case SIP_CANCEL:
20736 res = handle_request_cancel(p, req);
20737 break;
20738 case SIP_BYE:
20739 res = handle_request_bye(p, req);
20740 break;
20741 case SIP_MESSAGE:
20742 res = handle_request_message(p, req);
20743 break;
20744 case SIP_SUBSCRIBE:
20745 res = handle_request_subscribe(p, req, sin, seqno, e);
20746 break;
20747 case SIP_REGISTER:
20748 res = handle_request_register(p, req, sin, e);
20749 break;
20750 case SIP_INFO:
20751 if (req->debug)
20752 ast_verbose("Receiving INFO!\n");
20753 if (!req->ignore)
20754 handle_request_info(p, req);
20755 else
20756 transmit_response(p, "200 OK", req);
20757 break;
20758 case SIP_NOTIFY:
20759 res = handle_request_notify(p, req, sin, seqno, e);
20760 break;
20761 case SIP_ACK:
20762
20763 if (seqno == p->pendinginvite) {
20764 p->invitestate = INV_TERMINATED;
20765 p->pendinginvite = 0;
20766 acked = __sip_ack(p, seqno, 1 , 0);
20767 if (find_sdp(req)) {
20768 if (process_sdp(p, req, SDP_T38_NONE))
20769 return -1;
20770 }
20771 check_pendings(p);
20772 } else if (p->glareinvite == seqno) {
20773
20774 p->glareinvite = 0;
20775 acked = __sip_ack(p, seqno, 1, 0);
20776 }
20777 if (!acked) {
20778
20779
20780 p->method = oldmethod;
20781 }
20782 if (!p->lastinvite && ast_strlen_zero(p->randdata))
20783 p->needdestroy = 1;
20784 break;
20785 default:
20786 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
20787 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
20788 cmd, ast_inet_ntoa(p->sa.sin_addr));
20789
20790 if (!p->initreq.headers)
20791 p->needdestroy = 1;
20792 break;
20793 }
20794 return res;
20795 }
20796
20797 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
20798 {
20799 struct sip_request *req;
20800
20801 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
20802 if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
20803
20804 if (option_debug) {
20805 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
20806 }
20807 }
20808 ast_free(req);
20809 }
20810 }
20811
20812 static int scheduler_process_request_queue(const void *data)
20813 {
20814 struct sip_pvt *p = (struct sip_pvt *) data;
20815 int recount = 0;
20816 int nounlock = 0;
20817 int lockretry;
20818
20819 for (lockretry = 10; lockretry > 0; lockretry--) {
20820 sip_pvt_lock(p);
20821
20822
20823
20824 if (!p->owner || !ast_channel_trylock(p->owner)) {
20825 break;
20826 }
20827
20828 if (lockretry != 1) {
20829 sip_pvt_unlock(p);
20830
20831 usleep(1);
20832 }
20833 }
20834
20835 if (!lockretry) {
20836 int retry = !AST_LIST_EMPTY(&p->request_queue);
20837
20838
20839
20840
20841
20842
20843 sip_pvt_unlock(p);
20844 if (!retry) {
20845 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
20846 }
20847 return retry;
20848 };
20849
20850 process_request_queue(p, &recount, &nounlock);
20851 p->request_queue_sched_id = -1;
20852
20853 if (p->owner && !nounlock) {
20854 ast_channel_unlock(p->owner);
20855 }
20856 sip_pvt_unlock(p);
20857
20858 if (recount) {
20859 ast_update_use_count();
20860 }
20861
20862 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
20863
20864 return 0;
20865 }
20866
20867 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
20868 {
20869 struct sip_request *newreq;
20870
20871 if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
20872 return -1;
20873 }
20874
20875 copy_request(newreq, req);
20876 AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
20877 if (p->request_queue_sched_id == -1) {
20878 if ((p->request_queue_sched_id = ast_sched_add(sched, 10, scheduler_process_request_queue, dialog_ref(p, "Increment refcount to pass dialog pointer to sched callback"))) == -1) {
20879 dialog_unref(p, "Decrement refcount due to sched_add failure");
20880 }
20881 }
20882
20883 return 0;
20884 }
20885
20886
20887
20888
20889
20890
20891 static int sipsock_read(int *id, int fd, short events, void *ignore)
20892 {
20893 struct sip_request req;
20894 struct sockaddr_in sin = { 0, };
20895 int res;
20896 socklen_t len = sizeof(sin);
20897 static char readbuf[65535];
20898
20899 memset(&req, 0, sizeof(req));
20900 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
20901 if (res < 0) {
20902 #if !defined(__FreeBSD__)
20903 if (errno == EAGAIN)
20904 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
20905 else
20906 #endif
20907 if (errno != ECONNREFUSED)
20908 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
20909 return 1;
20910 }
20911
20912 readbuf[res] = '\0';
20913
20914 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
20915 return 1;
20916 }
20917
20918 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
20919 return -1;
20920 }
20921
20922 req.len = res;
20923 req.socket.fd = sipsock;
20924 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
20925 req.socket.tcptls_session = NULL;
20926 req.socket.port = bindaddr.sin_port;
20927
20928 handle_request_do(&req, &sin);
20929 if (req.data) {
20930 ast_free(req.data);
20931 req.data = NULL;
20932 }
20933
20934 return 1;
20935 }
20936
20937 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
20938 {
20939 struct sip_pvt *p;
20940 int recount = 0;
20941 int nounlock = 0;
20942 int lockretry;
20943
20944 if (sip_debug_test_addr(sin))
20945 req->debug = 1;
20946 if (pedanticsipchecking)
20947 req->len = lws2sws(req->data->str, req->len);
20948 if (req->debug) {
20949 ast_verbose("\n<--- SIP read from %s://%s:%d --->\n%s\n<------------->\n",
20950 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
20951 ntohs(sin->sin_port), req->data->str);
20952 }
20953
20954 if (parse_request(req) == -1) {
20955 ast_str_reset(req->data);
20956 return 1;
20957 }
20958 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
20959
20960 if (req->debug)
20961 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
20962
20963 if (req->headers < 2) {
20964 ast_str_reset(req->data);
20965 return 1;
20966 }
20967
20968
20969 for (lockretry = 10; lockretry > 0; lockretry--) {
20970 ast_mutex_lock(&netlock);
20971
20972
20973 p = find_call(req, sin, req->method);
20974 if (p == NULL) {
20975 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
20976 ast_mutex_unlock(&netlock);
20977 return 1;
20978 }
20979
20980 copy_socket_data(&p->socket, &req->socket);
20981
20982
20983
20984 if (!p->owner || !ast_channel_trylock(p->owner))
20985 break;
20986
20987 if (lockretry != 1) {
20988 sip_pvt_unlock(p);
20989 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop");
20990 ast_mutex_unlock(&netlock);
20991
20992 usleep(1);
20993 }
20994 }
20995 p->recv = *sin;
20996
20997 if (p->do_history)
20998 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
20999
21000 if (!lockretry) {
21001 if (!queue_request(p, req)) {
21002
21003 sip_pvt_unlock(p);
21004 ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
21005 ast_mutex_unlock(&netlock);
21006 return 1;
21007 }
21008
21009 if (p->owner)
21010 ast_log(LOG_ERROR, "Channel lock for %s could not be obtained, and request was unable to be queued.\n", S_OR(p->owner->name, "- no channel name ??? - "));
21011 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
21012 if (req->method != SIP_ACK)
21013 transmit_response(p, "503 Server error", req);
21014
21015 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
21016 sip_pvt_unlock(p);
21017 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry");
21018 ast_mutex_unlock(&netlock);
21019 return 1;
21020 }
21021
21022
21023
21024
21025 if (!AST_LIST_EMPTY(&p->request_queue)) {
21026 AST_SCHED_DEL_UNREF(sched, p->request_queue_sched_id, dialog_unref(p, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
21027 process_request_queue(p, &recount, &nounlock);
21028 }
21029
21030 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
21031
21032 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21033 }
21034
21035 if (recount)
21036 ast_update_use_count();
21037
21038 if (p->owner && !nounlock)
21039 ast_channel_unlock(p->owner);
21040 sip_pvt_unlock(p);
21041 ast_mutex_unlock(&netlock);
21042 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
21043 return 1;
21044 }
21045
21046
21047
21048
21049
21050
21051
21052 static int sip_standard_port(enum sip_transport type, int port)
21053 {
21054 if (type & SIP_TRANSPORT_TLS)
21055 return port == STANDARD_TLS_PORT;
21056 else
21057 return port == STANDARD_SIP_PORT;
21058 }
21059
21060 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
21061 {
21062 struct sip_threadinfo *th = obj;
21063 struct sockaddr_in *s = arg;
21064
21065 if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
21066 return CMP_MATCH | CMP_STOP;
21067 }
21068
21069 return 0;
21070 }
21071
21072
21073
21074
21075
21076
21077 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
21078 {
21079 struct sip_threadinfo *th;
21080 struct ast_tcptls_session_instance *tcptls_instance = NULL;
21081
21082 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
21083 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
21084 ao2_t_ref(th, -1, "decrement ref from callback");
21085 }
21086 return tcptls_instance;
21087 }
21088
21089
21090 static int sip_prepare_socket(struct sip_pvt *p)
21091 {
21092 struct sip_socket *s = &p->socket;
21093 static const char name[] = "SIP socket";
21094 struct sip_threadinfo *th = NULL;
21095 struct ast_tcptls_session_instance *tcptls_session;
21096 struct ast_tcptls_session_args tmp_ca = {
21097 .name = name,
21098 .accept_fd = -1,
21099 };
21100 struct ast_tcptls_session_args *ca;
21101
21102
21103 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
21104 return s->fd;
21105 }
21106 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
21107 (s->tcptls_session) &&
21108 (s->tcptls_session->fd != -1)) {
21109 return s->tcptls_session->fd;
21110 }
21111
21112 if (p->outboundproxy && p->outboundproxy->transport) {
21113 s->type = p->outboundproxy->transport;
21114 }
21115
21116 if (s->type == SIP_TRANSPORT_UDP) {
21117 s->fd = sipsock;
21118 return s->fd;
21119 }
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131 tmp_ca.remote_address = *(sip_real_dst(p));
21132 if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
21133 s->fd = tcptls_session->fd;
21134 if (s->tcptls_session) {
21135 ao2_ref(s->tcptls_session, -1);
21136 s->tcptls_session = NULL;
21137 }
21138 s->tcptls_session = tcptls_session;
21139 return s->fd;
21140
21141 } else if (s->tcptls_session) {
21142 return s->fd;
21143 }
21144
21145
21146
21147 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
21148 !(ca->name = ast_strdup(name))) {
21149 goto create_tcptls_session_fail;
21150 }
21151 ca->accept_fd = -1;
21152 ca->remote_address = *(sip_real_dst(p));
21153
21154 if (s->type == SIP_TRANSPORT_TLS) {
21155 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
21156 goto create_tcptls_session_fail;
21157 }
21158 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
21159
21160 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
21161 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
21162 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
21163 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
21164
21165 goto create_tcptls_session_fail;
21166 }
21167
21168
21169 if (!ast_strlen_zero(p->tohost)) {
21170 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
21171 }
21172 }
21173
21174 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
21175 goto create_tcptls_session_fail;
21176 }
21177
21178 s->fd = s->tcptls_session->fd;
21179
21180
21181
21182
21183
21184 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
21185 goto create_tcptls_session_fail;
21186
21187 }
21188
21189
21190 ao2_ref(s->tcptls_session, +1);
21191
21192 if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
21193 ast_debug(1, "Unable to launch '%s'.", ca->name);
21194 ao2_ref(s->tcptls_session, -1);
21195 goto create_tcptls_session_fail;
21196 }
21197
21198 return s->fd;
21199
21200 create_tcptls_session_fail:
21201 if (ca) {
21202 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
21203 }
21204 if (s->tcptls_session) {
21205 close(tcptls_session->fd);
21206 s->fd = tcptls_session->fd = -1;
21207 ao2_ref(s->tcptls_session, -1);
21208 s->tcptls_session = NULL;
21209 }
21210 if (th) {
21211 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
21212 }
21213
21214 return -1;
21215 }
21216
21217
21218
21219
21220
21221 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
21222 {
21223 char *port;
21224
21225 if ((*hostname = strstr(line, "://"))) {
21226 *hostname += 3;
21227
21228 if (!strncasecmp(line, "tcp", 3))
21229 *transport = SIP_TRANSPORT_TCP;
21230 else if (!strncasecmp(line, "tls", 3))
21231 *transport = SIP_TRANSPORT_TLS;
21232 else if (!strncasecmp(line, "udp", 3))
21233 *transport = SIP_TRANSPORT_UDP;
21234 else
21235 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
21236 } else {
21237 *hostname = line;
21238 *transport = SIP_TRANSPORT_UDP;
21239 }
21240
21241 if ((line = strrchr(*hostname, '@')))
21242 line++;
21243 else
21244 line = *hostname;
21245
21246 if ((port = strrchr(line, ':'))) {
21247 *port++ = '\0';
21248
21249 if (!sscanf(port, "%5u", portnum)) {
21250 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
21251 port = NULL;
21252 }
21253 }
21254
21255 if (!port) {
21256 if (*transport & SIP_TRANSPORT_TLS) {
21257 *portnum = STANDARD_TLS_PORT;
21258 } else {
21259 *portnum = STANDARD_SIP_PORT;
21260 }
21261 }
21262
21263 return 0;
21264 }
21265
21266
21267
21268
21269
21270
21271 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
21272 {
21273 struct sip_mailbox *mailbox;
21274
21275 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21276 struct ast_event *event;
21277 event = ast_event_get_cached(AST_EVENT_MWI,
21278 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21279 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21280 AST_EVENT_IE_END);
21281 if (!event)
21282 continue;
21283 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
21284 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
21285 ast_event_destroy(event);
21286 }
21287
21288 return (*new || *old) ? 0 : 1;
21289 }
21290
21291
21292 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
21293 {
21294
21295 struct sip_pvt *p;
21296 int newmsgs = 0, oldmsgs = 0;
21297
21298 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
21299 return 0;
21300
21301
21302 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
21303 return 0;
21304
21305 if (event) {
21306 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
21307 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
21308 } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
21309
21310 } else if (cache_only) {
21311 return 0;
21312 } else {
21313 struct ast_str *mailbox_str = ast_str_alloca(512);
21314 peer_mailboxes_to_str(&mailbox_str, peer);
21315 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
21316 }
21317
21318 if (peer->mwipvt) {
21319
21320 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
21321 } else {
21322
21323 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
21324 return -1;
21325
21326
21327
21328
21329 set_socket_transport(&p->socket, 0);
21330 if (create_addr_from_peer(p, peer)) {
21331
21332 dialog_unlink_all(p, TRUE, TRUE);
21333 dialog_unref(p, "unref dialog p just created via sip_alloc");
21334
21335 return 0;
21336 }
21337
21338 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
21339 build_via(p);
21340 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
21341 build_callid_pvt(p);
21342 ao2_t_link(dialogs, p, "Linking in under new name");
21343
21344 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21345 }
21346
21347
21348 ast_set_flag(&p->flags[0], SIP_OUTGOING);
21349
21350 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
21351 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
21352 return 0;
21353 }
21354
21355
21356 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
21357 {
21358
21359 if (!dialog->rtp || !dialog->owner)
21360 return;
21361
21362
21363 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
21364 return;
21365
21366
21367 if (dialog->t38.state == T38_ENABLED)
21368 return;
21369
21370
21371 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
21372 return;
21373
21374
21375 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
21376 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
21377
21378 dialog->lastrtptx = time(NULL);
21379 ast_rtp_sendcng(dialog->rtp, 0);
21380 }
21381
21382
21383
21384
21385
21386
21387
21388
21389 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
21390 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
21391
21392
21393 struct sockaddr_in sin;
21394 ast_rtp_get_peer(dialog->rtp, &sin);
21395 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
21396 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
21397
21398 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
21399 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
21400 sip_pvt_unlock(dialog);
21401 usleep(1);
21402 sip_pvt_lock(dialog);
21403 }
21404 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
21405 dialog->owner->name, (long) (t - dialog->lastrtprx));
21406
21407 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
21408 ast_channel_unlock(dialog->owner);
21409
21410
21411
21412
21413 ast_rtp_set_rtptimeout(dialog->rtp, 0);
21414 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
21415 if (dialog->vrtp) {
21416 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
21417 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
21418 }
21419 }
21420 }
21421 }
21422 }
21423
21424
21425
21426
21427
21428 static void *do_monitor(void *data)
21429 {
21430 int res;
21431 time_t t;
21432 int reloading;
21433
21434
21435 if (sipsock > -1)
21436 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
21437
21438
21439 for(;;) {
21440
21441 ast_mutex_lock(&sip_reload_lock);
21442 reloading = sip_reloading;
21443 sip_reloading = FALSE;
21444 ast_mutex_unlock(&sip_reload_lock);
21445 if (reloading) {
21446 ast_verb(1, "Reloading SIP\n");
21447 sip_do_reload(sip_reloadreason);
21448
21449
21450 if (sipsock > -1) {
21451 if (sipsock_read_id)
21452 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
21453 else
21454 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
21455 } else if (sipsock_read_id) {
21456 ast_io_remove(io, sipsock_read_id);
21457 sipsock_read_id = NULL;
21458 }
21459 }
21460
21461
21462 t = time(NULL);
21463
21464
21465
21466
21467 ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
21468 "callback to remove dialogs w/needdestroy");
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480 pthread_testcancel();
21481
21482 res = ast_sched_wait(sched);
21483 if ((res < 0) || (res > 1000))
21484 res = 1000;
21485 res = ast_io_wait(io, res);
21486 if (res > 20)
21487 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
21488 ast_mutex_lock(&monlock);
21489 res = ast_sched_runq(sched);
21490 if (res >= 20)
21491 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
21492 ast_mutex_unlock(&monlock);
21493 }
21494
21495
21496 return NULL;
21497 }
21498
21499
21500 static int restart_monitor(void)
21501 {
21502
21503 if (monitor_thread == AST_PTHREADT_STOP)
21504 return 0;
21505 ast_mutex_lock(&monlock);
21506 if (monitor_thread == pthread_self()) {
21507 ast_mutex_unlock(&monlock);
21508 ast_log(LOG_WARNING, "Cannot kill myself\n");
21509 return -1;
21510 }
21511 if (monitor_thread != AST_PTHREADT_NULL) {
21512
21513 pthread_kill(monitor_thread, SIGURG);
21514 } else {
21515
21516 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
21517 ast_mutex_unlock(&monlock);
21518 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
21519 return -1;
21520 }
21521 }
21522 ast_mutex_unlock(&monlock);
21523 return 0;
21524 }
21525
21526
21527
21528 static void restart_session_timer(struct sip_pvt *p)
21529 {
21530 if (!p->stimer) {
21531 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
21532 return;
21533 }
21534
21535 if (p->stimer->st_active == TRUE) {
21536 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
21537 dialog_unref(p, "Removing session timer ref"));
21538 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
21539 start_session_timer(p);
21540 }
21541 }
21542
21543
21544
21545 static void stop_session_timer(struct sip_pvt *p)
21546 {
21547 if (!p->stimer) {
21548 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
21549 return;
21550 }
21551
21552 if (p->stimer->st_active == TRUE) {
21553 p->stimer->st_active = FALSE;
21554 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
21555 dialog_unref(p, "removing session timer ref"));
21556 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
21557 }
21558 }
21559
21560
21561
21562 static void start_session_timer(struct sip_pvt *p)
21563 {
21564 if (!p->stimer) {
21565 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
21566 return;
21567 }
21568
21569 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
21570 dialog_ref(p, "adding session timer ref"));
21571 if (p->stimer->st_schedid < 0) {
21572 dialog_unref(p, "removing session timer ref");
21573 ast_log(LOG_ERROR, "ast_sched_add failed.\n");
21574 }
21575 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
21576 }
21577
21578
21579
21580 static int proc_session_timer(const void *vp)
21581 {
21582 struct sip_pvt *p = (struct sip_pvt *) vp;
21583 int sendreinv = FALSE;
21584 int res = 0;
21585
21586 if (!p->stimer) {
21587 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
21588 goto return_unref;
21589 }
21590
21591 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
21592
21593 if (!p->owner) {
21594 goto return_unref;
21595 }
21596
21597 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
21598 goto return_unref;
21599 }
21600
21601 switch (p->stimer->st_ref) {
21602 case SESSION_TIMER_REFRESHER_UAC:
21603 if (p->outgoing_call == TRUE) {
21604 sendreinv = TRUE;
21605 }
21606 break;
21607 case SESSION_TIMER_REFRESHER_UAS:
21608 if (p->outgoing_call != TRUE) {
21609 sendreinv = TRUE;
21610 }
21611 break;
21612 default:
21613 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
21614 goto return_unref;
21615 }
21616
21617 if (sendreinv == TRUE) {
21618 res = 1;
21619 transmit_reinvite_with_sdp(p, FALSE, TRUE);
21620 } else {
21621 p->stimer->st_expirys++;
21622 if (p->stimer->st_expirys >= 2) {
21623 if (p->stimer->quit_flag) {
21624 goto return_unref;
21625 }
21626 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
21627 sip_pvt_lock(p);
21628 while (p->owner && ast_channel_trylock(p->owner)) {
21629 sip_pvt_unlock(p);
21630 usleep(1);
21631 if (p->stimer && p->stimer->quit_flag) {
21632 goto return_unref;
21633 }
21634 sip_pvt_lock(p);
21635 }
21636
21637 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
21638 ast_channel_unlock(p->owner);
21639 sip_pvt_unlock(p);
21640 }
21641 }
21642
21643 return_unref:
21644 if (!res) {
21645
21646 if (p->stimer) {
21647 p->stimer->st_schedid = -1;
21648 stop_session_timer(p);
21649 }
21650
21651
21652
21653 dialog_unref(p, "removing session timer ref");
21654 }
21655
21656 return res;
21657 }
21658
21659
21660
21661 int parse_minse (const char *p_hdrval, int *const p_interval)
21662 {
21663 if (ast_strlen_zero(p_hdrval)) {
21664 ast_log(LOG_WARNING, "Null Min-SE header\n");
21665 return -1;
21666 }
21667
21668 *p_interval = 0;
21669 p_hdrval = ast_skip_blanks(p_hdrval);
21670 if (!sscanf(p_hdrval, "%30d", p_interval)) {
21671 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
21672 return -1;
21673 }
21674
21675 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
21676 return 0;
21677 }
21678
21679
21680
21681 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
21682 {
21683 char *p_token;
21684 int ref_idx;
21685 char *p_se_hdr;
21686
21687 if (ast_strlen_zero(p_hdrval)) {
21688 ast_log(LOG_WARNING, "Null Session-Expires header\n");
21689 return -1;
21690 }
21691
21692 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
21693 *p_interval = 0;
21694
21695 p_se_hdr = ast_strdupa(p_hdrval);
21696 p_se_hdr = ast_skip_blanks(p_se_hdr);
21697
21698 while ((p_token = strsep(&p_se_hdr, ";"))) {
21699 p_token = ast_skip_blanks(p_token);
21700 if (!sscanf(p_token, "%30d", p_interval)) {
21701 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
21702 return -1;
21703 }
21704
21705 ast_debug(2, "Session-Expires: %d\n", *p_interval);
21706
21707 if (!p_se_hdr)
21708 continue;
21709
21710 p_se_hdr = ast_skip_blanks(p_se_hdr);
21711 ref_idx = strlen("refresher=");
21712 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
21713 p_se_hdr += ref_idx;
21714 p_se_hdr = ast_skip_blanks(p_se_hdr);
21715
21716 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
21717 *p_ref = SESSION_TIMER_REFRESHER_UAC;
21718 ast_debug(2, "Refresher: UAC\n");
21719 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
21720 *p_ref = SESSION_TIMER_REFRESHER_UAS;
21721 ast_debug(2, "Refresher: UAS\n");
21722 } else {
21723 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
21724 return -1;
21725 }
21726 break;
21727 }
21728 }
21729 return 0;
21730 }
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
21741 {
21742 int rtn;
21743 const char *p_hdrval;
21744 int minse;
21745
21746 p_hdrval = get_header(rsp, "Min-SE");
21747 if (ast_strlen_zero(p_hdrval)) {
21748 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
21749 return;
21750 }
21751 rtn = parse_minse(p_hdrval, &minse);
21752 if (rtn != 0) {
21753 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
21754 return;
21755 }
21756 p->stimer->st_interval = minse;
21757 transmit_invite(p, SIP_INVITE, 1, 2);
21758 }
21759
21760
21761
21762
21763
21764
21765 int st_get_se(struct sip_pvt *p, int max)
21766 {
21767 if (max == TRUE) {
21768 if (p->stimer->st_cached_max_se) {
21769 return p->stimer->st_cached_max_se;
21770 } else if (p->peername) {
21771 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
21772 if (pp) {
21773 p->stimer->st_cached_max_se = pp->stimer.st_max_se;
21774 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
21775 return (p->stimer->st_cached_max_se);
21776 }
21777 }
21778 p->stimer->st_cached_max_se = global_max_se;
21779 return (p->stimer->st_cached_max_se);
21780 } else {
21781 if (p->stimer->st_cached_min_se) {
21782 return p->stimer->st_cached_min_se;
21783 } else if (p->peername) {
21784 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
21785 if (pp) {
21786 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
21787 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
21788 return (p->stimer->st_cached_min_se);
21789 }
21790 }
21791 p->stimer->st_cached_min_se = global_min_se;
21792 return (p->stimer->st_cached_min_se);
21793 }
21794 }
21795
21796
21797
21798
21799
21800 enum st_refresher st_get_refresher(struct sip_pvt *p)
21801 {
21802 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
21803 return p->stimer->st_cached_ref;
21804
21805 if (p->peername) {
21806 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
21807 if (pp) {
21808 p->stimer->st_cached_ref = pp->stimer.st_ref;
21809 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
21810 return pp->stimer.st_ref;
21811 }
21812 }
21813
21814 p->stimer->st_cached_ref = global_st_refresher;
21815 return global_st_refresher;
21816 }
21817
21818
21819
21820
21821
21822 enum st_mode st_get_mode(struct sip_pvt *p)
21823 {
21824 if (!p->stimer)
21825 sip_st_alloc(p);
21826
21827 if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
21828 return p->stimer->st_cached_mode;
21829
21830 if (p->peername) {
21831 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
21832 if (pp) {
21833 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
21834 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
21835 return pp->stimer.st_mode_oper;
21836 }
21837 }
21838
21839 p->stimer->st_cached_mode = global_st_mode;
21840 return global_st_mode;
21841 }
21842
21843
21844
21845 static int sip_poke_noanswer(const void *data)
21846 {
21847 struct sip_peer *peer = (struct sip_peer *)data;
21848
21849 peer->pokeexpire = -1;
21850
21851 if (peer->lastms > -1) {
21852 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
21853 if (sip_cfg.peer_rtupdate) {
21854 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
21855 }
21856 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
21857 if (global_regextenonqualify) {
21858 register_peer_exten(peer, FALSE);
21859 }
21860 }
21861
21862 if (peer->call) {
21863 dialog_unlink_all(peer->call, TRUE, TRUE);
21864 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21865
21866 }
21867
21868 peer->lastms = -1;
21869 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
21870
21871
21872 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
21873 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
21874 unref_peer(_data, "removing poke peer ref"),
21875 unref_peer(peer, "removing poke peer ref"),
21876 ref_peer(peer, "adding poke peer ref"));
21877
21878
21879 unref_peer(peer, "release peer poke noanswer ref");
21880
21881 return 0;
21882 }
21883
21884
21885
21886
21887
21888
21889 static int sip_poke_peer(struct sip_peer *peer, int force)
21890 {
21891 struct sip_pvt *p;
21892 int xmitres = 0;
21893
21894 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
21895
21896
21897 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
21898 unref_peer(peer, "removing poke peer ref"));
21899
21900 peer->lastms = 0;
21901 if (peer->call) {
21902 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21903 }
21904 return 0;
21905 }
21906 if (peer->call) {
21907 if (sipdebug) {
21908 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
21909 }
21910 dialog_unlink_all(peer->call, TRUE, TRUE);
21911 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21912
21913 }
21914 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
21915 return -1;
21916 }
21917 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
21918
21919 p->sa = peer->addr;
21920 p->recv = peer->addr;
21921 copy_socket_data(&p->socket, &peer->socket);
21922 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
21923 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
21924
21925
21926 if (!ast_strlen_zero(peer->fullcontact))
21927 ast_string_field_set(p, fullcontact, peer->fullcontact);
21928
21929 if (!ast_strlen_zero(peer->tohost))
21930 ast_string_field_set(p, tohost, peer->tohost);
21931 else
21932 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
21933
21934
21935 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
21936 build_via(p);
21937 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
21938 build_callid_pvt(p);
21939 ao2_t_link(dialogs, p, "Linking in under new name");
21940
21941 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
21942 unref_peer(peer, "removing poke peer ref"));
21943
21944 if (p->relatedpeer)
21945 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
21946 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
21947 ast_set_flag(&p->flags[0], SIP_OUTGOING);
21948 #ifdef VOCAL_DATA_HACK
21949 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
21950 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
21951 #else
21952 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
21953 #endif
21954 peer->ps = ast_tvnow();
21955 if (xmitres == XMIT_ERROR) {
21956 sip_poke_noanswer(peer);
21957 } else if (!force) {
21958 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
21959 unref_peer(_data, "removing poke peer ref"),
21960 unref_peer(peer, "removing poke peer ref"),
21961 ref_peer(peer, "adding poke peer ref"));
21962 }
21963 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
21964 return 0;
21965 }
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000 static int sip_devicestate(void *data)
22001 {
22002 char *host;
22003 char *tmp;
22004 struct sip_peer *p;
22005
22006 int res = AST_DEVICE_INVALID;
22007
22008
22009 host = ast_strdupa(data ? data : "");
22010 if ((tmp = strchr(host, '@')))
22011 host = tmp + 1;
22012
22013 ast_debug(3, "Checking device state for peer %s\n", host);
22014
22015
22016
22017
22018
22019
22020
22021
22022 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
22023 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035 if (p->onHold)
22036
22037 res = AST_DEVICE_ONHOLD;
22038 else if (p->inRinging) {
22039 if (p->inRinging == p->inUse)
22040 res = AST_DEVICE_RINGING;
22041 else
22042 res = AST_DEVICE_RINGINUSE;
22043 } else if (p->call_limit && (p->inUse == p->call_limit))
22044
22045 res = AST_DEVICE_BUSY;
22046 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
22047
22048 res = AST_DEVICE_BUSY;
22049 else if (p->call_limit && p->inUse)
22050
22051 res = AST_DEVICE_INUSE;
22052 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
22053
22054 res = AST_DEVICE_UNAVAILABLE;
22055 else
22056 res = AST_DEVICE_NOT_INUSE;
22057 } else {
22058
22059 res = AST_DEVICE_UNAVAILABLE;
22060 }
22061 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
22062 } else {
22063 res = AST_DEVICE_UNKNOWN;
22064 }
22065
22066 return res;
22067 }
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
22080 {
22081 struct sip_pvt *p;
22082 struct ast_channel *tmpc = NULL;
22083 char *ext = NULL, *host;
22084 char tmp[256];
22085 char *dest = data;
22086 char *dnid;
22087 char *secret = NULL;
22088 char *md5secret = NULL;
22089 char *authname = NULL;
22090 char *trans = NULL;
22091 enum sip_transport transport = 0;
22092 int oldformat = format;
22093
22094
22095
22096
22097
22098
22099
22100
22101 format &= AST_FORMAT_AUDIO_MASK;
22102 if (!format) {
22103 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));
22104 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
22105 return NULL;
22106 }
22107 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
22108
22109 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
22110 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
22111 *cause = AST_CAUSE_SWITCH_CONGESTION;
22112 return NULL;
22113 }
22114
22115 p->outgoing_call = TRUE;
22116
22117 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
22118 dialog_unlink_all(p, TRUE, TRUE);
22119 dialog_unref(p, "unref dialog p from mem fail");
22120
22121 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
22122 *cause = AST_CAUSE_SWITCH_CONGESTION;
22123 return NULL;
22124 }
22125
22126
22127 ast_copy_string(tmp, dest, sizeof(tmp));
22128
22129
22130
22131 dnid = strchr(tmp, '!');
22132 if (dnid != NULL) {
22133 *dnid++ = '\0';
22134 ast_string_field_set(p, todnid, dnid);
22135 }
22136
22137
22138 host = strchr(tmp, '@');
22139 if (host) {
22140 *host++ = '\0';
22141 ext = tmp;
22142 secret = strchr(ext, ':');
22143 }
22144 if (secret) {
22145 *secret++ = '\0';
22146 md5secret = strchr(secret, ':');
22147 }
22148 if (md5secret) {
22149 *md5secret++ = '\0';
22150 authname = strchr(md5secret, ':');
22151 }
22152 if (authname) {
22153 *authname++ = '\0';
22154 trans = strchr(authname, ':');
22155 }
22156 if (trans) {
22157 *trans++ = '\0';
22158 if (!strcasecmp(trans, "tcp"))
22159 transport = SIP_TRANSPORT_TCP;
22160 else if (!strcasecmp(trans, "tls"))
22161 transport = SIP_TRANSPORT_TLS;
22162 else {
22163 if (strcasecmp(trans, "udp"))
22164 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
22165 transport = SIP_TRANSPORT_UDP;
22166 }
22167 } else {
22168 transport = SIP_TRANSPORT_UDP;
22169 }
22170
22171 if (!host) {
22172 ext = strchr(tmp, '/');
22173 if (ext)
22174 *ext++ = '\0';
22175 host = tmp;
22176 }
22177
22178 set_socket_transport(&p->socket, transport);
22179
22180
22181
22182
22183
22184
22185 if (create_addr(p, host, NULL, 1)) {
22186 *cause = AST_CAUSE_UNREGISTERED;
22187 ast_debug(3, "Cant create SIP call - target device not registered\n");
22188 dialog_unlink_all(p, TRUE, TRUE);
22189 dialog_unref(p, "unref dialog p UNREGISTERED");
22190
22191 return NULL;
22192 }
22193 if (ast_strlen_zero(p->peername) && ext)
22194 ast_string_field_set(p, peername, ext);
22195
22196 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22197 build_via(p);
22198 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22199 build_callid_pvt(p);
22200 ao2_t_link(dialogs, p, "Linking in under new name");
22201
22202
22203
22204
22205
22206
22207 if (ext) {
22208 ast_string_field_set(p, username, ext);
22209 ast_string_field_set(p, fullcontact, NULL);
22210 }
22211 if (secret && !ast_strlen_zero(secret))
22212 ast_string_field_set(p, peersecret, secret);
22213
22214 if (md5secret && !ast_strlen_zero(md5secret))
22215 ast_string_field_set(p, peermd5secret, md5secret);
22216
22217 if (authname && !ast_strlen_zero(authname))
22218 ast_string_field_set(p, authname, authname);
22219 #if 0
22220 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
22221 #endif
22222 p->prefcodec = oldformat;
22223 p->jointcapability = oldformat;
22224 sip_pvt_lock(p);
22225 tmpc = sip_new(p, AST_STATE_DOWN, host);
22226 if (global_callevents)
22227 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
22228 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
22229 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
22230 sip_pvt_unlock(p);
22231 if (!tmpc) {
22232 dialog_unlink_all(p, TRUE, TRUE);
22233
22234 }
22235 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
22236 ast_update_use_count();
22237 restart_monitor();
22238 return tmpc;
22239 }
22240
22241
22242 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
22243 {
22244 if (ast_strlen_zero(value))
22245 return;
22246
22247 if (!ast_false(value)) {
22248 char buf[64];
22249 char *word, *next;
22250
22251 ast_copy_string(buf, value, sizeof(buf));
22252 next = buf;
22253 while ((word = strsep(&next, ","))) {
22254 if (!strcasecmp(word, "port"))
22255 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
22256 else if (!strcasecmp(word, "invite"))
22257 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
22258 else
22259 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
22260 }
22261 }
22262 }
22263
22264
22265
22266
22267
22268 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
22269 int *maxdatagram)
22270 {
22271 int res = 1;
22272
22273 if (!strcasecmp(v->name, "t38pt_udptl")) {
22274 char *buf = ast_strdupa(v->value);
22275 char *word, *next = buf;
22276
22277 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
22278
22279 while ((word = strsep(&next, ","))) {
22280 if (ast_true(word) || !strcasecmp(word, "fec")) {
22281 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
22282 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
22283 } else if (!strcasecmp(word, "redundancy")) {
22284 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
22285 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
22286 } else if (!strcasecmp(word, "none")) {
22287 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
22288 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
22289 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
22290 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
22291 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
22292 *maxdatagram = global_t38_maxdatagram;
22293 }
22294 }
22295 }
22296 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
22297 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
22298 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
22299 } else {
22300 res = 0;
22301 }
22302
22303 return res;
22304 }
22305
22306
22307
22308
22309
22310
22311
22312
22313 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
22314 {
22315 int res = 1;
22316
22317 if (!strcasecmp(v->name, "trustrpid")) {
22318 ast_set_flag(&mask[0], SIP_TRUSTRPID);
22319 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
22320 } else if (!strcasecmp(v->name, "sendrpid")) {
22321 ast_set_flag(&mask[0], SIP_SENDRPID);
22322 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
22323 } else if (!strcasecmp(v->name, "g726nonstandard")) {
22324 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
22325 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
22326 } else if (!strcasecmp(v->name, "useclientcode")) {
22327 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
22328 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
22329 } else if (!strcasecmp(v->name, "dtmfmode")) {
22330 ast_set_flag(&mask[0], SIP_DTMF);
22331 ast_clear_flag(&flags[0], SIP_DTMF);
22332 if (!strcasecmp(v->value, "inband"))
22333 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
22334 else if (!strcasecmp(v->value, "rfc2833"))
22335 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
22336 else if (!strcasecmp(v->value, "info"))
22337 ast_set_flag(&flags[0], SIP_DTMF_INFO);
22338 else if (!strcasecmp(v->value, "shortinfo"))
22339 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
22340 else if (!strcasecmp(v->value, "auto"))
22341 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
22342 else {
22343 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
22344 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
22345 }
22346 } else if (!strcasecmp(v->name, "nat")) {
22347 ast_set_flag(&mask[0], SIP_NAT);
22348 ast_clear_flag(&flags[0], SIP_NAT);
22349 if (!strcasecmp(v->value, "never"))
22350 ast_set_flag(&flags[0], SIP_NAT_NEVER);
22351 else if (!strcasecmp(v->value, "route"))
22352 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
22353 else if (ast_true(v->value))
22354 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
22355 else
22356 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
22357 } else if (!strcasecmp(v->name, "canreinvite")) {
22358 ast_set_flag(&mask[0], SIP_REINVITE);
22359 ast_clear_flag(&flags[0], SIP_REINVITE);
22360 if (ast_true(v->value)) {
22361 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
22362 } else if (!ast_false(v->value)) {
22363 char buf[64];
22364 char *word, *next = buf;
22365
22366 ast_copy_string(buf, v->value, sizeof(buf));
22367 while ((word = strsep(&next, ","))) {
22368 if (!strcasecmp(word, "update")) {
22369 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
22370 } else if (!strcasecmp(word, "nonat")) {
22371 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
22372 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
22373 } else {
22374 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
22375 }
22376 }
22377 }
22378 } else if (!strcasecmp(v->name, "insecure")) {
22379 ast_set_flag(&mask[0], SIP_INSECURE);
22380 ast_clear_flag(&flags[0], SIP_INSECURE);
22381 set_insecure_flags(&flags[0], v->value, v->lineno);
22382 } else if (!strcasecmp(v->name, "progressinband")) {
22383 ast_set_flag(&mask[0], SIP_PROG_INBAND);
22384 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
22385 if (ast_true(v->value))
22386 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
22387 else if (strcasecmp(v->value, "never"))
22388 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
22389 } else if (!strcasecmp(v->name, "promiscredir")) {
22390 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
22391 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
22392 } else if (!strcasecmp(v->name, "videosupport")) {
22393 if (!strcasecmp(v->value, "always")) {
22394 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
22395 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
22396 } else {
22397 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
22398 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
22399 }
22400 } else if (!strcasecmp(v->name, "textsupport")) {
22401 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
22402 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
22403 res = 1;
22404 } else if (!strcasecmp(v->name, "allowoverlap")) {
22405 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
22406 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
22407 } else if (!strcasecmp(v->name, "allowsubscribe")) {
22408 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
22409 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
22410 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
22411 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
22412 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
22413 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
22414 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
22415 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
22416 } else if (!strcasecmp(v->name, "buggymwi")) {
22417 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
22418 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
22419 } else if (!strcasecmp(v->name, "constantssrc")) {
22420 ast_set_flag(&mask[1], SIP_PAGE2_CONSTANT_SSRC);
22421 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_CONSTANT_SSRC);
22422 } else if (!strcasecmp(v->name, "faxdetect")) {
22423 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
22424 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FAX_DETECT);
22425 } else
22426 res = 0;
22427
22428 return res;
22429 }
22430
22431
22432 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
22433 {
22434 struct domain *d;
22435
22436 if (ast_strlen_zero(domain)) {
22437 ast_log(LOG_WARNING, "Zero length domain.\n");
22438 return 1;
22439 }
22440
22441 if (!(d = ast_calloc(1, sizeof(*d))))
22442 return 0;
22443
22444 ast_copy_string(d->domain, domain, sizeof(d->domain));
22445
22446 if (!ast_strlen_zero(context))
22447 ast_copy_string(d->context, context, sizeof(d->context));
22448
22449 d->mode = mode;
22450
22451 AST_LIST_LOCK(&domain_list);
22452 AST_LIST_INSERT_TAIL(&domain_list, d, list);
22453 AST_LIST_UNLOCK(&domain_list);
22454
22455 if (sipdebug)
22456 ast_debug(1, "Added local SIP domain '%s'\n", domain);
22457
22458 return 1;
22459 }
22460
22461
22462 static int check_sip_domain(const char *domain, char *context, size_t len)
22463 {
22464 struct domain *d;
22465 int result = 0;
22466
22467 AST_LIST_LOCK(&domain_list);
22468 AST_LIST_TRAVERSE(&domain_list, d, list) {
22469 if (strcasecmp(d->domain, domain))
22470 continue;
22471
22472 if (len && !ast_strlen_zero(d->context))
22473 ast_copy_string(context, d->context, len);
22474
22475 result = 1;
22476 break;
22477 }
22478 AST_LIST_UNLOCK(&domain_list);
22479
22480 return result;
22481 }
22482
22483
22484 static void clear_sip_domains(void)
22485 {
22486 struct domain *d;
22487
22488 AST_LIST_LOCK(&domain_list);
22489 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
22490 ast_free(d);
22491 AST_LIST_UNLOCK(&domain_list);
22492 }
22493
22494
22495
22496 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
22497 {
22498 char authcopy[256];
22499 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
22500 struct sip_auth *a, *b, *auth;
22501
22502 if (ast_strlen_zero(configuration))
22503 return authlist;
22504
22505 ast_debug(1, "Auth config :: %s\n", configuration);
22506
22507 ast_copy_string(authcopy, configuration, sizeof(authcopy));
22508 username = authcopy;
22509
22510
22511 realm = strrchr(username, '@');
22512 if (realm)
22513 *realm++ = '\0';
22514 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
22515 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
22516 return authlist;
22517 }
22518
22519
22520 if ((secret = strchr(username, ':'))) {
22521 *secret++ = '\0';
22522 } else if ((md5secret = strchr(username, '#'))) {
22523 *md5secret++ = '\0';
22524 }
22525
22526 if (!(auth = ast_calloc(1, sizeof(*auth))))
22527 return authlist;
22528
22529 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
22530 ast_copy_string(auth->username, username, sizeof(auth->username));
22531 if (secret)
22532 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
22533 if (md5secret)
22534 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
22535
22536
22537 for (b = NULL, a = authlist; a ; b = a, a = a->next)
22538 ;
22539 if (b)
22540 b->next = auth;
22541 else
22542 authlist = auth;
22543
22544 ast_verb(3, "Added authentication for realm %s\n", realm);
22545
22546 return authlist;
22547
22548 }
22549
22550
22551 static int clear_realm_authentication(struct sip_auth *authlist)
22552 {
22553 struct sip_auth *a = authlist;
22554 struct sip_auth *b;
22555
22556 while (a) {
22557 b = a;
22558 a = a->next;
22559 ast_free(b);
22560 }
22561
22562 return 1;
22563 }
22564
22565
22566 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
22567 {
22568 struct sip_auth *a;
22569
22570 for (a = authlist; a; a = a->next) {
22571 if (!strcasecmp(a->realm, realm))
22572 break;
22573 }
22574
22575 return a;
22576 }
22577
22578
22579
22580
22581 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
22582 {
22583 struct ast_variable *tmpvar = NULL;
22584 char *varname = ast_strdupa(buf), *varval = NULL;
22585
22586 if ((varval = strchr(varname, '='))) {
22587 *varval++ = '\0';
22588 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
22589 tmpvar->next = list;
22590 list = tmpvar;
22591 }
22592 }
22593 return list;
22594 }
22595
22596
22597 static void set_peer_defaults(struct sip_peer *peer)
22598 {
22599 if (peer->expire == 0) {
22600
22601
22602
22603 peer->expire = -1;
22604 peer->pokeexpire = -1;
22605 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
22606 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
22607 }
22608 peer->type = SIP_TYPE_PEER;
22609 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
22610 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
22611 strcpy(peer->context, default_context);
22612 strcpy(peer->subscribecontext, default_subscribecontext);
22613 strcpy(peer->language, default_language);
22614 strcpy(peer->mohinterpret, default_mohinterpret);
22615 strcpy(peer->mohsuggest, default_mohsuggest);
22616 peer->addr.sin_family = AF_INET;
22617 peer->defaddr.sin_family = AF_INET;
22618 peer->capability = global_capability;
22619 peer->maxcallbitrate = default_maxcallbitrate;
22620 peer->rtptimeout = global_rtptimeout;
22621 peer->rtpholdtimeout = global_rtpholdtimeout;
22622 peer->rtpkeepalive = global_rtpkeepalive;
22623 peer->allowtransfer = global_allowtransfer;
22624 peer->autoframing = global_autoframing;
22625 peer->t38_maxdatagram = global_t38_maxdatagram;
22626 peer->qualifyfreq = global_qualifyfreq;
22627 if (global_callcounter)
22628 peer->call_limit=999;
22629 strcpy(peer->vmexten, default_vmexten);
22630 peer->secret[0] = '\0';
22631 peer->md5secret[0] = '\0';
22632 peer->cid_num[0] = '\0';
22633 peer->cid_name[0] = '\0';
22634 peer->fromdomain[0] = '\0';
22635 peer->fromuser[0] = '\0';
22636 peer->regexten[0] = '\0';
22637 peer->callgroup = 0;
22638 peer->pickupgroup = 0;
22639 peer->maxms = default_qualify;
22640 peer->prefs = default_prefs;
22641 peer->stimer.st_mode_oper = global_st_mode;
22642 peer->stimer.st_ref = global_st_refresher;
22643 peer->stimer.st_min_se = global_min_se;
22644 peer->stimer.st_max_se = global_max_se;
22645 peer->timer_t1 = global_t1;
22646 peer->timer_b = global_timer_b;
22647 clear_peer_mailboxes(peer);
22648 }
22649
22650
22651 static struct sip_peer *temp_peer(const char *name)
22652 {
22653 struct sip_peer *peer;
22654
22655 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
22656 return NULL;
22657
22658 ast_atomic_fetchadd_int(&apeerobjs, 1);
22659 set_peer_defaults(peer);
22660
22661 ast_copy_string(peer->name, name, sizeof(peer->name));
22662
22663 peer->selfdestruct = TRUE;
22664 peer->host_dynamic = TRUE;
22665 peer->prefs = default_prefs;
22666 reg_source_db(peer);
22667
22668 return peer;
22669 }
22670
22671
22672 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
22673 {
22674 char *next, *mbox, *context;
22675
22676 next = ast_strdupa(value);
22677
22678 while ((mbox = context = strsep(&next, ","))) {
22679 struct sip_mailbox *mailbox;
22680
22681 if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
22682 continue;
22683
22684 strsep(&context, "@");
22685 if (ast_strlen_zero(mbox)) {
22686 ast_free(mailbox);
22687 continue;
22688 }
22689 mailbox->mailbox = ast_strdup(mbox);
22690 mailbox->context = ast_strdup(context);
22691
22692 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
22693 }
22694 }
22695
22696
22697 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
22698 {
22699 struct sip_peer *peer = NULL;
22700 struct ast_ha *oldha = NULL;
22701 int found = 0;
22702 int firstpass = 1;
22703 uint16_t port = 0;
22704 int format = 0;
22705 time_t regseconds = 0;
22706 struct ast_flags peerflags[2] = {{(0)}};
22707 struct ast_flags mask[2] = {{(0)}};
22708 char callback[256] = "";
22709 struct sip_peer tmp_peer;
22710 const char *srvlookup = NULL;
22711 static int deprecation_warning = 1;
22712 int alt_fullcontact = alt ? 1 : 0;
22713 struct ast_str *fullcontact = ast_str_alloca(512);
22714
22715 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
22716
22717
22718
22719
22720
22721 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
22722 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
22723 }
22724
22725 if (peer) {
22726
22727 found++;
22728 if (!(peer->the_mark))
22729 firstpass = 0;
22730 } else {
22731 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
22732 return NULL;
22733
22734 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
22735 ast_atomic_fetchadd_int(&rpeerobjs, 1);
22736 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
22737 } else
22738 ast_atomic_fetchadd_int(&speerobjs, 1);
22739 }
22740
22741
22742 if (firstpass) {
22743 peer->lastmsgssent = -1;
22744 oldha = peer->ha;
22745 peer->ha = NULL;
22746 set_peer_defaults(peer);
22747 peer->type = 0;
22748 }
22749 if (!found && name)
22750 ast_copy_string(peer->name, name, sizeof(peer->name));
22751
22752
22753 if (peer->chanvars) {
22754 ast_variables_destroy(peer->chanvars);
22755 peer->chanvars = NULL;
22756
22757 }
22758
22759 if (found)
22760 peer->portinuri = 0;
22761
22762
22763 clear_realm_authentication(peer->auth);
22764 peer->auth = NULL;
22765 peer->default_outbound_transport = 0;
22766 peer->transports = 0;
22767
22768 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
22769 if (!devstate_only) {
22770 if (handle_common_options(&peerflags[0], &mask[0], v)) {
22771 continue;
22772 }
22773 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
22774 continue;
22775 }
22776 if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
22777 char *val = ast_strdupa(v->value);
22778 char *trans;
22779
22780 while ((trans = strsep(&val, ","))) {
22781 trans = ast_skip_blanks(trans);
22782
22783 if (!strncasecmp(trans, "udp", 3)) {
22784 peer->transports |= SIP_TRANSPORT_UDP;
22785 } else if (!strncasecmp(trans, "tcp", 3)) {
22786 peer->transports |= SIP_TRANSPORT_TCP;
22787 } else if (!strncasecmp(trans, "tls", 3)) {
22788 peer->transports |= SIP_TRANSPORT_TLS;
22789 } else {
22790 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
22791 }
22792
22793 if (!peer->default_outbound_transport) {
22794 peer->default_outbound_transport = peer->transports;
22795 }
22796 }
22797 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
22798 ast_get_time_t(v->value, ®seconds, 0, NULL);
22799 } else if (realtime && !strcasecmp(v->name, "name")) {
22800 ast_copy_string(peer->name, v->value, sizeof(peer->name));
22801 } else if (!strcasecmp(v->name, "type")) {
22802 if (!strcasecmp(v->value, "peer")) {
22803 peer->type |= SIP_TYPE_PEER;
22804 } else if (!strcasecmp(v->value, "user")) {
22805 peer->type |= SIP_TYPE_USER;
22806 } else if (!strcasecmp(v->value, "friend")) {
22807 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
22808 }
22809 } else if (!strcasecmp(v->name, "secret")) {
22810 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
22811 } else if (!strcasecmp(v->name, "md5secret")) {
22812 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
22813 } else if (!strcasecmp(v->name, "auth")) {
22814 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
22815 } else if (!strcasecmp(v->name, "callerid")) {
22816 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
22817 } else if (!strcasecmp(v->name, "fullname")) {
22818 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
22819 } else if (!strcasecmp(v->name, "trunkname")) {
22820
22821 ast_copy_string(peer->cid_name, "", sizeof(peer->cid_name));
22822 } else if (!strcasecmp(v->name, "cid_number")) {
22823 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
22824 } else if (!strcasecmp(v->name, "context")) {
22825 ast_copy_string(peer->context, v->value, sizeof(peer->context));
22826 } else if (!strcasecmp(v->name, "subscribecontext")) {
22827 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
22828 } else if (!strcasecmp(v->name, "fromdomain")) {
22829 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
22830 } else if (!strcasecmp(v->name, "usereqphone")) {
22831 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
22832 } else if (!strcasecmp(v->name, "fromuser")) {
22833 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
22834 } else if (!strcasecmp(v->name, "outboundproxy")) {
22835 char *port, *next, *force, *proxyname;
22836 int forceopt = FALSE;
22837
22838 next = proxyname = ast_strdupa(v->value);
22839 if ((port = strchr(proxyname, ':'))) {
22840 *port++ = '\0';
22841 next = port;
22842 }
22843 if ((force = strchr(next, ','))) {
22844 *force++ = '\0';
22845 forceopt = strcmp(force, "force");
22846 }
22847
22848 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
22849 } else if (!strcasecmp(v->name, "host")) {
22850 if (!strcasecmp(v->value, "dynamic")) {
22851
22852 if (!found || !peer->host_dynamic) {
22853
22854
22855 memset(&peer->addr.sin_addr, 0, 4);
22856 peer->addr.sin_port = 0;
22857 }
22858 peer->host_dynamic = TRUE;
22859 } else {
22860
22861 AST_SCHED_DEL_UNREF(sched, peer->expire,
22862 unref_peer(peer, "removing register expire ref"));
22863
22864 peer->addr.sin_port = 0;
22865 peer->host_dynamic = FALSE;
22866 srvlookup = v->value;
22867 if (global_dynamic_exclude_static) {
22868 int err = 0;
22869 global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
22870 if (err) {
22871 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22872 }
22873 }
22874 }
22875 } else if (!strcasecmp(v->name, "defaultip")) {
22876 if (ast_get_ip(&peer->defaddr, v->value)) {
22877 unref_peer(peer, "unref_peer: from build_peer defaultip");
22878 return NULL;
22879 }
22880 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
22881 int ha_error = 0;
22882 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
22883 if (ha_error) {
22884 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22885 }
22886 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
22887 int ha_error = 0;
22888 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
22889 if (ha_error) {
22890 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22891 }
22892 } else if (!strcasecmp(v->name, "port")) {
22893 peer->portinuri = 1;
22894 if (!(port = port_str2int(v->value, 0))) {
22895 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
22896 }
22897 } else if (!strcasecmp(v->name, "callingpres")) {
22898 peer->callingpres = ast_parse_caller_presentation(v->value);
22899 if (peer->callingpres == -1) {
22900 peer->callingpres = atoi(v->value);
22901 }
22902 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
22903 ast_copy_string(peer->username, v->value, sizeof(peer->username));
22904 if (!strcasecmp(v->name, "username")) {
22905 if (deprecation_warning) {
22906 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
22907 deprecation_warning = 0;
22908 }
22909 peer->deprecated_username = 1;
22910 }
22911 } else if (!strcasecmp(v->name, "language")) {
22912 ast_copy_string(peer->language, v->value, sizeof(peer->language));
22913 } else if (!strcasecmp(v->name, "regexten")) {
22914 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
22915 } else if (!strcasecmp(v->name, "callbackextension")) {
22916 ast_copy_string(callback, v->value, sizeof(callback));
22917 } else if (!strcasecmp(v->name, "amaflags")) {
22918 format = ast_cdr_amaflags2int(v->value);
22919 if (format < 0) {
22920 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
22921 } else {
22922 peer->amaflags = format;
22923 }
22924 } else if (!strcasecmp(v->name, "accountcode")) {
22925 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
22926 } else if (!strcasecmp(v->name, "mohinterpret")) {
22927 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
22928 } else if (!strcasecmp(v->name, "mohsuggest")) {
22929 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
22930 } else if (!strcasecmp(v->name, "parkinglot")) {
22931 ast_copy_string(peer->parkinglot, v->value, sizeof(peer->parkinglot));
22932 } else if (!strcasecmp(v->name, "mailbox")) {
22933 add_peer_mailboxes(peer, v->value);
22934 } else if (!strcasecmp(v->name, "hasvoicemail")) {
22935
22936
22937 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
22938 add_peer_mailboxes(peer, name);
22939 }
22940 } else if (!strcasecmp(v->name, "subscribemwi")) {
22941 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
22942 } else if (!strcasecmp(v->name, "vmexten")) {
22943 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
22944 } else if (!strcasecmp(v->name, "callgroup")) {
22945 peer->callgroup = ast_get_group(v->value);
22946 } else if (!strcasecmp(v->name, "allowtransfer")) {
22947 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
22948 } else if (!strcasecmp(v->name, "pickupgroup")) {
22949 peer->pickupgroup = ast_get_group(v->value);
22950 } else if (!strcasecmp(v->name, "allow")) {
22951 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
22952 if (error) {
22953 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22954 }
22955 } else if (!strcasecmp(v->name, "disallow")) {
22956 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
22957 if (error) {
22958 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22959 }
22960 } else if (!strcasecmp(v->name, "registertrying")) {
22961 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
22962 } else if (!strcasecmp(v->name, "autoframing")) {
22963 peer->autoframing = ast_true(v->value);
22964 } else if (!strcasecmp(v->name, "rtptimeout")) {
22965 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
22966 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
22967 peer->rtptimeout = global_rtptimeout;
22968 }
22969 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
22970 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
22971 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
22972 peer->rtpholdtimeout = global_rtpholdtimeout;
22973 }
22974 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
22975 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
22976 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
22977 peer->rtpkeepalive = global_rtpkeepalive;
22978 }
22979 } else if (!strcasecmp(v->name, "timert1")) {
22980 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
22981 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
22982 peer->timer_t1 = global_t1;
22983 }
22984
22985
22986 if (peer->timer_b < peer->timer_t1 * 64) {
22987 peer->timer_b = peer->timer_t1 * 64;
22988 }
22989 } else if (!strcasecmp(v->name, "timerb")) {
22990 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
22991 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
22992 peer->timer_b = global_timer_b;
22993 }
22994 if (peer->timer_b < peer->timer_t1 * 64) {
22995 static int warning = 0;
22996 if (warning++ % 20 == 0) {
22997 ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
22998 }
22999 }
23000 } else if (!strcasecmp(v->name, "setvar")) {
23001 peer->chanvars = add_var(v->value, peer->chanvars);
23002 } else if (!strcasecmp(v->name, "qualifyfreq")) {
23003 int i;
23004 if (sscanf(v->value, "%30d", &i) == 1) {
23005 peer->qualifyfreq = i * 1000;
23006 } else {
23007 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
23008 peer->qualifyfreq = global_qualifyfreq;
23009 }
23010 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
23011 peer->maxcallbitrate = atoi(v->value);
23012 if (peer->maxcallbitrate < 0) {
23013 peer->maxcallbitrate = default_maxcallbitrate;
23014 }
23015 } else if (!strcasecmp(v->name, "session-timers")) {
23016 int i = (int) str2stmode(v->value);
23017 if (i < 0) {
23018 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
23019 peer->stimer.st_mode_oper = global_st_mode;
23020 } else {
23021 peer->stimer.st_mode_oper = i;
23022 }
23023 } else if (!strcasecmp(v->name, "session-expires")) {
23024 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
23025 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
23026 peer->stimer.st_max_se = global_max_se;
23027 }
23028 } else if (!strcasecmp(v->name, "session-minse")) {
23029 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
23030 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
23031 peer->stimer.st_min_se = global_min_se;
23032 }
23033 if (peer->stimer.st_min_se < 90) {
23034 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
23035 peer->stimer.st_min_se = global_min_se;
23036 }
23037 } else if (!strcasecmp(v->name, "session-refresher")) {
23038 int i = (int) str2strefresher(v->value);
23039 if (i < 0) {
23040 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
23041 peer->stimer.st_ref = global_st_refresher;
23042 } else {
23043 peer->stimer.st_ref = i;
23044 }
23045 }
23046 }
23047
23048
23049 if (realtime && !strcasecmp(v->name, "lastms")) {
23050 sscanf(v->value, "%30d", &peer->lastms);
23051 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
23052 inet_aton(v->value, &(peer->addr.sin_addr));
23053 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
23054 if (alt_fullcontact && !alt) {
23055
23056
23057
23058
23059
23060 alt_fullcontact = 0;
23061 ast_str_reset(fullcontact);
23062 }
23063
23064 if (fullcontact->used > 0) {
23065 ast_str_append(&fullcontact, 0, ";%s", v->value);
23066 } else {
23067 ast_str_set(&fullcontact, 0, "%s", v->value);
23068 }
23069 } else if (!strcasecmp(v->name, "qualify")) {
23070 if (!strcasecmp(v->value, "no")) {
23071 peer->maxms = 0;
23072 } else if (!strcasecmp(v->value, "yes")) {
23073 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
23074 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
23075 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);
23076 peer->maxms = 0;
23077 }
23078 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
23079
23080
23081
23082
23083 ast_log(LOG_WARNING, "Qualify is incompatible with dynamic uncached realtime. Please either turn rtcachefriends on or turn qualify off on peer '%s'\n", peer->name);
23084 peer->maxms = 0;
23085 }
23086 } else if (!strcasecmp(v->name, "callcounter")) {
23087 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
23088 } else if (!strcasecmp(v->name, "call-limit")) {
23089 peer->call_limit = atoi(v->value);
23090 if (peer->call_limit < 0) {
23091 peer->call_limit = 0;
23092 }
23093 } else if (!strcasecmp(v->name, "busylevel")) {
23094 peer->busy_level = atoi(v->value);
23095 if (peer->busy_level < 0) {
23096 peer->busy_level = 0;
23097 }
23098 }
23099 }
23100
23101 if (!peer->default_outbound_transport) {
23102 peer->transports = SIP_TRANSPORT_UDP;
23103 peer->default_outbound_transport = SIP_TRANSPORT_UDP;
23104 }
23105
23106
23107
23108
23109
23110 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
23111 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
23112
23113 set_socket_transport(&peer->socket, peer->default_outbound_transport);
23114 }
23115
23116 if (port && !realtime && peer->host_dynamic) {
23117 peer->defaddr.sin_port = htons(port);
23118 } else if (port) {
23119 peer->addr.sin_port = htons(port);
23120 }
23121
23122 if (ast_str_strlen(fullcontact)) {
23123 ast_copy_string(peer->fullcontact, fullcontact->str, sizeof(peer->fullcontact));
23124 peer->rt_fromcontact = TRUE;
23125
23126
23127
23128
23129
23130
23131
23132
23133 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
23134 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
23135 }
23136 }
23137
23138 if (srvlookup && peer->dnsmgr == NULL) {
23139 char transport[MAXHOSTNAMELEN];
23140 char _srvlookup[MAXHOSTNAMELEN];
23141 char *params;
23142
23143 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
23144 if ((params = strchr(_srvlookup, ';'))) {
23145 *params++ = '\0';
23146 }
23147
23148 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
23149
23150 if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, global_srvlookup && !peer->portinuri ? transport : NULL)) {
23151 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
23152 unref_peer(peer, "getting rid of a peer pointer");
23153 return NULL;
23154 }
23155
23156 ast_copy_string(peer->tohost, srvlookup, sizeof(peer->tohost));
23157 }
23158
23159 if (!peer->addr.sin_port) {
23160 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
23161 }
23162 if (!peer->defaddr.sin_port) {
23163 peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
23164 }
23165 if (!peer->socket.port) {
23166 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
23167 }
23168
23169 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
23170 time_t nowtime = time(NULL);
23171
23172 if ((nowtime - regseconds) > 0) {
23173 destroy_association(peer);
23174 memset(&peer->addr, 0, sizeof(peer->addr));
23175 peer->lastms = -1;
23176 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
23177 }
23178 }
23179
23180
23181 if (!devstate_only && realtime && peer->lastms > 0) {
23182 ref_peer(peer, "schedule qualify");
23183 sip_poke_peer(peer, 0);
23184 }
23185
23186 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
23187 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
23188 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
23189 global_allowsubscribe = TRUE;
23190 }
23191 if (!found && peer->host_dynamic && !peer->is_realtime) {
23192 reg_source_db(peer);
23193 }
23194
23195
23196
23197 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
23198 !AST_LIST_EMPTY(&peer->mailboxes)) {
23199 add_peer_mwi_subs(peer);
23200
23201
23202
23203 sip_send_mwi_to_peer(peer, NULL, 1);
23204 }
23205
23206 peer->the_mark = 0;
23207
23208 ast_free_ha(oldha);
23209 if (!ast_strlen_zero(callback)) {
23210 char *reg_string;
23211
23212 if (asprintf(®_string, "%s?%s:%s@%s/%s", peer->name, peer->username, peer->secret, peer->tohost, callback) < 0) {
23213 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
23214 } else if (reg_string) {
23215 sip_register(reg_string, 0);
23216 ast_free(reg_string);
23217 }
23218 }
23219 return peer;
23220 }
23221
23222 static int peer_markall_func(void *device, void *arg, int flags)
23223 {
23224 struct sip_peer *peer = device;
23225 peer->the_mark = 1;
23226 return 0;
23227 }
23228
23229
23230
23231
23232
23233
23234
23235 static int reload_config(enum channelreloadreason reason)
23236 {
23237 struct ast_config *cfg, *ucfg;
23238 struct ast_variable *v;
23239 struct sip_peer *peer;
23240 char *cat, *stringp, *context, *oldregcontext;
23241 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
23242 struct ast_flags dummy[2];
23243 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
23244 int auto_sip_domains = FALSE;
23245 struct sockaddr_in old_bindaddr = bindaddr;
23246 int registry_count = 0, peer_count = 0;
23247 time_t run_start, run_end;
23248
23249 run_start = time(0);
23250 ast_unload_realtime("sipregs");
23251 ast_unload_realtime("sippeers");
23252 cfg = ast_config_load(config, config_flags);
23253
23254
23255 if (!cfg) {
23256 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
23257 return -1;
23258 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
23259 ucfg = ast_config_load("users.conf", config_flags);
23260 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
23261 return 1;
23262
23263 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
23264 cfg = ast_config_load(config, config_flags);
23265 } else {
23266 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
23267 ucfg = ast_config_load("users.conf", config_flags);
23268 }
23269
23270
23271 memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
23272 memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
23273
23274 ast_free_ha(global_contact_ha);
23275 global_contact_ha = NULL;
23276
23277 default_tls_cfg.enabled = FALSE;
23278
23279 sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
23280 sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
23281
23282 if (reason != CHANNEL_MODULE_LOAD) {
23283 ast_debug(4, "--------------- SIP reload started\n");
23284
23285 clear_realm_authentication(authl);
23286 clear_sip_domains();
23287 authl = NULL;
23288
23289
23290
23291 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
23292
23293 ASTOBJ_RDLOCK(iterator);
23294 if (iterator->call) {
23295 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
23296
23297 dialog_unlink_all(iterator->call, TRUE, TRUE);
23298 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
23299 }
23300 if (iterator->expire > -1) {
23301 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
23302 }
23303 if (iterator->timeout > -1) {
23304 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
23305 }
23306 ASTOBJ_UNLOCK(iterator);
23307
23308 } while(0));
23309
23310
23311 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
23312 ast_debug(4, "--------------- Done destroying registry list\n");
23313 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, 0, "callback to mark all peers");
23314 }
23315
23316
23317 if (reason != CHANNEL_MODULE_LOAD) {
23318 ast_free(default_tls_cfg.certfile);
23319 ast_free(default_tls_cfg.cipher);
23320 ast_free(default_tls_cfg.cafile);
23321 ast_free(default_tls_cfg.capath);
23322 }
23323 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
23324 default_tls_cfg.cipher = ast_strdup("");
23325 default_tls_cfg.cafile = ast_strdup("");
23326 default_tls_cfg.capath = ast_strdup("");
23327
23328
23329 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
23330 oldregcontext = oldcontexts;
23331
23332
23333
23334 sipdebug &= sip_debug_console;
23335 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
23336 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
23337
23338
23339 memset(&bindaddr, 0, sizeof(bindaddr));
23340 memset(&stunaddr, 0, sizeof(stunaddr));
23341 memset(&internip, 0, sizeof(internip));
23342
23343
23344 ast_free_ha(localaddr);
23345 memset(&localaddr, 0, sizeof(localaddr));
23346 memset(&externip, 0, sizeof(externip));
23347 memset(&default_prefs, 0 , sizeof(default_prefs));
23348 memset(&global_outboundproxy, 0, sizeof(struct sip_proxy));
23349 global_outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
23350 global_outboundproxy.ip.sin_family = AF_INET;
23351 global_outboundproxy.force = FALSE;
23352 ourport_tcp = STANDARD_SIP_PORT;
23353 ourport_tls = STANDARD_TLS_PORT;
23354 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
23355 global_srvlookup = DEFAULT_SRVLOOKUP;
23356 global_tos_sip = DEFAULT_TOS_SIP;
23357 global_tos_audio = DEFAULT_TOS_AUDIO;
23358 global_tos_video = DEFAULT_TOS_VIDEO;
23359 global_tos_text = DEFAULT_TOS_TEXT;
23360 global_cos_sip = DEFAULT_COS_SIP;
23361 global_cos_audio = DEFAULT_COS_AUDIO;
23362 global_cos_video = DEFAULT_COS_VIDEO;
23363 global_cos_text = DEFAULT_COS_TEXT;
23364
23365 externhost[0] = '\0';
23366 externexpire = 0;
23367 externrefresh = 10;
23368
23369
23370 allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
23371 global_regcontext[0] = '\0';
23372 global_regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
23373 global_notifyringing = DEFAULT_NOTIFYRINGING;
23374 global_notifyhold = FALSE;
23375 global_directrtpsetup = FALSE;
23376 global_alwaysauthreject = 0;
23377 global_allowsubscribe = FALSE;
23378 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
23379 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
23380 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
23381 global_prematuremediafilter = FALSE;
23382 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
23383 ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
23384 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
23385 compactheaders = DEFAULT_COMPACTHEADERS;
23386 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
23387 global_regattempts_max = 0;
23388 pedanticsipchecking = DEFAULT_PEDANTIC;
23389 autocreatepeer = DEFAULT_AUTOCREATEPEER;
23390 global_autoframing = 0;
23391 global_allowguest = DEFAULT_ALLOWGUEST;
23392 global_callcounter = DEFAULT_CALLCOUNTER;
23393 global_match_auth_username = FALSE;
23394 global_rtptimeout = 0;
23395 global_rtpholdtimeout = 0;
23396 global_rtpkeepalive = 0;
23397 global_allowtransfer = TRANSFER_OPENFORALL;
23398 global_rtautoclear = 120;
23399 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23400 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
23401 sip_cfg.peer_rtupdate = TRUE;
23402 global_dynamic_exclude_static = 0;
23403
23404
23405 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
23406 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
23407 global_min_se = DEFAULT_MIN_SE;
23408 global_max_se = DEFAULT_MAX_SE;
23409
23410
23411 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
23412 default_subscribecontext[0] = '\0';
23413 default_language[0] = '\0';
23414 default_fromdomain[0] = '\0';
23415 default_qualify = DEFAULT_QUALIFY;
23416 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
23417 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
23418 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
23419 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
23420 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
23421 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
23422 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);
23423
23424
23425 dumphistory = FALSE;
23426 recordhistory = FALSE;
23427 sipdebug &= ~sip_debug_config;
23428
23429
23430 global_relaxdtmf = FALSE;
23431 global_callevents = FALSE;
23432 global_authfailureevents = FALSE;
23433 global_t1 = SIP_TIMER_T1;
23434 global_timer_b = 64 * SIP_TIMER_T1;
23435 global_t1min = DEFAULT_T1MIN;
23436 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
23437 global_t38_maxdatagram = -1;
23438 global_shrinkcallerid = 1;
23439
23440 global_matchexterniplocally = FALSE;
23441
23442
23443 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
23444
23445 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23446 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
23447 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
23448 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
23449
23450
23451
23452 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
23453 if (handle_common_options(&global_flags[0], &dummy[0], v))
23454 continue;
23455 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
23456 continue;
23457 }
23458
23459 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
23460 continue;
23461
23462 if (!strcasecmp(v->name, "context")) {
23463 ast_copy_string(default_context, v->value, sizeof(default_context));
23464 } else if (!strcasecmp(v->name, "subscribecontext")) {
23465 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
23466 } else if (!strcasecmp(v->name, "callcounter")) {
23467 global_callcounter = ast_true(v->value) ? 1 : 0;
23468 } else if (!strcasecmp(v->name, "allowguest")) {
23469 global_allowguest = ast_true(v->value) ? 1 : 0;
23470 } else if (!strcasecmp(v->name, "realm")) {
23471 ast_copy_string(global_realm, v->value, sizeof(global_realm));
23472 } else if (!strcasecmp(v->name, "useragent")) {
23473 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
23474 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
23475 } else if (!strcasecmp(v->name, "sdpsession")) {
23476 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
23477 } else if (!strcasecmp(v->name, "sdpowner")) {
23478
23479 if (!strstr(v->value, " "))
23480 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
23481 else
23482 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
23483 } else if (!strcasecmp(v->name, "allowtransfer")) {
23484 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
23485 } else if (!strcasecmp(v->name, "rtcachefriends")) {
23486 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
23487 } else if (!strcasecmp(v->name, "rtsavesysname")) {
23488 sip_cfg.rtsave_sysname = ast_true(v->value);
23489 } else if (!strcasecmp(v->name, "rtupdate")) {
23490 sip_cfg.peer_rtupdate = ast_true(v->value);
23491 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
23492 sip_cfg.ignore_regexpire = ast_true(v->value);
23493 } else if (!strcasecmp(v->name, "timert1")) {
23494
23495
23496
23497 global_t1 = atoi(v->value);
23498
23499 global_timer_b = global_t1 * 64;
23500 } else if (!strcasecmp(v->name, "t1min")) {
23501 global_t1min = atoi(v->value);
23502 } else if (!strcasecmp(v->name, "tcpenable")) {
23503 sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
23504 ast_debug(2, "Enabling TCP socket for listening\n");
23505 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
23506 int family = sip_tcp_desc.local_address.sin_family;
23507 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
23508 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
23509 sip_tcp_desc.local_address.sin_family = family;
23510 ast_debug(2, "Setting TCP socket address to %s\n", v->value);
23511 } else if (!strcasecmp(v->name, "tlsenable")) {
23512 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
23513 sip_tls_desc.local_address.sin_family = AF_INET;
23514 } else if (!strcasecmp(v->name, "tlscertfile")) {
23515 ast_free(default_tls_cfg.certfile);
23516 default_tls_cfg.certfile = ast_strdup(v->value);
23517 } else if (!strcasecmp(v->name, "tlscipher")) {
23518 ast_free(default_tls_cfg.cipher);
23519 default_tls_cfg.cipher = ast_strdup(v->value);
23520 } else if (!strcasecmp(v->name, "tlscafile")) {
23521 ast_free(default_tls_cfg.cafile);
23522 default_tls_cfg.cafile = ast_strdup(v->value);
23523 } else if (!strcasecmp(v->name, "tlscapath")) {
23524 ast_free(default_tls_cfg.capath);
23525 default_tls_cfg.capath = ast_strdup(v->value);
23526 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
23527 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
23528 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
23529 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
23530 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
23531 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
23532 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
23533 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
23534 global_dynamic_exclude_static = ast_true(v->value);
23535 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
23536 int ha_error = 0;
23537 global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
23538 if (ha_error) {
23539 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23540 }
23541 } else if (!strcasecmp(v->name, "rtautoclear")) {
23542 int i = atoi(v->value);
23543 if (i > 0)
23544 global_rtautoclear = i;
23545 else
23546 i = 0;
23547 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
23548 } else if (!strcasecmp(v->name, "usereqphone")) {
23549 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
23550 } else if (!strcasecmp(v->name, "prematuremedia")) {
23551 global_prematuremediafilter = ast_true(v->value);
23552 } else if (!strcasecmp(v->name, "relaxdtmf")) {
23553 global_relaxdtmf = ast_true(v->value);
23554 } else if (!strcasecmp(v->name, "vmexten")) {
23555 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
23556 } else if (!strcasecmp(v->name, "rtptimeout")) {
23557 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
23558 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
23559 global_rtptimeout = 0;
23560 }
23561 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
23562 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
23563 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
23564 global_rtpholdtimeout = 0;
23565 }
23566 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
23567 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
23568 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
23569 global_rtpkeepalive = 0;
23570 }
23571 } else if (!strcasecmp(v->name, "compactheaders")) {
23572 compactheaders = ast_true(v->value);
23573 } else if (!strcasecmp(v->name, "notifymimetype")) {
23574 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
23575 } else if (!strcasecmp(v->name, "directrtpsetup")) {
23576 global_directrtpsetup = ast_true(v->value);
23577 } else if (!strcasecmp(v->name, "notifyringing")) {
23578 global_notifyringing = ast_true(v->value);
23579 } else if (!strcasecmp(v->name, "notifyhold")) {
23580 global_notifyhold = ast_true(v->value);
23581 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
23582 global_alwaysauthreject = ast_true(v->value);
23583 } else if (!strcasecmp(v->name, "mohinterpret")) {
23584 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
23585 } else if (!strcasecmp(v->name, "mohsuggest")) {
23586 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
23587 } else if (!strcasecmp(v->name, "language")) {
23588 ast_copy_string(default_language, v->value, sizeof(default_language));
23589 } else if (!strcasecmp(v->name, "regcontext")) {
23590 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
23591 stringp = newcontexts;
23592
23593 cleanup_stale_contexts(stringp, oldregcontext);
23594
23595 while ((context = strsep(&stringp, "&"))) {
23596 ast_copy_string(used_context, context, sizeof(used_context));
23597 ast_context_find_or_create(NULL, NULL, context, "SIP");
23598 }
23599 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
23600 } else if (!strcasecmp(v->name, "regextenonqualify")) {
23601 global_regextenonqualify = ast_true(v->value);
23602 } else if (!strcasecmp(v->name, "callerid")) {
23603 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
23604 } else if (!strcasecmp(v->name, "fromdomain")) {
23605 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
23606 } else if (!strcasecmp(v->name, "outboundproxy")) {
23607 int portnum;
23608 char *tok, *proxyname;
23609
23610 if (ast_strlen_zero(v->value)) {
23611 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
23612 continue;
23613 }
23614
23615 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
23616
23617 sip_parse_host(tok, v->lineno, &proxyname, &portnum, &global_outboundproxy.transport);
23618
23619 global_outboundproxy.ip.sin_port = htons(portnum);
23620
23621 if ((tok = strtok(NULL, ","))) {
23622 global_outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
23623 } else {
23624 global_outboundproxy.force = FALSE;
23625 }
23626
23627 if (ast_strlen_zero(proxyname)) {
23628 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
23629 global_outboundproxy.name[0] = '\0';
23630 continue;
23631 }
23632
23633 ast_copy_string(global_outboundproxy.name, proxyname, sizeof(global_outboundproxy.name));
23634
23635 proxy_update(&global_outboundproxy);
23636 } else if (!strcasecmp(v->name, "autocreatepeer")) {
23637 autocreatepeer = ast_true(v->value);
23638 } else if (!strcasecmp(v->name, "match_auth_username")) {
23639 global_match_auth_username = ast_true(v->value);
23640 } else if (!strcasecmp(v->name, "srvlookup")) {
23641 global_srvlookup = ast_true(v->value);
23642 } else if (!strcasecmp(v->name, "pedantic")) {
23643 pedanticsipchecking = ast_true(v->value);
23644 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
23645 max_expiry = atoi(v->value);
23646 if (max_expiry < 1)
23647 max_expiry = DEFAULT_MAX_EXPIRY;
23648 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
23649 min_expiry = atoi(v->value);
23650 if (min_expiry < 1)
23651 min_expiry = DEFAULT_MIN_EXPIRY;
23652 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
23653 default_expiry = atoi(v->value);
23654 if (default_expiry < 1)
23655 default_expiry = DEFAULT_DEFAULT_EXPIRY;
23656 } else if (!strcasecmp(v->name, "sipdebug")) {
23657 if (ast_true(v->value))
23658 sipdebug |= sip_debug_config;
23659 } else if (!strcasecmp(v->name, "dumphistory")) {
23660 dumphistory = ast_true(v->value);
23661 } else if (!strcasecmp(v->name, "recordhistory")) {
23662 recordhistory = ast_true(v->value);
23663 } else if (!strcasecmp(v->name, "registertimeout")) {
23664 global_reg_timeout = atoi(v->value);
23665 if (global_reg_timeout < 1)
23666 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
23667 } else if (!strcasecmp(v->name, "registerattempts")) {
23668 global_regattempts_max = atoi(v->value);
23669 } else if (!strcasecmp(v->name, "stunaddr")) {
23670 stunaddr.sin_port = htons(3478);
23671 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
23672 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
23673 externexpire = time(NULL);
23674 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
23675 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
23676 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
23677 } else if (!strcasecmp(v->name, "localnet")) {
23678 struct ast_ha *na;
23679 int ha_error = 0;
23680
23681 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
23682 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
23683 else
23684 localaddr = na;
23685 if (ha_error)
23686 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
23687 } else if (!strcasecmp(v->name, "externip")) {
23688 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
23689 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
23690 externexpire = 0;
23691
23692 if (!externip.sin_port)
23693 externip.sin_port = bindaddr.sin_port;
23694 } else if (!strcasecmp(v->name, "externhost")) {
23695 ast_copy_string(externhost, v->value, sizeof(externhost));
23696 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
23697 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
23698 externexpire = time(NULL);
23699
23700 if (!externip.sin_port)
23701 externip.sin_port = bindaddr.sin_port;
23702 } else if (!strcasecmp(v->name, "externrefresh")) {
23703 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
23704 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
23705 externrefresh = 10;
23706 }
23707 } else if (!strcasecmp(v->name, "allow")) {
23708 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
23709 if (error)
23710 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
23711 } else if (!strcasecmp(v->name, "disallow")) {
23712 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
23713 if (error)
23714 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
23715 } else if (!strcasecmp(v->name, "autoframing")) {
23716 global_autoframing = ast_true(v->value);
23717 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
23718 allow_external_domains = ast_true(v->value);
23719 } else if (!strcasecmp(v->name, "autodomain")) {
23720 auto_sip_domains = ast_true(v->value);
23721 } else if (!strcasecmp(v->name, "domain")) {
23722 char *domain = ast_strdupa(v->value);
23723 char *cntx = strchr(domain, ',');
23724
23725 if (cntx)
23726 *cntx++ = '\0';
23727
23728 if (ast_strlen_zero(cntx))
23729 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
23730 if (ast_strlen_zero(domain))
23731 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
23732 else
23733 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
23734 } else if (!strcasecmp(v->name, "register")) {
23735 if (sip_register(v->value, v->lineno) == 0)
23736 registry_count++;
23737 } else if (!strcasecmp(v->name, "tos_sip")) {
23738 if (ast_str2tos(v->value, &global_tos_sip))
23739 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
23740 } else if (!strcasecmp(v->name, "tos_audio")) {
23741 if (ast_str2tos(v->value, &global_tos_audio))
23742 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
23743 } else if (!strcasecmp(v->name, "tos_video")) {
23744 if (ast_str2tos(v->value, &global_tos_video))
23745 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
23746 } else if (!strcasecmp(v->name, "tos_text")) {
23747 if (ast_str2tos(v->value, &global_tos_text))
23748 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
23749 } else if (!strcasecmp(v->name, "cos_sip")) {
23750 if (ast_str2cos(v->value, &global_cos_sip))
23751 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
23752 } else if (!strcasecmp(v->name, "cos_audio")) {
23753 if (ast_str2cos(v->value, &global_cos_audio))
23754 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
23755 } else if (!strcasecmp(v->name, "cos_video")) {
23756 if (ast_str2cos(v->value, &global_cos_video))
23757 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
23758 } else if (!strcasecmp(v->name, "cos_text")) {
23759 if (ast_str2cos(v->value, &global_cos_text))
23760 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
23761 } else if (!strcasecmp(v->name, "bindport")) {
23762 int i;
23763 if (sscanf(v->value, "%5d", &i) == 1) {
23764 bindaddr.sin_port = htons(i);
23765 } else {
23766 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
23767 }
23768 } else if (!strcasecmp(v->name, "hash_user")) {
23769 int i;
23770 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23771 hash_user_size = i;
23772 } else {
23773 ast_log(LOG_WARNING, "Invalid hash_user size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23774 }
23775 } else if (!strcasecmp(v->name, "hash_peer")) {
23776 int i;
23777 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23778 hash_peer_size = i;
23779 } else {
23780 ast_log(LOG_WARNING, "Invalid hash_peer size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23781 }
23782 } else if (!strcasecmp(v->name, "hash_dialog")) {
23783 int i;
23784 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23785 hash_dialog_size = i;
23786 } else {
23787 ast_log(LOG_WARNING, "Invalid hash_dialog size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23788 }
23789 } else if (!strcasecmp(v->name, "qualify")) {
23790 if (!strcasecmp(v->value, "no")) {
23791 default_qualify = 0;
23792 } else if (!strcasecmp(v->value, "yes")) {
23793 default_qualify = DEFAULT_MAXMS;
23794 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
23795 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
23796 default_qualify = 0;
23797 }
23798 } else if (!strcasecmp(v->name, "qualifyfreq")) {
23799 int i;
23800 if (sscanf(v->value, "%30d", &i) == 1)
23801 global_qualifyfreq = i * 1000;
23802 else {
23803 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
23804 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
23805 }
23806 } else if (!strcasecmp(v->name, "callevents")) {
23807 global_callevents = ast_true(v->value);
23808 } else if (!strcasecmp(v->name, "authfailureevents")) {
23809 global_authfailureevents = ast_true(v->value);
23810 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
23811 default_maxcallbitrate = atoi(v->value);
23812 if (default_maxcallbitrate < 0)
23813 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
23814 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
23815 global_matchexterniplocally = ast_true(v->value);
23816 } else if (!strcasecmp(v->name, "constantssrc")) {
23817 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_CONSTANT_SSRC);
23818 } else if (!strcasecmp(v->name, "session-timers")) {
23819 int i = (int) str2stmode(v->value);
23820 if (i < 0) {
23821 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
23822 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
23823 } else {
23824 global_st_mode = i;
23825 }
23826 } else if (!strcasecmp(v->name, "session-expires")) {
23827 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
23828 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
23829 global_max_se = DEFAULT_MAX_SE;
23830 }
23831 } else if (!strcasecmp(v->name, "session-minse")) {
23832 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
23833 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
23834 global_min_se = DEFAULT_MIN_SE;
23835 }
23836 if (global_min_se < 90) {
23837 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
23838 global_min_se = DEFAULT_MIN_SE;
23839 }
23840 } else if (!strcasecmp(v->name, "session-refresher")) {
23841 int i = (int) str2strefresher(v->value);
23842 if (i < 0) {
23843 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
23844 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
23845 } else {
23846 global_st_refresher = i;
23847 }
23848 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
23849 if (ast_true(v->value)) {
23850 global_shrinkcallerid = 1;
23851 } else if (ast_false(v->value)) {
23852 global_shrinkcallerid = 0;
23853 } else {
23854 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
23855 }
23856 }
23857 }
23858
23859 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
23860 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
23861 allow_external_domains = 1;
23862 }
23863
23864
23865 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
23866
23867 if (!strcasecmp(v->name, "auth"))
23868 authl = add_realm_authentication(authl, v->value, v->lineno);
23869 }
23870
23871 if (ucfg) {
23872 struct ast_variable *gen;
23873 int genhassip, genregistersip;
23874 const char *hassip, *registersip;
23875
23876 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
23877 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
23878 gen = ast_variable_browse(ucfg, "general");
23879 cat = ast_category_browse(ucfg, NULL);
23880 while (cat) {
23881 if (strcasecmp(cat, "general")) {
23882 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
23883 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
23884 if (ast_true(hassip) || (!hassip && genhassip)) {
23885 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
23886 if (peer) {
23887
23888 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23889 ao2_t_link(peers, peer, "link peer into peer table");
23890 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
23891 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
23892 }
23893
23894 unref_peer(peer, "unref_peer: from reload_config");
23895 peer_count++;
23896 }
23897 }
23898 if (ast_true(registersip) || (!registersip && genregistersip)) {
23899 char tmp[256];
23900 const char *host = ast_variable_retrieve(ucfg, cat, "host");
23901 const char *username = ast_variable_retrieve(ucfg, cat, "username");
23902 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
23903 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
23904 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
23905 if (!host)
23906 host = ast_variable_retrieve(ucfg, "general", "host");
23907 if (!username)
23908 username = ast_variable_retrieve(ucfg, "general", "username");
23909 if (!secret)
23910 secret = ast_variable_retrieve(ucfg, "general", "secret");
23911 if (!contact)
23912 contact = "s";
23913 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
23914 if (!ast_strlen_zero(secret)) {
23915 if (!ast_strlen_zero(authuser)) {
23916 snprintf(tmp, sizeof(tmp), "%s:%s:%s@%s/%s", username, secret, authuser, host, contact);
23917 } else {
23918 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
23919 }
23920 } else if (!ast_strlen_zero(authuser)) {
23921 snprintf(tmp, sizeof(tmp), "%s::%s@%s/%s", username, authuser, host, contact);
23922 } else {
23923 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
23924 }
23925 if (sip_register(tmp, 0) == 0)
23926 registry_count++;
23927 }
23928 }
23929 }
23930 cat = ast_category_browse(ucfg, cat);
23931 }
23932 ast_config_destroy(ucfg);
23933 }
23934
23935
23936
23937 cat = NULL;
23938 while ( (cat = ast_category_browse(cfg, cat)) ) {
23939 const char *utype;
23940 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
23941 continue;
23942 utype = ast_variable_retrieve(cfg, cat, "type");
23943 if (!utype) {
23944 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
23945 continue;
23946 } else {
23947 if (!strcasecmp(utype, "user")) {
23948 ;
23949 } else if (!strcasecmp(utype, "friend")) {
23950 ;
23951 } else if (!strcasecmp(utype, "peer")) {
23952 ;
23953 } else {
23954 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
23955 continue;
23956 }
23957 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
23958 if (peer) {
23959 ao2_t_link(peers, peer, "link peer into peers table");
23960 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
23961 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
23962 }
23963 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
23964 peer_count++;
23965 }
23966 }
23967 }
23968
23969
23970 bindaddr.sin_family = AF_INET;
23971 internip = bindaddr;
23972 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
23973 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
23974 ast_config_destroy(cfg);
23975 return 0;
23976 }
23977 ast_mutex_lock(&netlock);
23978 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
23979 close(sipsock);
23980 sipsock = -1;
23981 }
23982 if (sipsock < 0) {
23983 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
23984 if (sipsock < 0) {
23985 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
23986 ast_config_destroy(cfg);
23987 return -1;
23988 } else {
23989
23990 const int reuseFlag = 1;
23991
23992 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
23993 (const char*)&reuseFlag,
23994 sizeof reuseFlag);
23995
23996 ast_enable_packet_fragmentation(sipsock);
23997
23998 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
23999 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
24000 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
24001 strerror(errno));
24002 close(sipsock);
24003 sipsock = -1;
24004 } else {
24005 ast_verb(2, "SIP Listening on %s:%d\n",
24006 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
24007 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
24008 }
24009 }
24010 }
24011 if (stunaddr.sin_addr.s_addr != 0) {
24012 ast_debug(1, "stun to %s:%d\n",
24013 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
24014 ast_stun_request(sipsock, &stunaddr,
24015 NULL, &externip);
24016 ast_debug(1, "STUN sees us at %s:%d\n",
24017 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
24018 }
24019 ast_mutex_unlock(&netlock);
24020
24021
24022 ast_tcptls_server_start(&sip_tcp_desc);
24023
24024
24025 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
24026
24027 if (ast_ssl_setup(sip_tls_desc.tls_cfg))
24028 ast_tcptls_server_start(&sip_tls_desc);
24029 else if (sip_tls_desc.tls_cfg->enabled) {
24030 sip_tls_desc.tls_cfg = NULL;
24031 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
24032 }
24033
24034
24035
24036
24037
24038
24039
24040 if (auto_sip_domains) {
24041 char temp[MAXHOSTNAMELEN];
24042
24043
24044 if (bindaddr.sin_addr.s_addr) {
24045 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
24046 } else if (internip.sin_addr.s_addr) {
24047
24048 add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
24049 } else {
24050 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
24051 }
24052
24053
24054 if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
24055 add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
24056
24057
24058 if (sip_tls_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tls_desc.local_address) && inaddrcmp(&sip_tcp_desc.local_address, &sip_tls_desc.local_address))
24059 add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
24060
24061
24062 if (externip.sin_addr.s_addr)
24063 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
24064
24065
24066 if (!ast_strlen_zero(externhost))
24067 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
24068
24069
24070 if (!gethostname(temp, sizeof(temp)))
24071 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
24072 }
24073
24074
24075 ast_config_destroy(cfg);
24076
24077
24078 if (notify_types)
24079 ast_config_destroy(notify_types);
24080 notify_types = ast_config_load(notify_config, config_flags);
24081
24082
24083 manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count);
24084 run_end = time(0);
24085 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
24086
24087 return 0;
24088 }
24089
24090 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
24091 {
24092 struct sip_pvt *p;
24093 struct ast_udptl *udptl = NULL;
24094
24095 p = chan->tech_pvt;
24096 if (!p)
24097 return NULL;
24098
24099 sip_pvt_lock(p);
24100 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
24101 udptl = p->udptl;
24102 sip_pvt_unlock(p);
24103 return udptl;
24104 }
24105
24106 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
24107 {
24108 struct sip_pvt *p;
24109
24110 p = chan->tech_pvt;
24111 if (!p)
24112 return -1;
24113 sip_pvt_lock(p);
24114 if (udptl)
24115 ast_udptl_get_peer(udptl, &p->udptlredirip);
24116 else
24117 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
24118 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
24119 if (!p->pendinginvite) {
24120 ast_debug(3, "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.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
24121 transmit_reinvite_with_sdp(p, TRUE, FALSE);
24122 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
24123 ast_debug(3, "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.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
24124 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
24125 }
24126 }
24127
24128 p->lastrtprx = p->lastrtptx = time(NULL);
24129 sip_pvt_unlock(p);
24130 return 0;
24131 }
24132
24133
24134 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
24135 {
24136 struct sip_pvt *p = NULL;
24137 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
24138
24139 if (!(p = chan->tech_pvt))
24140 return AST_RTP_GET_FAILED;
24141
24142 sip_pvt_lock(p);
24143 if (!(p->rtp)) {
24144 sip_pvt_unlock(p);
24145 return AST_RTP_GET_FAILED;
24146 }
24147
24148 *rtp = p->rtp;
24149
24150 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
24151 res = AST_RTP_TRY_PARTIAL;
24152 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
24153 res = AST_RTP_TRY_NATIVE;
24154 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
24155 res = AST_RTP_GET_FAILED;
24156
24157 sip_pvt_unlock(p);
24158
24159 return res;
24160 }
24161
24162
24163 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
24164 {
24165 struct sip_pvt *p = NULL;
24166 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
24167
24168 if (!(p = chan->tech_pvt))
24169 return AST_RTP_GET_FAILED;
24170
24171 sip_pvt_lock(p);
24172 if (!(p->vrtp)) {
24173 sip_pvt_unlock(p);
24174 return AST_RTP_GET_FAILED;
24175 }
24176
24177 *rtp = p->vrtp;
24178
24179 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
24180 res = AST_RTP_TRY_NATIVE;
24181
24182 sip_pvt_unlock(p);
24183
24184 return res;
24185 }
24186
24187
24188 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
24189 {
24190 struct sip_pvt *p = NULL;
24191 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
24192
24193 if (!(p = chan->tech_pvt))
24194 return AST_RTP_GET_FAILED;
24195
24196 sip_pvt_lock(p);
24197 if (!(p->trtp)) {
24198 sip_pvt_unlock(p);
24199 return AST_RTP_GET_FAILED;
24200 }
24201
24202 *rtp = p->trtp;
24203
24204 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
24205 res = AST_RTP_TRY_NATIVE;
24206
24207 sip_pvt_unlock(p);
24208
24209 return res;
24210 }
24211
24212
24213 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
24214 {
24215 struct sip_pvt *p;
24216 int changed = 0;
24217
24218 p = chan->tech_pvt;
24219 if (!p)
24220 return -1;
24221
24222
24223 if (!ast_bridged_channel(chan) && !global_directrtpsetup)
24224 return 0;
24225
24226 sip_pvt_lock(p);
24227 if (p->alreadygone) {
24228
24229 sip_pvt_unlock(p);
24230 return 0;
24231 }
24232
24233
24234
24235
24236 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
24237 sip_pvt_unlock(p);
24238 return 0;
24239 }
24240
24241 if (rtp) {
24242 changed |= ast_rtp_get_peer(rtp, &p->redirip);
24243 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
24244 memset(&p->redirip, 0, sizeof(p->redirip));
24245 changed = 1;
24246 }
24247 if (vrtp) {
24248 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
24249 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
24250 memset(&p->vredirip, 0, sizeof(p->vredirip));
24251 changed = 1;
24252 }
24253 if (trtp) {
24254 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
24255 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
24256 memset(&p->tredirip, 0, sizeof(p->tredirip));
24257 changed = 1;
24258 }
24259 if (codecs && (p->redircodecs != codecs)) {
24260 p->redircodecs = codecs;
24261 changed = 1;
24262 }
24263 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
24264 if (chan->_state != AST_STATE_UP) {
24265 if (p->do_history)
24266 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
24267 ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
24268 } else if (!p->pendinginvite) {
24269 ast_debug(3, "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.sin_addr));
24270 transmit_reinvite_with_sdp(p, FALSE, FALSE);
24271 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
24272 ast_debug(3, "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.sin_addr));
24273
24274 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
24275 }
24276 }
24277
24278 p->lastrtprx = p->lastrtptx = time(NULL);
24279 sip_pvt_unlock(p);
24280 return 0;
24281 }
24282
24283 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
24284 static char *descrip_dtmfmode = " SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
24285 static char *app_dtmfmode = "SIPDtmfMode";
24286
24287 static char *app_sipaddheader = "SIPAddHeader";
24288 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
24289
24290 static char *descrip_sipaddheader = ""
24291 " SIPAddHeader(Header: Content):\n"
24292 "Adds a header to a SIP call placed with DIAL.\n"
24293 "Remember to user the X-header if you are adding non-standard SIP\n"
24294 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
24295 "Adding the wrong headers may jeopardize the SIP dialog.\n"
24296 "Always returns 0\n";
24297
24298
24299
24300 static int sip_dtmfmode(struct ast_channel *chan, void *data)
24301 {
24302 struct sip_pvt *p;
24303 char *mode = data;
24304
24305 if (!data) {
24306 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
24307 return 0;
24308 }
24309 ast_channel_lock(chan);
24310 if (!IS_SIP_TECH(chan->tech)) {
24311 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
24312 ast_channel_unlock(chan);
24313 return 0;
24314 }
24315 p = chan->tech_pvt;
24316 if (!p) {
24317 ast_channel_unlock(chan);
24318 return 0;
24319 }
24320 sip_pvt_lock(p);
24321 if (!strcasecmp(mode, "info")) {
24322 ast_clear_flag(&p->flags[0], SIP_DTMF);
24323 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
24324 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
24325 } else if (!strcasecmp(mode, "shortinfo")) {
24326 ast_clear_flag(&p->flags[0], SIP_DTMF);
24327 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
24328 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
24329 } else if (!strcasecmp(mode, "rfc2833")) {
24330 ast_clear_flag(&p->flags[0], SIP_DTMF);
24331 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
24332 p->jointnoncodeccapability |= AST_RTP_DTMF;
24333 } else if (!strcasecmp(mode, "inband")) {
24334 ast_clear_flag(&p->flags[0], SIP_DTMF);
24335 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
24336 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
24337 } else
24338 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
24339 if (p->rtp)
24340 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
24341 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
24342 if (!p->dsp) {
24343 p->dsp = ast_dsp_new();
24344 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
24345 }
24346 } else {
24347 if (p->dsp) {
24348 ast_dsp_free(p->dsp);
24349 p->dsp = NULL;
24350 }
24351 }
24352 sip_pvt_unlock(p);
24353 ast_channel_unlock(chan);
24354 return 0;
24355 }
24356
24357
24358 static int sip_addheader(struct ast_channel *chan, void *data)
24359 {
24360 int no = 0;
24361 int ok = FALSE;
24362 char varbuf[30];
24363 char *inbuf = data, *subbuf;
24364
24365 if (ast_strlen_zero(inbuf)) {
24366 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
24367 return 0;
24368 }
24369 ast_channel_lock(chan);
24370
24371
24372 while (!ok && no <= 50) {
24373 no++;
24374 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
24375
24376
24377 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
24378 ok = TRUE;
24379 }
24380 }
24381 if (ok) {
24382 size_t len = strlen(inbuf);
24383 subbuf = alloca(len + 1);
24384 ast_get_encoded_str(inbuf, subbuf, len + 1);
24385 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
24386 if (sipdebug) {
24387 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
24388 }
24389 } else {
24390 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
24391 }
24392 ast_channel_unlock(chan);
24393 return 0;
24394 }
24395
24396
24397
24398
24399
24400
24401
24402 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
24403 {
24404 char *cdest;
24405 char *extension, *host, *port;
24406 char tmp[80];
24407
24408 cdest = ast_strdupa(dest);
24409
24410 extension = strsep(&cdest, "@");
24411 host = strsep(&cdest, ":");
24412 port = strsep(&cdest, ":");
24413 if (ast_strlen_zero(extension)) {
24414 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
24415 return 0;
24416 }
24417
24418
24419 if (!host) {
24420 char *localtmp;
24421
24422 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
24423 if (ast_strlen_zero(tmp)) {
24424 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
24425 return 0;
24426 }
24427 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
24428 && (localtmp = strchr(localtmp, '@'))) {
24429 char lhost[80], lport[80];
24430
24431 memset(lhost, 0, sizeof(lhost));
24432 memset(lport, 0, sizeof(lport));
24433 localtmp++;
24434
24435 sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
24436 if (ast_strlen_zero(lhost)) {
24437 ast_log(LOG_ERROR, "Can't find the host address\n");
24438 return 0;
24439 }
24440 host = ast_strdupa(lhost);
24441 if (!ast_strlen_zero(lport)) {
24442 port = ast_strdupa(lport);
24443 }
24444 }
24445 }
24446
24447 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
24448 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
24449
24450 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
24451 sip_alreadygone(p);
24452
24453 return 0;
24454 }
24455
24456
24457 static int sip_get_codec(struct ast_channel *chan)
24458 {
24459 struct sip_pvt *p = chan->tech_pvt;
24460 return p->jointcapability ? p->jointcapability : p->capability;
24461 }
24462
24463
24464
24465
24466
24467 static void sip_poke_all_peers(void)
24468 {
24469 int ms = 0;
24470 struct ao2_iterator i;
24471 struct sip_peer *peer;
24472
24473 if (!speerobjs)
24474 return;
24475
24476 i = ao2_iterator_init(peers, 0);
24477 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
24478 ao2_lock(peer);
24479 ms += 100;
24480 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
24481 unref_peer(_data, "removing poke peer ref"),
24482 unref_peer(peer, "removing poke peer ref"),
24483 ref_peer(peer, "adding poke peer ref"));
24484 ao2_unlock(peer);
24485 unref_peer(peer, "toss iterator peer ptr");
24486 }
24487 ao2_iterator_destroy(&i);
24488 }
24489
24490
24491 static void sip_send_all_registers(void)
24492 {
24493 int ms;
24494 int regspacing;
24495 if (!regobjs)
24496 return;
24497 regspacing = default_expiry * 1000/regobjs;
24498 if (regspacing > 100)
24499 regspacing = 100;
24500 ms = regspacing;
24501 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
24502 ASTOBJ_WRLOCK(iterator);
24503 ms += regspacing;
24504 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
24505 registry_unref(_data, "REPLACE sched del decs the refcount"),
24506 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
24507 registry_addref(iterator, "REPLACE sched add incs the refcount"));
24508 ASTOBJ_UNLOCK(iterator);
24509 } while (0)
24510 );
24511 }
24512
24513
24514 static int sip_do_reload(enum channelreloadreason reason)
24515 {
24516 time_t start_poke, end_poke;
24517
24518 reload_config(reason);
24519 ast_sched_dump(sched);
24520
24521 start_poke = time(0);
24522
24523 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, 0,
24524 "callback to remove marked peers");
24525
24526 ast_debug(4, "--------------- Done destroying pruned peers\n");
24527
24528
24529 sip_poke_all_peers();
24530
24531
24532 sip_send_all_registers();
24533 end_poke = time(0);
24534
24535 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
24536
24537 ast_debug(4, "--------------- SIP reload done\n");
24538
24539 return 0;
24540 }
24541
24542
24543 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
24544 {
24545
24546 switch (cmd) {
24547 case CLI_INIT:
24548 e->command = "sip reload";
24549 e->usage =
24550 "Usage: sip reload\n"
24551 " Reloads SIP configuration from sip.conf\n";
24552 return NULL;
24553 case CLI_GENERATE:
24554 return NULL;
24555 }
24556
24557 ast_mutex_lock(&sip_reload_lock);
24558 if (sip_reloading)
24559 ast_verbose("Previous SIP reload not yet done\n");
24560 else {
24561 sip_reloading = TRUE;
24562 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
24563 }
24564 ast_mutex_unlock(&sip_reload_lock);
24565 restart_monitor();
24566
24567 return CLI_SUCCESS;
24568 }
24569
24570
24571 static int reload(void)
24572 {
24573 if (sip_reload(0, 0, NULL))
24574 return 0;
24575 return 1;
24576 }
24577
24578 static struct ast_cli_entry cli_sip_do_history_deprecated = AST_CLI_DEFINE(sip_do_history_deprecated, "Enable/Disable SIP history");
24579
24580 static struct ast_cli_entry cli_sip[] = {
24581 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
24582 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
24583 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
24584 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
24585 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
24586 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
24587 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
24588 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
24589 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
24590 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
24591 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
24592 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
24593 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
24594 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
24595 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
24596 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
24597 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
24598 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
24599 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
24600 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history", .deprecate_cmd = &cli_sip_do_history_deprecated),
24601 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
24602 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
24603 };
24604
24605
24606 static int load_module(void)
24607 {
24608 ast_verbose("SIP channel loading...\n");
24609
24610
24611 peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
24612 peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
24613 dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
24614 threadt = ao2_t_container_alloc(hash_dialog_size, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
24615
24616 ASTOBJ_CONTAINER_INIT(®l);
24617
24618 if (!(sched = sched_context_create())) {
24619 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
24620 return AST_MODULE_LOAD_FAILURE;
24621 }
24622
24623 if (!(io = io_context_create())) {
24624 ast_log(LOG_ERROR, "Unable to create I/O context\n");
24625 sched_context_destroy(sched);
24626 return AST_MODULE_LOAD_FAILURE;
24627 }
24628
24629 sip_reloadreason = CHANNEL_MODULE_LOAD;
24630
24631 if(reload_config(sip_reloadreason))
24632 return AST_MODULE_LOAD_DECLINE;
24633
24634
24635
24636
24637
24638 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
24639 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
24640
24641
24642 if (ast_channel_register(&sip_tech)) {
24643 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
24644 io_context_destroy(io);
24645 sched_context_destroy(sched);
24646 return AST_MODULE_LOAD_FAILURE;
24647 }
24648
24649
24650 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
24651
24652
24653 ast_rtp_proto_register(&sip_rtp);
24654
24655
24656 ast_udptl_proto_register(&sip_udptl);
24657
24658
24659 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
24660 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
24661
24662
24663 ast_custom_function_register(&sip_header_function);
24664 ast_custom_function_register(&sippeer_function);
24665 ast_custom_function_register(&sipchaninfo_function);
24666 ast_custom_function_register(&checksipdomain_function);
24667
24668
24669 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
24670 "List SIP peers (text format)", mandescr_show_peers);
24671 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
24672 "Show SIP peer (text format)", mandescr_show_peer);
24673 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
24674 "Show SIP peer (text format)", mandescr_show_peer);
24675 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
24676 "Show SIP registrations (text format)", mandescr_show_registry);
24677 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
24678 "Send a SIP notify", mandescr_sipnotify);
24679 sip_poke_all_peers();
24680 sip_send_all_registers();
24681
24682
24683 restart_monitor();
24684
24685 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
24686 "name", RQ_CHAR, 10,
24687 "ipaddr", RQ_CHAR, 15,
24688 "port", RQ_UINTEGER2, 5,
24689 "regseconds", RQ_INTEGER4, 11,
24690 "defaultuser", RQ_CHAR, 10,
24691 "fullcontact", RQ_CHAR, 35,
24692 "regserver", RQ_CHAR, 20,
24693 "useragent", RQ_CHAR, 20,
24694 "lastms", RQ_INTEGER4, 11,
24695 SENTINEL);
24696
24697 return AST_MODULE_LOAD_SUCCESS;
24698 }
24699
24700
24701 static int unload_module(void)
24702 {
24703 struct sip_pvt *p;
24704 struct sip_threadinfo *th;
24705 struct ast_context *con;
24706 struct ao2_iterator i;
24707
24708 ast_sched_dump(sched);
24709
24710
24711 ast_channel_unregister(&sip_tech);
24712
24713
24714 ast_custom_function_unregister(&sipchaninfo_function);
24715 ast_custom_function_unregister(&sippeer_function);
24716 ast_custom_function_unregister(&sip_header_function);
24717 ast_custom_function_unregister(&checksipdomain_function);
24718
24719
24720 ast_unregister_application(app_dtmfmode);
24721 ast_unregister_application(app_sipaddheader);
24722
24723
24724 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
24725
24726
24727 ast_rtp_proto_unregister(&sip_rtp);
24728
24729
24730 ast_udptl_proto_unregister(&sip_udptl);
24731
24732
24733 ast_manager_unregister("SIPpeers");
24734 ast_manager_unregister("SIPshowpeer");
24735 ast_manager_unregister("SIPqualifypeer");
24736 ast_manager_unregister("SIPshowregistry");
24737 ast_manager_unregister("SIPnotify");
24738
24739
24740 if (sip_tcp_desc.master)
24741 ast_tcptls_server_stop(&sip_tcp_desc);
24742 if (sip_tls_desc.master)
24743 ast_tcptls_server_stop(&sip_tls_desc);
24744
24745
24746 i = ao2_iterator_init(threadt, 0);
24747 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
24748 pthread_t thread = th->threadid;
24749 th->stop = 1;
24750 pthread_kill(thread, SIGURG);
24751 pthread_join(thread, NULL);
24752 ao2_t_ref(th, -1, "decrement ref from iterator");
24753 }
24754 ao2_iterator_destroy(&i);
24755
24756
24757 i = ao2_iterator_init(dialogs, 0);
24758 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
24759 if (p->owner)
24760 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
24761 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
24762 }
24763 ao2_iterator_destroy(&i);
24764
24765 ast_mutex_lock(&monlock);
24766 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
24767 pthread_cancel(monitor_thread);
24768 pthread_kill(monitor_thread, SIGURG);
24769 pthread_join(monitor_thread, NULL);
24770 }
24771 monitor_thread = AST_PTHREADT_STOP;
24772 ast_mutex_unlock(&monlock);
24773
24774
24775 i = ao2_iterator_init(dialogs, 0);
24776 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
24777 dialog_unlink_all(p, TRUE, TRUE);
24778 ao2_t_ref(p, -1, "throw away iterator result");
24779 }
24780 ao2_iterator_destroy(&i);
24781
24782
24783 ast_free_ha(localaddr);
24784
24785 clear_realm_authentication(authl);
24786
24787
24788 if (default_tls_cfg.certfile)
24789 ast_free(default_tls_cfg.certfile);
24790 if (default_tls_cfg.cipher)
24791 ast_free(default_tls_cfg.cipher);
24792 if (default_tls_cfg.cafile)
24793 ast_free(default_tls_cfg.cafile);
24794 if (default_tls_cfg.capath)
24795 ast_free(default_tls_cfg.capath);
24796
24797 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
24798 ASTOBJ_CONTAINER_DESTROY(®l);
24799
24800 ao2_t_ref(peers, -1, "unref the peers table");
24801 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
24802 ao2_t_ref(dialogs, -1, "unref the dialogs table");
24803 ao2_t_ref(threadt, -1, "unref the thread table");
24804
24805 clear_sip_domains();
24806 ast_free_ha(global_contact_ha);
24807 close(sipsock);
24808 sched_context_destroy(sched);
24809 con = ast_context_find(used_context);
24810 if (con)
24811 ast_context_destroy(con, "SIP");
24812 ast_unload_realtime("sipregs");
24813 ast_unload_realtime("sippeers");
24814
24815 return 0;
24816 }
24817
24818 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
24819 .load = load_module,
24820 .unload = unload_module,
24821 .reload = reload,
24822 );