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
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159
00160
00161
00162
00163
00164
00165
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203
00204
00205
00206
00207
00208 #include "asterisk.h"
00209
00210 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 325277 $")
00211
00212 #include <ctype.h>
00213 #include <sys/ioctl.h>
00214 #include <fcntl.h>
00215 #include <signal.h>
00216 #include <sys/signal.h>
00217 #include <regex.h>
00218 #include <time.h>
00219
00220 #include "asterisk/network.h"
00221 #include "asterisk/paths.h"
00222
00223 #include "asterisk/lock.h"
00224 #include "asterisk/channel.h"
00225 #include "asterisk/config.h"
00226 #include "asterisk/module.h"
00227 #include "asterisk/pbx.h"
00228 #include "asterisk/sched.h"
00229 #include "asterisk/io.h"
00230 #include "asterisk/rtp.h"
00231 #include "asterisk/udptl.h"
00232 #include "asterisk/acl.h"
00233 #include "asterisk/manager.h"
00234 #include "asterisk/callerid.h"
00235 #include "asterisk/cli.h"
00236 #include "asterisk/app.h"
00237 #include "asterisk/musiconhold.h"
00238 #include "asterisk/dsp.h"
00239 #include "asterisk/features.h"
00240 #include "asterisk/srv.h"
00241 #include "asterisk/astdb.h"
00242 #include "asterisk/causes.h"
00243 #include "asterisk/utils.h"
00244 #include "asterisk/file.h"
00245 #include "asterisk/astobj.h"
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255
00256
00257
00258 #include "asterisk/astobj2.h"
00259 #include "asterisk/dnsmgr.h"
00260 #include "asterisk/devicestate.h"
00261 #include "asterisk/linkedlists.h"
00262 #include "asterisk/stringfields.h"
00263 #include "asterisk/monitor.h"
00264 #include "asterisk/netsock.h"
00265 #include "asterisk/localtime.h"
00266 #include "asterisk/abstract_jb.h"
00267 #include "asterisk/threadstorage.h"
00268 #include "asterisk/translate.h"
00269 #include "asterisk/ast_version.h"
00270 #include "asterisk/event.h"
00271 #include "asterisk/tcptls.h"
00272 #include "asterisk/strings.h"
00273
00274
00275
00276
00277
00278
00279
00280
00281
00282
00283
00284
00285
00286
00287
00288
00289
00290
00291
00292
00293
00294
00295
00296
00297
00298
00299
00300
00301
00302
00303
00304
00305
00306
00307
00308
00309
00310
00311
00312
00313
00314
00315
00316
00317
00318
00319
00320
00321
00322
00323
00324
00325
00326
00327
00328
00329
00330
00331
00332
00333
00334
00335
00336
00337
00338
00339
00340
00341
00342
00343
00344
00345
00346
00347
00348
00349
00350
00351
00352
00353
00354
00355
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365
00366
00367
00368
00369
00370
00371
00372
00373
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391
00392
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402
00403
00404
00405
00406
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443
00444
00445
00446
00447
00448
00449
00450
00451
00452
00453
00454
00455
00456
00457
00458
00459
00460
00461
00462
00463
00464
00465
00466
00467
00468
00469
00470
00471
00472
00473
00474
00475
00476 #ifndef FALSE
00477 #define FALSE 0
00478 #endif
00479
00480 #ifndef TRUE
00481 #define TRUE 1
00482 #endif
00483
00484
00485 #define FINDUSERS (1 << 0)
00486 #define FINDPEERS (1 << 1)
00487 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00488
00489 #define SIPBUFSIZE 512
00490
00491 #define XMIT_ERROR -2
00492
00493 #define SIP_RESERVED ";/?:@&=+$,# "
00494
00495
00496
00497 #define DEFAULT_DEFAULT_EXPIRY 120
00498 #define DEFAULT_MIN_EXPIRY 60
00499 #define DEFAULT_MAX_EXPIRY 3600
00500 #define DEFAULT_MWI_EXPIRY 3600
00501 #define DEFAULT_REGISTRATION_TIMEOUT 20
00502 #define DEFAULT_MAX_FORWARDS "70"
00503 #define DEFAULT_AUTHLIMIT 100
00504 #define DEFAULT_AUTHTIMEOUT 30
00505
00506
00507
00508 #define EXPIRY_GUARD_SECS 15
00509 #define EXPIRY_GUARD_LIMIT 30
00510
00511 #define EXPIRY_GUARD_MIN 500
00512
00513
00514
00515 #define EXPIRY_GUARD_PCT 0.20
00516
00517 #define DEFAULT_EXPIRY 900
00518
00519 static int min_expiry = DEFAULT_MIN_EXPIRY;
00520 static int max_expiry = DEFAULT_MAX_EXPIRY;
00521 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00522 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00523
00524 #define DEFAULT_QUALIFY_GAP 100
00525 #define DEFAULT_QUALIFY_PEERS 1
00526
00527
00528 #define CALLERID_UNKNOWN "Anonymous"
00529 #define FROMDOMAIN_INVALID "anonymous.invalid"
00530
00531 #define DEFAULT_MAXMS 2000
00532 #define DEFAULT_QUALIFYFREQ 60 * 1000
00533 #define DEFAULT_FREQ_NOTOK 10 * 1000
00534
00535 #define DEFAULT_RETRANS 1000
00536 #define MAX_RETRANS 6
00537 #define DEFAULT_TIMER_T1 500
00538 #define SIP_TRANS_TIMEOUT 64 * DEFAULT_TIMER_T1
00539
00540
00541 #define DEFAULT_TRANS_TIMEOUT -1
00542 #define PROVIS_KEEPALIVE_TIMEOUT 60000
00543 #define MAX_AUTHTRIES 3
00544
00545 #define SIP_MAX_HEADERS 64
00546 #define SIP_MAX_LINES 256
00547 #define SIP_MIN_PACKET 4096
00548 #define MAX_HISTORY_ENTRIES 50
00549
00550 #define INITIAL_CSEQ 101
00551
00552 #define DEFAULT_MAX_SE 1800
00553 #define DEFAULT_MIN_SE 90
00554
00555 #define SDP_MAX_RTPMAP_CODECS 32
00556
00557 static int unauth_sessions = 0;
00558 static int authlimit = DEFAULT_AUTHLIMIT;
00559 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00560
00561
00562 static struct ast_jb_conf default_jbconf =
00563 {
00564 .flags = 0,
00565 .max_size = -1,
00566 .resync_threshold = -1,
00567 .impl = "",
00568 .target_extra = -1,
00569 };
00570 static struct ast_jb_conf global_jbconf;
00571
00572 static const char config[] = "sip.conf";
00573 static const char notify_config[] = "sip_notify.conf";
00574
00575 #define RTP 1
00576 #define NO_RTP 0
00577
00578
00579
00580
00581
00582 enum transfermodes {
00583 TRANSFER_OPENFORALL,
00584 TRANSFER_CLOSED,
00585 };
00586
00587
00588
00589 enum sip_result {
00590 AST_SUCCESS = 0,
00591 AST_FAILURE = -1,
00592 };
00593
00594
00595
00596
00597 enum invitestates {
00598 INV_NONE = 0,
00599 INV_CALLING = 1,
00600 INV_PROCEEDING = 2,
00601 INV_EARLY_MEDIA = 3,
00602 INV_COMPLETED = 4,
00603 INV_CONFIRMED = 5,
00604 INV_TERMINATED = 6,
00605
00606 INV_CANCELLED = 7,
00607 };
00608
00609
00610
00611 static const struct invstate2stringtable {
00612 const enum invitestates state;
00613 const char *desc;
00614 } invitestate2string[] = {
00615 {INV_NONE, "None" },
00616 {INV_CALLING, "Calling (Trying)"},
00617 {INV_PROCEEDING, "Proceeding "},
00618 {INV_EARLY_MEDIA, "Early media"},
00619 {INV_COMPLETED, "Completed (done)"},
00620 {INV_CONFIRMED, "Confirmed (up)"},
00621 {INV_TERMINATED, "Done"},
00622 {INV_CANCELLED, "Cancelled"}
00623 };
00624
00625
00626
00627
00628 enum xmittype {
00629 XMIT_CRITICAL = 2,
00630
00631 XMIT_RELIABLE = 1,
00632 XMIT_UNRELIABLE = 0,
00633 };
00634
00635
00636 enum parse_register_result {
00637 PARSE_REGISTER_DENIED,
00638 PARSE_REGISTER_FAILED,
00639 PARSE_REGISTER_UPDATE,
00640 PARSE_REGISTER_QUERY,
00641 };
00642
00643
00644 enum subscriptiontype {
00645 NONE = 0,
00646 XPIDF_XML,
00647 DIALOG_INFO_XML,
00648 CPIM_PIDF_XML,
00649 PIDF_XML,
00650 MWI_NOTIFICATION
00651 };
00652
00653
00654
00655
00656
00657
00658 static const struct cfsubscription_types {
00659 enum subscriptiontype type;
00660 const char * const event;
00661 const char * const mediatype;
00662 const char * const text;
00663 } subscription_types[] = {
00664 { NONE, "-", "unknown", "unknown" },
00665
00666 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00667 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00668 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00669 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00670 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00671 };
00672
00673
00674
00675
00676
00677
00678
00679 enum sip_auth_type {
00680 PROXY_AUTH = 407,
00681 WWW_AUTH = 401,
00682 };
00683
00684
00685 enum check_auth_result {
00686 AUTH_DONT_KNOW = -100,
00687
00688
00689 AUTH_SUCCESSFUL = 0,
00690 AUTH_CHALLENGE_SENT = 1,
00691 AUTH_SECRET_FAILED = -1,
00692 AUTH_USERNAME_MISMATCH = -2,
00693 AUTH_NOT_FOUND = -3,
00694 AUTH_FAKE_AUTH = -4,
00695 AUTH_UNKNOWN_DOMAIN = -5,
00696 AUTH_PEER_NOT_DYNAMIC = -6,
00697 AUTH_ACL_FAILED = -7,
00698 AUTH_BAD_TRANSPORT = -8,
00699 };
00700
00701
00702 enum sipregistrystate {
00703 REG_STATE_UNREGISTERED = 0,
00704
00705
00706
00707
00708 REG_STATE_REGSENT,
00709
00710
00711
00712
00713 REG_STATE_AUTHSENT,
00714
00715
00716
00717
00718 REG_STATE_REGISTERED,
00719
00720 REG_STATE_REJECTED,
00721
00722
00723
00724
00725
00726 REG_STATE_TIMEOUT,
00727
00728
00729 REG_STATE_NOAUTH,
00730
00731
00732 REG_STATE_FAILED,
00733
00734 };
00735
00736
00737 enum st_mode {
00738 SESSION_TIMER_MODE_INVALID = 0,
00739 SESSION_TIMER_MODE_ACCEPT,
00740 SESSION_TIMER_MODE_ORIGINATE,
00741 SESSION_TIMER_MODE_REFUSE
00742 };
00743
00744
00745 enum st_refresher {
00746 SESSION_TIMER_REFRESHER_AUTO,
00747 SESSION_TIMER_REFRESHER_UAC,
00748 SESSION_TIMER_REFRESHER_UAS
00749 };
00750
00751
00752
00753
00754 enum sip_transport {
00755 SIP_TRANSPORT_UDP = 1,
00756 SIP_TRANSPORT_TCP = 1 << 1,
00757 SIP_TRANSPORT_TLS = 1 << 2,
00758 };
00759
00760
00761
00762
00763
00764
00765
00766
00767 struct sip_proxy {
00768 char name[MAXHOSTNAMELEN];
00769 struct sockaddr_in ip;
00770 time_t last_dnsupdate;
00771 enum sip_transport transport;
00772 int force;
00773
00774 };
00775
00776
00777 struct __show_chan_arg {
00778 int fd;
00779 int subscriptions;
00780 int numchans;
00781 };
00782
00783
00784
00785 enum can_create_dialog {
00786 CAN_NOT_CREATE_DIALOG,
00787 CAN_CREATE_DIALOG,
00788 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00789 };
00790
00791
00792
00793
00794
00795
00796
00797
00798
00799
00800
00801 enum sipmethod {
00802 SIP_UNKNOWN,
00803 SIP_RESPONSE,
00804 SIP_REGISTER,
00805 SIP_OPTIONS,
00806 SIP_NOTIFY,
00807 SIP_INVITE,
00808 SIP_ACK,
00809 SIP_PRACK,
00810 SIP_BYE,
00811 SIP_REFER,
00812 SIP_SUBSCRIBE,
00813 SIP_MESSAGE,
00814 SIP_UPDATE,
00815 SIP_INFO,
00816 SIP_CANCEL,
00817 SIP_PUBLISH,
00818 SIP_PING,
00819 };
00820
00821
00822 enum notifycid_setting {
00823 DISABLED = 0,
00824 ENABLED = 1,
00825 IGNORE_CONTEXT = 2,
00826 };
00827
00828
00829
00830
00831
00832 static const struct cfsip_methods {
00833 enum sipmethod id;
00834 int need_rtp;
00835 char * const text;
00836 enum can_create_dialog can_create;
00837 } sip_methods[] = {
00838 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
00839 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00840 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00841 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00842 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00843 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00844 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00845 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00846 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00847 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00848 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
00849 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00850 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00851 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00852 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00853 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00854 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00855 };
00856
00857 static unsigned int chan_idx;
00858
00859
00860
00861
00862
00863
00864
00865
00866
00867
00868
00869 #define SUPPORTED 1
00870 #define NOT_SUPPORTED 0
00871
00872
00873 #define SIP_OPT_REPLACES (1 << 0)
00874 #define SIP_OPT_100REL (1 << 1)
00875 #define SIP_OPT_TIMER (1 << 2)
00876 #define SIP_OPT_EARLY_SESSION (1 << 3)
00877 #define SIP_OPT_JOIN (1 << 4)
00878 #define SIP_OPT_PATH (1 << 5)
00879 #define SIP_OPT_PREF (1 << 6)
00880 #define SIP_OPT_PRECONDITION (1 << 7)
00881 #define SIP_OPT_PRIVACY (1 << 8)
00882 #define SIP_OPT_SDP_ANAT (1 << 9)
00883 #define SIP_OPT_SEC_AGREE (1 << 10)
00884 #define SIP_OPT_EVENTLIST (1 << 11)
00885 #define SIP_OPT_GRUU (1 << 12)
00886 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00887 #define SIP_OPT_NOREFERSUB (1 << 14)
00888 #define SIP_OPT_HISTINFO (1 << 15)
00889 #define SIP_OPT_RESPRIORITY (1 << 16)
00890 #define SIP_OPT_FROMCHANGE (1 << 17)
00891 #define SIP_OPT_RECLISTINV (1 << 18)
00892 #define SIP_OPT_RECLISTSUB (1 << 19)
00893 #define SIP_OPT_OUTBOUND (1 << 20)
00894 #define SIP_OPT_UNKNOWN (1 << 21)
00895
00896
00897
00898
00899 static const struct cfsip_options {
00900 int id;
00901 int supported;
00902 char * const text;
00903 } sip_options[] = {
00904
00905 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
00906
00907 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
00908
00909 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00910
00911 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
00912
00913 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
00914
00915 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
00916
00917 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
00918
00919 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
00920
00921 { SIP_OPT_OUTBOUND, NOT_SUPPORTED, "outbound" },
00922
00923 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
00924
00925 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
00926
00927 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00928
00929 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
00930
00931 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
00932
00933 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
00934
00935 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
00936
00937 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
00938
00939 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
00940
00941 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00942
00943 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
00944
00945 { SIP_OPT_TIMER, SUPPORTED, "timer" },
00946
00947 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00948 };
00949
00950
00951
00952
00953
00954
00955 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00956
00957
00958 #define STANDARD_SIP_PORT 5060
00959
00960 #define STANDARD_TLS_PORT 5061
00961
00962
00963
00964
00965
00966
00967
00968
00969
00970
00971
00972
00973
00974
00975
00976
00977
00978 #define DEFAULT_CONTEXT "default"
00979 #define DEFAULT_MOHINTERPRET "default"
00980 #define DEFAULT_MOHSUGGEST ""
00981 #define DEFAULT_VMEXTEN "asterisk"
00982 #define DEFAULT_CALLERID "asterisk"
00983 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
00984 #define DEFAULT_ALLOWGUEST TRUE
00985 #define DEFAULT_RTPKEEPALIVE 0
00986 #define DEFAULT_CALLCOUNTER FALSE
00987 #define DEFAULT_SRVLOOKUP TRUE
00988 #define DEFAULT_COMPACTHEADERS FALSE
00989 #define DEFAULT_TOS_SIP 0
00990 #define DEFAULT_TOS_AUDIO 0
00991 #define DEFAULT_TOS_VIDEO 0
00992 #define DEFAULT_TOS_TEXT 0
00993 #define DEFAULT_COS_SIP 4
00994 #define DEFAULT_COS_AUDIO 5
00995 #define DEFAULT_COS_VIDEO 6
00996 #define DEFAULT_COS_TEXT 5
00997 #define DEFAULT_ALLOW_EXT_DOM TRUE
00998 #define DEFAULT_REALM "asterisk"
00999 #define DEFAULT_NOTIFYRINGING TRUE
01000 #define DEFAULT_NOTIFYCID DISABLED
01001 #define DEFAULT_PEDANTIC FALSE
01002 #define DEFAULT_AUTOCREATEPEER FALSE
01003 #define DEFAULT_MATCHEXTERNIPLOCALLY FALSE
01004 #define DEFAULT_QUALIFY FALSE
01005 #define DEFAULT_CALLEVENTS FALSE
01006 #define DEFAULT_ALWAYSAUTHREJECT FALSE
01007 #define DEFAULT_REGEXTENONQUALIFY FALSE
01008 #define DEFAULT_T1MIN 100
01009 #define DEFAULT_MAX_CALL_BITRATE (384)
01010 #ifndef DEFAULT_USERAGENT
01011 #define DEFAULT_USERAGENT "Asterisk PBX"
01012 #define DEFAULT_SDPSESSION "Asterisk PBX"
01013 #define DEFAULT_SDPOWNER "root"
01014 #endif
01015
01016
01017
01018
01019
01020
01021
01022 static char default_language[MAX_LANGUAGE];
01023 static char default_callerid[AST_MAX_EXTENSION];
01024 static char default_fromdomain[AST_MAX_EXTENSION];
01025 static char default_notifymime[AST_MAX_EXTENSION];
01026 static int default_qualify;
01027 static char default_vmexten[AST_MAX_EXTENSION];
01028 static char default_mohinterpret[MAX_MUSICCLASS];
01029 static char default_mohsuggest[MAX_MUSICCLASS];
01030
01031 static char default_parkinglot[AST_MAX_CONTEXT];
01032 static int default_maxcallbitrate;
01033 static struct ast_codec_pref default_prefs;
01034 static unsigned int default_transports;
01035 static unsigned int default_primary_transport;
01036
01037
01038
01039
01040
01041
01042
01043
01044
01045
01046
01047
01048
01049 struct sip_settings {
01050 int peer_rtupdate;
01051 int rtsave_sysname;
01052 int ignore_regexpire;
01053 int rtautoclear;
01054 int directrtpsetup;
01055 int pedanticsipchecking;
01056 int autocreatepeer;
01057 int srvlookup;
01058 int allowguest;
01059 int alwaysauthreject;
01060 int compactheaders;
01061 int allow_external_domains;
01062 int callevents;
01063 int regextenonqualify;
01064 int matchexterniplocally;
01065 int notifyringing;
01066 int notifyhold;
01067 enum notifycid_setting notifycid;
01068 enum transfermodes allowtransfer;
01069 int allowsubscribe;
01070
01071 char realm[MAXHOSTNAMELEN];
01072 struct sip_proxy outboundproxy;
01073 char default_context[AST_MAX_CONTEXT];
01074 char default_subscribecontext[AST_MAX_CONTEXT];
01075 };
01076
01077 static struct sip_settings sip_cfg;
01078
01079 static int global_match_auth_username;
01080
01081 static int global_relaxdtmf;
01082 static int global_prematuremediafilter;
01083 static int global_relaxdtmf;
01084 static int global_rtptimeout;
01085 static int global_rtpholdtimeout;
01086 static int global_rtpkeepalive;
01087 static int global_reg_timeout;
01088 static int global_regattempts_max;
01089 static int global_shrinkcallerid;
01090 static int global_callcounter;
01091
01092
01093 static unsigned int global_tos_sip;
01094 static unsigned int global_tos_audio;
01095 static unsigned int global_tos_video;
01096 static unsigned int global_tos_text;
01097 static unsigned int global_cos_sip;
01098 static unsigned int global_cos_audio;
01099 static unsigned int global_cos_video;
01100 static unsigned int global_cos_text;
01101 static int recordhistory;
01102 static int dumphistory;
01103 static char global_regcontext[AST_MAX_CONTEXT];
01104 static char global_useragent[AST_MAX_EXTENSION];
01105 static char global_sdpsession[AST_MAX_EXTENSION];
01106 static char global_sdpowner[AST_MAX_EXTENSION];
01107 static int global_authfailureevents;
01108 static int global_t1;
01109 static int global_t1min;
01110 static int global_timer_b;
01111 static int global_autoframing;
01112 static int global_qualifyfreq;
01113 static int global_qualify_gap;
01114 static int global_qualify_peers;
01115
01116
01117
01118 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
01119
01120 static enum st_mode global_st_mode;
01121 static enum st_refresher global_st_refresher;
01122 static int global_min_se;
01123 static int global_max_se;
01124
01125 static int global_dynamic_exclude_static = 0;
01126
01127
01128
01129 static struct ast_ha *global_contact_ha = NULL;
01130
01131
01132
01133
01134 static int speerobjs = 0;
01135 static int rpeerobjs = 0;
01136 static int apeerobjs = 0;
01137 static int regobjs = 0;
01138
01139
01140 static struct ast_flags global_flags[2] = {{0}};
01141 static int global_t38_maxdatagram;
01142
01143 static char used_context[AST_MAX_CONTEXT];
01144
01145
01146 AST_MUTEX_DEFINE_STATIC(netlock);
01147
01148
01149
01150 AST_MUTEX_DEFINE_STATIC(monlock);
01151
01152 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
01153
01154
01155
01156 static pthread_t monitor_thread = AST_PTHREADT_NULL;
01157
01158 static int sip_reloading = FALSE;
01159 static enum channelreloadreason sip_reloadreason;
01160
01161 static struct sched_context *sched;
01162 static struct io_context *io;
01163 static int *sipsock_read_id;
01164
01165 #define DEC_CALL_LIMIT 0
01166 #define INC_CALL_LIMIT 1
01167 #define DEC_CALL_RINGING 2
01168 #define INC_CALL_RINGING 3
01169
01170
01171 struct sip_socket {
01172 enum sip_transport type;
01173 int fd;
01174 uint16_t port;
01175 struct ast_tcptls_session_instance *tcptls_session;
01176 };
01177
01178
01179
01180
01181
01182
01183
01184
01185
01186
01187
01188
01189
01190
01191
01192
01193
01194
01195
01196
01197
01198
01199
01200
01201
01202 struct sip_request {
01203 ptrdiff_t rlPart1;
01204 ptrdiff_t rlPart2;
01205 int len;
01206 int headers;
01207 int method;
01208 int lines;
01209 unsigned int sdp_start;
01210 unsigned int sdp_count;
01211 char debug;
01212 char has_to_tag;
01213 char ignore;
01214 char authenticated;
01215
01216 ptrdiff_t header[SIP_MAX_HEADERS];
01217
01218 ptrdiff_t line[SIP_MAX_LINES];
01219 struct ast_str *data;
01220 struct ast_str *content;
01221
01222 struct sip_socket socket;
01223 AST_LIST_ENTRY(sip_request) next;
01224 };
01225
01226
01227
01228
01229
01230
01231
01232
01233 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
01234
01235
01236 struct sip_dual {
01237 struct ast_channel *chan1;
01238 struct ast_channel *chan2;
01239 struct sip_request req;
01240 int seqno;
01241 };
01242
01243 struct sip_pkt;
01244
01245
01246 struct sip_invite_param {
01247 int addsipheaders;
01248 const char *uri_options;
01249 const char *vxml_url;
01250 char *auth;
01251 char *authheader;
01252 enum sip_auth_type auth_type;
01253 const char *replaces;
01254 int transfer;
01255 };
01256
01257
01258 struct sip_route {
01259 struct sip_route *next;
01260 char hop[0];
01261 };
01262
01263
01264 struct sip_via {
01265 char *via;
01266 const char *protocol;
01267 const char *sent_by;
01268 const char *branch;
01269 const char *maddr;
01270 unsigned int port;
01271 unsigned char ttl;
01272 };
01273
01274
01275 enum domain_mode {
01276 SIP_DOMAIN_AUTO,
01277 SIP_DOMAIN_CONFIG,
01278 };
01279
01280
01281
01282
01283
01284 struct domain {
01285 char domain[MAXHOSTNAMELEN];
01286 char context[AST_MAX_EXTENSION];
01287 enum domain_mode mode;
01288 AST_LIST_ENTRY(domain) list;
01289 };
01290
01291 static AST_LIST_HEAD_STATIC(domain_list, domain);
01292
01293
01294
01295 struct sip_history {
01296 AST_LIST_ENTRY(sip_history) list;
01297 char event[0];
01298 };
01299
01300 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
01301
01302
01303 struct sip_auth {
01304 char realm[AST_MAX_EXTENSION];
01305 char username[256];
01306 char secret[256];
01307 char md5secret[256];
01308 struct sip_auth *next;
01309 };
01310
01311
01312
01313
01314
01315
01316
01317
01318
01319
01320
01321 #define SIP_OUTGOING (1 << 0)
01322 #define SIP_RINGING (1 << 2)
01323 #define SIP_PROGRESS_SENT (1 << 3)
01324 #define SIP_NEEDREINVITE (1 << 4)
01325 #define SIP_PENDINGBYE (1 << 5)
01326 #define SIP_GOTREFER (1 << 6)
01327 #define SIP_CALL_LIMIT (1 << 7)
01328 #define SIP_INC_COUNT (1 << 8)
01329 #define SIP_INC_RINGING (1 << 9)
01330 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10)
01331
01332 #define SIP_PROMISCREDIR (1 << 11)
01333 #define SIP_TRUSTRPID (1 << 12)
01334 #define SIP_USEREQPHONE (1 << 13)
01335 #define SIP_USECLIENTCODE (1 << 14)
01336
01337
01338 #define SIP_DTMF (7 << 15)
01339 #define SIP_DTMF_RFC2833 (0 << 15)
01340 #define SIP_DTMF_INBAND (1 << 15)
01341 #define SIP_DTMF_INFO (2 << 15)
01342 #define SIP_DTMF_AUTO (3 << 15)
01343 #define SIP_DTMF_SHORTINFO (4 << 15)
01344
01345
01346 #define SIP_NAT (3 << 18)
01347 #define SIP_NAT_NEVER (0 << 18)
01348 #define SIP_NAT_RFC3581 (1 << 18)
01349 #define SIP_NAT_ROUTE (2 << 18)
01350 #define SIP_NAT_ALWAYS (3 << 18)
01351
01352
01353 #define SIP_REINVITE (7 << 20)
01354 #define SIP_REINVITE_NONE (0 << 20)
01355 #define SIP_DIRECT_MEDIA (1 << 20)
01356 #define SIP_DIRECT_MEDIA_NAT (2 << 20)
01357 #define SIP_REINVITE_UPDATE (4 << 20)
01358
01359
01360 #define SIP_INSECURE (3 << 23)
01361 #define SIP_INSECURE_NONE (0 << 23)
01362 #define SIP_INSECURE_PORT (1 << 23)
01363 #define SIP_INSECURE_INVITE (1 << 24)
01364
01365
01366 #define SIP_PROG_INBAND (3 << 25)
01367 #define SIP_PROG_INBAND_NEVER (0 << 25)
01368 #define SIP_PROG_INBAND_NO (1 << 25)
01369 #define SIP_PROG_INBAND_YES (2 << 25)
01370
01371 #define SIP_SENDRPID (1 << 29)
01372 #define SIP_G726_NONSTANDARD (1 << 31)
01373
01374
01375 #define SIP_FLAGS_TO_COPY \
01376 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01377 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01378 SIP_USEREQPHONE | SIP_INSECURE)
01379
01380
01381
01382
01383
01384
01385 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
01386 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
01387 #define SIP_PAGE2_HAVEPEERCONTEXT (1 << 3)
01388
01389 #define SIP_PAGE2_FORWARD_LOOP_DETECTED (1 << 8)
01390 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9)
01391
01392 #define SIP_PAGE2_RPORT_PRESENT (1 << 10)
01393 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14)
01394 #define SIP_PAGE2_TEXTSUPPORT (1 << 15)
01395 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)
01396 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17)
01397 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18)
01398 #define SIP_PAGE2_IGNORESDPVERSION (1 << 19)
01399
01400 #define SIP_PAGE2_T38SUPPORT (3 << 20)
01401 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20)
01402 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC (2 << 20)
01403 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY (3 << 20)
01404
01405 #define SIP_PAGE2_CALL_ONHOLD (3 << 23)
01406 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23)
01407 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23)
01408 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)
01409
01410 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
01411 #define SIP_PAGE2_BUGGY_MWI (1 << 26)
01412 #define SIP_PAGE2_DIALOG_ESTABLISHED (1 << 27)
01413 #define SIP_PAGE2_FAX_DETECT (3 << 28)
01414 #define SIP_PAGE2_FAX_DETECT_CNG (1 << 28)
01415 #define SIP_PAGE2_FAX_DETECT_T38 (2 << 28)
01416 #define SIP_PAGE2_FAX_DETECT_BOTH (3 << 28)
01417 #define SIP_PAGE2_REGISTERTRYING (1 << 29)
01418 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30)
01419 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS (1 << 31)
01420
01421 #define SIP_PAGE2_FLAGS_TO_COPY \
01422 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01423 SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01424 SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01425 SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | \
01426 SIP_PAGE2_HAVEPEERCONTEXT | SIP_PAGE2_FORWARD_LOOP_DETECTED)
01427
01428
01429
01430
01431
01432
01433
01434
01435
01436 enum sip_debug_e {
01437 sip_debug_none = 0,
01438 sip_debug_config = 1,
01439 sip_debug_console = 2,
01440 };
01441
01442 static enum sip_debug_e sipdebug;
01443
01444
01445
01446
01447
01448 static int sipdebug_text;
01449
01450
01451 enum t38state {
01452 T38_DISABLED = 0,
01453 T38_LOCAL_REINVITE,
01454 T38_PEER_REINVITE,
01455 T38_ENABLED
01456 };
01457
01458
01459 struct t38properties {
01460 enum t38state state;
01461 struct ast_control_t38_parameters our_parms;
01462 struct ast_control_t38_parameters their_parms;
01463 };
01464
01465
01466 enum referstatus {
01467 REFER_IDLE,
01468 REFER_SENT,
01469 REFER_RECEIVED,
01470 REFER_CONFIRMED,
01471 REFER_ACCEPTED,
01472 REFER_RINGING,
01473 REFER_200OK,
01474 REFER_FAILED,
01475 REFER_NOAUTH
01476 };
01477
01478
01479
01480
01481
01482
01483 struct _map_x_s {
01484 int x;
01485 const char *s;
01486 };
01487
01488 static const struct _map_x_s referstatusstrings[] = {
01489 { REFER_IDLE, "<none>" },
01490 { REFER_SENT, "Request sent" },
01491 { REFER_RECEIVED, "Request received" },
01492 { REFER_CONFIRMED, "Confirmed" },
01493 { REFER_ACCEPTED, "Accepted" },
01494 { REFER_RINGING, "Target ringing" },
01495 { REFER_200OK, "Done" },
01496 { REFER_FAILED, "Failed" },
01497 { REFER_NOAUTH, "Failed - auth failure" },
01498 { -1, NULL}
01499 };
01500
01501
01502
01503 struct sip_refer {
01504 char refer_to[AST_MAX_EXTENSION];
01505 char refer_to_domain[AST_MAX_EXTENSION];
01506 char refer_to_urioption[AST_MAX_EXTENSION];
01507 char refer_to_context[AST_MAX_EXTENSION];
01508 char referred_by[AST_MAX_EXTENSION];
01509 char referred_by_name[AST_MAX_EXTENSION];
01510 char refer_contact[AST_MAX_EXTENSION];
01511 char replaces_callid[SIPBUFSIZE];
01512 char replaces_callid_totag[SIPBUFSIZE/2];
01513 char replaces_callid_fromtag[SIPBUFSIZE/2];
01514 struct sip_pvt *refer_call;
01515
01516
01517
01518 int attendedtransfer;
01519 int localtransfer;
01520 enum referstatus status;
01521 };
01522
01523
01524
01525
01526
01527 struct sip_st_dlg {
01528 int st_active;
01529 int st_interval;
01530 int st_schedid;
01531 enum st_refresher st_ref;
01532 int st_expirys;
01533 int st_active_peer_ua;
01534 int st_cached_min_se;
01535 int st_cached_max_se;
01536 enum st_mode st_cached_mode;
01537 enum st_refresher st_cached_ref;
01538 unsigned char quit_flag:1;
01539 };
01540
01541
01542
01543
01544
01545 struct sip_st_cfg {
01546 enum st_mode st_mode_oper;
01547 enum st_refresher st_ref;
01548 int st_min_se;
01549 int st_max_se;
01550 };
01551
01552 struct offered_media {
01553 int offered;
01554 char text[128];
01555 };
01556
01557
01558
01559
01560
01561 struct sip_pvt {
01562 struct sip_pvt *next;
01563 enum invitestates invitestate;
01564 int method;
01565 AST_DECLARE_STRING_FIELDS(
01566 AST_STRING_FIELD(callid);
01567 AST_STRING_FIELD(randdata);
01568 AST_STRING_FIELD(accountcode);
01569 AST_STRING_FIELD(realm);
01570 AST_STRING_FIELD(nonce);
01571 AST_STRING_FIELD(opaque);
01572 AST_STRING_FIELD(qop);
01573 AST_STRING_FIELD(domain);
01574 AST_STRING_FIELD(from);
01575 AST_STRING_FIELD(useragent);
01576 AST_STRING_FIELD(exten);
01577 AST_STRING_FIELD(context);
01578 AST_STRING_FIELD(subscribecontext);
01579 AST_STRING_FIELD(subscribeuri);
01580 AST_STRING_FIELD(fromdomain);
01581 AST_STRING_FIELD(fromuser);
01582 AST_STRING_FIELD(fromname);
01583 AST_STRING_FIELD(tohost);
01584 AST_STRING_FIELD(todnid);
01585 AST_STRING_FIELD(language);
01586 AST_STRING_FIELD(mohinterpret);
01587 AST_STRING_FIELD(mohsuggest);
01588 AST_STRING_FIELD(rdnis);
01589 AST_STRING_FIELD(redircause);
01590 AST_STRING_FIELD(theirtag);
01591 AST_STRING_FIELD(username);
01592 AST_STRING_FIELD(peername);
01593 AST_STRING_FIELD(authname);
01594 AST_STRING_FIELD(uri);
01595 AST_STRING_FIELD(okcontacturi);
01596 AST_STRING_FIELD(peersecret);
01597 AST_STRING_FIELD(peermd5secret);
01598 AST_STRING_FIELD(cid_num);
01599 AST_STRING_FIELD(cid_name);
01600 AST_STRING_FIELD(fullcontact);
01601
01602 AST_STRING_FIELD(our_contact);
01603 AST_STRING_FIELD(rpid);
01604 AST_STRING_FIELD(rpid_from);
01605 AST_STRING_FIELD(url);
01606 AST_STRING_FIELD(parkinglot);
01607 );
01608 char via[128];
01609 struct sip_socket socket;
01610 unsigned int ocseq;
01611 unsigned int icseq;
01612 ast_group_t callgroup;
01613 ast_group_t pickupgroup;
01614 int lastinvite;
01615 struct ast_flags flags[2];
01616
01617
01618 char do_history;
01619 char alreadygone;
01620 char needdestroy;
01621 char outgoing_call;
01622 char answered_elsewhere;
01623 char novideo;
01624 char notext;
01625
01626 int timer_t1;
01627 int timer_b;
01628 unsigned int sipoptions;
01629 unsigned int reqsipoptions;
01630 struct ast_codec_pref prefs;
01631 int capability;
01632 int jointcapability;
01633 int peercapability;
01634 int prefcodec;
01635 int noncodeccapability;
01636 int jointnoncodeccapability;
01637 int redircodecs;
01638 int maxcallbitrate;
01639 int t38_maxdatagram;
01640 struct sip_proxy *outboundproxy;
01641 struct t38properties t38;
01642 struct sockaddr_in udptlredirip;
01643 struct ast_udptl *udptl;
01644 int callingpres;
01645 int authtries;
01646 int expiry;
01647 long branch;
01648 long invite_branch;
01649 char tag[11];
01650 int sessionid;
01651 int sessionversion;
01652 int64_t sessionversion_remote;
01653 int session_modify;
01654 unsigned int portinuri:1;
01655 struct sockaddr_in sa;
01656 struct sockaddr_in redirip;
01657 struct sockaddr_in vredirip;
01658 struct sockaddr_in tredirip;
01659 time_t lastrtprx;
01660 time_t lastrtptx;
01661 int rtptimeout;
01662 struct sockaddr_in recv;
01663 struct sockaddr_in ourip;
01664 struct ast_channel *owner;
01665 struct sip_route *route;
01666 int route_persistant;
01667 struct ast_variable *notify_headers;
01668 struct sip_auth *peerauth;
01669 int noncecount;
01670 unsigned int stalenonce:1;
01671 char lastmsg[256];
01672 int amaflags;
01673 int pendinginvite;
01674 int glareinvite;
01675
01676
01677 struct sip_request initreq;
01678
01679
01680
01681 int initid;
01682 int waitid;
01683 int autokillid;
01684 int t38id;
01685 enum transfermodes allowtransfer;
01686 struct sip_refer *refer;
01687 enum subscriptiontype subscribed;
01688 int stateid;
01689 int laststate;
01690 int dialogver;
01691
01692 struct ast_dsp *dsp;
01693
01694 struct sip_peer *relatedpeer;
01695
01696 struct sip_registry *registry;
01697 struct ast_rtp *rtp;
01698 struct ast_rtp *vrtp;
01699 struct ast_rtp *trtp;
01700 struct sip_pkt *packets;
01701 struct sip_history_head *history;
01702 size_t history_entries;
01703 struct ast_variable *chanvars;
01704 AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue;
01705 int request_queue_sched_id;
01706 int provisional_keepalive_sched_id;
01707 const char *last_provisional;
01708 struct sip_invite_param *options;
01709 int autoframing;
01710
01711
01712
01713 struct sip_st_dlg *stimer;
01714
01715 int red;
01716 int hangupcause;
01717
01718 struct sip_subscription_mwi *mwi;
01719
01720
01721
01722
01723
01724
01725
01726
01727
01728
01729
01730
01731
01732
01733 struct offered_media offered_media[4];
01734 };
01735
01736
01737
01738
01739
01740
01741
01742
01743
01744
01745 struct ao2_container *dialogs;
01746
01747 #define sip_pvt_lock(x) ao2_lock(x)
01748 #define sip_pvt_trylock(x) ao2_trylock(x)
01749 #define sip_pvt_unlock(x) ao2_unlock(x)
01750
01751
01752
01753
01754
01755
01756 #ifdef REF_DEBUG
01757 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01758 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01759
01760 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01761 {
01762 if (p)
01763 _ao2_ref_debug(p, 1, tag, file, line, func);
01764 else
01765 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01766 return p;
01767 }
01768
01769 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01770 {
01771 if (p)
01772 _ao2_ref_debug(p, -1, tag, file, line, func);
01773 return NULL;
01774 }
01775 #else
01776 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01777 {
01778 if (p)
01779 ao2_ref(p, 1);
01780 else
01781 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01782 return p;
01783 }
01784
01785 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01786 {
01787 if (p)
01788 ao2_ref(p, -1);
01789 return NULL;
01790 }
01791 #endif
01792
01793
01794
01795
01796
01797
01798
01799 struct sip_pkt {
01800 struct sip_pkt *next;
01801 int retrans;
01802 int method;
01803 int seqno;
01804 char is_resp;
01805 char is_fatal;
01806 int response_code;
01807 struct sip_pvt *owner;
01808 int retransid;
01809 int timer_a;
01810 int timer_t1;
01811 int packetlen;
01812 struct ast_str *data;
01813 };
01814
01815
01816
01817
01818
01819
01820
01821 struct sip_mailbox {
01822 char *mailbox;
01823 char *context;
01824 unsigned int delme:1;
01825
01826 struct ast_event_sub *event_sub;
01827 AST_LIST_ENTRY(sip_mailbox) entry;
01828 };
01829
01830 enum sip_peer_type {
01831 SIP_TYPE_PEER = (1 << 0),
01832 SIP_TYPE_USER = (1 << 1),
01833 };
01834
01835
01836
01837
01838 struct sip_peer {
01839 char name[80];
01840 AST_DECLARE_STRING_FIELDS(
01841 AST_STRING_FIELD(secret);
01842 AST_STRING_FIELD(md5secret);
01843 AST_STRING_FIELD(remotesecret);
01844 AST_STRING_FIELD(context);
01845 AST_STRING_FIELD(subscribecontext);
01846 AST_STRING_FIELD(username);
01847 AST_STRING_FIELD(accountcode);
01848 AST_STRING_FIELD(tohost);
01849 AST_STRING_FIELD(regexten);
01850 AST_STRING_FIELD(fromuser);
01851 AST_STRING_FIELD(fromdomain);
01852 AST_STRING_FIELD(fullcontact);
01853 AST_STRING_FIELD(cid_num);
01854 AST_STRING_FIELD(cid_name);
01855 AST_STRING_FIELD(vmexten);
01856 AST_STRING_FIELD(language);
01857 AST_STRING_FIELD(mohinterpret);
01858 AST_STRING_FIELD(mohsuggest);
01859 AST_STRING_FIELD(parkinglot);
01860 AST_STRING_FIELD(useragent);
01861 );
01862 struct sip_socket socket;
01863 enum sip_transport default_outbound_transport;
01864
01865 unsigned int transports:3;
01866 struct sip_auth *auth;
01867 int amaflags;
01868 int callingpres;
01869 int inUse;
01870 int inRinging;
01871 int onHold;
01872 int call_limit;
01873 int t38_maxdatagram;
01874 int busy_level;
01875 enum transfermodes allowtransfer;
01876 struct ast_codec_pref prefs;
01877 int lastmsgssent;
01878 unsigned int sipoptions;
01879 struct ast_flags flags[2];
01880
01881
01882 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01883
01884
01885 char is_realtime;
01886 char rt_fromcontact;
01887 char host_dynamic;
01888 char selfdestruct;
01889 char the_mark;
01890
01891 int expire;
01892 int capability;
01893 int rtptimeout;
01894 int rtpholdtimeout;
01895 int rtpkeepalive;
01896 ast_group_t callgroup;
01897 ast_group_t pickupgroup;
01898 struct sip_proxy *outboundproxy;
01899 struct ast_dnsmgr_entry *dnsmgr;
01900 struct sockaddr_in addr;
01901 int maxcallbitrate;
01902 unsigned int portinuri:1;
01903
01904
01905 struct sip_pvt *call;
01906 int pokeexpire;
01907 int lastms;
01908 int maxms;
01909 int qualifyfreq;
01910 struct timeval ps;
01911 struct sockaddr_in defaddr;
01912 struct ast_ha *ha;
01913 struct ast_ha *contactha;
01914 struct ast_variable *chanvars;
01915 struct sip_pvt *mwipvt;
01916 int autoframing;
01917 struct sip_st_cfg stimer;
01918 int timer_t1;
01919 int timer_b;
01920 int deprecated_username;
01921
01922
01923 enum sip_peer_type type;
01924 };
01925
01926
01927
01928
01929
01930
01931
01932
01933
01934
01935
01936
01937
01938
01939 struct sip_registry {
01940 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01941 AST_DECLARE_STRING_FIELDS(
01942 AST_STRING_FIELD(callid);
01943 AST_STRING_FIELD(realm);
01944 AST_STRING_FIELD(nonce);
01945 AST_STRING_FIELD(opaque);
01946 AST_STRING_FIELD(qop);
01947 AST_STRING_FIELD(domain);
01948 AST_STRING_FIELD(username);
01949 AST_STRING_FIELD(authuser);
01950 AST_STRING_FIELD(hostname);
01951 AST_STRING_FIELD(secret);
01952 AST_STRING_FIELD(md5secret);
01953 AST_STRING_FIELD(callback);
01954 AST_STRING_FIELD(random);
01955 AST_STRING_FIELD(peername);
01956 );
01957 enum sip_transport transport;
01958 int portno;
01959 int expire;
01960 int configured_expiry;
01961 int expiry;
01962 int regattempts;
01963 int timeout;
01964 int refresh;
01965 struct sip_pvt *call;
01966 enum sipregistrystate regstate;
01967 struct timeval regtime;
01968 int callid_valid;
01969 unsigned int ocseq;
01970 struct ast_dnsmgr_entry *dnsmgr;
01971 struct sockaddr_in us;
01972 int noncecount;
01973 char lastmsg[256];
01974 };
01975
01976 enum sip_tcptls_alert {
01977
01978 TCPTLS_ALERT_DATA,
01979
01980 TCPTLS_ALERT_STOP,
01981 };
01982
01983 struct tcptls_packet {
01984 AST_LIST_ENTRY(tcptls_packet) entry;
01985 struct ast_str *data;
01986 size_t len;
01987 };
01988
01989 struct sip_threadinfo {
01990 int stop;
01991 int alert_pipe[2];
01992 pthread_t threadid;
01993 struct ast_tcptls_session_instance *tcptls_session;
01994 enum sip_transport type;
01995 AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01996 };
01997
01998
01999 struct sip_subscription_mwi {
02000 ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
02001 AST_DECLARE_STRING_FIELDS(
02002 AST_STRING_FIELD(username);
02003 AST_STRING_FIELD(authuser);
02004 AST_STRING_FIELD(hostname);
02005 AST_STRING_FIELD(secret);
02006 AST_STRING_FIELD(mailbox);
02007 );
02008 enum sip_transport transport;
02009 int portno;
02010 int resub;
02011 unsigned int subscribed:1;
02012 struct sip_pvt *call;
02013 struct ast_dnsmgr_entry *dnsmgr;
02014 struct sockaddr_in us;
02015 };
02016
02017
02018 #ifdef LOW_MEMORY
02019 static const int HASH_PEER_SIZE = 17;
02020 static const int HASH_DIALOG_SIZE = 17;
02021 #else
02022 static const int HASH_PEER_SIZE = 563;
02023 static const int HASH_DIALOG_SIZE = 563;
02024 #endif
02025 static struct ao2_container *threadt;
02026
02027
02028 struct ao2_container *peers;
02029 struct ao2_container *peers_by_ip;
02030
02031
02032 static struct ast_register_list {
02033 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02034 int recheck;
02035 } regl;
02036
02037
02038 static struct ast_subscription_mwi_list {
02039 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02040 } submwil;
02041
02042
02043
02044
02045 static int peer_hash_cb(const void *obj, const int flags)
02046 {
02047 const struct sip_peer *peer = obj;
02048
02049 return ast_str_case_hash(peer->name);
02050 }
02051
02052
02053
02054
02055 static int peer_cmp_cb(void *obj, void *arg, int flags)
02056 {
02057 struct sip_peer *peer = obj, *peer2 = arg;
02058
02059 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02060 }
02061
02062
02063
02064
02065 static int peer_iphash_cb(const void *obj, const int flags)
02066 {
02067 const struct sip_peer *peer = obj;
02068 int ret1 = peer->addr.sin_addr.s_addr;
02069 if (ret1 < 0)
02070 ret1 = -ret1;
02071
02072 return ret1;
02073 }
02074
02075
02076
02077
02078
02079
02080
02081
02082
02083
02084
02085
02086
02087
02088
02089
02090
02091
02092
02093 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02094 {
02095 struct sip_peer *peer = obj, *peer2 = arg;
02096
02097 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02098
02099 return 0;
02100 }
02101
02102
02103 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02104
02105 return CMP_MATCH | CMP_STOP;
02106 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02107
02108
02109 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02110 (CMP_MATCH | CMP_STOP) : 0;
02111 }
02112
02113
02114 return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02115 }
02116
02117
02118 static int threadt_hash_cb(const void *obj, const int flags)
02119 {
02120 const struct sip_threadinfo *th = obj;
02121
02122 return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02123 }
02124
02125 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02126 {
02127 struct sip_threadinfo *th = obj, *th2 = arg;
02128
02129 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02130 }
02131
02132
02133
02134
02135 static int dialog_hash_cb(const void *obj, const int flags)
02136 {
02137 const struct sip_pvt *pvt = obj;
02138
02139 return ast_str_case_hash(pvt->callid);
02140 }
02141
02142
02143
02144
02145 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02146 {
02147 struct sip_pvt *pvt = obj, *pvt2 = arg;
02148
02149 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02150 }
02151
02152 static int temp_pvt_init(void *);
02153 static void temp_pvt_cleanup(void *);
02154
02155
02156 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02157
02158 #ifdef LOW_MEMORY
02159 static void ts_ast_rtp_destroy(void *);
02160
02161 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02162 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02163 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02164 #endif
02165
02166
02167
02168 static struct sip_auth *authl = NULL;
02169
02170
02171
02172
02173
02174
02175
02176
02177
02178
02179
02180
02181
02182
02183
02184
02185
02186
02187 static int sipsock = -1;
02188
02189 static struct sockaddr_in bindaddr;
02190
02191
02192
02193
02194
02195
02196
02197 static struct sockaddr_in internip;
02198
02199
02200
02201
02202
02203
02204
02205
02206
02207
02208
02209
02210
02211
02212
02213
02214
02215
02216
02217 static struct sockaddr_in externip;
02218
02219 static char externhost[MAXHOSTNAMELEN];
02220 static time_t externexpire;
02221 static int externrefresh = 10;
02222 static struct sockaddr_in stunaddr;
02223
02224
02225
02226
02227
02228
02229
02230 static struct ast_ha *localaddr;
02231
02232 static int ourport_tcp;
02233 static int ourport_tls;
02234 static struct sockaddr_in debugaddr;
02235
02236 static struct ast_config *notify_types = NULL;
02237
02238
02239
02240 #define UNLINK(element, head, prev) do { \
02241 if (prev) \
02242 (prev)->next = (element)->next; \
02243 else \
02244 (head) = (element)->next; \
02245 } while (0)
02246
02247 enum t38_action_flag {
02248 SDP_T38_NONE = 0,
02249 SDP_T38_INITIATE,
02250 SDP_T38_ACCEPT,
02251 };
02252
02253
02254
02255
02256
02257
02258 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02259 static int sip_devicestate(void *data);
02260 static int sip_sendtext(struct ast_channel *ast, const char *text);
02261 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02262 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02263 static int sip_hangup(struct ast_channel *ast);
02264 static int sip_answer(struct ast_channel *ast);
02265 static struct ast_frame *sip_read(struct ast_channel *ast);
02266 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02267 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02268 static int sip_transfer(struct ast_channel *ast, const char *dest);
02269 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02270 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02271 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02272 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02273 static const char *sip_get_callid(struct ast_channel *chan);
02274
02275 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02276 static int sip_standard_port(enum sip_transport type, int port);
02277 static int sip_prepare_socket(struct sip_pvt *p);
02278 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02279
02280
02281 static int sipsock_read(int *id, int fd, short events, void *ignore);
02282 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02283 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02284 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02285 static int retrans_pkt(const void *data);
02286 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);
02287 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02288 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02289 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02290 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02291 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02292 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);
02293 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02294 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02295 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02296 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02297 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02298 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02299 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02300 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02301 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02302 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02303 static int transmit_refer(struct sip_pvt *p, const char *dest);
02304 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02305 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02306 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02307 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02308 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02309 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02310 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02311 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02312 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02313 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02314
02315
02316 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02317 int useglobal_nat, const int intended_method, struct sip_request *req);
02318 static int __sip_autodestruct(const void *data);
02319 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02320 static int sip_cancel_destroy(struct sip_pvt *p);
02321 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02322 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02323 static void *registry_unref(struct sip_registry *reg, char *tag);
02324 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02325 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02326 static void __sip_pretend_ack(struct sip_pvt *p);
02327 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02328 static int auto_congest(const void *arg);
02329 static int update_call_counter(struct sip_pvt *fup, int event);
02330 static int hangup_sip2cause(int cause);
02331 static const char *hangup_cause2sip(int cause);
02332 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02333 static void free_old_route(struct sip_route *route);
02334 static void list_route(struct sip_route *route);
02335 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02336 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02337 struct sip_request *req, char *uri);
02338 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02339 static void check_pendings(struct sip_pvt *p);
02340 static void *sip_park_thread(void *stuff);
02341 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02342
02343 static void *sip_pickup_thread(void *stuff);
02344 static int sip_pickup(struct ast_channel *chan);
02345
02346 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02347
02348
02349 static void try_suggested_sip_codec(struct sip_pvt *p);
02350 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02351 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02352 static int find_sdp(struct sip_request *req);
02353 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02354 static int process_sdp_o(const char *o, struct sip_pvt *p);
02355 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02356 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02357 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02358 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02359 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);
02360 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02361 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02362 struct ast_str **m_buf, struct ast_str **a_buf,
02363 int debug, int *min_packet_size);
02364 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02365 struct ast_str **m_buf, struct ast_str **a_buf,
02366 int debug);
02367 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02368 static void do_setnat(struct sip_pvt *p, int natflags);
02369 static void stop_media_flows(struct sip_pvt *p);
02370
02371
02372 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02373 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02374 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02375 const char *secret, const char *md5secret, int sipmethod,
02376 char *uri, enum xmittype reliable, int ignore);
02377 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02378 int sipmethod, char *uri, enum xmittype reliable,
02379 struct sockaddr_in *sin, struct sip_peer **authpeer);
02380 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02381
02382
02383 static int check_sip_domain(const char *domain, char *context, size_t len);
02384 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02385 static void clear_sip_domains(void);
02386
02387
02388 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02389 static int clear_realm_authentication(struct sip_auth *authlist);
02390 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02391
02392
02393 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02394 static int sip_do_reload(enum channelreloadreason reason);
02395 static int reload_config(enum channelreloadreason reason);
02396 static int expire_register(const void *data);
02397 static void *do_monitor(void *data);
02398 static int restart_monitor(void);
02399 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02400 static struct ast_variable *copy_vars(struct ast_variable *src);
02401
02402 static int sip_refer_allocate(struct sip_pvt *p);
02403 static void ast_quiet_chan(struct ast_channel *chan);
02404 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02405 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02406
02407
02408
02409
02410
02411
02412
02413
02414 #define check_request_transport(peer, tmpl) ({ \
02415 int ret = 0; \
02416 if (peer->socket.type == tmpl->socket.type) \
02417 ; \
02418 else if (!(peer->transports & tmpl->socket.type)) {\
02419 ast_log(LOG_ERROR, \
02420 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02421 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02422 ); \
02423 ret = 1; \
02424 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02425 ast_log(LOG_WARNING, \
02426 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02427 peer->name, get_transport(tmpl->socket.type) \
02428 ); \
02429 } else { \
02430 ast_debug(1, \
02431 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02432 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02433 ); \
02434 }\
02435 (ret); \
02436 })
02437
02438
02439
02440 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02441 static int sip_devicestate(void *data);
02442 static int sip_poke_noanswer(const void *data);
02443 static int sip_poke_peer(struct sip_peer *peer, int force);
02444 static void sip_poke_all_peers(void);
02445 static void sip_peer_hold(struct sip_pvt *p, int hold);
02446 static void mwi_event_cb(const struct ast_event *, void *);
02447
02448
02449 static const char *sip_nat_mode(const struct sip_pvt *p);
02450 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02451 static char *transfermode2str(enum transfermodes mode) attribute_const;
02452 static const char *nat2str(int nat) attribute_const;
02453 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02454 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02455 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02456 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02457 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02458 static void print_group(int fd, ast_group_t group, int crlf);
02459 static const char *dtmfmode2str(int mode) attribute_const;
02460 static int str2dtmfmode(const char *str) attribute_unused;
02461 static const char *insecure2str(int mode) attribute_const;
02462 static void cleanup_stale_contexts(char *new, char *old);
02463 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02464 static const char *domain_mode_to_text(const enum domain_mode mode);
02465 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02466 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02467 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02468 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02469 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02470 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02471 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02472 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02473 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02474 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02475 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02476 static char *complete_sip_peer(const char *word, int state, int flags2);
02477 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02478 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02479 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02480 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02481 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02482 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02483 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02484 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02485 static char *sip_do_debug_ip(int fd, char *arg);
02486 static char *sip_do_debug_peer(int fd, char *arg);
02487 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02488 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02489 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02490 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02491 static int sip_addheader(struct ast_channel *chan, void *data);
02492 static int sip_do_reload(enum channelreloadreason reason);
02493 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02494 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02495
02496
02497
02498
02499
02500 static void sip_dump_history(struct sip_pvt *dialog);
02501 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02502 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02503
02504
02505
02506
02507 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02508 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02509 static void sip_dump_history(struct sip_pvt *dialog);
02510
02511
02512 static struct sip_peer *temp_peer(const char *name);
02513 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02514 static int update_call_counter(struct sip_pvt *fup, int event);
02515 static void sip_destroy_peer(struct sip_peer *peer);
02516 static void sip_destroy_peer_fn(void *peer);
02517 static void set_peer_defaults(struct sip_peer *peer);
02518 static struct sip_peer *temp_peer(const char *name);
02519 static void register_peer_exten(struct sip_peer *peer, int onoff);
02520 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02521 static int sip_poke_peer_s(const void *data);
02522 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02523 static void reg_source_db(struct sip_peer *peer);
02524 static void destroy_association(struct sip_peer *peer);
02525 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02526 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02527 static void set_socket_transport(struct sip_socket *socket, int transport);
02528
02529
02530 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);
02531 static void update_peer(struct sip_peer *p, int expire);
02532 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02533 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02534 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02535 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02536
02537
02538 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02539 static void sip_registry_destroy(struct sip_registry *reg);
02540 static int sip_register(const char *value, int lineno);
02541 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02542 static int sip_reregister(const void *data);
02543 static int __sip_do_register(struct sip_registry *r);
02544 static int sip_reg_timeout(const void *data);
02545 static void sip_send_all_registers(void);
02546 static int sip_reinvite_retry(const void *data);
02547
02548
02549 static void append_date(struct sip_request *req);
02550 static int determine_firstline_parts(struct sip_request *req);
02551 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02552 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02553 static int find_sip_method(const char *msg);
02554 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02555 static int parse_request(struct sip_request *req);
02556 static const char *get_header(const struct sip_request *req, const char *name);
02557 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02558 static int method_match(enum sipmethod id, const char *name);
02559 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02560 static char *get_in_brackets(char *tmp);
02561 static const char *find_alias(const char *name, const char *_default);
02562 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02563 static int lws2sws(char *msgbuf, int len);
02564 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02565 static char *remove_uri_parameters(char *uri);
02566 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02567 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02568 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02569 static int set_address_from_contact(struct sip_pvt *pvt);
02570 static void check_via(struct sip_pvt *p, struct sip_request *req);
02571 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02572 static int get_rpid_num(const char *input, char *output, int maxlen);
02573 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02574 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02575 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02576 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02577 static struct sip_via *parse_via(const char *header);
02578 static void free_via(struct sip_via *v);
02579
02580
02581 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02582 static void *sip_tcp_worker_fn(void *);
02583
02584
02585 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02586 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02587 static void deinit_req(struct sip_request *req);
02588 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02589 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02590 static int init_resp(struct sip_request *resp, const char *msg);
02591 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02592 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02593 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02594 static void build_via(struct sip_pvt *p);
02595 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02596 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02597 static char *generate_random_string(char *buf, size_t size);
02598 static void build_callid_pvt(struct sip_pvt *pvt);
02599 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02600 static void make_our_tag(char *tagbuf, size_t len);
02601 static int add_header(struct sip_request *req, const char *var, const char *value);
02602 static int add_content(struct sip_request *req, const char *line);
02603 static int finalize_content(struct sip_request *req);
02604 static int add_text(struct sip_request *req, const char *text);
02605 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02606 static int add_vidupdate(struct sip_request *req);
02607 static void add_route(struct sip_request *req, struct sip_route *route);
02608 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02609 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02610 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02611 static void set_destination(struct sip_pvt *p, char *uri);
02612 static void append_date(struct sip_request *req);
02613 static void build_contact(struct sip_pvt *p);
02614 static void build_rpid(struct sip_pvt *p);
02615
02616
02617 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02618 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);
02619 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02620 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02621 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02622 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02623 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02624 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02625 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02626 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02627 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02628 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02629 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02630
02631
02632 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02633 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02634 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02635 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02636 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02637 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02638
02639
02640 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);
02641 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02642 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02643 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02644 static int sip_get_codec(struct ast_channel *chan);
02645 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02646
02647
02648 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02649 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02650 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02651 static void change_t38_state(struct sip_pvt *p, int state);
02652
02653
02654 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02655 static int proc_session_timer(const void *vp);
02656 static void stop_session_timer(struct sip_pvt *p);
02657 static void start_session_timer(struct sip_pvt *p);
02658 static void restart_session_timer(struct sip_pvt *p);
02659 static const char *strefresher2str(enum st_refresher r);
02660 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02661 static int parse_minse(const char *p_hdrval, int *const p_interval);
02662 static int st_get_se(struct sip_pvt *, int max);
02663 static enum st_refresher st_get_refresher(struct sip_pvt *);
02664 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
02665 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02666
02667
02668 static int sip_subscribe_mwi(const char *value, int lineno);
02669 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02670 static void sip_send_all_mwi_subscriptions(void);
02671 static int sip_subscribe_mwi_do(const void *data);
02672 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02673
02674
02675 static const struct ast_channel_tech sip_tech = {
02676 .type = "SIP",
02677 .description = "Session Initiation Protocol (SIP)",
02678 .capabilities = AST_FORMAT_AUDIO_MASK,
02679 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02680 .requester = sip_request_call,
02681 .devicestate = sip_devicestate,
02682 .call = sip_call,
02683 .send_html = sip_sendhtml,
02684 .hangup = sip_hangup,
02685 .answer = sip_answer,
02686 .read = sip_read,
02687 .write = sip_write,
02688 .write_video = sip_write,
02689 .write_text = sip_write,
02690 .indicate = sip_indicate,
02691 .transfer = sip_transfer,
02692 .fixup = sip_fixup,
02693 .send_digit_begin = sip_senddigit_begin,
02694 .send_digit_end = sip_senddigit_end,
02695 .bridge = ast_rtp_bridge,
02696 .early_bridge = ast_rtp_early_bridge,
02697 .send_text = sip_sendtext,
02698 .func_channel_read = acf_channel_read,
02699 .queryoption = sip_queryoption,
02700 .get_pvt_uniqueid = sip_get_callid,
02701 };
02702
02703
02704
02705
02706
02707
02708
02709 static struct ast_channel_tech sip_tech_info;
02710
02711
02712
02713 static struct ast_tls_config sip_tls_cfg;
02714
02715
02716 static struct ast_tls_config default_tls_cfg;
02717
02718
02719 static struct ast_tcptls_session_args sip_tcp_desc = {
02720 .accept_fd = -1,
02721 .master = AST_PTHREADT_NULL,
02722 .tls_cfg = NULL,
02723 .poll_timeout = -1,
02724 .name = "SIP TCP server",
02725 .accept_fn = ast_tcptls_server_root,
02726 .worker_fn = sip_tcp_worker_fn,
02727 };
02728
02729
02730 static struct ast_tcptls_session_args sip_tls_desc = {
02731 .accept_fd = -1,
02732 .master = AST_PTHREADT_NULL,
02733 .tls_cfg = &sip_tls_cfg,
02734 .poll_timeout = -1,
02735 .name = "SIP TLS server",
02736 .accept_fn = ast_tcptls_server_root,
02737 .worker_fn = sip_tcp_worker_fn,
02738 };
02739
02740
02741 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
02742
02743
02744
02745
02746 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02747 {
02748 const struct _map_x_s *cur;
02749
02750 for (cur = table; cur->s; cur++)
02751 if (cur->x == x)
02752 return cur->s;
02753 return errorstring;
02754 }
02755
02756
02757
02758
02759 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02760 {
02761 const struct _map_x_s *cur;
02762
02763 for (cur = table; cur->s; cur++)
02764 if (!strcasecmp(cur->s, s))
02765 return cur->x;
02766 return errorvalue;
02767 }
02768
02769
02770
02771 static struct ast_rtp_protocol sip_rtp = {
02772 .type = "SIP",
02773 .get_rtp_info = sip_get_rtp_peer,
02774 .get_vrtp_info = sip_get_vrtp_peer,
02775 .get_trtp_info = sip_get_trtp_peer,
02776 .set_rtp_peer = sip_set_rtp_peer,
02777 .get_codec = sip_get_codec,
02778 };
02779
02780
02781
02782
02783 static struct ast_variable *copy_vars(struct ast_variable *src)
02784 {
02785 struct ast_variable *res = NULL, *tmp, *v = NULL;
02786
02787 for (v = src ; v ; v = v->next) {
02788 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02789 tmp->next = res;
02790 res = tmp;
02791 }
02792 }
02793 return res;
02794 }
02795
02796 static void tcptls_packet_destructor(void *obj)
02797 {
02798 struct tcptls_packet *packet = obj;
02799
02800 ast_free(packet->data);
02801 }
02802
02803 static void sip_tcptls_client_args_destructor(void *obj)
02804 {
02805 struct ast_tcptls_session_args *args = obj;
02806 if (args->tls_cfg) {
02807 ast_free(args->tls_cfg->certfile);
02808 ast_free(args->tls_cfg->cipher);
02809 ast_free(args->tls_cfg->cafile);
02810 ast_free(args->tls_cfg->capath);
02811 }
02812 ast_free(args->tls_cfg);
02813 ast_free((char *) args->name);
02814 }
02815
02816 static void sip_threadinfo_destructor(void *obj)
02817 {
02818 struct sip_threadinfo *th = obj;
02819 struct tcptls_packet *packet;
02820 if (th->alert_pipe[1] > -1) {
02821 close(th->alert_pipe[0]);
02822 }
02823 if (th->alert_pipe[1] > -1) {
02824 close(th->alert_pipe[1]);
02825 }
02826 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02827
02828 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02829 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02830 }
02831
02832 if (th->tcptls_session) {
02833 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02834 }
02835 }
02836
02837
02838 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02839 {
02840 struct sip_threadinfo *th;
02841
02842 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02843 return NULL;
02844 }
02845
02846 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02847
02848 if (pipe(th->alert_pipe) == -1) {
02849 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02850 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02851 return NULL;
02852 }
02853 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02854 th->tcptls_session = tcptls_session;
02855 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02856 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02857 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02858 return th;
02859 }
02860
02861
02862 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02863 {
02864 int res = len;
02865 struct sip_threadinfo *th = NULL;
02866 struct tcptls_packet *packet = NULL;
02867 struct sip_threadinfo tmp = {
02868 .tcptls_session = tcptls_session,
02869 };
02870 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02871
02872 if (!tcptls_session) {
02873 return XMIT_ERROR;
02874 }
02875
02876 ast_mutex_lock(&tcptls_session->lock);
02877
02878 if ((tcptls_session->fd == -1) ||
02879 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02880 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02881 !(packet->data = ast_str_create(len))) {
02882 goto tcptls_write_setup_error;
02883 }
02884
02885
02886 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02887 packet->len = len;
02888
02889
02890
02891
02892 ao2_lock(th);
02893 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02894 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02895 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02896 packet = NULL;
02897 res = XMIT_ERROR;
02898 } else {
02899 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02900 }
02901 ao2_unlock(th);
02902
02903 ast_mutex_unlock(&tcptls_session->lock);
02904 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02905 return res;
02906
02907 tcptls_write_setup_error:
02908 if (th) {
02909 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02910 }
02911 if (packet) {
02912 ao2_t_ref(packet, -1, "could not allocate packet's data");
02913 }
02914 ast_mutex_unlock(&tcptls_session->lock);
02915
02916 return XMIT_ERROR;
02917 }
02918
02919
02920 static void *sip_tcp_worker_fn(void *data)
02921 {
02922 struct ast_tcptls_session_instance *tcptls_session = data;
02923
02924 return _sip_tcp_helper_thread(NULL, tcptls_session);
02925 }
02926
02927
02928
02929
02930
02931
02932
02933
02934 static int sip_check_authtimeout(time_t start)
02935 {
02936 int timeout;
02937 time_t now;
02938 if(time(&now) == -1) {
02939 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02940 return -1;
02941 }
02942
02943 timeout = (authtimeout - (now - start)) * 1000;
02944 if (timeout < 0) {
02945
02946 return 0;
02947 }
02948
02949 return timeout;
02950 }
02951
02952
02953
02954
02955 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02956 {
02957 int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
02958 time_t start;
02959 struct sip_request req = { 0, } , reqcpy = { 0, };
02960 struct sip_threadinfo *me = NULL;
02961 char buf[1024] = "";
02962 struct pollfd fds[2] = { { 0 }, { 0 }, };
02963 struct ast_tcptls_session_args *ca = NULL;
02964
02965
02966
02967
02968
02969
02970
02971
02972
02973
02974
02975
02976 if (!tcptls_session->client) {
02977 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02978
02979 goto cleanup;
02980 }
02981
02982 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02983 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02984 goto cleanup;
02985 }
02986
02987 flags |= O_NONBLOCK;
02988 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02989 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02990 goto cleanup;
02991 }
02992
02993 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02994 goto cleanup;
02995 }
02996 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02997 } else {
02998 struct sip_threadinfo tmp = {
02999 .tcptls_session = tcptls_session,
03000 };
03001
03002 if ((!(ca = tcptls_session->parent)) ||
03003 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
03004 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
03005 goto cleanup;
03006 }
03007 }
03008
03009 flags = 1;
03010 if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
03011 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
03012 goto cleanup;
03013 }
03014
03015 me->threadid = pthread_self();
03016 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03017
03018
03019 fds[0].fd = tcptls_session->fd;
03020 fds[1].fd = me->alert_pipe[0];
03021 fds[0].events = fds[1].events = POLLIN | POLLPRI;
03022
03023 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
03024 goto cleanup;
03025 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
03026 goto cleanup;
03027
03028 if(time(&start) == -1) {
03029 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
03030 goto cleanup;
03031 }
03032
03033 for (;;) {
03034 struct ast_str *str_save;
03035
03036 if (!tcptls_session->client && req.authenticated && !authenticated) {
03037 authenticated = 1;
03038 ast_atomic_fetchadd_int(&unauth_sessions, -1);
03039 }
03040
03041
03042 if (!tcptls_session->client && !authenticated ) {
03043 if ((timeout = sip_check_authtimeout(start)) < 0) {
03044 goto cleanup;
03045 }
03046
03047 if (timeout == 0) {
03048 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03049 goto cleanup;
03050 }
03051 } else {
03052 timeout = -1;
03053 }
03054
03055 res = ast_poll(fds, 2, timeout);
03056 if (res < 0) {
03057 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03058 goto cleanup;
03059 } else if (res == 0) {
03060
03061 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03062 goto cleanup;
03063 }
03064
03065
03066
03067 if (fds[0].revents) {
03068 after_poll = 1;
03069
03070 fds[0].revents = 0;
03071
03072
03073 str_save = req.data;
03074 memset(&req, 0, sizeof(req));
03075 req.data = str_save;
03076 ast_str_reset(req.data);
03077
03078 str_save = reqcpy.data;
03079 memset(&reqcpy, 0, sizeof(reqcpy));
03080 reqcpy.data = str_save;
03081 ast_str_reset(reqcpy.data);
03082
03083 memset(buf, 0, sizeof(buf));
03084
03085 if (tcptls_session->ssl) {
03086 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03087 req.socket.port = htons(ourport_tls);
03088 } else {
03089 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03090 req.socket.port = htons(ourport_tcp);
03091 }
03092 req.socket.fd = tcptls_session->fd;
03093
03094
03095 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
03096 if (!tcptls_session->client && !authenticated ) {
03097 if ((timeout = sip_check_authtimeout(start)) < 0) {
03098 goto cleanup;
03099 }
03100
03101 if (timeout == 0) {
03102 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03103 goto cleanup;
03104 }
03105 } else {
03106 timeout = -1;
03107 }
03108
03109 if (!tcptls_session->ssl || need_poll) {
03110 need_poll = 0;
03111 after_poll = 1;
03112 res = ast_wait_for_input(tcptls_session->fd, timeout);
03113 if (res < 0) {
03114 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03115 goto cleanup;
03116 } else if (res == 0) {
03117
03118 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03119 goto cleanup;
03120 }
03121 }
03122
03123 ast_mutex_lock(&tcptls_session->lock);
03124 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03125 ast_mutex_unlock(&tcptls_session->lock);
03126 if (after_poll) {
03127 goto cleanup;
03128 } else {
03129 need_poll = 1;
03130 continue;
03131 }
03132 }
03133 ast_mutex_unlock(&tcptls_session->lock);
03134 after_poll = 0;
03135 if (me->stop)
03136 goto cleanup;
03137 ast_str_append(&req.data, 0, "%s", buf);
03138 req.len = req.data->used;
03139 }
03140 copy_request(&reqcpy, &req);
03141 parse_request(&reqcpy);
03142
03143 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03144 while (cl > 0) {
03145 size_t bytes_read;
03146 if (!tcptls_session->client && !authenticated ) {
03147 if ((timeout = sip_check_authtimeout(start)) < 0) {
03148 goto cleanup;
03149 }
03150
03151 if (timeout == 0) {
03152 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03153 goto cleanup;
03154 }
03155 } else {
03156 timeout = -1;
03157 }
03158
03159 if (!tcptls_session->ssl || need_poll) {
03160 res = ast_wait_for_input(tcptls_session->fd, timeout);
03161 if (res < 0) {
03162 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03163 goto cleanup;
03164 } else if (res == 0) {
03165
03166 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03167 goto cleanup;
03168 }
03169 }
03170
03171 ast_mutex_lock(&tcptls_session->lock);
03172 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03173 ast_mutex_unlock(&tcptls_session->lock);
03174 if (after_poll) {
03175 goto cleanup;
03176 } else {
03177 need_poll = 1;
03178 continue;
03179 }
03180 }
03181 buf[bytes_read] = '\0';
03182 ast_mutex_unlock(&tcptls_session->lock);
03183 after_poll = 0;
03184 if (me->stop)
03185 goto cleanup;
03186 cl -= strlen(buf);
03187 ast_str_append(&req.data, 0, "%s", buf);
03188 req.len = req.data->used;
03189 }
03190 }
03191
03192
03193
03194 req.socket.tcptls_session = tcptls_session;
03195 handle_request_do(&req, &tcptls_session->remote_address);
03196 }
03197
03198 if (fds[1].revents) {
03199 enum sip_tcptls_alert alert;
03200 struct tcptls_packet *packet;
03201
03202 fds[1].revents = 0;
03203
03204 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03205 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03206 continue;
03207 }
03208
03209 switch (alert) {
03210 case TCPTLS_ALERT_STOP:
03211 goto cleanup;
03212 case TCPTLS_ALERT_DATA:
03213 ao2_lock(me);
03214 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03215 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03216 }
03217 ao2_unlock(me);
03218
03219 if (packet) {
03220 if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03221 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03222 }
03223 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03224 }
03225 break;
03226 default:
03227 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03228 }
03229 }
03230 }
03231
03232 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03233
03234 cleanup:
03235 if (tcptls_session && !tcptls_session->client && !authenticated) {
03236 ast_atomic_fetchadd_int(&unauth_sessions, -1);
03237 }
03238
03239 if (me) {
03240 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03241 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03242 }
03243 deinit_req(&reqcpy);
03244 deinit_req(&req);
03245
03246
03247 if (ca) {
03248 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03249 }
03250
03251 if (tcptls_session) {
03252 ast_mutex_lock(&tcptls_session->lock);
03253 if (tcptls_session->f) {
03254 fclose(tcptls_session->f);
03255 tcptls_session->f = NULL;
03256 }
03257 if (tcptls_session->fd != -1) {
03258 close(tcptls_session->fd);
03259 tcptls_session->fd = -1;
03260 }
03261 tcptls_session->parent = NULL;
03262 ast_mutex_unlock(&tcptls_session->lock);
03263
03264 ao2_ref(tcptls_session, -1);
03265 tcptls_session = NULL;
03266 }
03267 return NULL;
03268 }
03269
03270 #ifdef REF_DEBUG
03271 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
03272 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
03273 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03274 {
03275 if (peer)
03276 _ao2_ref_debug(peer, 1, tag, file, line, func);
03277 else
03278 ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
03279 return peer;
03280 }
03281
03282 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03283 {
03284 if (peer)
03285 _ao2_ref_debug(peer, -1, tag, file, line, func);
03286 return NULL;
03287 }
03288 #else
03289
03290
03291
03292
03293
03294 static void *unref_peer(struct sip_peer *peer, char *tag)
03295 {
03296 ao2_t_ref(peer, -1, tag);
03297 return NULL;
03298 }
03299
03300 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03301 {
03302 ao2_t_ref(peer, 1, tag);
03303 return peer;
03304 }
03305 #endif
03306
03307 static void peer_sched_cleanup(struct sip_peer *peer)
03308 {
03309 if (peer->pokeexpire != -1) {
03310 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
03311 unref_peer(peer, "removing poke peer ref"));
03312 }
03313 if (peer->expire != -1) {
03314 AST_SCHED_DEL_UNREF(sched, peer->expire,
03315 unref_peer(peer, "remove register expire ref"));
03316 }
03317 }
03318
03319 typedef enum {
03320 SIP_PEERS_MARKED,
03321 SIP_PEERS_ALL,
03322 } peer_unlink_flag_t;
03323
03324
03325
03326 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03327 {
03328 struct sip_peer *peer = peerobj;
03329 peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03330
03331 if (which == SIP_PEERS_ALL || peer->the_mark) {
03332 peer_sched_cleanup(peer);
03333 return CMP_MATCH;
03334 }
03335 return 0;
03336 }
03337
03338 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03339 {
03340 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03341 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03342 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03343 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03344 }
03345
03346
03347 static void unlink_marked_peers_from_tables(void)
03348 {
03349 unlink_peers_from_tables(SIP_PEERS_MARKED);
03350 }
03351
03352 static void unlink_all_peers_from_tables(void)
03353 {
03354 unlink_peers_from_tables(SIP_PEERS_ALL);
03355 }
03356
03357
03358 static void unlink_peer_from_tables(struct sip_peer *peer)
03359 {
03360 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03361 if (peer->addr.sin_addr.s_addr) {
03362 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03363 }
03364 }
03365
03366
03367
03368
03369
03370
03371
03372
03373
03374
03375
03376
03377 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03378 {
03379 struct sip_proxy *old_obproxy = pvt->outboundproxy;
03380
03381
03382
03383 if (proxy && proxy != &sip_cfg.outboundproxy) {
03384 ao2_ref(proxy, +1);
03385 }
03386 pvt->outboundproxy = proxy;
03387 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03388 ao2_ref(old_obproxy, -1);
03389 }
03390 }
03391
03392
03393
03394
03395
03396
03397
03398
03399 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03400 {
03401 struct sip_pkt *cp;
03402
03403 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03404
03405 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03406
03407
03408 if (dialog->owner) {
03409 if (lockowner)
03410 ast_channel_lock(dialog->owner);
03411 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03412 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03413 if (lockowner)
03414 ast_channel_unlock(dialog->owner);
03415 }
03416 if (dialog->registry) {
03417 if (dialog->registry->call == dialog)
03418 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03419 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03420 }
03421 if (dialog->stateid > -1) {
03422 ast_extension_state_del(dialog->stateid, NULL);
03423 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03424 dialog->stateid = -1;
03425 }
03426
03427 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03428 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03429 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03430 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03431
03432
03433 while((cp = dialog->packets)) {
03434 dialog->packets = dialog->packets->next;
03435 AST_SCHED_DEL(sched, cp->retransid);
03436 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03437 if (cp->data) {
03438 ast_free(cp->data);
03439 }
03440 ast_free(cp);
03441 }
03442
03443 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"));
03444
03445 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"));
03446
03447 if (dialog->autokillid > -1)
03448 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"));
03449
03450 if (dialog->request_queue_sched_id > -1) {
03451 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"));
03452 }
03453
03454 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"));
03455
03456 if (dialog->t38id > -1) {
03457 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"));
03458 }
03459
03460 if (dialog->stimer) {
03461 stop_session_timer(dialog);
03462 }
03463
03464 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03465 return NULL;
03466 }
03467
03468 static void *registry_unref(struct sip_registry *reg, char *tag)
03469 {
03470 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03471 ASTOBJ_UNREF(reg, sip_registry_destroy);
03472 return NULL;
03473 }
03474
03475
03476 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03477 {
03478 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03479 return ASTOBJ_REF(reg);
03480 }
03481
03482
03483 static struct ast_udptl_protocol sip_udptl = {
03484 type: "SIP",
03485 get_udptl_info: sip_get_udptl_peer,
03486 set_udptl_peer: sip_set_udptl_peer,
03487 };
03488
03489 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03490 __attribute__((format(printf, 2, 3)));
03491
03492
03493
03494 static const char *referstatus2str(enum referstatus rstatus)
03495 {
03496 return map_x_s(referstatusstrings, rstatus, "");
03497 }
03498
03499 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03500 {
03501 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03502 pvt->needdestroy = 1;
03503 }
03504
03505
03506
03507
03508 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03509 {
03510 if (p->initreq.headers)
03511 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03512 else
03513 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03514
03515 copy_request(&p->initreq, req);
03516 parse_request(&p->initreq);
03517 if (req->debug)
03518 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03519 }
03520
03521
03522 static void sip_alreadygone(struct sip_pvt *dialog)
03523 {
03524 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03525 dialog->alreadygone = 1;
03526 }
03527
03528
03529 static int proxy_update(struct sip_proxy *proxy)
03530 {
03531
03532
03533 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03534
03535
03536 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03537 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03538 return FALSE;
03539 }
03540 }
03541 proxy->last_dnsupdate = time(NULL);
03542 return TRUE;
03543 }
03544
03545
03546
03547
03548
03549 static int port_str2int(const char *pt, unsigned int standard)
03550 {
03551 int port = standard;
03552 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03553 port = standard;
03554 }
03555
03556 return port;
03557 }
03558
03559
03560 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03561 {
03562 struct sip_proxy *proxy;
03563
03564 if (ast_strlen_zero(name)) {
03565 return NULL;
03566 }
03567
03568 proxy = ao2_alloc(sizeof(*proxy), NULL);
03569 if (!proxy)
03570 return NULL;
03571 proxy->force = force;
03572 ast_copy_string(proxy->name, name, sizeof(proxy->name));
03573 proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03574 proxy->ip.sin_family = AF_INET;
03575 proxy_update(proxy);
03576 return proxy;
03577 }
03578
03579
03580 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03581 {
03582 if (peer && peer->outboundproxy) {
03583 if (sipdebug)
03584 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03585 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03586 return peer->outboundproxy;
03587 }
03588 if (sip_cfg.outboundproxy.name[0]) {
03589 if (sipdebug)
03590 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03591 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03592 return &sip_cfg.outboundproxy;
03593 }
03594 if (sipdebug)
03595 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03596 return NULL;
03597 }
03598
03599
03600
03601
03602
03603
03604
03605 static int method_match(enum sipmethod id, const char *name)
03606 {
03607 int len = strlen(sip_methods[id].text);
03608 int l_name = name ? strlen(name) : 0;
03609
03610 return (l_name >= len && name[len] < 33 &&
03611 !strncasecmp(sip_methods[id].text, name, len));
03612 }
03613
03614
03615 static int find_sip_method(const char *msg)
03616 {
03617 int i, res = 0;
03618
03619 if (ast_strlen_zero(msg))
03620 return 0;
03621 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03622 if (method_match(i, msg))
03623 res = sip_methods[i].id;
03624 }
03625 return res;
03626 }
03627
03628
03629 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03630 {
03631 char *next, *sep;
03632 char *temp;
03633 unsigned int profile = 0;
03634 int i, found;
03635
03636 if (ast_strlen_zero(supported) )
03637 return 0;
03638 temp = ast_strdupa(supported);
03639
03640 if (sipdebug)
03641 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03642
03643 for (next = temp; next; next = sep) {
03644 found = FALSE;
03645 if ( (sep = strchr(next, ',')) != NULL)
03646 *sep++ = '\0';
03647 next = ast_skip_blanks(next);
03648 if (sipdebug)
03649 ast_debug(3, "Found SIP option: -%s-\n", next);
03650 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03651 if (!strcasecmp(next, sip_options[i].text)) {
03652 profile |= sip_options[i].id;
03653 found = TRUE;
03654 if (sipdebug)
03655 ast_debug(3, "Matched SIP option: %s\n", next);
03656 break;
03657 }
03658 }
03659
03660
03661
03662
03663
03664 if (!found)
03665 profile |= SIP_OPT_UNKNOWN;
03666
03667 if (!found && sipdebug) {
03668 if (!strncasecmp(next, "x-", 2))
03669 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03670 else
03671 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03672 }
03673 }
03674
03675 if (pvt)
03676 pvt->sipoptions = profile;
03677 return profile;
03678 }
03679
03680
03681 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
03682 {
03683 if (!sipdebug)
03684 return 0;
03685 if (debugaddr.sin_addr.s_addr) {
03686 if (((ntohs(debugaddr.sin_port) != 0)
03687 && (debugaddr.sin_port != addr->sin_port))
03688 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03689 return 0;
03690 }
03691 return 1;
03692 }
03693
03694
03695 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03696 {
03697 if (p->outboundproxy)
03698 return &p->outboundproxy->ip;
03699
03700 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03701 }
03702
03703
03704 static const char *sip_nat_mode(const struct sip_pvt *p)
03705 {
03706 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03707 }
03708
03709
03710 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03711 {
03712 if (!sipdebug)
03713 return 0;
03714 return sip_debug_test_addr(sip_real_dst(p));
03715 }
03716
03717
03718 static int get_transport_str2enum(const char *transport)
03719 {
03720 int res = 0;
03721
03722 if (ast_strlen_zero(transport)) {
03723 return res;
03724 }
03725
03726 if (!strcasecmp(transport, "udp")) {
03727 res |= SIP_TRANSPORT_UDP;
03728 }
03729 if (!strcasecmp(transport, "tcp")) {
03730 res |= SIP_TRANSPORT_TCP;
03731 }
03732 if (!strcasecmp(transport, "tls")) {
03733 res |= SIP_TRANSPORT_TLS;
03734 }
03735
03736 return res;
03737 }
03738
03739
03740 static inline const char *get_transport_list(unsigned int transports) {
03741 switch (transports) {
03742 case SIP_TRANSPORT_UDP:
03743 return "UDP";
03744 case SIP_TRANSPORT_TCP:
03745 return "TCP";
03746 case SIP_TRANSPORT_TLS:
03747 return "TLS";
03748 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03749 return "TCP,UDP";
03750 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03751 return "TLS,UDP";
03752 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03753 return "TLS,TCP";
03754 default:
03755 return transports ?
03756 "TLS,TCP,UDP" : "UNKNOWN";
03757 }
03758 }
03759
03760
03761 static inline const char *get_transport(enum sip_transport t)
03762 {
03763 switch (t) {
03764 case SIP_TRANSPORT_UDP:
03765 return "UDP";
03766 case SIP_TRANSPORT_TCP:
03767 return "TCP";
03768 case SIP_TRANSPORT_TLS:
03769 return "TLS";
03770 }
03771
03772 return "UNKNOWN";
03773 }
03774
03775
03776 static inline const char *get_srv_protocol(enum sip_transport t)
03777 {
03778 switch (t) {
03779 case SIP_TRANSPORT_UDP:
03780 return "udp";
03781 case SIP_TRANSPORT_TLS:
03782 case SIP_TRANSPORT_TCP:
03783 return "tcp";
03784 }
03785
03786 return "udp";
03787 }
03788
03789
03790 static inline const char *get_srv_service(enum sip_transport t)
03791 {
03792 switch (t) {
03793 case SIP_TRANSPORT_TCP:
03794 case SIP_TRANSPORT_UDP:
03795 return "sip";
03796 case SIP_TRANSPORT_TLS:
03797 return "sips";
03798 }
03799 return "sip";
03800 }
03801
03802
03803
03804
03805
03806
03807
03808 static inline const char *get_transport_pvt(struct sip_pvt *p)
03809 {
03810 if (p->outboundproxy && p->outboundproxy->transport) {
03811 set_socket_transport(&p->socket, p->outboundproxy->transport);
03812 }
03813
03814 return get_transport(p->socket.type);
03815 }
03816
03817
03818
03819
03820
03821
03822 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03823 {
03824 int res = 0;
03825 const struct sockaddr_in *dst = sip_real_dst(p);
03826
03827 ast_debug(2, "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));
03828
03829 if (sip_prepare_socket(p) < 0)
03830 return XMIT_ERROR;
03831
03832 if (p->socket.type == SIP_TRANSPORT_UDP) {
03833 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03834 } else if (p->socket.tcptls_session) {
03835 res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03836 } else {
03837 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03838 return XMIT_ERROR;
03839 }
03840
03841 if (res == -1) {
03842 switch (errno) {
03843 case EBADF:
03844 case EHOSTUNREACH:
03845 case ENETDOWN:
03846 case ENETUNREACH:
03847 case ECONNREFUSED:
03848 res = XMIT_ERROR;
03849 }
03850 }
03851 if (res != len)
03852 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));
03853
03854 return res;
03855 }
03856
03857
03858 static void build_via(struct sip_pvt *p)
03859 {
03860
03861 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03862
03863
03864 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03865 get_transport_pvt(p),
03866 ast_inet_ntoa(p->ourip.sin_addr),
03867 ntohs(p->ourip.sin_port), (int) p->branch, rport);
03868 }
03869
03870
03871
03872
03873
03874
03875
03876
03877 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03878 {
03879 struct sockaddr_in theirs;
03880
03881
03882
03883
03884
03885
03886
03887
03888
03889
03890
03891
03892 int want_remap;
03893
03894 *us = internip;
03895
03896 ast_ouraddrfor(them, &us->sin_addr);
03897 theirs.sin_addr = *them;
03898
03899 want_remap = localaddr &&
03900 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03901 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03902
03903 if (want_remap &&
03904 (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03905
03906 if (externexpire && time(NULL) >= externexpire) {
03907 if (stunaddr.sin_addr.s_addr) {
03908 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03909 } else {
03910 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03911 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03912 }
03913 externexpire = time(NULL) + externrefresh;
03914 }
03915 if (externip.sin_addr.s_addr)
03916 *us = externip;
03917 else
03918 ast_log(LOG_WARNING, "stun failed\n");
03919 ast_debug(1, "Target address %s is not local, substituting externip\n",
03920 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03921 } else if (p) {
03922
03923 switch (p->socket.type) {
03924 case SIP_TRANSPORT_TCP:
03925 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03926 *us = sip_tcp_desc.local_address;
03927 } else {
03928 us->sin_port = sip_tcp_desc.local_address.sin_port;
03929 }
03930 break;
03931 case SIP_TRANSPORT_TLS:
03932 if (sip_tls_desc.local_address.sin_addr.s_addr) {
03933 *us = sip_tls_desc.local_address;
03934 } else {
03935 us->sin_port = sip_tls_desc.local_address.sin_port;
03936 }
03937 break;
03938 case SIP_TRANSPORT_UDP:
03939
03940 default:
03941 if (bindaddr.sin_addr.s_addr) {
03942 *us = bindaddr;
03943 }
03944 }
03945 } else if (bindaddr.sin_addr.s_addr) {
03946 *us = bindaddr;
03947 }
03948 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));
03949 }
03950
03951
03952 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03953 {
03954 char buf[80], *c = buf;
03955 struct sip_history *hist;
03956 int l;
03957
03958 vsnprintf(buf, sizeof(buf), fmt, ap);
03959 strsep(&c, "\r\n");
03960 l = strlen(buf) + 1;
03961 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03962 return;
03963 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03964 ast_free(hist);
03965 return;
03966 }
03967 memcpy(hist->event, buf, l);
03968 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03969 struct sip_history *oldest;
03970 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03971 p->history_entries--;
03972 ast_free(oldest);
03973 }
03974 AST_LIST_INSERT_TAIL(p->history, hist, list);
03975 p->history_entries++;
03976 }
03977
03978
03979 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03980 {
03981 va_list ap;
03982
03983 if (!p)
03984 return;
03985
03986 if (!p->do_history && !recordhistory && !dumphistory)
03987 return;
03988
03989 va_start(ap, fmt);
03990 append_history_va(p, fmt, ap);
03991 va_end(ap);
03992
03993 return;
03994 }
03995
03996
03997 static int retrans_pkt(const void *data)
03998 {
03999 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
04000 int reschedule = DEFAULT_RETRANS;
04001 int xmitres = 0;
04002
04003
04004 sip_pvt_lock(pkt->owner);
04005
04006 if (pkt->retrans < MAX_RETRANS) {
04007 pkt->retrans++;
04008 if (!pkt->timer_t1) {
04009 if (sipdebug)
04010 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);
04011 } else {
04012 int siptimer_a;
04013
04014 if (sipdebug)
04015 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
04016 if (!pkt->timer_a)
04017 pkt->timer_a = 2 ;
04018 else
04019 pkt->timer_a = 2 * pkt->timer_a;
04020
04021
04022 siptimer_a = pkt->timer_t1 * pkt->timer_a;
04023 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
04024 siptimer_a = 4000;
04025
04026
04027 reschedule = siptimer_a;
04028 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);
04029 }
04030
04031 if (sip_debug_test_pvt(pkt->owner)) {
04032 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
04033 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
04034 pkt->retrans, sip_nat_mode(pkt->owner),
04035 ast_inet_ntoa(dst->sin_addr),
04036 ntohs(dst->sin_port), pkt->data->str);
04037 }
04038
04039 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
04040 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
04041 if (xmitres == XMIT_ERROR) {
04042 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
04043 } else {
04044 sip_pvt_unlock(pkt->owner);
04045 return reschedule;
04046 }
04047 }
04048
04049 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
04050 if (pkt->is_fatal || sipdebug)
04051 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions \n",
04052 pkt->owner->callid, pkt->seqno,
04053 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
04054 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
04055 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions \n", pkt->owner->callid);
04056
04057 }
04058 if (xmitres == XMIT_ERROR) {
04059 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
04060 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04061 } else {
04062 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04063 }
04064 pkt->retransid = -1;
04065
04066 if (pkt->is_fatal) {
04067 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
04068 sip_pvt_unlock(pkt->owner);
04069 usleep(1);
04070 sip_pvt_lock(pkt->owner);
04071 }
04072
04073 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
04074 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
04075
04076 if (pkt->owner->owner) {
04077 sip_alreadygone(pkt->owner);
04078 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions ).\n", pkt->owner->callid);
04079 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
04080 ast_channel_unlock(pkt->owner->owner);
04081 } else {
04082
04083
04084
04085 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04086 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04087 sip_alreadygone(pkt->owner);
04088 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04089 }
04090 }
04091 }
04092
04093 if (pkt->method == SIP_BYE) {
04094
04095 sip_alreadygone(pkt->owner);
04096 if (pkt->owner->owner)
04097 ast_channel_unlock(pkt->owner->owner);
04098 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04099 pvt_set_needdestroy(pkt->owner, "no response to BYE");
04100 }
04101
04102
04103 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04104 if (cur == pkt) {
04105 UNLINK(cur, pkt->owner->packets, prev);
04106 sip_pvt_unlock(pkt->owner);
04107 if (pkt->owner)
04108 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04109 if (pkt->data)
04110 ast_free(pkt->data);
04111 pkt->data = NULL;
04112 ast_free(pkt);
04113 return 0;
04114 }
04115 }
04116
04117 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04118 sip_pvt_unlock(pkt->owner);
04119 return 0;
04120 }
04121
04122
04123
04124
04125 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)
04126 {
04127 struct sip_pkt *pkt = NULL;
04128 int siptimer_a = DEFAULT_RETRANS;
04129 int xmitres = 0;
04130 int respid;
04131
04132 if (sipmethod == SIP_INVITE) {
04133
04134 p->pendinginvite = seqno;
04135 }
04136
04137
04138
04139
04140 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04141 xmitres = __sip_xmit(p, data, len);
04142 if (xmitres == XMIT_ERROR) {
04143 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04144 return AST_FAILURE;
04145 } else {
04146 return AST_SUCCESS;
04147 }
04148 }
04149
04150 if (!(pkt = ast_calloc(1, sizeof(*pkt))))
04151 return AST_FAILURE;
04152
04153 if (!(pkt->data = ast_str_create(len))) {
04154 ast_free(pkt);
04155 return AST_FAILURE;
04156 }
04157 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
04158 pkt->packetlen = len;
04159
04160 pkt->method = sipmethod;
04161 pkt->seqno = seqno;
04162 pkt->is_resp = resp;
04163 pkt->is_fatal = fatal;
04164 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04165 pkt->next = p->packets;
04166 p->packets = pkt;
04167 if (resp) {
04168
04169 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04170 pkt->response_code = respid;
04171 }
04172 }
04173 pkt->timer_t1 = p->timer_t1;
04174 pkt->retransid = -1;
04175 if (pkt->timer_t1)
04176 siptimer_a = pkt->timer_t1 * 2;
04177
04178
04179 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04180 if (sipdebug)
04181 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
04182
04183 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
04184
04185 if (xmitres == XMIT_ERROR) {
04186 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04187 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04188 AST_SCHED_DEL(sched, pkt->retransid);
04189 p->packets = pkt->next;
04190 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04191 ast_free(pkt->data);
04192 ast_free(pkt);
04193 return AST_FAILURE;
04194 } else {
04195 return AST_SUCCESS;
04196 }
04197 }
04198
04199
04200
04201
04202
04203
04204 static int __sip_autodestruct(const void *data)
04205 {
04206 struct sip_pvt *p = (struct sip_pvt *)data;
04207
04208
04209 if (p->subscribed) {
04210 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
04211 p->subscribed = NONE;
04212 append_history(p, "Subscribestatus", "timeout");
04213 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04214 return 10000;
04215 }
04216
04217
04218 if (p->packets) {
04219 if (!p->needdestroy) {
04220 char method_str[31];
04221 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04222 append_history(p, "ReliableXmit", "timeout");
04223 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04224 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04225 pvt_set_needdestroy(p, "autodestruct");
04226 }
04227 }
04228 return 10000;
04229 } else {
04230
04231 __sip_pretend_ack(p);
04232 }
04233 }
04234
04235
04236 p->autokillid = -1;
04237
04238
04239
04240
04241
04242 sip_pvt_lock(p);
04243 while (p->owner && ast_channel_trylock(p->owner)) {
04244 sip_pvt_unlock(p);
04245 sched_yield();
04246 sip_pvt_lock(p);
04247 }
04248
04249 if (p->owner) {
04250 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
04251 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
04252 ast_channel_unlock(p->owner);
04253 } else if (p->refer && !p->alreadygone) {
04254 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04255 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04256 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04257 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04258 } else {
04259 append_history(p, "AutoDestroy", "%s", p->callid);
04260 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04261 dialog_unlink_all(p, TRUE, TRUE);
04262
04263
04264
04265 }
04266
04267 sip_pvt_unlock(p);
04268
04269 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04270
04271 return 0;
04272 }
04273
04274
04275 static void sip_scheddestroy(struct sip_pvt *p, int ms)
04276 {
04277 if (ms < 0) {
04278 if (p->timer_t1 == 0) {
04279 p->timer_t1 = global_t1;
04280 p->timer_b = global_timer_b;
04281 }
04282 ms = p->timer_t1 * 64;
04283 }
04284 if (sip_debug_test_pvt(p))
04285 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04286 if (sip_cancel_destroy(p))
04287 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
04288
04289 if (p->do_history)
04290 append_history(p, "SchedDestroy", "%d ms", ms);
04291 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04292
04293 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04294 stop_session_timer(p);
04295 }
04296
04297
04298
04299
04300
04301 static int sip_cancel_destroy(struct sip_pvt *p)
04302 {
04303 if (p->autokillid > -1) {
04304 append_history(p, "CancelDestroy", "");
04305 AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04306 }
04307 return 0;
04308 }
04309
04310
04311
04312 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04313 {
04314 struct sip_pkt *cur, *prev = NULL;
04315 const char *msg = "Not Found";
04316 int res = FALSE;
04317
04318
04319
04320
04321
04322
04323 if (p->outboundproxy && !p->outboundproxy->force){
04324 ref_proxy(p, NULL);
04325 }
04326
04327 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04328 if (cur->seqno != seqno || cur->is_resp != resp)
04329 continue;
04330 if (cur->is_resp || cur->method == sipmethod) {
04331 res = TRUE;
04332 msg = "Found";
04333 if (!resp && (seqno == p->pendinginvite)) {
04334 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04335 p->pendinginvite = 0;
04336 }
04337 if (cur->retransid > -1) {
04338 if (sipdebug)
04339 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04340 }
04341
04342
04343
04344
04345
04346
04347
04348
04349
04350
04351
04352
04353
04354
04355
04356
04357 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04358 sip_pvt_unlock(p);
04359 usleep(1);
04360 sip_pvt_lock(p);
04361 }
04362 UNLINK(cur, p->packets, prev);
04363 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04364 if (cur->data)
04365 ast_free(cur->data);
04366 ast_free(cur);
04367 break;
04368 }
04369 }
04370 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04371 p->callid, resp ? "Response" : "Request", seqno, msg);
04372 return res;
04373 }
04374
04375
04376
04377 static void __sip_pretend_ack(struct sip_pvt *p)
04378 {
04379 struct sip_pkt *cur = NULL;
04380
04381 while (p->packets) {
04382 int method;
04383 if (cur == p->packets) {
04384 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04385 return;
04386 }
04387 cur = p->packets;
04388 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04389 __sip_ack(p, cur->seqno, cur->is_resp, method);
04390 }
04391 }
04392
04393
04394 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04395 {
04396 struct sip_pkt *cur;
04397 int res = FALSE;
04398
04399 for (cur = p->packets; cur; cur = cur->next) {
04400 if (cur->seqno == seqno && cur->is_resp == resp &&
04401 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04402
04403 if (cur->retransid > -1) {
04404 if (sipdebug)
04405 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04406 }
04407 AST_SCHED_DEL(sched, cur->retransid);
04408 res = TRUE;
04409 break;
04410 }
04411 }
04412 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");
04413 return res;
04414 }
04415
04416
04417
04418 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04419 {
04420 copy_request(dst, src);
04421 parse_request(dst);
04422 }
04423
04424
04425 static void add_blank(struct sip_request *req)
04426 {
04427 if (!req->lines) {
04428
04429 ast_str_append(&req->data, 0, "\r\n");
04430 req->len = ast_str_strlen(req->data);
04431 }
04432 }
04433
04434 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04435 {
04436 const char *msg = NULL;
04437
04438 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04439 msg = "183 Session Progress";
04440 }
04441
04442 if (pvt->invitestate < INV_COMPLETED) {
04443 if (with_sdp) {
04444 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04445 } else {
04446 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04447 }
04448 return PROVIS_KEEPALIVE_TIMEOUT;
04449 }
04450
04451 return 0;
04452 }
04453
04454 static int send_provisional_keepalive(const void *data) {
04455 struct sip_pvt *pvt = (struct sip_pvt *) data;
04456
04457 return send_provisional_keepalive_full(pvt, 0);
04458 }
04459
04460 static int send_provisional_keepalive_with_sdp(const void *data) {
04461 struct sip_pvt *pvt = (void *)data;
04462
04463 return send_provisional_keepalive_full(pvt, 1);
04464 }
04465
04466 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04467 {
04468 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"));
04469
04470 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04471 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04472 }
04473
04474
04475 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04476 {
04477 int res;
04478
04479 finalize_content(req);
04480 add_blank(req);
04481 if (sip_debug_test_pvt(p)) {
04482 const struct sockaddr_in *dst = sip_real_dst(p);
04483
04484 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04485 reliable ? "Reliably " : "", sip_nat_mode(p),
04486 ast_inet_ntoa(dst->sin_addr),
04487 ntohs(dst->sin_port), req->data->str);
04488 }
04489 if (p->do_history) {
04490 struct sip_request tmp = { .rlPart1 = 0, };
04491 parse_copy(&tmp, req);
04492 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04493 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04494 deinit_req(&tmp);
04495 }
04496
04497
04498 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04499 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"));
04500 }
04501
04502 res = (reliable) ?
04503 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04504 __sip_xmit(p, req->data, req->len);
04505 deinit_req(req);
04506 if (res > 0)
04507 return 0;
04508 return res;
04509 }
04510
04511
04512 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04513 {
04514 int res;
04515
04516
04517
04518
04519 if (p->outboundproxy) {
04520 p->sa = p->outboundproxy->ip;
04521 }
04522
04523 finalize_content(req);
04524 add_blank(req);
04525 if (sip_debug_test_pvt(p)) {
04526 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04527 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);
04528 else
04529 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);
04530 }
04531 if (p->do_history) {
04532 struct sip_request tmp = { .rlPart1 = 0, };
04533 parse_copy(&tmp, req);
04534 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04535 deinit_req(&tmp);
04536 }
04537 res = (reliable) ?
04538 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04539 __sip_xmit(p, req->data, req->len);
04540 deinit_req(req);
04541 return res;
04542 }
04543
04544
04545 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04546 {
04547 int res = -1;
04548 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04549 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04550
04551 switch (option) {
04552 case AST_OPTION_T38_STATE:
04553
04554 if (*datalen != sizeof(enum ast_t38_state)) {
04555 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04556 return -1;
04557 }
04558
04559 sip_pvt_lock(p);
04560
04561
04562 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04563 switch (p->t38.state) {
04564 case T38_LOCAL_REINVITE:
04565 case T38_PEER_REINVITE:
04566 state = T38_STATE_NEGOTIATING;
04567 break;
04568 case T38_ENABLED:
04569 state = T38_STATE_NEGOTIATED;
04570 break;
04571 default:
04572 state = T38_STATE_UNKNOWN;
04573 }
04574 }
04575
04576 sip_pvt_unlock(p);
04577
04578 *((enum ast_t38_state *) data) = state;
04579 res = 0;
04580
04581 break;
04582 default:
04583 break;
04584 }
04585
04586 return res;
04587 }
04588
04589
04590
04591
04592
04593 static const char *find_closing_quote(const char *start, const char *lim)
04594 {
04595 char last_char = '\0';
04596 const char *s;
04597 for (s = start; *s && s != lim; last_char = *s++) {
04598 if (*s == '"' && last_char != '\\')
04599 break;
04600 }
04601 return s;
04602 }
04603
04604
04605
04606
04607
04608
04609
04610
04611
04612
04613
04614
04615
04616 static char *get_in_brackets(char *tmp)
04617 {
04618 const char *parse = tmp;
04619 char *first_bracket;
04620
04621
04622
04623
04624
04625 while ( (first_bracket = strchr(parse, '<')) ) {
04626 char *first_quote = strchr(parse, '"');
04627
04628 if (!first_quote || first_quote > first_bracket)
04629 break;
04630
04631 parse = find_closing_quote(first_quote + 1, NULL);
04632 if (!*parse) {
04633
04634 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04635 break;
04636 }
04637 parse++;
04638 }
04639 if (first_bracket) {
04640 char *second_bracket = strchr(first_bracket + 1, '>');
04641 if (second_bracket) {
04642 *second_bracket = '\0';
04643 tmp = first_bracket + 1;
04644 } else {
04645 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04646 }
04647 }
04648
04649 return tmp;
04650 }
04651
04652
04653
04654
04655
04656
04657
04658
04659
04660
04661
04662
04663
04664
04665
04666
04667
04668
04669
04670
04671 static int parse_uri(char *uri, const char *scheme,
04672 char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04673 {
04674 char *name = NULL;
04675 int error = 0;
04676
04677
04678 if (pass)
04679 *pass = "";
04680 if (port)
04681 *port = "";
04682 if (scheme) {
04683 int l;
04684 char *scheme2 = ast_strdupa(scheme);
04685 char *cur = strsep(&scheme2, ",");
04686 for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04687 l = strlen(cur);
04688 if (!strncasecmp(uri, cur, l)) {
04689 uri += l;
04690 break;
04691 }
04692 }
04693 if (ast_strlen_zero(cur)) {
04694 ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04695 error = -1;
04696 }
04697 }
04698 if (transport) {
04699 char *t, *type = "";
04700 *transport = "";
04701 if ((t = strstr(uri, "transport="))) {
04702 strsep(&t, "=");
04703 if ((type = strsep(&t, ";"))) {
04704 *transport = type;
04705 }
04706 }
04707 }
04708
04709 if (!domain) {
04710
04711
04712
04713 } else {
04714
04715
04716
04717 char *c, *dom = "";
04718
04719 if ((c = strchr(uri, '@')) == NULL) {
04720
04721 dom = uri;
04722 name = "";
04723 } else {
04724 *c++ = '\0';
04725 dom = c;
04726 name = uri;
04727 }
04728
04729
04730 dom = strsep(&dom, ";");
04731 name = strsep(&name, ";");
04732
04733 if (port && (c = strchr(dom, ':'))) {
04734 *c++ = '\0';
04735 *port = c;
04736 }
04737 if (pass && (c = strchr(name, ':'))) {
04738 *c++ = '\0';
04739 *pass = c;
04740 }
04741 *domain = dom;
04742 }
04743 if (ret_name)
04744 *ret_name = name;
04745 if (options)
04746 *options = uri ? uri : "";
04747
04748 return error;
04749 }
04750
04751
04752 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04753 {
04754 struct sip_pvt *p = chan->tech_pvt;
04755
04756 if (subclass != AST_HTML_URL)
04757 return -1;
04758
04759 ast_string_field_build(p, url, "<%s>;mode=active", data);
04760
04761 if (sip_debug_test_pvt(p))
04762 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04763
04764 switch (chan->_state) {
04765 case AST_STATE_RING:
04766 transmit_response(p, "100 Trying", &p->initreq);
04767 break;
04768 case AST_STATE_RINGING:
04769 transmit_response(p, "180 Ringing", &p->initreq);
04770 break;
04771 case AST_STATE_UP:
04772 if (!p->pendinginvite) {
04773 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04774 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04775 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04776 }
04777 break;
04778 default:
04779 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04780 }
04781
04782 return 0;
04783 }
04784
04785
04786 static const char *sip_get_callid(struct ast_channel *chan)
04787 {
04788 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04789 }
04790
04791
04792
04793 static int sip_sendtext(struct ast_channel *ast, const char *text)
04794 {
04795 struct sip_pvt *p = ast->tech_pvt;
04796 int debug = sip_debug_test_pvt(p);
04797
04798 if (debug)
04799 ast_verbose("Sending text %s on %s\n", text, ast->name);
04800 if (!p)
04801 return -1;
04802
04803
04804 if (!text)
04805 return 0;
04806 if (debug)
04807 ast_verbose("Really sending text %s on %s\n", text, ast->name);
04808 transmit_message_with_text(p, text);
04809 return 0;
04810 }
04811
04812
04813
04814
04815
04816
04817 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)
04818 {
04819 char port[10];
04820 char ipaddr[INET_ADDRSTRLEN];
04821 char regseconds[20];
04822 char *tablename = NULL;
04823 char str_lastms[20];
04824
04825 const char *sysname = ast_config_AST_SYSTEM_NAME;
04826 char *syslabel = NULL;
04827
04828 time_t nowtime = time(NULL) + expirey;
04829 const char *fc = fullcontact ? "fullcontact" : NULL;
04830
04831 int realtimeregs = ast_check_realtime("sipregs");
04832
04833 tablename = realtimeregs ? "sipregs" : "sippeers";
04834
04835
04836 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04837 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04838 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04839 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04840
04841 if (ast_strlen_zero(sysname))
04842 sysname = NULL;
04843 else if (sip_cfg.rtsave_sysname)
04844 syslabel = "regserver";
04845
04846
04847
04848
04849
04850
04851
04852 if (fc) {
04853 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04854 "port", port, "regseconds", regseconds,
04855 deprecated_username ? "username" : "defaultuser", defaultuser,
04856 "useragent", useragent, "lastms", str_lastms,
04857 fc, fullcontact, syslabel, sysname, SENTINEL);
04858 } else {
04859 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04860 "port", port, "regseconds", regseconds,
04861 "useragent", useragent, "lastms", str_lastms,
04862 deprecated_username ? "username" : "defaultuser", defaultuser,
04863 syslabel, sysname, SENTINEL);
04864 }
04865 }
04866
04867
04868 static void register_peer_exten(struct sip_peer *peer, int onoff)
04869 {
04870 char multi[256];
04871 char *stringp, *ext, *context;
04872 struct pbx_find_info q = { .stacklen = 0 };
04873
04874
04875
04876
04877
04878 if (ast_strlen_zero(global_regcontext))
04879 return;
04880
04881 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04882 stringp = multi;
04883 while ((ext = strsep(&stringp, "&"))) {
04884 if ((context = strchr(ext, '@'))) {
04885 *context++ = '\0';
04886 if (!ast_context_find(context)) {
04887 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04888 continue;
04889 }
04890 } else {
04891 context = global_regcontext;
04892 }
04893 if (onoff) {
04894 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04895 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04896 ast_strdup(peer->name), ast_free_ptr, "SIP");
04897 }
04898 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04899 ast_context_remove_extension(context, ext, 1, NULL);
04900 }
04901 }
04902 }
04903
04904
04905 static void destroy_mailbox(struct sip_mailbox *mailbox)
04906 {
04907 if (mailbox->mailbox)
04908 ast_free(mailbox->mailbox);
04909 if (mailbox->context)
04910 ast_free(mailbox->context);
04911 if (mailbox->event_sub)
04912 ast_event_unsubscribe(mailbox->event_sub);
04913 ast_free(mailbox);
04914 }
04915
04916
04917 static void clear_peer_mailboxes(struct sip_peer *peer)
04918 {
04919 struct sip_mailbox *mailbox;
04920
04921 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04922 destroy_mailbox(mailbox);
04923 }
04924
04925 static void sip_destroy_peer_fn(void *peer)
04926 {
04927 sip_destroy_peer(peer);
04928 }
04929
04930
04931 static void sip_destroy_peer(struct sip_peer *peer)
04932 {
04933 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04934 if (peer->outboundproxy)
04935 ao2_ref(peer->outboundproxy, -1);
04936 peer->outboundproxy = NULL;
04937
04938
04939 if (peer->call) {
04940 dialog_unlink_all(peer->call, TRUE, TRUE);
04941 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04942 }
04943
04944
04945 if (peer->mwipvt) {
04946 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04947 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04948 }
04949
04950 if (peer->chanvars) {
04951 ast_variables_destroy(peer->chanvars);
04952 peer->chanvars = NULL;
04953 }
04954
04955 register_peer_exten(peer, FALSE);
04956 ast_free_ha(peer->ha);
04957 if (peer->selfdestruct)
04958 ast_atomic_fetchadd_int(&apeerobjs, -1);
04959 else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04960 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04961 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04962 } else
04963 ast_atomic_fetchadd_int(&speerobjs, -1);
04964 clear_realm_authentication(peer->auth);
04965 peer->auth = NULL;
04966 if (peer->dnsmgr)
04967 ast_dnsmgr_release(peer->dnsmgr);
04968 clear_peer_mailboxes(peer);
04969
04970 if (peer->socket.tcptls_session) {
04971 ao2_ref(peer->socket.tcptls_session, -1);
04972 peer->socket.tcptls_session = NULL;
04973 }
04974
04975 ast_string_field_free_memory(peer);
04976 }
04977
04978
04979 static void update_peer(struct sip_peer *p, int expire)
04980 {
04981 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04982 if (sip_cfg.peer_rtupdate &&
04983 (p->is_realtime || rtcachefriends)) {
04984 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04985 }
04986 }
04987
04988 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04989 {
04990 struct ast_variable *var = NULL;
04991 struct ast_flags flags = {0};
04992 char *cat = NULL;
04993 const char *insecure;
04994 while ((cat = ast_category_browse(cfg, cat))) {
04995 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04996 set_insecure_flags(&flags, insecure, -1);
04997 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04998 var = ast_category_root(cfg, cat);
04999 break;
05000 }
05001 }
05002 return var;
05003 }
05004
05005 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
05006 {
05007 struct ast_variable *tmp;
05008 for (tmp = var; tmp; tmp = tmp->next) {
05009 if (!newpeername && !strcasecmp(tmp->name, "name"))
05010 newpeername = tmp->value;
05011 }
05012 return newpeername;
05013 }
05014
05015
05016
05017
05018
05019
05020
05021 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
05022 {
05023 struct sip_peer *peer;
05024 struct ast_variable *var = NULL;
05025 struct ast_variable *varregs = NULL;
05026 struct ast_variable *tmp;
05027 struct ast_config *peerlist = NULL;
05028 char ipaddr[INET_ADDRSTRLEN];
05029 char portstring[6];
05030 char *cat = NULL;
05031 unsigned short portnum;
05032 int realtimeregs = ast_check_realtime("sipregs");
05033
05034
05035 if (newpeername) {
05036 if (realtimeregs)
05037 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05038
05039 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
05040 if (!var && sin)
05041 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
05042 if (!var) {
05043 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05044
05045
05046
05047
05048
05049
05050 if (var && sin) {
05051 for (tmp = var; tmp; tmp = tmp->next) {
05052 if (!strcasecmp(tmp->name, "host")) {
05053 struct hostent *hp;
05054 struct ast_hostent ahp;
05055 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
05056
05057 ast_variables_destroy(var);
05058 var = NULL;
05059 }
05060 break;
05061 }
05062 }
05063 }
05064 }
05065 }
05066
05067 if (!var && sin) {
05068 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
05069 portnum = ntohs(sin->sin_port);
05070 sprintf(portstring, "%u", portnum);
05071 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);
05072 if (var) {
05073 if (realtimeregs) {
05074 newpeername = get_name_from_variable(var, newpeername);
05075 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05076 }
05077 } else {
05078 if (realtimeregs)
05079 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL);
05080 else
05081 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL);
05082 if (varregs) {
05083 newpeername = get_name_from_variable(varregs, newpeername);
05084 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05085 }
05086 }
05087 if (!var) {
05088 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
05089 if (peerlist) {
05090 var = get_insecure_variable_from_config(peerlist);
05091 if(var) {
05092 if (realtimeregs) {
05093 newpeername = get_name_from_variable(var, newpeername);
05094 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05095 }
05096 } else {
05097 peerlist = NULL;
05098 cat = NULL;
05099 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
05100 if(peerlist) {
05101 var = get_insecure_variable_from_config(peerlist);
05102 if(var) {
05103 if (realtimeregs) {
05104 newpeername = get_name_from_variable(var, newpeername);
05105 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05106 }
05107 }
05108 }
05109 }
05110 } else {
05111 if (realtimeregs) {
05112 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
05113 if (peerlist) {
05114 varregs = get_insecure_variable_from_config(peerlist);
05115 if (varregs) {
05116 newpeername = get_name_from_variable(varregs, newpeername);
05117 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05118 }
05119 }
05120 } else {
05121 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
05122 if (peerlist) {
05123 var = get_insecure_variable_from_config(peerlist);
05124 if (var) {
05125 newpeername = get_name_from_variable(var, newpeername);
05126 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05127 }
05128 }
05129 }
05130 }
05131 }
05132 }
05133
05134 if (!var) {
05135 if (peerlist)
05136 ast_config_destroy(peerlist);
05137 return NULL;
05138 }
05139
05140 for (tmp = var; tmp; tmp = tmp->next) {
05141 if (!newpeername && !strcasecmp(tmp->name, "name")) {
05142 newpeername = tmp->value;
05143 }
05144 }
05145
05146 if (!newpeername) {
05147 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
05148 if(peerlist)
05149 ast_config_destroy(peerlist);
05150 else
05151 ast_variables_destroy(var);
05152 return NULL;
05153 }
05154
05155
05156
05157 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05158 if (!peer) {
05159 if(peerlist)
05160 ast_config_destroy(peerlist);
05161 else {
05162 ast_variables_destroy(var);
05163 ast_variables_destroy(varregs);
05164 }
05165 return NULL;
05166 }
05167
05168 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05169
05170 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05171
05172 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05173 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05174 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05175 unref_peer(_data, "remove registration ref"),
05176 unref_peer(peer, "remove registration ref"),
05177 ref_peer(peer, "add registration ref"));
05178 }
05179 ao2_t_link(peers, peer, "link peer into peers table");
05180 if (peer->addr.sin_addr.s_addr) {
05181 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05182 }
05183 }
05184 peer->is_realtime = 1;
05185 if (peerlist)
05186 ast_config_destroy(peerlist);
05187 else {
05188 ast_variables_destroy(var);
05189 ast_variables_destroy(varregs);
05190 }
05191
05192 return peer;
05193 }
05194
05195
05196 static int find_by_name(void *obj, void *arg, void *data, int flags)
05197 {
05198 struct sip_peer *search = obj, *match = arg;
05199 int *which_objects = data;
05200
05201
05202 if (strcmp(search->name, match->name)) {
05203 return 0;
05204 }
05205
05206 switch (*which_objects) {
05207 case FINDUSERS:
05208 if (!(search->type & SIP_TYPE_USER)) {
05209 return 0;
05210 }
05211 break;
05212 case FINDPEERS:
05213 if (!(search->type & SIP_TYPE_PEER)) {
05214 return 0;
05215 }
05216 break;
05217 case FINDALLDEVICES:
05218 break;
05219 }
05220
05221 return CMP_MATCH | CMP_STOP;
05222 }
05223
05224
05225
05226
05227
05228
05229
05230
05231
05232
05233
05234
05235
05236
05237 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
05238 {
05239 struct sip_peer *p = NULL;
05240 struct sip_peer tmp_peer;
05241
05242 if (peer) {
05243 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05244 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05245 } else if (sin) {
05246 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
05247 tmp_peer.addr.sin_port = sin->sin_port;
05248 tmp_peer.flags[0].flags = 0;
05249 tmp_peer.transports = transport;
05250 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
05251 if (!p) {
05252 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05253 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
05254 if (p) {
05255 return p;
05256 }
05257 }
05258 }
05259
05260 if (!p && (realtime || devstate_only)) {
05261 p = realtime_peer(peer, sin, devstate_only);
05262 if (p) {
05263 switch (which_objects) {
05264 case FINDUSERS:
05265 if (!(p->type & SIP_TYPE_USER)) {
05266 unref_peer(p, "Wrong type of realtime SIP endpoint");
05267 return NULL;
05268 }
05269 break;
05270 case FINDPEERS:
05271 if (!(p->type & SIP_TYPE_PEER)) {
05272 unref_peer(p, "Wrong type of realtime SIP endpoint");
05273 return NULL;
05274 }
05275 break;
05276 case FINDALLDEVICES:
05277 break;
05278 }
05279 }
05280 }
05281
05282 return p;
05283 }
05284
05285
05286 static void do_setnat(struct sip_pvt *p, int natflags)
05287 {
05288 const char *mode = natflags ? "On" : "Off";
05289
05290 if (p->rtp) {
05291 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05292 ast_rtp_setnat(p->rtp, natflags);
05293 }
05294 if (p->vrtp) {
05295 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05296 ast_rtp_setnat(p->vrtp, natflags);
05297 }
05298 if (p->udptl) {
05299 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05300 ast_udptl_setnat(p->udptl, natflags);
05301 }
05302 if (p->trtp) {
05303 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05304 ast_rtp_setnat(p->trtp, natflags);
05305 }
05306 }
05307
05308
05309 static void change_t38_state(struct sip_pvt *p, int state)
05310 {
05311 int old = p->t38.state;
05312 struct ast_channel *chan = p->owner;
05313 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05314
05315
05316 if (old == state)
05317 return;
05318
05319 p->t38.state = state;
05320 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05321
05322
05323 if (!chan)
05324 return;
05325
05326
05327 switch (state) {
05328 case T38_PEER_REINVITE:
05329 parameters = p->t38.their_parms;
05330 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05331 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05332 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05333 break;
05334 case T38_ENABLED:
05335 parameters = p->t38.their_parms;
05336 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05337 parameters.request_response = AST_T38_NEGOTIATED;
05338 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05339 break;
05340 case T38_DISABLED:
05341 if (old == T38_ENABLED) {
05342 parameters.request_response = AST_T38_TERMINATED;
05343 } else if (old == T38_LOCAL_REINVITE) {
05344 parameters.request_response = AST_T38_REFUSED;
05345 }
05346 break;
05347 case T38_LOCAL_REINVITE:
05348
05349 break;
05350 }
05351
05352
05353 if (parameters.request_response)
05354 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05355 }
05356
05357
05358 static void set_t38_capabilities(struct sip_pvt *p)
05359 {
05360 if (p->udptl) {
05361 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05362 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05363 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05364 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05365 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05366 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05367 }
05368 }
05369 }
05370
05371 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05372 {
05373 if (to_sock->tcptls_session) {
05374 ao2_ref(to_sock->tcptls_session, -1);
05375 to_sock->tcptls_session = NULL;
05376 }
05377
05378 if (from_sock->tcptls_session) {
05379 ao2_ref(from_sock->tcptls_session, +1);
05380 }
05381
05382 *to_sock = *from_sock;
05383 }
05384
05385
05386
05387
05388
05389
05390
05391
05392 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05393 {
05394
05395
05396
05397
05398 if (dialog->socket.type && check_request_transport(peer, dialog))
05399 return -1;
05400 copy_socket_data(&dialog->socket, &peer->socket);
05401
05402 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05403 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05404 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05405 dialog->recv = dialog->sa;
05406 } else
05407 return -1;
05408
05409 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05410 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05411 dialog->capability = peer->capability;
05412 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05413 (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05414 !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05415 dialog->vrtp) {
05416 ast_rtp_destroy(dialog->vrtp);
05417 dialog->vrtp = NULL;
05418 }
05419 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05420 ast_rtp_destroy(dialog->trtp);
05421 dialog->trtp = NULL;
05422 }
05423 dialog->prefs = peer->prefs;
05424 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05425
05426 if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05427 dialog->t38_maxdatagram = peer->t38_maxdatagram;
05428 set_t38_capabilities(dialog);
05429 } else {
05430
05431 ast_debug(1, "UDPTL creation failed on dialog.\n");
05432 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05433 }
05434 } else if (dialog->udptl) {
05435 ast_udptl_destroy(dialog->udptl);
05436 dialog->udptl = NULL;
05437 }
05438 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05439
05440 if (dialog->rtp) {
05441 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05442 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05443 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05444 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05445 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05446
05447 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05448 dialog->autoframing = peer->autoframing;
05449 }
05450 if (dialog->vrtp) {
05451 ast_rtp_setdtmf(dialog->vrtp, 0);
05452 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05453 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05454 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05455 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05456 }
05457 if (dialog->trtp) {
05458 ast_rtp_setdtmf(dialog->trtp, 0);
05459 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05460 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05461 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05462 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05463 }
05464
05465 ast_string_field_set(dialog, peername, peer->name);
05466 ast_string_field_set(dialog, authname, peer->username);
05467 ast_string_field_set(dialog, username, peer->username);
05468 ast_string_field_set(dialog, peersecret, peer->secret);
05469 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05470 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05471 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05472 ast_string_field_set(dialog, tohost, peer->tohost);
05473 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05474 ast_string_field_set(dialog, context, peer->context);
05475 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05476 ref_proxy(dialog, obproxy_get(dialog, peer));
05477 dialog->callgroup = peer->callgroup;
05478 dialog->pickupgroup = peer->pickupgroup;
05479 dialog->allowtransfer = peer->allowtransfer;
05480 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05481 dialog->rtptimeout = peer->rtptimeout;
05482 dialog->peerauth = peer->auth;
05483 dialog->maxcallbitrate = peer->maxcallbitrate;
05484 if (ast_strlen_zero(dialog->tohost))
05485 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05486 if (!ast_strlen_zero(peer->fromdomain)) {
05487 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05488 if (!dialog->initreq.headers) {
05489 char *c;
05490 char *tmpcall = ast_strdupa(dialog->callid);
05491
05492 c = strchr(tmpcall, '@');
05493 if (c) {
05494 *c = '\0';
05495 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05496 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05497 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05498 }
05499 }
05500 }
05501 if (!ast_strlen_zero(peer->fromuser))
05502 ast_string_field_set(dialog, fromuser, peer->fromuser);
05503 if (!ast_strlen_zero(peer->language))
05504 ast_string_field_set(dialog, language, peer->language);
05505
05506
05507
05508
05509 if (peer->maxms && peer->lastms)
05510 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05511 else
05512 dialog->timer_t1 = peer->timer_t1;
05513
05514
05515
05516 if (peer->timer_b)
05517 dialog->timer_b = peer->timer_b;
05518 else
05519 dialog->timer_b = 64 * dialog->timer_t1;
05520
05521 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05522 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05523 dialog->noncodeccapability |= AST_RTP_DTMF;
05524 else
05525 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05526 if (peer->call_limit)
05527 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05528 if (!dialog->portinuri)
05529 dialog->portinuri = peer->portinuri;
05530
05531 dialog->chanvars = copy_vars(peer->chanvars);
05532
05533 return 0;
05534 }
05535
05536
05537
05538
05539 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05540 {
05541 struct hostent *hp;
05542 struct ast_hostent ahp;
05543 struct sip_peer *peer;
05544 char *port;
05545 int portno = 0;
05546 char host[MAXHOSTNAMELEN], *hostn;
05547 char peername[256];
05548 int srv_ret = 0;
05549
05550 ast_copy_string(peername, opeer, sizeof(peername));
05551 port = strchr(peername, ':');
05552 if (port) {
05553 *port++ = '\0';
05554 dialog->portinuri = 1;
05555 }
05556 dialog->sa.sin_family = AF_INET;
05557 dialog->timer_t1 = global_t1;
05558 dialog->timer_b = global_timer_b;
05559 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05560
05561 if (peer) {
05562 int res;
05563 if (newdialog) {
05564 set_socket_transport(&dialog->socket, 0);
05565 }
05566 res = create_addr_from_peer(dialog, peer);
05567 if (!ast_strlen_zero(port)) {
05568 if ((portno = atoi(port))) {
05569 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05570 }
05571 }
05572 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05573 return res;
05574 }
05575
05576 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05577
05578 ast_string_field_set(dialog, tohost, peername);
05579
05580
05581 ref_proxy(dialog, obproxy_get(dialog, NULL));
05582
05583 if (sin) {
05584
05585 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05586 if (!sin->sin_port) {
05587 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05588 } else {
05589 portno = ntohs(sin->sin_port);
05590 }
05591 } else {
05592
05593
05594
05595
05596
05597
05598 hostn = peername;
05599
05600
05601
05602 if (!port && sip_cfg.srvlookup) {
05603 char service[MAXHOSTNAMELEN];
05604 int tportno;
05605 snprintf(service, sizeof(service), "_%s._%s.%s",
05606 get_srv_service(dialog->socket.type),
05607 get_srv_protocol(dialog->socket.type), peername);
05608 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05609 if (srv_ret > 0) {
05610 hostn = host;
05611 portno = tportno;
05612 }
05613 }
05614 if (!portno)
05615 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05616 hp = ast_gethostbyname(hostn, &ahp);
05617 if (!hp) {
05618 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05619 return -1;
05620 }
05621 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05622 }
05623
05624 if (!dialog->socket.type)
05625 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05626 if (!dialog->socket.port)
05627 dialog->socket.port = bindaddr.sin_port;
05628 dialog->sa.sin_port = htons(portno);
05629 dialog->recv = dialog->sa;
05630 return 0;
05631 }
05632
05633
05634
05635
05636 static int auto_congest(const void *arg)
05637 {
05638 struct sip_pvt *p = (struct sip_pvt *)arg;
05639
05640 sip_pvt_lock(p);
05641 p->initid = -1;
05642 if (p->owner) {
05643
05644 if (!ast_channel_trylock(p->owner)) {
05645 append_history(p, "Cong", "Auto-congesting (timer)");
05646 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05647 ast_channel_unlock(p->owner);
05648 }
05649
05650
05651 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05652 }
05653 sip_pvt_unlock(p);
05654 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05655 return 0;
05656 }
05657
05658
05659
05660
05661 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05662 {
05663 int res;
05664 struct sip_pvt *p = ast->tech_pvt;
05665 struct varshead *headp;
05666 struct ast_var_t *current;
05667 const char *referer = NULL;
05668
05669 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05670 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05671 return -1;
05672 }
05673
05674
05675 headp=&ast->varshead;
05676 AST_LIST_TRAVERSE(headp, current, entries) {
05677
05678 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05679 p->options->vxml_url = ast_var_value(current);
05680 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05681 p->options->uri_options = ast_var_value(current);
05682 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05683
05684 p->options->addsipheaders = 1;
05685 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05686 ast_string_field_set(p, fromdomain, ast_var_value(current));
05687 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05688
05689 p->options->transfer = 1;
05690 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05691
05692 referer = ast_var_value(current);
05693 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05694
05695 p->options->replaces = ast_var_value(current);
05696 }
05697 }
05698
05699 res = 0;
05700 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05701
05702
05703
05704
05705 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05706
05707 if (p->options->transfer) {
05708 char buf[SIPBUFSIZE/2];
05709
05710 if (referer) {
05711 if (sipdebug)
05712 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05713 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05714 } else
05715 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05716 ast_string_field_set(p, cid_name, buf);
05717 }
05718 ast_debug(1, "Outgoing Call for %s\n", p->username);
05719
05720 res = update_call_counter(p, INC_CALL_RINGING);
05721
05722 if (res == -1) {
05723 ast->hangupcause = AST_CAUSE_USER_BUSY;
05724 return res;
05725 }
05726 p->callingpres = ast->cid.cid_pres;
05727 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05728 p->jointnoncodeccapability = p->noncodeccapability;
05729
05730
05731 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05732 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05733 res = -1;
05734 } else {
05735 int xmitres;
05736
05737 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05738 if (xmitres == XMIT_ERROR)
05739 return -1;
05740 p->invitestate = INV_CALLING;
05741
05742
05743 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05744 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05745 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05746 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05747 }
05748 return res;
05749 }
05750
05751
05752
05753 static void sip_registry_destroy(struct sip_registry *reg)
05754 {
05755
05756 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05757
05758 if (reg->call) {
05759
05760
05761 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05762 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05763 dialog_unlink_all(reg->call, TRUE, TRUE);
05764 reg->call = dialog_unref(reg->call, "unref reg->call");
05765
05766 }
05767 AST_SCHED_DEL(sched, reg->expire);
05768 AST_SCHED_DEL(sched, reg->timeout);
05769
05770 ast_string_field_free_memory(reg);
05771 ast_atomic_fetchadd_int(®objs, -1);
05772 ast_dnsmgr_release(reg->dnsmgr);
05773 ast_free(reg);
05774 }
05775
05776
05777 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05778 {
05779 if (mwi->call) {
05780 mwi->call->mwi = NULL;
05781 sip_destroy(mwi->call);
05782 }
05783
05784 AST_SCHED_DEL(sched, mwi->resub);
05785 ast_string_field_free_memory(mwi);
05786 ast_dnsmgr_release(mwi->dnsmgr);
05787 ast_free(mwi);
05788 }
05789
05790
05791 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05792 {
05793 struct sip_request *req;
05794
05795
05796 if (p->stimer) {
05797 p->stimer->quit_flag = 1;
05798 stop_session_timer(p);
05799 ast_free(p->stimer);
05800 p->stimer = NULL;
05801 }
05802
05803 if (sip_debug_test_pvt(p))
05804 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05805
05806 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05807 update_call_counter(p, DEC_CALL_LIMIT);
05808 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05809 }
05810
05811
05812 if (p->owner) {
05813 if (lockowner)
05814 ast_channel_lock(p->owner);
05815 if (option_debug)
05816 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05817 p->owner->tech_pvt = NULL;
05818
05819 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05820 if (lockowner)
05821 ast_channel_unlock(p->owner);
05822
05823 usleep(1);
05824 }
05825
05826
05827 if (p->relatedpeer && p->relatedpeer->mwipvt)
05828 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05829 if (p->relatedpeer && p->relatedpeer->call == p)
05830 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05831
05832 if (p->relatedpeer)
05833 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05834
05835 if (p->registry) {
05836 if (p->registry->call == p)
05837 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05838 p->registry = registry_unref(p->registry, "delete p->registry");
05839 }
05840
05841 if (p->mwi) {
05842 p->mwi->call = NULL;
05843 }
05844
05845 if (dumphistory)
05846 sip_dump_history(p);
05847
05848 if (p->options)
05849 ast_free(p->options);
05850
05851 if (p->notify_headers) {
05852 ast_variables_destroy(p->notify_headers);
05853 p->notify_headers = NULL;
05854 }
05855 if (p->rtp) {
05856 ast_rtp_destroy(p->rtp);
05857 }
05858 if (p->vrtp) {
05859 ast_rtp_destroy(p->vrtp);
05860 }
05861 if (p->trtp) {
05862 while (ast_rtp_get_bridged(p->trtp))
05863 usleep(1);
05864 ast_rtp_destroy(p->trtp);
05865 }
05866 if (p->udptl)
05867 ast_udptl_destroy(p->udptl);
05868 if (p->refer)
05869 ast_free(p->refer);
05870 if (p->route) {
05871 free_old_route(p->route);
05872 p->route = NULL;
05873 }
05874 deinit_req(&p->initreq);
05875
05876
05877 if (p->history) {
05878 struct sip_history *hist;
05879 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05880 ast_free(hist);
05881 p->history_entries--;
05882 }
05883 ast_free(p->history);
05884 p->history = NULL;
05885 }
05886
05887 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05888 ast_free(req);
05889 }
05890
05891 if (p->chanvars) {
05892 ast_variables_destroy(p->chanvars);
05893 p->chanvars = NULL;
05894 }
05895
05896 ast_string_field_free_memory(p);
05897
05898 if (p->socket.tcptls_session) {
05899 ao2_ref(p->socket.tcptls_session, -1);
05900 p->socket.tcptls_session = NULL;
05901 }
05902 }
05903
05904
05905
05906
05907
05908
05909
05910
05911
05912
05913
05914
05915
05916
05917
05918 static int update_call_counter(struct sip_pvt *fup, int event)
05919 {
05920 char name[256];
05921 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05922 int outgoing = fup->outgoing_call;
05923 struct sip_peer *p = NULL;
05924
05925 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05926
05927
05928
05929
05930 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05931 return 0;
05932
05933 ast_copy_string(name, fup->username, sizeof(name));
05934
05935
05936 if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) {
05937 inuse = &p->inUse;
05938 call_limit = &p->call_limit;
05939 inringing = &p->inRinging;
05940 ast_copy_string(name, fup->peername, sizeof(name));
05941 }
05942 if (!p) {
05943 ast_debug(2, "%s is not a local device, no call limit\n", name);
05944 return 0;
05945 }
05946
05947 switch(event) {
05948
05949 case DEC_CALL_LIMIT:
05950
05951 if (inuse) {
05952 sip_pvt_lock(fup);
05953 ao2_lock(p);
05954 if (*inuse > 0) {
05955 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05956 (*inuse)--;
05957 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05958 }
05959 } else {
05960 *inuse = 0;
05961 }
05962 ao2_unlock(p);
05963 sip_pvt_unlock(fup);
05964 }
05965
05966
05967 if (inringing) {
05968 sip_pvt_lock(fup);
05969 ao2_lock(p);
05970 if (*inringing > 0) {
05971 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05972 (*inringing)--;
05973 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05974 }
05975 } else {
05976 *inringing = 0;
05977 }
05978 ao2_unlock(p);
05979 sip_pvt_unlock(fup);
05980 }
05981
05982
05983 sip_pvt_lock(fup);
05984 ao2_lock(p);
05985 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05986 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05987 ao2_unlock(p);
05988 sip_pvt_unlock(fup);
05989 sip_peer_hold(fup, FALSE);
05990 } else {
05991 ao2_unlock(p);
05992 sip_pvt_unlock(fup);
05993 }
05994 if (sipdebug)
05995 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05996 break;
05997
05998 case INC_CALL_RINGING:
05999 case INC_CALL_LIMIT:
06000
06001 if (*call_limit > 0 ) {
06002 if (*inuse >= *call_limit) {
06003 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06004 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06005 return -1;
06006 }
06007 }
06008 if (inringing && (event == INC_CALL_RINGING)) {
06009 sip_pvt_lock(fup);
06010 ao2_lock(p);
06011 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06012 (*inringing)++;
06013 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06014 }
06015 ao2_unlock(p);
06016 sip_pvt_unlock(fup);
06017 }
06018 if (inuse) {
06019 sip_pvt_lock(fup);
06020 ao2_lock(p);
06021 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06022 (*inuse)++;
06023 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06024 }
06025 ao2_unlock(p);
06026 sip_pvt_unlock(fup);
06027 }
06028 if (sipdebug) {
06029 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06030 }
06031 break;
06032
06033 case DEC_CALL_RINGING:
06034 if (inringing) {
06035 sip_pvt_lock(fup);
06036 ao2_lock(p);
06037 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06038 if (*inringing > 0) {
06039 (*inringing)--;
06040 }
06041 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06042 }
06043 ao2_unlock(p);
06044 sip_pvt_unlock(fup);
06045 }
06046 break;
06047
06048 default:
06049 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06050 }
06051
06052 if (p) {
06053 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
06054 unref_peer(p, "update_call_counter: unref_peer from call counter");
06055 }
06056 return 0;
06057 }
06058
06059
06060 static void sip_destroy_fn(void *p)
06061 {
06062 sip_destroy(p);
06063 }
06064
06065
06066
06067
06068
06069
06070 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
06071 {
06072 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06073 __sip_destroy(p, TRUE, TRUE);
06074 return NULL;
06075 }
06076
06077
06078 static int hangup_sip2cause(int cause)
06079 {
06080
06081
06082 switch(cause) {
06083 case 401:
06084 return AST_CAUSE_CALL_REJECTED;
06085 case 403:
06086 return AST_CAUSE_CALL_REJECTED;
06087 case 404:
06088 return AST_CAUSE_UNALLOCATED;
06089 case 405:
06090 return AST_CAUSE_INTERWORKING;
06091 case 407:
06092 return AST_CAUSE_CALL_REJECTED;
06093 case 408:
06094 return AST_CAUSE_NO_USER_RESPONSE;
06095 case 409:
06096 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06097 case 410:
06098 return AST_CAUSE_NUMBER_CHANGED;
06099 case 411:
06100 return AST_CAUSE_INTERWORKING;
06101 case 413:
06102 return AST_CAUSE_INTERWORKING;
06103 case 414:
06104 return AST_CAUSE_INTERWORKING;
06105 case 415:
06106 return AST_CAUSE_INTERWORKING;
06107 case 420:
06108 return AST_CAUSE_NO_ROUTE_DESTINATION;
06109 case 480:
06110 return AST_CAUSE_NO_ANSWER;
06111 case 481:
06112 return AST_CAUSE_INTERWORKING;
06113 case 482:
06114 return AST_CAUSE_INTERWORKING;
06115 case 483:
06116 return AST_CAUSE_NO_ANSWER;
06117 case 484:
06118 return AST_CAUSE_INVALID_NUMBER_FORMAT;
06119 case 485:
06120 return AST_CAUSE_UNALLOCATED;
06121 case 486:
06122 return AST_CAUSE_BUSY;
06123 case 487:
06124 return AST_CAUSE_INTERWORKING;
06125 case 488:
06126 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06127 case 491:
06128 return AST_CAUSE_INTERWORKING;
06129 case 493:
06130 return AST_CAUSE_INTERWORKING;
06131 case 500:
06132 return AST_CAUSE_FAILURE;
06133 case 501:
06134 return AST_CAUSE_FACILITY_REJECTED;
06135 case 502:
06136 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06137 case 503:
06138 return AST_CAUSE_CONGESTION;
06139 case 504:
06140 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06141 case 505:
06142 return AST_CAUSE_INTERWORKING;
06143 case 600:
06144 return AST_CAUSE_USER_BUSY;
06145 case 603:
06146 return AST_CAUSE_CALL_REJECTED;
06147 case 604:
06148 return AST_CAUSE_UNALLOCATED;
06149 case 606:
06150 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06151 default:
06152 return AST_CAUSE_NORMAL;
06153 }
06154
06155 return 0;
06156 }
06157
06158
06159
06160
06161
06162
06163
06164
06165
06166
06167
06168
06169
06170
06171
06172
06173
06174
06175
06176
06177
06178
06179
06180
06181
06182
06183
06184
06185
06186
06187
06188
06189
06190 static const char *hangup_cause2sip(int cause)
06191 {
06192 switch (cause) {
06193 case AST_CAUSE_UNALLOCATED:
06194 case AST_CAUSE_NO_ROUTE_DESTINATION:
06195 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
06196 return "404 Not Found";
06197 case AST_CAUSE_CONGESTION:
06198 case AST_CAUSE_SWITCH_CONGESTION:
06199 return "503 Service Unavailable";
06200 case AST_CAUSE_NO_USER_RESPONSE:
06201 return "408 Request Timeout";
06202 case AST_CAUSE_NO_ANSWER:
06203 case AST_CAUSE_UNREGISTERED:
06204 return "480 Temporarily unavailable";
06205 case AST_CAUSE_CALL_REJECTED:
06206 return "403 Forbidden";
06207 case AST_CAUSE_NUMBER_CHANGED:
06208 return "410 Gone";
06209 case AST_CAUSE_NORMAL_UNSPECIFIED:
06210 return "480 Temporarily unavailable";
06211 case AST_CAUSE_INVALID_NUMBER_FORMAT:
06212 return "484 Address incomplete";
06213 case AST_CAUSE_USER_BUSY:
06214 return "486 Busy here";
06215 case AST_CAUSE_FAILURE:
06216 return "500 Server internal failure";
06217 case AST_CAUSE_FACILITY_REJECTED:
06218 return "501 Not Implemented";
06219 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06220 return "503 Service Unavailable";
06221
06222 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06223 return "502 Bad Gateway";
06224 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06225 return "488 Not Acceptable Here";
06226
06227 case AST_CAUSE_NOTDEFINED:
06228 default:
06229 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06230 return NULL;
06231 }
06232
06233
06234 return 0;
06235 }
06236
06237
06238
06239
06240 static int sip_hangup(struct ast_channel *ast)
06241 {
06242 struct sip_pvt *p = ast->tech_pvt;
06243 int needcancel = FALSE;
06244 int needdestroy = 0;
06245 struct ast_channel *oldowner = ast;
06246
06247 if (!p) {
06248 ast_debug(1, "Asked to hangup channel that was not connected\n");
06249 return 0;
06250 }
06251 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06252 ast_debug(1, "This call was answered elsewhere");
06253 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06254 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06255 }
06256 append_history(p, "Cancel", "Call answered elsewhere");
06257 p->answered_elsewhere = TRUE;
06258 }
06259
06260
06261 if (p->owner)
06262 p->hangupcause = p->owner->hangupcause;
06263
06264 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06265 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06266 if (sipdebug)
06267 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06268 update_call_counter(p, DEC_CALL_LIMIT);
06269 }
06270 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06271 if (p->autokillid > -1 && sip_cancel_destroy(p))
06272 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06273 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06274 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
06275 p->needdestroy = 0;
06276 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06277 sip_pvt_lock(p);
06278 p->owner = NULL;
06279 sip_pvt_unlock(p);
06280 ast_module_unref(ast_module_info->self);
06281 return 0;
06282 }
06283
06284 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06285 if (p->refer)
06286 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06287 else
06288 ast_debug(1, "Hanging up zombie call. Be scared.\n");
06289 } else
06290 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06291
06292 sip_pvt_lock(p);
06293 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06294 if (sipdebug)
06295 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06296 update_call_counter(p, DEC_CALL_LIMIT);
06297 }
06298
06299
06300 if (p->owner != ast) {
06301 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06302 sip_pvt_unlock(p);
06303 return 0;
06304 }
06305
06306
06307 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06308 needcancel = TRUE;
06309 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06310 }
06311
06312 stop_media_flows(p);
06313
06314 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06315
06316
06317 if (p->dsp)
06318 ast_dsp_free(p->dsp);
06319
06320 p->owner = NULL;
06321 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06322
06323 ast_module_unref(ast_module_info->self);
06324
06325
06326
06327
06328
06329
06330 if (p->alreadygone)
06331 needdestroy = 1;
06332 else if (p->invitestate != INV_CALLING)
06333 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06334
06335
06336 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06337 if (needcancel) {
06338 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06339
06340
06341 if (p->invitestate == INV_CALLING) {
06342
06343 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06344
06345 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06346 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06347 } else {
06348 struct sip_pkt *cur;
06349
06350 for (cur = p->packets; cur; cur = cur->next) {
06351 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06352 }
06353 p->invitestate = INV_CANCELLED;
06354
06355 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06356
06357
06358 needdestroy = 0;
06359 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06360 }
06361 } else {
06362 const char *res;
06363 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"));
06364 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06365 transmit_response_reliable(p, res, &p->initreq);
06366 else
06367 transmit_response_reliable(p, "603 Declined", &p->initreq);
06368 p->invitestate = INV_TERMINATED;
06369 }
06370 } else {
06371 if (p->stimer->st_active == TRUE) {
06372 stop_session_timer(p);
06373 }
06374
06375 if (!p->pendinginvite) {
06376 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06377 char *audioqos = "";
06378 char *videoqos = "";
06379 char *textqos = "";
06380
06381
06382
06383
06384 while (bridge && ast_channel_trylock(bridge)) {
06385 sip_pvt_unlock(p);
06386 do {
06387
06388 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06389 } while (sip_pvt_trylock(p));
06390 bridge = ast_bridged_channel(oldowner);
06391 }
06392
06393 if (p->rtp)
06394 ast_rtp_set_vars(oldowner, p->rtp);
06395
06396 if (bridge) {
06397 struct sip_pvt *q = bridge->tech_pvt;
06398
06399 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06400 ast_rtp_set_vars(bridge, q->rtp);
06401 ast_channel_unlock(bridge);
06402 }
06403
06404 if (p->vrtp)
06405 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06406 if (p->trtp)
06407 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06408
06409 if (oldowner->_state == AST_STATE_UP) {
06410 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06411 }
06412
06413
06414 if (p->do_history) {
06415 if (p->rtp)
06416 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06417 if (p->vrtp)
06418 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06419 if (p->trtp)
06420 append_history(p, "RTCPtext", "Quality:%s", textqos);
06421 }
06422 if (p->rtp && oldowner)
06423 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06424 if (p->vrtp && oldowner)
06425 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06426 if (p->trtp && oldowner)
06427 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06428 } else {
06429
06430
06431 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06432 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06433 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"));
06434 if (sip_cancel_destroy(p))
06435 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06436 }
06437 }
06438 }
06439 if (needdestroy) {
06440 pvt_set_needdestroy(p, "hangup");
06441 }
06442 sip_pvt_unlock(p);
06443 return 0;
06444 }
06445
06446
06447 static void try_suggested_sip_codec(struct sip_pvt *p)
06448 {
06449 int fmt;
06450 const char *codec;
06451
06452 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06453 if (!codec)
06454 return;
06455
06456 fmt = ast_getformatbyname(codec);
06457 if (fmt) {
06458 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06459 if (p->jointcapability & fmt) {
06460 p->jointcapability &= fmt;
06461 p->capability &= fmt;
06462 } else
06463 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06464 } else
06465 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06466 return;
06467 }
06468
06469
06470
06471 static int sip_answer(struct ast_channel *ast)
06472 {
06473 int res = 0;
06474 struct sip_pvt *p = ast->tech_pvt;
06475
06476 sip_pvt_lock(p);
06477 if (ast->_state != AST_STATE_UP) {
06478 try_suggested_sip_codec(p);
06479
06480 ast_setstate(ast, AST_STATE_UP);
06481 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06482 ast_rtp_new_source(p->rtp);
06483 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06484 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06485 }
06486 sip_pvt_unlock(p);
06487 return res;
06488 }
06489
06490
06491 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06492 {
06493 struct sip_pvt *p = ast->tech_pvt;
06494 int res = 0;
06495
06496 switch (frame->frametype) {
06497 case AST_FRAME_VOICE:
06498 if (!(frame->subclass & ast->nativeformats)) {
06499 char s1[512], s2[512], s3[512];
06500 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06501 frame->subclass,
06502 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06503 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06504 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06505 ast->readformat,
06506 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06507 ast->writeformat);
06508 return 0;
06509 }
06510 if (p) {
06511 sip_pvt_lock(p);
06512 if (p->t38.state == T38_ENABLED) {
06513
06514 sip_pvt_unlock(p);
06515 break;
06516 } else if (p->rtp) {
06517
06518 if ((ast->_state != AST_STATE_UP) &&
06519 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06520 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06521 ast_rtp_new_source(p->rtp);
06522 if (!global_prematuremediafilter) {
06523 p->invitestate = INV_EARLY_MEDIA;
06524 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06525 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06526 }
06527 }
06528 p->lastrtptx = time(NULL);
06529 res = ast_rtp_write(p->rtp, frame);
06530 }
06531 sip_pvt_unlock(p);
06532 }
06533 break;
06534 case AST_FRAME_VIDEO:
06535 if (p) {
06536 sip_pvt_lock(p);
06537 if (p->vrtp) {
06538
06539 if ((ast->_state != AST_STATE_UP) &&
06540 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06541 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06542 p->invitestate = INV_EARLY_MEDIA;
06543 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06544 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06545 }
06546 p->lastrtptx = time(NULL);
06547 res = ast_rtp_write(p->vrtp, frame);
06548 }
06549 sip_pvt_unlock(p);
06550 }
06551 break;
06552 case AST_FRAME_TEXT:
06553 if (p) {
06554 sip_pvt_lock(p);
06555 if (p->red) {
06556 red_buffer_t140(p->trtp, frame);
06557 } else {
06558 if (p->trtp) {
06559
06560 if ((ast->_state != AST_STATE_UP) &&
06561 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06562 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06563 p->invitestate = INV_EARLY_MEDIA;
06564 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06565 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06566 }
06567 p->lastrtptx = time(NULL);
06568 res = ast_rtp_write(p->trtp, frame);
06569 }
06570 }
06571 sip_pvt_unlock(p);
06572 }
06573 break;
06574 case AST_FRAME_IMAGE:
06575 return 0;
06576 break;
06577 case AST_FRAME_MODEM:
06578 if (p) {
06579 sip_pvt_lock(p);
06580
06581
06582
06583
06584 if ((ast->_state == AST_STATE_UP) &&
06585 p->udptl &&
06586 (p->t38.state == T38_ENABLED)) {
06587 res = ast_udptl_write(p->udptl, frame);
06588 }
06589 sip_pvt_unlock(p);
06590 }
06591 break;
06592 default:
06593 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06594 return 0;
06595 }
06596
06597 return res;
06598 }
06599
06600
06601
06602 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06603 {
06604 int ret = -1;
06605 struct sip_pvt *p;
06606
06607 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06608 ast_debug(1, "New channel is zombie\n");
06609 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06610 ast_debug(1, "Old channel is zombie\n");
06611
06612 if (!newchan || !newchan->tech_pvt) {
06613 if (!newchan)
06614 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06615 else
06616 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06617 return -1;
06618 }
06619 p = newchan->tech_pvt;
06620
06621 sip_pvt_lock(p);
06622 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06623 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06624 if (p->owner != oldchan)
06625 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06626 else {
06627 p->owner = newchan;
06628
06629
06630
06631
06632
06633
06634 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06635 ret = 0;
06636 }
06637 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06638
06639 sip_pvt_unlock(p);
06640 return ret;
06641 }
06642
06643 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06644 {
06645 struct sip_pvt *p = ast->tech_pvt;
06646 int res = 0;
06647
06648 sip_pvt_lock(p);
06649 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06650 case SIP_DTMF_INBAND:
06651 res = -1;
06652 break;
06653 case SIP_DTMF_RFC2833:
06654 if (p->rtp)
06655 ast_rtp_senddigit_begin(p->rtp, digit);
06656 break;
06657 default:
06658 break;
06659 }
06660 sip_pvt_unlock(p);
06661
06662 return res;
06663 }
06664
06665
06666
06667 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06668 {
06669 struct sip_pvt *p = ast->tech_pvt;
06670 int res = 0;
06671
06672 sip_pvt_lock(p);
06673 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06674 case SIP_DTMF_INFO:
06675 case SIP_DTMF_SHORTINFO:
06676 transmit_info_with_digit(p, digit, duration);
06677 break;
06678 case SIP_DTMF_RFC2833:
06679 if (p->rtp)
06680 ast_rtp_senddigit_end_with_duration(p->rtp, digit, duration);
06681 break;
06682 case SIP_DTMF_INBAND:
06683 res = -1;
06684 break;
06685 }
06686 sip_pvt_unlock(p);
06687
06688 return res;
06689 }
06690
06691
06692 static int sip_transfer(struct ast_channel *ast, const char *dest)
06693 {
06694 struct sip_pvt *p = ast->tech_pvt;
06695 int res;
06696
06697 if (dest == NULL)
06698 dest = "";
06699 sip_pvt_lock(p);
06700 if (ast->_state == AST_STATE_RING)
06701 res = sip_sipredirect(p, dest);
06702 else
06703 res = transmit_refer(p, dest);
06704 sip_pvt_unlock(p);
06705 return res;
06706 }
06707
06708
06709 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06710 {
06711 int res = 0;
06712
06713 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06714 return -1;
06715 }
06716 switch (parameters->request_response) {
06717 case AST_T38_NEGOTIATED:
06718 case AST_T38_REQUEST_NEGOTIATE:
06719
06720 if (!parameters->max_ifp) {
06721 change_t38_state(p, T38_DISABLED);
06722 if (p->t38.state == T38_PEER_REINVITE) {
06723 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"));
06724 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06725 }
06726 break;
06727 } else if (p->t38.state == T38_PEER_REINVITE) {
06728 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"));
06729 p->t38.our_parms = *parameters;
06730
06731
06732
06733 if (!p->t38.their_parms.fill_bit_removal) {
06734 p->t38.our_parms.fill_bit_removal = FALSE;
06735 }
06736 if (!p->t38.their_parms.transcoding_mmr) {
06737 p->t38.our_parms.transcoding_mmr = FALSE;
06738 }
06739 if (!p->t38.their_parms.transcoding_jbig) {
06740 p->t38.our_parms.transcoding_jbig = FALSE;
06741 }
06742 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06743 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06744 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06745 change_t38_state(p, T38_ENABLED);
06746 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06747 } else if (p->t38.state != T38_ENABLED) {
06748 p->t38.our_parms = *parameters;
06749 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06750 change_t38_state(p, T38_LOCAL_REINVITE);
06751 if (!p->pendinginvite) {
06752 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06753 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06754 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06755 }
06756 }
06757 break;
06758 case AST_T38_TERMINATED:
06759 case AST_T38_REFUSED:
06760 case AST_T38_REQUEST_TERMINATE:
06761 if (p->t38.state == T38_PEER_REINVITE) {
06762 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"));
06763 change_t38_state(p, T38_DISABLED);
06764 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06765 } else if (p->t38.state == T38_ENABLED)
06766 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06767 break;
06768 case AST_T38_REQUEST_PARMS: {
06769 struct ast_control_t38_parameters parameters = p->t38.their_parms;
06770
06771 if (p->t38.state == T38_PEER_REINVITE) {
06772 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"));
06773 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06774 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06775 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
06776
06777
06778
06779
06780 res = AST_T38_REQUEST_PARMS;
06781 }
06782 break;
06783 }
06784 default:
06785 res = -1;
06786 break;
06787 }
06788
06789 return res;
06790 }
06791
06792
06793
06794
06795
06796
06797 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06798 {
06799 struct sip_pvt *p = ast->tech_pvt;
06800 int res = 0;
06801
06802 sip_pvt_lock(p);
06803 switch(condition) {
06804 case AST_CONTROL_RINGING:
06805 if (ast->_state == AST_STATE_RING) {
06806 p->invitestate = INV_EARLY_MEDIA;
06807 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06808 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06809
06810 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06811 ast_set_flag(&p->flags[0], SIP_RINGING);
06812 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06813 break;
06814 } else {
06815
06816 }
06817 }
06818 res = -1;
06819 break;
06820 case AST_CONTROL_BUSY:
06821 if (ast->_state != AST_STATE_UP) {
06822 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06823 p->invitestate = INV_COMPLETED;
06824 sip_alreadygone(p);
06825 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06826 break;
06827 }
06828 res = -1;
06829 break;
06830 case AST_CONTROL_CONGESTION:
06831 if (ast->_state != AST_STATE_UP) {
06832 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06833 p->invitestate = INV_COMPLETED;
06834 sip_alreadygone(p);
06835 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06836 break;
06837 }
06838 res = -1;
06839 break;
06840 case AST_CONTROL_PROCEEDING:
06841 if ((ast->_state != AST_STATE_UP) &&
06842 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06843 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06844 transmit_response(p, "100 Trying", &p->initreq);
06845 p->invitestate = INV_PROCEEDING;
06846 break;
06847 }
06848 res = -1;
06849 break;
06850 case AST_CONTROL_PROGRESS:
06851 if ((ast->_state != AST_STATE_UP) &&
06852 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06853 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06854 p->invitestate = INV_EARLY_MEDIA;
06855 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06856 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06857 break;
06858 }
06859 res = -1;
06860 break;
06861 case AST_CONTROL_HOLD:
06862 ast_rtp_new_source(p->rtp);
06863 ast_moh_start(ast, data, p->mohinterpret);
06864 break;
06865 case AST_CONTROL_UNHOLD:
06866 ast_rtp_new_source(p->rtp);
06867 ast_moh_stop(ast);
06868 break;
06869 case AST_CONTROL_VIDUPDATE:
06870 if (p->vrtp && !p->novideo) {
06871 transmit_info_with_vidupdate(p);
06872
06873 } else
06874 res = -1;
06875 break;
06876 case AST_CONTROL_T38_PARAMETERS:
06877 if (datalen != sizeof(struct ast_control_t38_parameters)) {
06878 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);
06879 res = -1;
06880 } else {
06881 const struct ast_control_t38_parameters *parameters = data;
06882 res = interpret_t38_parameters(p, parameters);
06883 }
06884 break;
06885 case AST_CONTROL_SRCUPDATE:
06886 ast_rtp_new_source(p->rtp);
06887 break;
06888 case AST_CONTROL_SRCCHANGE:
06889 ast_rtp_change_source(p->rtp);
06890 break;
06891 case -1:
06892 res = -1;
06893 break;
06894 default:
06895 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06896 res = -1;
06897 break;
06898 }
06899 sip_pvt_unlock(p);
06900 return res;
06901 }
06902
06903
06904
06905
06906
06907
06908
06909 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06910 {
06911 struct ast_channel *tmp;
06912 struct ast_variable *v = NULL;
06913 int fmt;
06914 int what;
06915 int video;
06916 int text;
06917 int needvideo = 0;
06918 int needtext = 0;
06919 char buf[SIPBUFSIZE];
06920 char *decoded_exten;
06921
06922 {
06923 const char *my_name;
06924
06925 if (title) {
06926 my_name = title;
06927 } else {
06928 char *port = NULL;
06929 my_name = ast_strdupa(i->fromdomain);
06930 if ((port = strchr(i->fromdomain, ':'))) {
06931 *port = '\0';
06932 }
06933 }
06934
06935 sip_pvt_unlock(i);
06936
06937 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));
06938
06939 }
06940 if (!tmp) {
06941 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06942 sip_pvt_lock(i);
06943 return NULL;
06944 }
06945 sip_pvt_lock(i);
06946
06947 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;
06948
06949
06950
06951 if (i->jointcapability) {
06952 what = i->jointcapability;
06953 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06954 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06955 } else if (i->capability) {
06956 what = i->capability;
06957 video = i->capability & AST_FORMAT_VIDEO_MASK;
06958 text = i->capability & AST_FORMAT_TEXT_MASK;
06959 } else {
06960 what = global_capability;
06961 video = global_capability & AST_FORMAT_VIDEO_MASK;
06962 text = global_capability & AST_FORMAT_TEXT_MASK;
06963 }
06964
06965
06966 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06967 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06968 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06969 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06970 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06971 if (i->prefcodec)
06972 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06973
06974
06975 fmt = ast_best_codec(tmp->nativeformats);
06976
06977
06978
06979
06980
06981 if (i->vrtp) {
06982 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06983 needvideo = AST_FORMAT_VIDEO_MASK;
06984 else if (i->prefcodec)
06985 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
06986 else
06987 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06988 }
06989
06990 if (i->trtp) {
06991 if (i->prefcodec)
06992 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
06993 else
06994 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
06995 }
06996
06997 if (needvideo)
06998 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06999 else
07000 ast_debug(3, "This channel will not be able to handle video.\n");
07001
07002 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
07003 (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
07004 int features = 0;
07005
07006 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07007 features |= DSP_FEATURE_DIGIT_DETECT;
07008 }
07009
07010 if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
07011 features |= DSP_FEATURE_FAX_DETECT;
07012 }
07013
07014 i->dsp = ast_dsp_new();
07015 ast_dsp_set_features(i->dsp, features);
07016 if (global_relaxdtmf)
07017 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
07018 }
07019
07020
07021 if (i->rtp) {
07022 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
07023 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
07024 }
07025 if (needvideo && i->vrtp) {
07026 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
07027 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
07028 }
07029 if (needtext && i->trtp)
07030 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
07031 if (i->udptl)
07032 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07033
07034 if (state == AST_STATE_RING)
07035 tmp->rings = 1;
07036 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07037 tmp->writeformat = fmt;
07038 tmp->rawwriteformat = fmt;
07039 tmp->readformat = fmt;
07040 tmp->rawreadformat = fmt;
07041 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07042
07043 tmp->callgroup = i->callgroup;
07044 tmp->pickupgroup = i->pickupgroup;
07045 tmp->cid.cid_pres = i->callingpres;
07046 if (!ast_strlen_zero(i->parkinglot))
07047 ast_string_field_set(tmp, parkinglot, i->parkinglot);
07048 if (!ast_strlen_zero(i->accountcode))
07049 ast_string_field_set(tmp, accountcode, i->accountcode);
07050 if (i->amaflags)
07051 tmp->amaflags = i->amaflags;
07052 if (!ast_strlen_zero(i->language))
07053 ast_string_field_set(tmp, language, i->language);
07054 i->owner = tmp;
07055 ast_module_ref(ast_module_info->self);
07056 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07057
07058
07059
07060
07061 if (ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07062
07063 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
07064 } else {
07065 decoded_exten = ast_strdupa(i->exten);
07066 ast_uri_decode(decoded_exten);
07067 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
07068 }
07069
07070
07071
07072 tmp->cid.cid_ani = ast_strdup(i->cid_num);
07073 if (!ast_strlen_zero(i->rdnis))
07074 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
07075
07076 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
07077 tmp->cid.cid_dnid = ast_strdup(i->exten);
07078
07079 tmp->priority = 1;
07080 if (!ast_strlen_zero(i->uri))
07081 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07082 if (!ast_strlen_zero(i->domain))
07083 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07084 if (!ast_strlen_zero(i->callid))
07085 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07086 if (i->rtp)
07087 ast_jb_configure(tmp, &global_jbconf);
07088
07089
07090 for (v = i->chanvars ; v ; v = v->next) {
07091 char valuebuf[1024];
07092 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07093 }
07094
07095 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
07096 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
07097 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07098 ast_hangup(tmp);
07099 tmp = NULL;
07100 }
07101
07102 if (i->do_history)
07103 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07104
07105
07106 if (sip_cfg.callevents)
07107 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07108 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07109 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07110
07111 return tmp;
07112 }
07113
07114
07115 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07116 {
07117 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07118 return ast_skip_blanks(line + nameLen + 1);
07119
07120 return "";
07121 }
07122
07123
07124
07125
07126
07127 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07128 {
07129 int len = strlen(name);
07130
07131 while (*start < (req->sdp_start + req->sdp_count)) {
07132 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07133 if (r[0] != '\0')
07134 return r;
07135 }
07136
07137
07138 (*start)++;
07139
07140 return "";
07141 }
07142
07143
07144
07145
07146
07147
07148 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07149 {
07150 char type = '\0';
07151 const char *line = NULL;
07152
07153 if (stop > (req->sdp_start + req->sdp_count)) {
07154 stop = req->sdp_start + req->sdp_count;
07155 }
07156
07157 while (*start < stop) {
07158 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07159 if (line[1] == '=') {
07160 type = line[0];
07161 *value = ast_skip_blanks(line + 2);
07162 break;
07163 }
07164 }
07165
07166 return type;
07167 }
07168
07169
07170 static char *get_body(struct sip_request *req, char *name, char delimiter)
07171 {
07172 int x;
07173 int len = strlen(name);
07174 char *r;
07175
07176 for (x = 0; x < req->lines; x++) {
07177 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07178 if (r[0] != '\0')
07179 return r;
07180 }
07181
07182 return "";
07183 }
07184
07185
07186 static const char *find_alias(const char *name, const char *_default)
07187 {
07188
07189 static const struct cfalias {
07190 char * const fullname;
07191 char * const shortname;
07192 } aliases[] = {
07193 { "Content-Type", "c" },
07194 { "Content-Encoding", "e" },
07195 { "From", "f" },
07196 { "Call-ID", "i" },
07197 { "Contact", "m" },
07198 { "Content-Length", "l" },
07199 { "Subject", "s" },
07200 { "To", "t" },
07201 { "Supported", "k" },
07202 { "Refer-To", "r" },
07203 { "Referred-By", "b" },
07204 { "Allow-Events", "u" },
07205 { "Event", "o" },
07206 { "Via", "v" },
07207 { "Accept-Contact", "a" },
07208 { "Reject-Contact", "j" },
07209 { "Request-Disposition", "d" },
07210 { "Session-Expires", "x" },
07211 { "Identity", "y" },
07212 { "Identity-Info", "n" },
07213 };
07214 int x;
07215
07216 for (x = 0; x < ARRAY_LEN(aliases); x++) {
07217 if (!strcasecmp(aliases[x].fullname, name))
07218 return aliases[x].shortname;
07219 }
07220
07221 return _default;
07222 }
07223
07224 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07225 {
07226 int pass;
07227
07228
07229
07230
07231
07232
07233
07234
07235
07236
07237 for (pass = 0; name && pass < 2;pass++) {
07238 int x, len = strlen(name);
07239 for (x = *start; x < req->headers; x++) {
07240 char *header = REQ_OFFSET_TO_STR(req, header[x]);
07241 if (!strncasecmp(header, name, len)) {
07242 char *r = header + len;
07243 if (sip_cfg.pedanticsipchecking)
07244 r = ast_skip_blanks(r);
07245
07246 if (*r == ':') {
07247 *start = x+1;
07248 return ast_skip_blanks(r+1);
07249 }
07250 }
07251 }
07252 if (pass == 0)
07253 name = find_alias(name, NULL);
07254 }
07255
07256
07257 return "";
07258 }
07259
07260
07261
07262
07263 static const char *get_header(const struct sip_request *req, const char *name)
07264 {
07265 int start = 0;
07266 return __get_header(req, name, &start);
07267 }
07268
07269
07270 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07271 {
07272
07273 struct ast_frame *f;
07274
07275 if (!p->rtp) {
07276
07277 return &ast_null_frame;
07278 }
07279
07280 switch(ast->fdno) {
07281 case 0:
07282 f = ast_rtp_read(p->rtp);
07283 break;
07284 case 1:
07285 f = ast_rtcp_read(p->rtp);
07286 break;
07287 case 2:
07288 f = ast_rtp_read(p->vrtp);
07289 break;
07290 case 3:
07291 f = ast_rtcp_read(p->vrtp);
07292 break;
07293 case 4:
07294 f = ast_rtp_read(p->trtp);
07295 if (sipdebug_text) {
07296 int i;
07297 unsigned char* arr = f->data.ptr;
07298 for (i=0; i < f->datalen; i++)
07299 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07300 ast_verbose(" -> ");
07301 for (i=0; i < f->datalen; i++)
07302 ast_verbose("%02X ", arr[i]);
07303 ast_verbose("\n");
07304 }
07305 break;
07306 case 5:
07307 f = ast_udptl_read(p->udptl);
07308 break;
07309 default:
07310 f = &ast_null_frame;
07311 }
07312
07313 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07314 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07315 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07316 return &ast_null_frame;
07317 }
07318
07319
07320 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07321 return f;
07322
07323 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07324 if (!(f->subclass & p->jointcapability)) {
07325 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07326 ast_getformatname(f->subclass), p->owner->name);
07327 return &ast_null_frame;
07328 }
07329 ast_debug(1, "Oooh, format changed to %d %s\n",
07330 f->subclass, ast_getformatname(f->subclass));
07331 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07332 ast_set_read_format(p->owner, p->owner->readformat);
07333 ast_set_write_format(p->owner, p->owner->writeformat);
07334 }
07335
07336 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) {
07337 f = ast_dsp_process(p->owner, p->dsp, f);
07338 if (f && f->frametype == AST_FRAME_DTMF) {
07339 if (f->subclass == 'f') {
07340 if (option_debug)
07341 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07342 *faxdetect = 1;
07343
07344 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07345 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07346 } else {
07347 ast_dsp_free(p->dsp);
07348 p->dsp = NULL;
07349 }
07350 } else {
07351 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07352 }
07353 }
07354 }
07355
07356 return f;
07357 }
07358
07359
07360 static struct ast_frame *sip_read(struct ast_channel *ast)
07361 {
07362 struct ast_frame *fr;
07363 struct sip_pvt *p = ast->tech_pvt;
07364 int faxdetected = FALSE;
07365
07366 sip_pvt_lock(p);
07367 fr = sip_rtp_read(ast, p, &faxdetected);
07368 p->lastrtprx = time(NULL);
07369
07370
07371 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07372 if (strcmp(ast->exten, "fax")) {
07373 const char *target_context = S_OR(ast->macrocontext, ast->context);
07374
07375
07376
07377
07378
07379 sip_pvt_unlock(p);
07380 ast_channel_unlock(ast);
07381 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07382 ast_channel_lock(ast);
07383 sip_pvt_lock(p);
07384 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07385 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07386 if (ast_async_goto(ast, target_context, "fax", 1)) {
07387 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07388 }
07389 fr = &ast_null_frame;
07390 } else {
07391 ast_channel_lock(ast);
07392 sip_pvt_lock(p);
07393 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07394 }
07395 }
07396 }
07397
07398
07399 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07400 fr = &ast_null_frame;
07401 }
07402
07403 sip_pvt_unlock(p);
07404
07405 return fr;
07406 }
07407
07408
07409
07410 static char *generate_random_string(char *buf, size_t size)
07411 {
07412 long val[4];
07413 int x;
07414
07415 for (x=0; x<4; x++)
07416 val[x] = ast_random();
07417 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07418
07419 return buf;
07420 }
07421
07422
07423 static void build_callid_pvt(struct sip_pvt *pvt)
07424 {
07425 char buf[33];
07426
07427 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07428
07429 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07430
07431 }
07432
07433
07434 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07435 {
07436 char buf[33];
07437
07438 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07439
07440 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07441 }
07442
07443
07444 static void make_our_tag(char *tagbuf, size_t len)
07445 {
07446 snprintf(tagbuf, len, "as%08lx", ast_random());
07447 }
07448
07449
07450 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07451 {
07452 struct sip_st_dlg *stp;
07453
07454 if (p->stimer) {
07455 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07456 return p->stimer;
07457 }
07458
07459 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07460 return NULL;
07461
07462 p->stimer = stp;
07463
07464 stp->st_schedid = -1;
07465
07466 return p->stimer;
07467 }
07468
07469
07470
07471
07472
07473 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07474 int useglobal_nat, const int intended_method, struct sip_request *req)
07475 {
07476 struct sip_pvt *p;
07477
07478 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07479 return NULL;
07480
07481 if (ast_string_field_init(p, 512)) {
07482 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07483 return NULL;
07484 }
07485
07486 if (req) {
07487 set_socket_transport(&p->socket, req->socket.type);
07488 } else {
07489 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07490 }
07491
07492 p->socket.fd = -1;
07493 p->method = intended_method;
07494 p->initid = -1;
07495 p->waitid = -1;
07496 p->autokillid = -1;
07497 p->request_queue_sched_id = -1;
07498 p->provisional_keepalive_sched_id = -1;
07499 p->t38id = -1;
07500 p->subscribed = NONE;
07501 p->stateid = -1;
07502 p->sessionversion_remote = -1;
07503 p->session_modify = TRUE;
07504 p->stimer = NULL;
07505 p->prefs = default_prefs;
07506
07507 if (intended_method != SIP_OPTIONS) {
07508 p->timer_t1 = global_t1;
07509 p->timer_b = global_timer_b;
07510 }
07511
07512 if (!sin)
07513 p->ourip = internip;
07514 else {
07515 p->sa = *sin;
07516 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07517 }
07518
07519
07520 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07521 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07522
07523 p->do_history = recordhistory;
07524
07525 p->branch = ast_random();
07526 make_our_tag(p->tag, sizeof(p->tag));
07527 p->ocseq = INITIAL_CSEQ;
07528
07529 if (sip_methods[intended_method].need_rtp) {
07530 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07531
07532 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07533 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07534 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07535 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07536 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07537 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07538 if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07539
07540 ast_log(LOG_ERROR, "UDPTL creation failed\n");
07541 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07542 }
07543 }
07544 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
07545 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07546 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07547 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07548 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07549 if (p->chanvars) {
07550 ast_variables_destroy(p->chanvars);
07551 p->chanvars = NULL;
07552 }
07553 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07554 return NULL;
07555 p->t38_maxdatagram = global_t38_maxdatagram;
07556 }
07557 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07558 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07559 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07560 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07561 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07562 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07563 if (p->vrtp) {
07564 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07565 ast_rtp_setdtmf(p->vrtp, 0);
07566 ast_rtp_setdtmfcompensate(p->vrtp, 0);
07567 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07568 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07569 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07570 }
07571 if (p->trtp) {
07572 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07573 ast_rtp_setdtmf(p->trtp, 0);
07574 ast_rtp_setdtmfcompensate(p->trtp, 0);
07575 }
07576 if (p->udptl)
07577 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07578 p->maxcallbitrate = default_maxcallbitrate;
07579 p->autoframing = global_autoframing;
07580 ast_rtp_codec_setpref(p->rtp, &p->prefs);
07581 }
07582
07583 if (useglobal_nat && sin) {
07584
07585 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07586 p->recv = *sin;
07587 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07588 }
07589
07590 if (p->method != SIP_REGISTER)
07591 ast_string_field_set(p, fromdomain, default_fromdomain);
07592 build_via(p);
07593 if (!callid)
07594 build_callid_pvt(p);
07595 else
07596 ast_string_field_set(p, callid, callid);
07597
07598 ast_string_field_set(p, mohinterpret, default_mohinterpret);
07599 ast_string_field_set(p, mohsuggest, default_mohsuggest);
07600 p->capability = global_capability;
07601 p->allowtransfer = sip_cfg.allowtransfer;
07602 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07603 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07604 p->noncodeccapability |= AST_RTP_DTMF;
07605 if (p->udptl) {
07606 p->t38_maxdatagram = global_t38_maxdatagram;
07607 set_t38_capabilities(p);
07608 }
07609 ast_string_field_set(p, context, sip_cfg.default_context);
07610 ast_string_field_set(p, parkinglot, default_parkinglot);
07611
07612 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07613
07614
07615
07616 ao2_t_link(dialogs, p, "link pvt into dialogs table");
07617
07618 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");
07619 return p;
07620 }
07621
07622 static void free_via(struct sip_via *v)
07623 {
07624 if (!v) {
07625 return;
07626 }
07627
07628 ast_free(v->via);
07629 ast_free(v);
07630 }
07631
07632
07633
07634
07635
07636
07637
07638
07639
07640
07641
07642
07643
07644
07645
07646
07647
07648
07649
07650
07651
07652
07653
07654
07655
07656
07657
07658
07659
07660
07661
07662
07663
07664
07665 static struct sip_via *parse_via(const char *header)
07666 {
07667 struct sip_via *v = ast_calloc(1, sizeof(*v));
07668 char *via, *parm;
07669
07670 if (!v) {
07671 return NULL;
07672 }
07673
07674 v->via = ast_strdup(header);
07675 v->ttl = 1;
07676
07677 via = v->via;
07678
07679 if (ast_strlen_zero(via)) {
07680 ast_log(LOG_ERROR, "received request without a Via header\n");
07681 free_via(v);
07682 return NULL;
07683 }
07684
07685
07686 via = strsep(&via, ",");
07687
07688
07689 v->protocol = strsep(&via, " \t\r\n");
07690 if (ast_strlen_zero(v->protocol)) {
07691 ast_log(LOG_ERROR, "missing sent-protocol in Via header\n");
07692 free_via(v);
07693 return NULL;
07694 }
07695 v->protocol = ast_skip_blanks(v->protocol);
07696
07697 if (via) {
07698 via = ast_skip_blanks(via);
07699 }
07700
07701
07702 v->sent_by = strsep(&via, "; \t\r\n");
07703 if (ast_strlen_zero(v->sent_by)) {
07704 ast_log(LOG_ERROR, "missing sent-by in Via header\n");
07705 free_via(v);
07706 return NULL;
07707 }
07708 v->sent_by = ast_skip_blanks(v->sent_by);
07709
07710
07711 if ((parm = strchr(v->sent_by, ':'))) {
07712 char *endptr;
07713
07714 v->port = strtol(++parm, &endptr, 10);
07715 }
07716
07717
07718 while ((parm = strsep(&via, "; \t\r\n"))) {
07719 char *c;
07720 if ((c = strstr(parm, "maddr="))) {
07721 v->maddr = ast_skip_blanks(c + sizeof("maddr=") - 1);
07722 } else if ((c = strstr(parm, "branch="))) {
07723 v->branch = ast_skip_blanks(c + sizeof("branch=") - 1);
07724 } else if ((c = strstr(parm, "ttl="))) {
07725 char *endptr;
07726 c = ast_skip_blanks(c + sizeof("ttl=") - 1);
07727 v->ttl = strtol(c, &endptr, 10);
07728
07729
07730 if (c == endptr) {
07731 v->ttl = 1;
07732 }
07733 }
07734 }
07735
07736 return v;
07737 }
07738
07739
07740
07741
07742
07743
07744
07745
07746 static int addr_is_multicast(struct in_addr *addr)
07747 {
07748 return ((ntohl(addr->s_addr) & 0xf0000000) == 0xe0000000);
07749 }
07750
07751
07752
07753
07754
07755
07756
07757
07758
07759
07760
07761
07762
07763
07764
07765
07766 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07767 {
07768 struct sip_via *via = parse_via(get_header(req, "Via"));
07769
07770 if (!via) {
07771 ast_log(LOG_ERROR, "error processing via header\n");
07772 return -1;
07773 }
07774
07775 if (via->maddr) {
07776 struct hostent *hp;
07777 struct ast_hostent ahp;
07778
07779 hp = ast_gethostbyname(via->maddr, &ahp);
07780 if (hp == NULL) {
07781 ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07782 ast_log(LOG_ERROR, "error processing via header\n");
07783 free_via(via);
07784 return -1;
07785 }
07786
07787 p->sa.sin_family = AF_INET;
07788 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
07789
07790 if (addr_is_multicast(&p->sa.sin_addr)) {
07791 setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07792 }
07793 }
07794
07795 p->sa.sin_port = htons(via->port ? via->port : STANDARD_SIP_PORT);
07796
07797 free_via(via);
07798 return 0;
07799 }
07800
07801
07802 struct find_call_cb_arg {
07803 enum sipmethod method;
07804 const char *callid;
07805 const char *fromtag;
07806 const char *totag;
07807 const char *tag;
07808 };
07809
07810
07811
07812
07813
07814 static int find_call_cb(void *__pvt, void *__arg, int flags)
07815 {
07816 struct sip_pvt *p = __pvt;
07817 struct find_call_cb_arg *arg = __arg;
07818
07819 int found = FALSE;
07820
07821 if (!ast_strlen_zero(p->callid)) {
07822 if (arg->method == SIP_REGISTER)
07823 found = (!strcmp(p->callid, arg->callid));
07824 else {
07825 found = !strcmp(p->callid, arg->callid);
07826 if (sip_cfg.pedanticsipchecking && found) {
07827 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);
07828 }
07829 }
07830
07831 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);
07832
07833
07834 if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) {
07835 if (p->tag[0] == '\0' && arg->totag[0]) {
07836
07837 found = FALSE;
07838 } else if (arg->totag[0]) {
07839 if (strcmp(arg->totag, p->tag)) {
07840 found = FALSE;
07841 }
07842 }
07843 if (!found)
07844 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);
07845 }
07846 }
07847 return found;
07848 }
07849
07850
07851
07852
07853
07854
07855 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07856 {
07857 struct sip_pvt *p = NULL;
07858 char *tag = "";
07859 char totag[128];
07860 char fromtag[128];
07861 struct find_call_cb_arg arg;
07862 const char *callid = get_header(req, "Call-ID");
07863 const char *from = get_header(req, "From");
07864 const char *to = get_header(req, "To");
07865 const char *cseq = get_header(req, "Cseq");
07866 struct sip_pvt *sip_pvt_ptr;
07867
07868
07869
07870 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07871 ast_strlen_zero(from) || ast_strlen_zero(cseq))
07872 return NULL;
07873
07874 arg.method = req->method;
07875 arg.callid = callid;
07876 arg.fromtag = fromtag;
07877 arg.totag = totag;
07878 arg.tag = "";
07879
07880 if (sip_cfg.pedanticsipchecking) {
07881
07882
07883
07884
07885
07886
07887 if (gettag(req, "To", totag, sizeof(totag)))
07888 req->has_to_tag = 1;
07889 gettag(req, "From", fromtag, sizeof(fromtag));
07890
07891 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07892
07893 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);
07894
07895
07896 if (ast_strlen_zero(fromtag)) {
07897 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07898 return NULL;
07899 }
07900
07901 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07902 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07903 return NULL;
07904 }
07905 }
07906
07907 restartsearch:
07908 if (!sip_cfg.pedanticsipchecking) {
07909 struct sip_pvt tmp_dialog = {
07910 .callid = callid,
07911 };
07912 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07913 if (sip_pvt_ptr) {
07914
07915 sip_pvt_lock(sip_pvt_ptr);
07916 return sip_pvt_ptr;
07917 }
07918 } else {
07919 ao2_lock(dialogs);
07920 p = ao2_t_callback(dialogs, 0 , find_call_cb, &arg, "pedantic linear search for dialog");
07921 if (p) {
07922 if (sip_pvt_trylock(p)) {
07923 ao2_unlock(dialogs);
07924 usleep(1);
07925 p = dialog_unref(p, "pedantic linear search for dialog unref to restart search");
07926 goto restartsearch;
07927 }
07928 ao2_unlock(dialogs);
07929 return p;
07930 }
07931 ao2_unlock(dialogs);
07932 }
07933
07934
07935 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07936 if (intended_method == SIP_REFER) {
07937
07938 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07939 } else if (intended_method == SIP_NOTIFY) {
07940
07941
07942 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 No subscription");
07943 } else {
07944
07945 if ((p = sip_alloc(callid, sin, 1, intended_method, req))) {
07946
07947 sip_pvt_lock(p);
07948 } else {
07949
07950
07951
07952
07953
07954
07955
07956
07957 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07958 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07959 }
07960 }
07961 return p;
07962 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07963
07964 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07965 ast_debug(2, "Got a request with unsupported SIP method.\n");
07966 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07967
07968 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07969 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07970 }
07971
07972
07973 if (intended_method == SIP_RESPONSE)
07974 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07975
07976 return NULL;
07977 }
07978
07979
07980 static int sip_register(const char *value, int lineno)
07981 {
07982 struct sip_registry *reg;
07983 int portnum = 0;
07984 enum sip_transport transport = SIP_TRANSPORT_UDP;
07985 char buf[256] = "";
07986 char *userpart = NULL, *hostpart = NULL;
07987
07988 AST_DECLARE_APP_ARGS(pre1,
07989 AST_APP_ARG(peer);
07990 AST_APP_ARG(userpart);
07991 );
07992 AST_DECLARE_APP_ARGS(pre2,
07993 AST_APP_ARG(transport);
07994 AST_APP_ARG(blank);
07995 AST_APP_ARG(userpart);
07996 );
07997 AST_DECLARE_APP_ARGS(user1,
07998 AST_APP_ARG(userpart);
07999 AST_APP_ARG(secret);
08000 AST_APP_ARG(authuser);
08001 );
08002 AST_DECLARE_APP_ARGS(host1,
08003 AST_APP_ARG(hostpart);
08004 AST_APP_ARG(expiry);
08005 );
08006 AST_DECLARE_APP_ARGS(host2,
08007 AST_APP_ARG(hostpart);
08008 AST_APP_ARG(extension);
08009 );
08010 AST_DECLARE_APP_ARGS(host3,
08011 AST_APP_ARG(host);
08012 AST_APP_ARG(port);
08013 );
08014
08015 if (!value)
08016 return -1;
08017 ast_copy_string(buf, value, sizeof(buf));
08018
08019
08020
08021
08022
08023
08024 if ((hostpart = strrchr(buf, '@'))) {
08025 *hostpart++ = '\0';
08026 userpart = buf;
08027 }
08028
08029 if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
08030 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
08031 return -1;
08032 }
08033
08034
08035
08036
08037
08038
08039 AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
08040 if (ast_strlen_zero(pre1.userpart)) {
08041 pre1.userpart = pre1.peer;
08042 pre1.peer = NULL;
08043 }
08044
08045
08046
08047
08048
08049
08050
08051 AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
08052 if (ast_strlen_zero(pre2.userpart)) {
08053 pre2.userpart = pre2.transport;
08054 pre2.transport = NULL;
08055 } else {
08056 pre2.transport[strlen(pre2.transport) - 1] = '\0';
08057 }
08058
08059 if (!ast_strlen_zero(pre2.blank)) {
08060 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
08061 return -1;
08062 }
08063
08064
08065
08066
08067
08068
08069
08070
08071
08072 AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
08073
08074
08075
08076
08077
08078
08079
08080
08081
08082
08083 AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
08084
08085
08086
08087
08088
08089
08090
08091
08092
08093
08094
08095 AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
08096
08097
08098
08099
08100
08101
08102
08103
08104
08105
08106
08107
08108 AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
08109
08110 if (host3.port) {
08111 if (!(portnum = port_str2int(host3.port, 0))) {
08112 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
08113 }
08114 }
08115
08116
08117 if (!pre2.transport) {
08118 transport = SIP_TRANSPORT_UDP;
08119 } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
08120 transport = SIP_TRANSPORT_TCP;
08121 } else if (!strncasecmp(pre2.transport, "tls", 3)) {
08122 transport = SIP_TRANSPORT_TLS;
08123 } else if (!strncasecmp(pre2.transport, "udp", 3)) {
08124 transport = SIP_TRANSPORT_UDP;
08125 } else {
08126 transport = SIP_TRANSPORT_UDP;
08127 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
08128 }
08129
08130
08131 if (!portnum) {
08132 if (transport == SIP_TRANSPORT_TLS) {
08133 portnum = STANDARD_TLS_PORT;
08134 } else {
08135 portnum = STANDARD_SIP_PORT;
08136 }
08137 }
08138
08139 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
08140 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08141 return -1;
08142 }
08143
08144 if (ast_string_field_init(reg, 256)) {
08145 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
08146 ast_free(reg);
08147 return -1;
08148 }
08149
08150 ast_atomic_fetchadd_int(®objs, 1);
08151 ASTOBJ_INIT(reg);
08152 ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
08153 ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
08154 ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
08155 ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
08156 ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
08157 ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
08158
08159 reg->transport = transport;
08160 reg->timeout = reg->expire = -1;
08161 reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
08162 reg->portno = portnum;
08163 reg->callid_valid = FALSE;
08164 reg->ocseq = INITIAL_CSEQ;
08165 ASTOBJ_CONTAINER_LINK(®l, reg);
08166 registry_unref(reg, "unref the reg pointer");
08167 return 0;
08168 }
08169
08170
08171 static int sip_subscribe_mwi(const char *value, int lineno)
08172 {
08173 struct sip_subscription_mwi *mwi;
08174 int portnum = 0;
08175 enum sip_transport transport = SIP_TRANSPORT_UDP;
08176 char buf[256] = "";
08177 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08178
08179 if (!value) {
08180 return -1;
08181 }
08182
08183 ast_copy_string(buf, value, sizeof(buf));
08184
08185 sip_parse_host(buf, lineno, &username, &portnum, &transport);
08186
08187 if ((hostname = strrchr(username, '@'))) {
08188 *hostname++ = '\0';
08189 }
08190
08191 if ((secret = strchr(username, ':'))) {
08192 *secret++ = '\0';
08193 if ((authuser = strchr(secret, ':'))) {
08194 *authuser++ = '\0';
08195 }
08196 }
08197
08198 if ((mailbox = strchr(hostname, '/'))) {
08199 *mailbox++ = '\0';
08200 }
08201
08202 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08203 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
08204 return -1;
08205 }
08206
08207 if ((porta = strchr(hostname, ':'))) {
08208 *porta++ = '\0';
08209 if (!(portnum = atoi(porta))) {
08210 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08211 return -1;
08212 }
08213 }
08214
08215 if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
08216 return -1;
08217 }
08218
08219 if (ast_string_field_init(mwi, 256)) {
08220 ast_free(mwi);
08221 return -1;
08222 }
08223
08224 ASTOBJ_INIT(mwi);
08225 ast_string_field_set(mwi, username, username);
08226 if (secret) {
08227 ast_string_field_set(mwi, secret, secret);
08228 }
08229 if (authuser) {
08230 ast_string_field_set(mwi, authuser, authuser);
08231 }
08232 ast_string_field_set(mwi, hostname, hostname);
08233 ast_string_field_set(mwi, mailbox, mailbox);
08234 mwi->resub = -1;
08235 mwi->portno = portnum;
08236 mwi->transport = transport;
08237
08238 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08239 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08240
08241 return 0;
08242 }
08243
08244
08245
08246 static int lws2sws(char *msgbuf, int len)
08247 {
08248 int h = 0, t = 0;
08249 int lws = 0;
08250
08251 for (; h < len;) {
08252
08253 if (msgbuf[h] == '\r') {
08254 h++;
08255 continue;
08256 }
08257
08258 if (msgbuf[h] == '\n') {
08259
08260 if (h + 1 == len)
08261 break;
08262
08263 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08264
08265 h++;
08266 continue;
08267 }
08268
08269 msgbuf[t++] = msgbuf[h++];
08270 lws = 0;
08271 continue;
08272 }
08273 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08274 if (lws) {
08275 h++;
08276 continue;
08277 }
08278 msgbuf[t++] = msgbuf[h++];
08279 lws = 1;
08280 continue;
08281 }
08282 msgbuf[t++] = msgbuf[h++];
08283 if (lws)
08284 lws = 0;
08285 }
08286 msgbuf[t] = '\0';
08287 return t;
08288 }
08289
08290
08291
08292
08293 static int parse_request(struct sip_request *req)
08294 {
08295 char *c = req->data->str;
08296 ptrdiff_t *dst = req->header;
08297 int i = 0, lim = SIP_MAX_HEADERS - 1;
08298 unsigned int skipping_headers = 0;
08299 ptrdiff_t current_header_offset = 0;
08300 char *previous_header = "";
08301
08302 req->header[0] = 0;
08303 req->headers = -1;
08304 for (; *c; c++) {
08305 if (*c == '\r') {
08306 *c = '\0';
08307 } else if (*c == '\n') {
08308 *c = '\0';
08309 current_header_offset = (c + 1) - req->data->str;
08310 previous_header = req->data->str + dst[i];
08311 if (skipping_headers) {
08312
08313
08314
08315 if (ast_strlen_zero(previous_header)) {
08316 skipping_headers = 0;
08317 }
08318 dst[i] = current_header_offset;
08319 continue;
08320 }
08321 if (sipdebug) {
08322 ast_debug(4, "%7s %2d [%3d]: %s\n",
08323 req->headers < 0 ? "Header" : "Body",
08324 i, (int) strlen(previous_header), previous_header);
08325 }
08326 if (ast_strlen_zero(previous_header) && req->headers < 0) {
08327 req->headers = i;
08328 dst = req->line;
08329 i = 0;
08330 lim = SIP_MAX_LINES - 1;
08331 } else {
08332 if (i++ == lim) {
08333
08334
08335
08336 if (req->headers != -1) {
08337 break;
08338 } else {
08339 req->headers = i;
08340 dst = req->line;
08341 i = 0;
08342 lim = SIP_MAX_LINES - 1;
08343 skipping_headers = 1;
08344 }
08345 }
08346 }
08347 dst[i] = current_header_offset;
08348 }
08349 }
08350
08351
08352
08353
08354
08355
08356 previous_header = req->data->str + dst[i];
08357 if ((i < lim) && !ast_strlen_zero(previous_header)) {
08358 if (sipdebug) {
08359 ast_debug(4, "%7s %2d [%3d]: %s\n",
08360 req->headers < 0 ? "Header" : "Body",
08361 i, (int) strlen(previous_header), previous_header );
08362 }
08363 i++;
08364 }
08365
08366
08367 if (req->headers >= 0) {
08368 req->lines = i;
08369 } else {
08370 req->headers = i;
08371 req->lines = 0;
08372
08373 req->line[0] = ast_str_strlen(req->data);
08374 }
08375
08376 if (*c) {
08377 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08378 }
08379
08380
08381 return determine_firstline_parts(req);
08382 }
08383
08384
08385
08386
08387
08388
08389
08390
08391
08392 static int find_sdp(struct sip_request *req)
08393 {
08394 const char *content_type;
08395 const char *content_length;
08396 const char *search;
08397 char *boundary;
08398 unsigned int x;
08399 int boundaryisquoted = FALSE;
08400 int found_application_sdp = FALSE;
08401 int found_end_of_headers = FALSE;
08402
08403 content_length = get_header(req, "Content-Length");
08404
08405 if (!ast_strlen_zero(content_length)) {
08406 if (sscanf(content_length, "%30u", &x) != 1) {
08407 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08408 return 0;
08409 }
08410
08411
08412
08413 if (x == 0)
08414 return 0;
08415 }
08416
08417 content_type = get_header(req, "Content-Type");
08418
08419
08420 if (!strncasecmp(content_type, "application/sdp", 15)) {
08421 req->sdp_start = 0;
08422 req->sdp_count = req->lines;
08423 return req->lines ? 1 : 0;
08424 }
08425
08426
08427 if (strncasecmp(content_type, "multipart/mixed", 15))
08428 return 0;
08429
08430
08431 if ((search = strcasestr(content_type, ";boundary=")))
08432 search += 10;
08433 else if ((search = strcasestr(content_type, "; boundary=")))
08434 search += 11;
08435 else
08436 return 0;
08437
08438 if (ast_strlen_zero(search))
08439 return 0;
08440
08441
08442 if (*search == '\"') {
08443 search++;
08444 boundaryisquoted = TRUE;
08445 }
08446
08447
08448
08449 boundary = ast_strdupa(search - 2);
08450 boundary[0] = boundary[1] = '-';
08451
08452 if (boundaryisquoted)
08453 boundary[strlen(boundary) - 1] = '\0';
08454
08455
08456
08457
08458 for (x = 0; x < (req->lines); x++) {
08459 char *line = REQ_OFFSET_TO_STR(req, line[x]);
08460 if (!strncasecmp(line, boundary, strlen(boundary))){
08461 if (found_application_sdp && found_end_of_headers) {
08462 req->sdp_count = (x - 1) - req->sdp_start;
08463 return 1;
08464 }
08465 found_application_sdp = FALSE;
08466 }
08467 if (!strcasecmp(line, "Content-Type: application/sdp"))
08468 found_application_sdp = TRUE;
08469
08470 if (ast_strlen_zero(line)) {
08471 if (found_application_sdp && !found_end_of_headers){
08472 req->sdp_start = x;
08473 found_end_of_headers = TRUE;
08474 }
08475 }
08476 }
08477 if (found_application_sdp && found_end_of_headers) {
08478 req->sdp_count = x - req->sdp_start;
08479 return TRUE;
08480 }
08481 return FALSE;
08482 }
08483
08484
08485 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08486 {
08487 if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08488 sip_peer_hold(dialog, holdstate);
08489 if (sip_cfg.callevents)
08490 manager_event(EVENT_FLAG_CALL, "Hold",
08491 "Status: %s\r\n"
08492 "Channel: %s\r\n"
08493 "Uniqueid: %s\r\n",
08494 holdstate ? "On" : "Off",
08495 dialog->owner->name,
08496 dialog->owner->uniqueid);
08497 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08498 if (!holdstate) {
08499 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
08500 return;
08501 }
08502
08503
08504 if (sendonly == 1)
08505 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08506 else if (sendonly == 2)
08507 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08508 else
08509 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08510 return;
08511 }
08512
08513 enum media_type {
08514 SDP_AUDIO,
08515 SDP_VIDEO,
08516 SDP_IMAGE,
08517 SDP_TEXT,
08518 };
08519
08520 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08521 {
08522 const char *m;
08523 const char *c;
08524 int miterator = req->sdp_start;
08525 int citerator = req->sdp_start;
08526 int x = 0;
08527 int numberofports;
08528 int len;
08529 char host[258] = "";
08530 struct ast_hostent audiohp;
08531 struct hostent *hp;
08532
08533 c = get_sdp_iterate(&citerator, req, "c");
08534 if (sscanf(c, "IN IP4 %256s", host) != 1) {
08535 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08536
08537 }
08538
08539 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08540 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08541 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08542 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08543 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08544
08545
08546
08547
08548 c = get_sdp_iterate(&citerator, req, "c");
08549 if (!ast_strlen_zero(c)) {
08550 sscanf(c, "IN IP4 %256s", host);
08551 }
08552 break;
08553 }
08554 }
08555
08556 if (ast_strlen_zero(host) || x == 0) {
08557 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08558 return -1;
08559 }
08560
08561 hp = ast_gethostbyname(host, &audiohp);
08562 if (!hp) {
08563 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08564 return -1;
08565 }
08566
08567 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08568 sin->sin_port = htons(x);
08569 return 0;
08570 }
08571
08572
08573
08574
08575
08576
08577 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08578 {
08579
08580 int start = req->sdp_start;
08581 int next = start;
08582 int iterator = start;
08583
08584
08585 char type = '\0';
08586 const char *value = NULL;
08587 const char *m = NULL;
08588 const char *nextm = NULL;
08589 int len = -1;
08590
08591
08592 struct ast_hostent sessionhp;
08593 struct ast_hostent audiohp;
08594 struct ast_hostent videohp;
08595 struct ast_hostent texthp;
08596 struct ast_hostent imagehp;
08597 struct hostent *hp = NULL;
08598 struct hostent *vhp = NULL;
08599 struct hostent *thp = NULL;
08600 struct hostent *ihp = NULL;
08601 int portno = -1;
08602 int vportno = -1;
08603 int tportno = -1;
08604 int udptlportno = -1;
08605 struct sockaddr_in sin = { 0, };
08606 struct sockaddr_in vsin = { 0, };
08607 struct sockaddr_in isin = { 0, };
08608 struct sockaddr_in tsin = { 0, };
08609
08610
08611 int peercapability = 0, peernoncodeccapability = 0;
08612 int vpeercapability = 0, vpeernoncodeccapability = 0;
08613 int tpeercapability = 0, tpeernoncodeccapability = 0;
08614
08615 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08616 int newjointcapability;
08617 int newpeercapability;
08618 int newnoncodeccapability;
08619
08620 const char *codecs;
08621 int codec;
08622
08623
08624 int sendonly = -1;
08625 int vsendonly = -1;
08626 int numberofports;
08627 int numberofmediastreams = 0;
08628 int last_rtpmap_codec = 0;
08629 int red_data_pt[10];
08630 int red_num_gen = 0;
08631 char red_fmtp[100] = "empty";
08632 int debug = sip_debug_test_pvt(p);
08633
08634
08635 char buf[SIPBUFSIZE];
08636
08637
08638
08639 if (!p->rtp) {
08640 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08641 return -1;
08642 }
08643
08644
08645 #ifdef LOW_MEMORY
08646 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08647 #else
08648 newaudiortp = alloca(ast_rtp_alloc_size());
08649 #endif
08650 memset(newaudiortp, 0, ast_rtp_alloc_size());
08651 ast_rtp_new_init(newaudiortp);
08652 ast_rtp_pt_clear(newaudiortp);
08653
08654 #ifdef LOW_MEMORY
08655 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08656 #else
08657 newvideortp = alloca(ast_rtp_alloc_size());
08658 #endif
08659 memset(newvideortp, 0, ast_rtp_alloc_size());
08660 ast_rtp_new_init(newvideortp);
08661 ast_rtp_pt_clear(newvideortp);
08662
08663 #ifdef LOW_MEMORY
08664 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08665 #else
08666 newtextrtp = alloca(ast_rtp_alloc_size());
08667 #endif
08668 memset(newtextrtp, 0, ast_rtp_alloc_size());
08669 ast_rtp_new_init(newtextrtp);
08670 ast_rtp_pt_clear(newtextrtp);
08671
08672
08673 p->lastrtprx = p->lastrtptx = time(NULL);
08674
08675 memset(p->offered_media, 0, sizeof(p->offered_media));
08676
08677
08678
08679 p->novideo = TRUE;
08680 p->notext = TRUE;
08681
08682 if (p->vrtp)
08683 ast_rtp_pt_clear(newvideortp);
08684
08685 if (p->trtp)
08686 ast_rtp_pt_clear(newtextrtp);
08687
08688
08689 nextm = get_sdp_iterate(&next, req, "m");
08690 if (ast_strlen_zero(nextm)) {
08691 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08692 return -1;
08693 }
08694
08695
08696 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08697 int processed = FALSE;
08698 switch (type) {
08699 case 'o':
08700
08701
08702
08703 if (!process_sdp_o(value, p))
08704 return (p->session_modify == FALSE) ? 0 : -1;
08705 break;
08706 case 'c':
08707 if (process_sdp_c(value, &sessionhp)) {
08708 processed = TRUE;
08709 hp = &sessionhp.hp;
08710 vhp = hp;
08711 thp = hp;
08712 ihp = hp;
08713 }
08714 break;
08715 case 'a':
08716 if (process_sdp_a_sendonly(value, &sendonly)) {
08717 processed = TRUE;
08718 vsendonly = sendonly;
08719 }
08720 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08721 processed = TRUE;
08722 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08723 processed = TRUE;
08724 else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08725 processed = TRUE;
08726 else if (process_sdp_a_image(value, p))
08727 processed = TRUE;
08728 break;
08729 }
08730
08731 if (option_debug > 2)
08732 ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08733 }
08734
08735
08736
08737
08738 while (!ast_strlen_zero(nextm)) {
08739 int audio = FALSE;
08740 int video = FALSE;
08741 int image = FALSE;
08742 int text = FALSE;
08743 int x;
08744
08745 numberofports = 1;
08746 len = -1;
08747 start = next;
08748 m = nextm;
08749 iterator = next;
08750 nextm = get_sdp_iterate(&next, req, "m");
08751
08752
08753 if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08754 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08755 audio = TRUE;
08756 p->offered_media[SDP_AUDIO].offered = TRUE;
08757 numberofmediastreams++;
08758 portno = x;
08759
08760
08761 codecs = m + len;
08762 ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08763 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08764 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08765 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08766 return -1;
08767 }
08768 if (debug)
08769 ast_verbose("Found RTP audio format %d\n", codec);
08770
08771 ast_rtp_set_m_type(newaudiortp, codec);
08772 }
08773
08774 } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08775 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08776 video = TRUE;
08777 p->novideo = FALSE;
08778 p->offered_media[SDP_VIDEO].offered = TRUE;
08779 numberofmediastreams++;
08780 vportno = x;
08781
08782
08783 codecs = m + len;
08784 ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08785 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08786 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08787 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08788 return -1;
08789 }
08790 if (debug)
08791 ast_verbose("Found RTP video format %d\n", codec);
08792 ast_rtp_set_m_type(newvideortp, codec);
08793 }
08794
08795 } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08796 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08797 text = TRUE;
08798 p->notext = FALSE;
08799 p->offered_media[SDP_TEXT].offered = TRUE;
08800 numberofmediastreams++;
08801 tportno = x;
08802
08803
08804 codecs = m + len;
08805 ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08806 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08807 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08808 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08809 return -1;
08810 }
08811 if (debug)
08812 ast_verbose("Found RTP text format %d\n", codec);
08813 ast_rtp_set_m_type(newtextrtp, codec);
08814 }
08815
08816 } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08817 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08818 image = TRUE;
08819 if (debug)
08820 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08821 p->offered_media[SDP_IMAGE].offered = TRUE;
08822 udptlportno = x;
08823 numberofmediastreams++;
08824
08825 if (p->t38.state != T38_ENABLED) {
08826 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08827
08828
08829
08830 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08831 }
08832 } else {
08833 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08834 continue;
08835 }
08836
08837
08838 if (numberofports > 1)
08839 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08840
08841
08842
08843
08844 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08845 int processed = FALSE;
08846
08847 switch (type) {
08848 case 'c':
08849 if (audio) {
08850 if (process_sdp_c(value, &audiohp)) {
08851 processed = TRUE;
08852 hp = &audiohp.hp;
08853 }
08854 } else if (video) {
08855 if (process_sdp_c(value, &videohp)) {
08856 processed = TRUE;
08857 vhp = &videohp.hp;
08858 }
08859 } else if (text) {
08860 if (process_sdp_c(value, &texthp)) {
08861 processed = TRUE;
08862 thp = &texthp.hp;
08863 }
08864 } else if (image) {
08865 if (process_sdp_c(value, &imagehp)) {
08866 processed = TRUE;
08867 ihp = &imagehp.hp;
08868 }
08869 }
08870 break;
08871 case 'a':
08872
08873 if (audio) {
08874 if (process_sdp_a_sendonly(value, &sendonly))
08875 processed = TRUE;
08876 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08877 processed = TRUE;
08878 }
08879
08880 else if (video) {
08881 if (process_sdp_a_sendonly(value, &vsendonly))
08882 processed = TRUE;
08883 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08884 processed = TRUE;
08885 }
08886
08887 else if (text) {
08888 if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08889 processed = TRUE;
08890 }
08891
08892 else if (image) {
08893 if (process_sdp_a_image(value, p))
08894 processed = TRUE;
08895 }
08896 break;
08897 }
08898
08899 if (option_debug > 2)
08900 ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08901 (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08902 type, value,
08903 (processed == TRUE)? "OK." : "UNSUPPORTED.");
08904 }
08905 }
08906
08907
08908
08909 if (!hp && !vhp && !thp && !ihp) {
08910 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08911 return -1;
08912 }
08913
08914 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
08915
08916
08917 return -2;
08918
08919 if (numberofmediastreams > 3)
08920
08921 return -3;
08922
08923 if (udptlportno == -1) {
08924 change_t38_state(p, T38_DISABLED);
08925 }
08926
08927
08928
08929 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08930 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08931 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08932
08933 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08934 newpeercapability = (peercapability | vpeercapability | tpeercapability);
08935 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08936
08937 if (debug) {
08938
08939 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08940
08941 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08942 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08943 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08944 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08945 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08946 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08947
08948 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08949 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08950 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08951 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08952 }
08953 if (!newjointcapability && (portno != -1)) {
08954 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08955
08956 return -1;
08957 }
08958
08959
08960 if (p->rtp) {
08961 if (portno > 0) {
08962 sin.sin_family = AF_INET;
08963 sin.sin_port = htons(portno);
08964 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08965 ast_rtp_set_peer(p->rtp, &sin);
08966 if (debug)
08967 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08968
08969
08970 p->jointcapability = newjointcapability;
08971 p->peercapability = newpeercapability;
08972 p->jointnoncodeccapability = newnoncodeccapability;
08973
08974 ast_rtp_pt_copy(p->rtp, newaudiortp);
08975
08976 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08977 ast_clear_flag(&p->flags[0], SIP_DTMF);
08978 if (newnoncodeccapability & AST_RTP_DTMF) {
08979
08980 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08981
08982 ast_rtp_setdtmf(p->rtp, 1);
08983 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08984 } else {
08985 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08986 }
08987 }
08988 } else if (udptlportno > 0) {
08989 if (debug)
08990 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08991 } else {
08992 ast_rtp_stop(p->rtp);
08993 if (debug)
08994 ast_verbose("Peer doesn't provide audio\n");
08995 }
08996 }
08997
08998
08999 if (p->vrtp) {
09000 if (vportno > 0) {
09001 vsin.sin_family = AF_INET;
09002 vsin.sin_port = htons(vportno);
09003 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
09004 ast_rtp_set_peer(p->vrtp, &vsin);
09005 if (debug)
09006 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
09007 ast_rtp_pt_copy(p->vrtp, newvideortp);
09008 } else {
09009 ast_rtp_stop(p->vrtp);
09010 if (debug)
09011 ast_verbose("Peer doesn't provide video\n");
09012 }
09013 }
09014
09015
09016 if (p->trtp) {
09017 if (tportno > 0) {
09018 tsin.sin_family = AF_INET;
09019 tsin.sin_port = htons(tportno);
09020 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
09021 ast_rtp_set_peer(p->trtp, &tsin);
09022 if (debug)
09023 ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
09024 if ((p->jointcapability & AST_FORMAT_T140RED)) {
09025 p->red = 1;
09026 rtp_red_init(p->trtp, 300, red_data_pt, 2);
09027 } else {
09028 p->red = 0;
09029 }
09030 ast_rtp_pt_copy(p->trtp, newtextrtp);
09031 } else {
09032 ast_rtp_stop(p->trtp);
09033 if (debug)
09034 ast_verbose("Peer doesn't provide T.140\n");
09035 }
09036 }
09037
09038 if (p->udptl) {
09039 if (udptlportno > 0) {
09040 isin.sin_family = AF_INET;
09041 isin.sin_port = htons(udptlportno);
09042 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09043 struct sockaddr_in remote_address = { 0, };
09044 ast_rtp_get_peer(p->rtp, &remote_address);
09045 if (remote_address.sin_addr.s_addr) {
09046 memcpy(&isin, &remote_address, sizeof(isin));
09047 if (debug) {
09048 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));
09049 }
09050 }
09051 } else {
09052 memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
09053 }
09054 ast_udptl_set_peer(p->udptl, &isin);
09055 if (debug)
09056 ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
09057
09058
09059 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09060
09061 ast_udptl_set_far_max_datagram(p->udptl, 0);
09062 }
09063
09064
09065 if ((t38action == SDP_T38_ACCEPT) &&
09066 (p->t38.state == T38_LOCAL_REINVITE)) {
09067 change_t38_state(p, T38_ENABLED);
09068 } else if ((t38action == SDP_T38_INITIATE) &&
09069 p->owner && p->lastinvite) {
09070 change_t38_state(p, T38_PEER_REINVITE);
09071
09072 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09073 ast_channel_lock(p->owner);
09074 if (strcmp(p->owner->exten, "fax")) {
09075 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09076 ast_channel_unlock(p->owner);
09077 if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
09078 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09079 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09080 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09081 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09082 }
09083 } else {
09084 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09085 }
09086 } else {
09087 ast_channel_unlock(p->owner);
09088 }
09089 }
09090 }
09091 } else {
09092 ast_udptl_stop(p->udptl);
09093 if (debug)
09094 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09095 }
09096 }
09097
09098 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09099 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09100 return 0;
09101 }
09102
09103
09104 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09105
09106 if (!p->owner)
09107 return 0;
09108
09109 ast_debug(4, "We have an owner, now see if we need to change this call\n");
09110
09111 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09112 if (debug) {
09113 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09114 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09115 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09116 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09117 }
09118 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09119 ast_set_read_format(p->owner, p->owner->readformat);
09120 ast_set_write_format(p->owner, p->owner->writeformat);
09121 }
09122
09123 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)
09124 && (sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
09125 isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
09126 && (!sendonly || sendonly == -1)) {
09127 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09128
09129 ast_queue_frame(p->owner, &ast_null_frame);
09130 change_hold_state(p, req, FALSE, sendonly);
09131 } else if (!(sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
09132 isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
09133 || (sendonly && sendonly != -1)) {
09134 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09135 S_OR(p->mohsuggest, NULL),
09136 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09137 if (sendonly)
09138 ast_rtp_stop(p->rtp);
09139
09140
09141 ast_queue_frame(p->owner, &ast_null_frame);
09142 change_hold_state(p, req, TRUE, sendonly);
09143 }
09144
09145 return 0;
09146 }
09147
09148 static int process_sdp_o(const char *o, struct sip_pvt *p)
09149 {
09150 char *o_copy;
09151 char *token;
09152 int64_t rua_version;
09153
09154
09155
09156
09157
09158
09159
09160
09161
09162
09163 p->session_modify = TRUE;
09164
09165 if (ast_strlen_zero(o)) {
09166 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09167 return FALSE;
09168 }
09169
09170 o_copy = ast_strdupa(o);
09171 token = strsep(&o_copy, " ");
09172 if (!o_copy) {
09173 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09174 return FALSE;
09175 }
09176 token = strsep(&o_copy, " ");
09177 if (!o_copy) {
09178 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09179 return FALSE;
09180 }
09181 token = strsep(&o_copy, " ");
09182 if (!o_copy) {
09183 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09184 return FALSE;
09185 }
09186 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09187 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09188 return FALSE;
09189 }
09190
09191
09192
09193
09194
09195
09196
09197
09198
09199
09200
09201
09202
09203
09204
09205
09206
09207
09208
09209 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09210 (p->sessionversion_remote < 0) ||
09211 (p->sessionversion_remote < rua_version)) {
09212 p->sessionversion_remote = rua_version;
09213 } else {
09214 if (p->t38.state == T38_LOCAL_REINVITE) {
09215 p->sessionversion_remote = rua_version;
09216 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);
09217 } else {
09218 p->session_modify = FALSE;
09219 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09220 return FALSE;
09221 }
09222 }
09223
09224 return TRUE;
09225 }
09226
09227 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
09228 {
09229 char host[258];
09230 struct hostent *hp;
09231
09232
09233 if (sscanf(c, "IN IP4 %255s", host) != 1) {
09234 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09235 return FALSE;
09236 } else {
09237 if (!(hp = ast_gethostbyname(host, ast_hp))) {
09238 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09239 return FALSE;
09240 }
09241 return TRUE;
09242 }
09243 return FALSE;
09244 }
09245
09246 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09247 {
09248 int found = FALSE;
09249
09250 if (!strcasecmp(a, "sendonly")) {
09251 if (*sendonly == -1)
09252 *sendonly = 1;
09253 found = TRUE;
09254 } else if (!strcasecmp(a, "inactive")) {
09255 if (*sendonly == -1)
09256 *sendonly = 2;
09257 found = TRUE;
09258 } else if (!strcasecmp(a, "sendrecv")) {
09259 if (*sendonly == -1)
09260 *sendonly = 0;
09261 found = TRUE;
09262 }
09263 return found;
09264 }
09265
09266 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
09267 {
09268 int found = FALSE;
09269 int codec;
09270 char mimeSubtype[128];
09271 char fmtp_string[64];
09272 unsigned int sample_rate;
09273 int debug = sip_debug_test_pvt(p);
09274
09275 if (!strncasecmp(a, "ptime", 5)) {
09276 char *tmp = strrchr(a, ':');
09277 long int framing = 0;
09278 if (tmp) {
09279 tmp++;
09280 framing = strtol(tmp, NULL, 10);
09281 if (framing == LONG_MIN || framing == LONG_MAX) {
09282 framing = 0;
09283 ast_debug(1, "Can't read framing from SDP: %s\n", a);
09284 }
09285 }
09286 if (framing && p->autoframing) {
09287 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09288 int codec_n;
09289 int format = 0;
09290 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
09291 format = ast_rtp_codec_getformat(codec_n);
09292 if (!format)
09293 continue;
09294 if (option_debug)
09295 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
09296 ast_codec_pref_setsize(pref, format, framing);
09297 }
09298 ast_rtp_codec_setpref(p->rtp, pref);
09299 }
09300 found = TRUE;
09301 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09302
09303 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09304 if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
09305 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
09306 if (debug)
09307 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09308
09309 (*last_rtpmap_codec)++;
09310 found = TRUE;
09311 } else {
09312 ast_rtp_unset_m_type(newaudiortp, codec);
09313 if (debug)
09314 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09315 }
09316 } else {
09317 if (debug)
09318 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09319 }
09320 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09321 struct rtpPayloadType payload;
09322
09323 payload = ast_rtp_lookup_pt(newaudiortp, codec);
09324 if (payload.code && payload.isAstFormat) {
09325 unsigned int bit_rate;
09326
09327 switch (payload.code) {
09328 case AST_FORMAT_SIREN7:
09329 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09330 if (bit_rate != 32000) {
09331 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09332 ast_rtp_unset_m_type(newaudiortp, codec);
09333 } else {
09334 found = TRUE;
09335 }
09336 }
09337 break;
09338 case AST_FORMAT_SIREN14:
09339 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09340 if (bit_rate != 48000) {
09341 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09342 ast_rtp_unset_m_type(newaudiortp, codec);
09343 } else {
09344 found = TRUE;
09345 }
09346 }
09347 break;
09348 }
09349 }
09350 }
09351
09352 return found;
09353 }
09354
09355 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
09356 {
09357 int found = FALSE;
09358 int codec;
09359 char mimeSubtype[128];
09360 unsigned int sample_rate;
09361 int debug = sip_debug_test_pvt(p);
09362
09363 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09364
09365 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09366
09367 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09368 if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
09369 if (debug)
09370 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09371
09372 (*last_rtpmap_codec)++;
09373 found = TRUE;
09374 } else {
09375 ast_rtp_unset_m_type(newvideortp, codec);
09376 if (debug)
09377 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09378 }
09379 }
09380 } else {
09381 if (debug)
09382 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09383 }
09384 }
09385
09386 return found;
09387 }
09388
09389 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)
09390 {
09391 int found = FALSE;
09392 int codec;
09393 char mimeSubtype[128];
09394 unsigned int sample_rate;
09395 char *red_cp;
09396 int debug = sip_debug_test_pvt(p);
09397
09398 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09399
09400 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09401 if (!strncasecmp(mimeSubtype, "T140", 4)) {
09402 if (p->trtp) {
09403
09404 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09405 found = TRUE;
09406 }
09407 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
09408 if (p->trtp) {
09409 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09410 sprintf(red_fmtp, "fmtp:%d ", codec);
09411 if (debug)
09412 ast_verbose("RED submimetype has payload type: %d\n", codec);
09413 found = TRUE;
09414 }
09415 }
09416 } else {
09417 if (debug)
09418 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09419 }
09420 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09421
09422 red_cp = &red_fmtp[strlen(red_fmtp)];
09423 strncpy(red_fmtp, a, 100);
09424
09425 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09426 red_cp = strtok(red_cp, "/");
09427 while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
09428 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09429 red_cp = strtok(NULL, "/");
09430 }
09431 red_cp = red_fmtp;
09432 found = TRUE;
09433 }
09434
09435 return found;
09436 }
09437
09438 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09439 {
09440 int found = FALSE;
09441 char s[256];
09442 unsigned int x;
09443
09444 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09445 ast_debug(3, "MaxBufferSize:%d\n", x);
09446 found = TRUE;
09447 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09448 ast_debug(3, "T38MaxBitRate: %d\n", x);
09449 switch (x) {
09450 case 14400:
09451 p->t38.their_parms.rate = AST_T38_RATE_14400;
09452 break;
09453 case 12000:
09454 p->t38.their_parms.rate = AST_T38_RATE_12000;
09455 break;
09456 case 9600:
09457 p->t38.their_parms.rate = AST_T38_RATE_9600;
09458 break;
09459 case 7200:
09460 p->t38.their_parms.rate = AST_T38_RATE_7200;
09461 break;
09462 case 4800:
09463 p->t38.their_parms.rate = AST_T38_RATE_4800;
09464 break;
09465 case 2400:
09466 p->t38.their_parms.rate = AST_T38_RATE_2400;
09467 break;
09468 }
09469 found = TRUE;
09470 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09471 ast_debug(3, "FaxVersion: %u\n", x);
09472 p->t38.their_parms.version = x;
09473 found = TRUE;
09474 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09475
09476 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09477 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09478 x = p->t38_maxdatagram;
09479 }
09480 ast_debug(3, "FaxMaxDatagram: %u\n", x);
09481 ast_udptl_set_far_max_datagram(p->udptl, x);
09482 found = TRUE;
09483 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09484 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09485 ast_debug(3, "FillBitRemoval: %d\n", x);
09486 if (x == 1) {
09487 p->t38.their_parms.fill_bit_removal = TRUE;
09488 }
09489 } else {
09490 ast_debug(3, "FillBitRemoval\n");
09491 p->t38.their_parms.fill_bit_removal = TRUE;
09492 }
09493 found = TRUE;
09494 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09495 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09496 ast_debug(3, "Transcoding MMR: %d\n", x);
09497 if (x == 1) {
09498 p->t38.their_parms.transcoding_mmr = TRUE;
09499 }
09500 } else {
09501 ast_debug(3, "Transcoding MMR\n");
09502 p->t38.their_parms.transcoding_mmr = TRUE;
09503 }
09504 found = TRUE;
09505 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09506 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09507 ast_debug(3, "Transcoding JBIG: %d\n", x);
09508 if (x == 1) {
09509 p->t38.their_parms.transcoding_jbig = TRUE;
09510 }
09511 } else {
09512 ast_debug(3, "Transcoding JBIG\n");
09513 p->t38.their_parms.transcoding_jbig = TRUE;
09514 }
09515 found = TRUE;
09516 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09517 ast_debug(3, "RateManagement: %s\n", s);
09518 if (!strcasecmp(s, "localTCF"))
09519 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09520 else if (!strcasecmp(s, "transferredTCF"))
09521 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09522 found = TRUE;
09523 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09524 ast_debug(3, "UDP EC: %s\n", s);
09525 if (!strcasecmp(s, "t38UDPRedundancy")) {
09526 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09527 } else if (!strcasecmp(s, "t38UDPFEC")) {
09528 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09529 } else {
09530 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09531 }
09532 found = TRUE;
09533 }
09534
09535 return found;
09536 }
09537
09538
09539 #ifdef LOW_MEMORY
09540 static void ts_ast_rtp_destroy(void *data)
09541 {
09542 struct ast_rtp *tmp = data;
09543 ast_rtp_destroy(tmp);
09544 }
09545 #endif
09546
09547
09548
09549
09550 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09551 {
09552 int res;
09553 if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
09554 res = add_header(req, "Supported", "replaces, timer");
09555 } else {
09556 res = add_header(req, "Supported", "replaces");
09557 }
09558 return res;
09559 }
09560
09561
09562 static int add_header(struct sip_request *req, const char *var, const char *value)
09563 {
09564 if (req->headers == SIP_MAX_HEADERS) {
09565 ast_log(LOG_WARNING, "Out of SIP header space\n");
09566 return -1;
09567 }
09568
09569 if (req->lines) {
09570 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09571 return -1;
09572 }
09573
09574 if (sip_cfg.compactheaders) {
09575 var = find_alias(var, var);
09576 }
09577
09578 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09579 req->header[req->headers] = req->len;
09580
09581 req->len = ast_str_strlen(req->data);
09582 req->headers++;
09583
09584 return 0;
09585 }
09586
09587
09588 static int finalize_content(struct sip_request *req)
09589 {
09590 char clen[10];
09591
09592 if (req->lines) {
09593 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09594 return -1;
09595 }
09596
09597 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09598 add_header(req, "Content-Length", clen);
09599
09600 if (ast_str_strlen(req->content)) {
09601 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09602 req->len = ast_str_strlen(req->data);
09603 }
09604 req->lines = ast_str_strlen(req->content) ? 1 : 0;
09605 return 0;
09606 }
09607
09608
09609 static int add_content(struct sip_request *req, const char *line)
09610 {
09611 if (req->lines) {
09612 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09613 return -1;
09614 }
09615
09616 ast_str_append(&req->content, 0, "%s", line);
09617 return 0;
09618 }
09619
09620
09621 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09622 {
09623 const char *tmp = get_header(orig, field);
09624
09625 if (!ast_strlen_zero(tmp))
09626 return add_header(req, field, tmp);
09627 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09628 return -1;
09629 }
09630
09631
09632 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09633 {
09634 int start = 0;
09635 int copied = 0;
09636 for (;;) {
09637 const char *tmp = __get_header(orig, field, &start);
09638
09639 if (ast_strlen_zero(tmp))
09640 break;
09641
09642 add_header(req, field, tmp);
09643 copied++;
09644 }
09645 return copied ? 0 : -1;
09646 }
09647
09648
09649
09650
09651
09652
09653
09654
09655
09656 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09657 {
09658 int copied = 0;
09659 int start = 0;
09660
09661 for (;;) {
09662 char new[512];
09663 const char *oh = __get_header(orig, field, &start);
09664
09665 if (ast_strlen_zero(oh))
09666 break;
09667
09668 if (!copied) {
09669 char leftmost[512], *others, *rport;
09670
09671
09672 ast_copy_string(leftmost, oh, sizeof(leftmost));
09673 others = strchr(leftmost, ',');
09674 if (others)
09675 *others++ = '\0';
09676
09677
09678 rport = strstr(leftmost, ";rport");
09679 if (rport && *(rport+6) == '=')
09680 rport = NULL;
09681
09682
09683 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09684
09685 char *end;
09686
09687 rport = strstr(leftmost, ";rport");
09688
09689 if (rport) {
09690 end = strchr(rport + 1, ';');
09691 if (end)
09692 memmove(rport, end, strlen(end) + 1);
09693 else
09694 *rport = '\0';
09695 }
09696
09697
09698 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09699 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09700 ntohs(p->recv.sin_port),
09701 others ? "," : "", others ? others : "");
09702 } else {
09703
09704 snprintf(new, sizeof(new), "%s;received=%s%s%s",
09705 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09706 others ? "," : "", others ? others : "");
09707 }
09708 oh = new;
09709 }
09710 add_header(req, field, oh);
09711 copied++;
09712 }
09713 if (!copied) {
09714 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09715 return -1;
09716 }
09717 return 0;
09718 }
09719
09720
09721 static void add_route(struct sip_request *req, struct sip_route *route)
09722 {
09723 char r[SIPBUFSIZE*2], *p;
09724 int n, rem = sizeof(r);
09725
09726 if (!route)
09727 return;
09728
09729 p = r;
09730 for (;route ; route = route->next) {
09731 n = strlen(route->hop);
09732 if (rem < n+3)
09733 break;
09734 if (p != r) {
09735 *p++ = ',';
09736 --rem;
09737 }
09738 *p++ = '<';
09739 ast_copy_string(p, route->hop, rem);
09740 p += n;
09741 *p++ = '>';
09742 rem -= (n+2);
09743 }
09744 *p = '\0';
09745 add_header(req, "Route", r);
09746 }
09747
09748
09749
09750
09751
09752
09753
09754
09755
09756
09757 static void set_destination(struct sip_pvt *p, char *uri)
09758 {
09759 char *h, *maddr, hostname[256];
09760 int port, hn;
09761 struct hostent *hp;
09762 struct ast_hostent ahp;
09763 int debug=sip_debug_test_pvt(p);
09764 int tls_on = FALSE;
09765 int use_dns = sip_cfg.srvlookup;
09766
09767 if (debug)
09768 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09769
09770
09771 h = strchr(uri, '@');
09772 if (h)
09773 ++h;
09774 else {
09775 h = uri;
09776 if (!strncasecmp(h, "sip:", 4)) {
09777 h += 4;
09778 } else if (!strncasecmp(h, "sips:", 5)) {
09779 h += 5;
09780 tls_on = TRUE;
09781 }
09782 }
09783 hn = strcspn(h, ":;>") + 1;
09784 if (hn > sizeof(hostname))
09785 hn = sizeof(hostname);
09786 ast_copy_string(hostname, h, hn);
09787
09788 h += hn - 1;
09789
09790
09791 if (*h == ':') {
09792
09793 ++h;
09794 port = strtol(h, &h, 10);
09795 use_dns = FALSE;
09796 } else
09797 port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09798
09799
09800 maddr = strstr(h, "maddr=");
09801 if (maddr) {
09802 maddr += 6;
09803 hn = strspn(maddr, "0123456789.") + 1;
09804 if (hn > sizeof(hostname))
09805 hn = sizeof(hostname);
09806 ast_copy_string(hostname, maddr, hn);
09807 }
09808
09809
09810
09811 hp = ast_gethostbyname(hostname, &ahp);
09812 if (hp == NULL) {
09813 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09814 return;
09815 }
09816 p->sa.sin_family = AF_INET;
09817 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09818 p->sa.sin_port = htons(port);
09819 if (debug)
09820 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09821 }
09822
09823
09824 static int init_resp(struct sip_request *resp, const char *msg)
09825 {
09826
09827 memset(resp, 0, sizeof(*resp));
09828 resp->method = SIP_RESPONSE;
09829 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09830 goto e_return;
09831 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09832 goto e_free_data;
09833 resp->header[0] = 0;
09834 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09835 resp->len = resp->data->used;
09836 resp->headers++;
09837 return 0;
09838
09839 e_free_data:
09840 ast_free(resp->data);
09841 resp->data = NULL;
09842 e_return:
09843 return -1;
09844 }
09845
09846
09847 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09848 {
09849
09850 memset(req, 0, sizeof(*req));
09851 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09852 goto e_return;
09853 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09854 goto e_free_data;
09855 req->method = sipmethod;
09856 req->header[0] = 0;
09857 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09858 req->len = ast_str_strlen(req->data);
09859 req->headers++;
09860 return 0;
09861
09862 e_free_data:
09863 ast_free(req->data);
09864 req->data = NULL;
09865 e_return:
09866 return -1;
09867 }
09868
09869
09870 static void deinit_req(struct sip_request *req)
09871 {
09872 if (req->data) {
09873 ast_free(req->data);
09874 req->data = NULL;
09875 }
09876 if (req->content) {
09877 ast_free(req->content);
09878 req->content = NULL;
09879 }
09880 }
09881
09882
09883
09884 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09885
09886
09887
09888
09889
09890
09891
09892
09893
09894
09895
09896
09897
09898
09899
09900 switch (method) {
09901
09902 case SIP_INVITE:
09903 case SIP_UPDATE:
09904 case SIP_SUBSCRIBE:
09905 case SIP_NOTIFY:
09906 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09907 return 1;
09908 break;
09909
09910
09911 case SIP_REGISTER:
09912 case SIP_OPTIONS:
09913 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09914 return 1;
09915 break;
09916
09917
09918 case SIP_BYE:
09919 case SIP_PRACK:
09920 case SIP_MESSAGE:
09921 case SIP_PUBLISH:
09922 if (msg[0] == '3' || !strncmp(msg, "485", 3))
09923 return 1;
09924 break;
09925
09926
09927 case SIP_REFER:
09928 if (msg[0] >= '2' && msg[0] <= '6')
09929 return 1;
09930 break;
09931
09932
09933 case SIP_ACK:
09934 case SIP_CANCEL:
09935 case SIP_INFO:
09936 case SIP_PING:
09937 default:
09938 return 0;
09939 }
09940 return 0;
09941 }
09942
09943
09944 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09945 {
09946 char newto[256];
09947 const char *ot;
09948
09949 init_resp(resp, msg);
09950 copy_via_headers(p, resp, req, "Via");
09951 if (msg[0] == '1' || msg[0] == '2')
09952 copy_all_header(resp, req, "Record-Route");
09953 copy_header(resp, req, "From");
09954 ot = get_header(req, "To");
09955 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09956
09957
09958 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09959 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09960 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09961 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09962 else
09963 ast_copy_string(newto, ot, sizeof(newto));
09964 ot = newto;
09965 }
09966 add_header(resp, "To", ot);
09967 copy_header(resp, req, "Call-ID");
09968 copy_header(resp, req, "CSeq");
09969 if (!ast_strlen_zero(global_useragent))
09970 add_header(resp, "Server", global_useragent);
09971 add_header(resp, "Allow", ALLOWED_METHODS);
09972 add_supported_header(p, resp);
09973
09974
09975 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09976 char se_hdr[256];
09977 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09978 strefresher2str(p->stimer->st_ref));
09979 add_header(resp, "Session-Expires", se_hdr);
09980 }
09981
09982 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09983
09984
09985 char tmp[256];
09986
09987 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09988 add_header(resp, "Expires", tmp);
09989 if (p->expiry) {
09990 char contact[SIPBUFSIZE];
09991 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09992 char *brackets = strchr(contact_uri, '<');
09993 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09994 add_header(resp, "Contact", contact);
09995 }
09996 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09997 add_header(resp, "Contact", p->our_contact);
09998 }
09999
10000 if (!ast_strlen_zero(p->url)) {
10001 add_header(resp, "Access-URL", p->url);
10002 ast_string_field_set(p, url, NULL);
10003 }
10004
10005
10006
10007
10008
10009
10010
10011 p->sa = p->recv;
10012
10013 if (process_via(p, req)) {
10014 ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10015 }
10016
10017 return 0;
10018 }
10019
10020
10021 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
10022 {
10023 struct sip_request *orig = &p->initreq;
10024 char stripped[80];
10025 char tmp[80];
10026 char newto[256];
10027 const char *c;
10028 const char *ot, *of;
10029 int is_strict = FALSE;
10030 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
10031
10032 memset(req, 0, sizeof(struct sip_request));
10033
10034 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10035
10036 if (!seqno) {
10037 p->ocseq++;
10038 seqno = p->ocseq;
10039 }
10040
10041
10042 if (sipmethod == SIP_CANCEL) {
10043 p->branch = p->invite_branch;
10044 build_via(p);
10045 } else if (newbranch && (sipmethod == SIP_INVITE)) {
10046 p->branch ^= ast_random();
10047 p->invite_branch = p->branch;
10048 build_via(p);
10049 } else if (newbranch) {
10050 p->branch ^= ast_random();
10051 build_via(p);
10052 }
10053
10054
10055 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10056 is_strict = TRUE;
10057 if (sipdebug)
10058 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10059 }
10060
10061 if (sipmethod == SIP_CANCEL)
10062 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10063 else if (sipmethod == SIP_ACK) {
10064
10065
10066 if (!ast_strlen_zero(p->okcontacturi))
10067 c = is_strict ? p->route->hop : p->okcontacturi;
10068 else
10069 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10070 } else if (!ast_strlen_zero(p->okcontacturi))
10071 c = is_strict ? p->route->hop : p->okcontacturi;
10072 else if (!ast_strlen_zero(p->uri))
10073 c = p->uri;
10074 else {
10075 char *n;
10076
10077 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10078 sizeof(stripped));
10079 n = get_in_brackets(stripped);
10080 c = remove_uri_parameters(n);
10081 }
10082 init_req(req, sipmethod, c);
10083
10084 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
10085
10086 add_header(req, "Via", p->via);
10087 if (p->route) {
10088 set_destination(p, p->route->hop);
10089 add_route(req, is_strict ? p->route->next : p->route);
10090 }
10091 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10092
10093 ot = get_header(orig, "To");
10094 of = get_header(orig, "From");
10095
10096
10097
10098 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10099
10100
10101 if (is_outbound && !ast_strlen_zero(p->theirtag))
10102 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10103 else if (!is_outbound)
10104 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10105 else
10106 snprintf(newto, sizeof(newto), "%s", ot);
10107 ot = newto;
10108 }
10109
10110 if (is_outbound) {
10111 add_header(req, "From", of);
10112 add_header(req, "To", ot);
10113 } else {
10114 add_header(req, "From", ot);
10115 add_header(req, "To", of);
10116 }
10117
10118 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10119 add_header(req, "Contact", p->our_contact);
10120
10121 copy_header(req, orig, "Call-ID");
10122 add_header(req, "CSeq", tmp);
10123
10124 if (!ast_strlen_zero(global_useragent))
10125 add_header(req, "User-Agent", global_useragent);
10126
10127 if (!ast_strlen_zero(p->rpid))
10128 add_header(req, "Remote-Party-ID", p->rpid);
10129
10130 if (!ast_strlen_zero(p->url)) {
10131 add_header(req, "Access-URL", p->url);
10132 ast_string_field_set(p, url, NULL);
10133 }
10134
10135
10136
10137
10138
10139
10140
10141
10142 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10143 && sipmethod == SIP_INVITE) {
10144 char se_hdr[256];
10145 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10146 strefresher2str(p->stimer->st_ref));
10147 add_header(req, "Session-Expires", se_hdr);
10148 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10149 add_header(req, "Min-SE", se_hdr);
10150 }
10151
10152 return 0;
10153 }
10154
10155
10156 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10157 {
10158 struct sip_request resp;
10159 int seqno = 0;
10160
10161 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10162 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10163 return -1;
10164 }
10165 respprep(&resp, p, msg, req);
10166
10167
10168 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
10169 char buf[10];
10170
10171 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10172 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10173 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10174 }
10175 return send_response(p, &resp, reliable, seqno);
10176 }
10177
10178 static int temp_pvt_init(void *data)
10179 {
10180 struct sip_pvt *p = data;
10181
10182 p->do_history = 0;
10183 return ast_string_field_init(p, 512);
10184 }
10185
10186 static void temp_pvt_cleanup(void *data)
10187 {
10188 struct sip_pvt *p = data;
10189
10190 ast_string_field_free_memory(p);
10191
10192 ast_free(data);
10193 }
10194
10195
10196 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)
10197 {
10198 struct sip_pvt *p = NULL;
10199
10200 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10201 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10202 return -1;
10203 }
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213 p->method = intended_method;
10214
10215 if (!sin)
10216 p->ourip = internip;
10217 else {
10218 p->sa = *sin;
10219 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10220 }
10221
10222 p->branch = ast_random();
10223 make_our_tag(p->tag, sizeof(p->tag));
10224 p->ocseq = INITIAL_CSEQ;
10225
10226 if (useglobal_nat && sin) {
10227 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
10228 p->recv = *sin;
10229 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
10230 }
10231
10232 ast_string_field_set(p, fromdomain, default_fromdomain);
10233 build_via(p);
10234 ast_string_field_set(p, callid, callid);
10235
10236 copy_socket_data(&p->socket, &req->socket);
10237
10238
10239 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10240
10241
10242 ast_string_field_init(p, 0);
10243
10244 return 0;
10245 }
10246
10247
10248 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10249 {
10250 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10251 }
10252
10253
10254 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
10255 {
10256 struct sip_request resp;
10257 respprep(&resp, p, msg, req);
10258 append_date(&resp);
10259 add_header(&resp, "Unsupported", unsupported);
10260 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10261 }
10262
10263
10264 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10265 {
10266 struct sip_request resp;
10267 char minse_str[20];
10268
10269 respprep(&resp, p, msg, req);
10270 append_date(&resp);
10271
10272 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10273 add_header(&resp, "Min-SE", minse_str);
10274 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10275 }
10276
10277
10278
10279
10280
10281 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10282 {
10283 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10284 }
10285
10286
10287 static void append_date(struct sip_request *req)
10288 {
10289 char tmpdat[256];
10290 struct tm tm;
10291 time_t t = time(NULL);
10292
10293 gmtime_r(&t, &tm);
10294 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10295 add_header(req, "Date", tmpdat);
10296 }
10297
10298
10299 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10300 {
10301 struct sip_request resp;
10302 respprep(&resp, p, msg, req);
10303 append_date(&resp);
10304 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10305 }
10306
10307
10308 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10309 {
10310 struct sip_request resp;
10311 respprep(&resp, p, msg, req);
10312 add_header(&resp, "Accept", "application/sdp");
10313 return send_response(p, &resp, reliable, 0);
10314 }
10315
10316
10317 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)
10318 {
10319 struct sip_request resp;
10320 char tmp[512];
10321 int seqno = 0;
10322
10323 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10324 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10325 return -1;
10326 }
10327
10328
10329 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
10330 respprep(&resp, p, msg, req);
10331 add_header(&resp, header, tmp);
10332 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10333 return send_response(p, &resp, reliable, seqno);
10334 }
10335
10336
10337 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10338 {
10339 int res;
10340
10341 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
10342 p->last_provisional = msg;
10343 update_provisional_keepalive(p, with_sdp);
10344 }
10345
10346 return res;
10347 }
10348
10349
10350 static int add_text(struct sip_request *req, const char *text)
10351 {
10352
10353 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10354 add_content(req, text);
10355 return 0;
10356 }
10357
10358
10359
10360
10361
10362 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10363 {
10364 char tmp[256];
10365 int event;
10366 if (mode) {
10367
10368 if (digit == '*')
10369 event = 10;
10370 else if (digit == '#')
10371 event = 11;
10372 else if ((digit >= 'A') && (digit <= 'D'))
10373 event = 12 + digit - 'A';
10374 else
10375 event = atoi(&digit);
10376 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10377 add_header(req, "Content-Type", "application/dtmf");
10378 add_content(req, tmp);
10379 } else {
10380
10381 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10382 add_header(req, "Content-Type", "application/dtmf-relay");
10383 add_content(req, tmp);
10384 }
10385 return 0;
10386 }
10387
10388
10389
10390 static int add_vidupdate(struct sip_request *req)
10391 {
10392 const char *xml_is_a_huge_waste_of_space =
10393 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
10394 " <media_control>\r\n"
10395 " <vc_primitive>\r\n"
10396 " <to_encoder>\r\n"
10397 " <picture_fast_update>\r\n"
10398 " </picture_fast_update>\r\n"
10399 " </to_encoder>\r\n"
10400 " </vc_primitive>\r\n"
10401 " </media_control>\r\n";
10402 add_header(req, "Content-Type", "application/media_control+xml");
10403 add_content(req, xml_is_a_huge_waste_of_space);
10404 return 0;
10405 }
10406
10407
10408 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
10409 struct ast_str **m_buf, struct ast_str **a_buf,
10410 int debug, int *min_packet_size)
10411 {
10412 int rtp_code;
10413 struct ast_format_list fmt;
10414
10415
10416 if (debug)
10417 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10418 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
10419 return;
10420
10421 if (p->rtp) {
10422 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
10423 fmt = ast_codec_pref_getsize(pref, codec);
10424 } else
10425 return;
10426 ast_str_append(m_buf, 0, " %d", rtp_code);
10427 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10428 ast_rtp_lookup_mime_subtype(1, codec,
10429 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10430 ast_rtp_lookup_sample_rate(1, codec));
10431
10432 switch (codec) {
10433 case AST_FORMAT_G729A:
10434
10435 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10436 break;
10437 case AST_FORMAT_G723_1:
10438
10439 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10440 break;
10441 case AST_FORMAT_ILBC:
10442
10443 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10444 break;
10445 case AST_FORMAT_SIREN7:
10446
10447 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10448 break;
10449 case AST_FORMAT_SIREN14:
10450
10451 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10452 break;
10453 }
10454
10455 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10456 *min_packet_size = fmt.cur_ms;
10457
10458
10459 if ((*min_packet_size)==0 && fmt.cur_ms)
10460 *min_packet_size = fmt.cur_ms;
10461 }
10462
10463
10464
10465 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
10466 struct ast_str **m_buf, struct ast_str **a_buf,
10467 int debug, int *min_packet_size)
10468 {
10469 int rtp_code;
10470
10471 if (!p->vrtp)
10472 return;
10473
10474 if (debug)
10475 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10476
10477 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
10478 return;
10479
10480 ast_str_append(m_buf, 0, " %d", rtp_code);
10481 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10482 ast_rtp_lookup_mime_subtype(1, codec, 0),
10483 ast_rtp_lookup_sample_rate(1, codec));
10484
10485 }
10486
10487
10488 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10489 struct ast_str **m_buf, struct ast_str **a_buf,
10490 int debug, int *min_packet_size)
10491 {
10492 int rtp_code;
10493
10494 if (!p->trtp)
10495 return;
10496
10497 if (debug)
10498 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10499
10500 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10501 return;
10502
10503 ast_str_append(m_buf, 0, " %d", rtp_code);
10504 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10505 ast_rtp_lookup_mime_subtype(1, codec, 0),
10506 ast_rtp_lookup_sample_rate(1, codec));
10507
10508
10509 if (codec == AST_FORMAT_T140RED) {
10510 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10511 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10512 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10513 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10514
10515 }
10516 }
10517
10518
10519
10520 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10521 {
10522 switch (rate) {
10523 case AST_T38_RATE_2400:
10524 return 2400;
10525 case AST_T38_RATE_4800:
10526 return 4800;
10527 case AST_T38_RATE_7200:
10528 return 7200;
10529 case AST_T38_RATE_9600:
10530 return 9600;
10531 case AST_T38_RATE_12000:
10532 return 12000;
10533 case AST_T38_RATE_14400:
10534 return 14400;
10535 default:
10536 return 0;
10537 }
10538 }
10539
10540
10541 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10542 struct ast_str **m_buf, struct ast_str **a_buf,
10543 int debug)
10544 {
10545 int rtp_code;
10546
10547 if (debug)
10548 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10549 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10550 return;
10551
10552 ast_str_append(m_buf, 0, " %d", rtp_code);
10553 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10554 ast_rtp_lookup_mime_subtype(0, format, 0),
10555 ast_rtp_lookup_sample_rate(0, format));
10556 if (format == AST_RTP_DTMF)
10557 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10558 }
10559
10560
10561
10562
10563 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10564 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10565 struct sockaddr_in *dest, struct sockaddr_in *vdest)
10566 {
10567
10568 ast_rtp_get_us(p->rtp, sin);
10569 if (p->vrtp)
10570 ast_rtp_get_us(p->vrtp, vsin);
10571 if (p->trtp)
10572 ast_rtp_get_us(p->trtp, tsin);
10573
10574
10575
10576 if (p->redirip.sin_addr.s_addr) {
10577 dest->sin_port = p->redirip.sin_port;
10578 dest->sin_addr = p->redirip.sin_addr;
10579 } else {
10580 dest->sin_addr = p->ourip.sin_addr;
10581 dest->sin_port = sin->sin_port;
10582 }
10583 if (needvideo) {
10584
10585 if (p->vredirip.sin_addr.s_addr) {
10586 vdest->sin_addr = p->vredirip.sin_addr;
10587 vdest->sin_port = p->vredirip.sin_port;
10588 } else {
10589 vdest->sin_addr = p->ourip.sin_addr;
10590 vdest->sin_port = vsin->sin_port;
10591 }
10592 }
10593
10594 }
10595
10596
10597
10598
10599
10600
10601
10602 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10603 {
10604 int alreadysent = 0;
10605 int doing_directmedia = FALSE;
10606
10607 struct sockaddr_in sin;
10608 struct sockaddr_in vsin;
10609 struct sockaddr_in tsin;
10610 struct sockaddr_in dest;
10611 struct sockaddr_in udptlsin;
10612 struct sockaddr_in vdest = { 0, };
10613 struct sockaddr_in tdest = { 0, };
10614 struct sockaddr_in udptldest = { 0, };
10615
10616
10617 char *version = "v=0\r\n";
10618 char subject[256];
10619 char owner[256];
10620 char connection[256];
10621 char *session_time = "t=0 0\r\n";
10622 char bandwidth[256] = "";
10623 char *hold = "";
10624 struct ast_str *m_audio = ast_str_alloca(256);
10625 struct ast_str *m_video = ast_str_alloca(256);
10626 struct ast_str *m_text = ast_str_alloca(256);
10627 struct ast_str *m_modem = ast_str_alloca(256);
10628 struct ast_str *a_audio = ast_str_alloca(1024);
10629 struct ast_str *a_video = ast_str_alloca(1024);
10630 struct ast_str *a_text = ast_str_alloca(1024);
10631 struct ast_str *a_modem = ast_str_alloca(1024);
10632
10633 int x;
10634 int capability = 0;
10635 int needaudio = FALSE;
10636 int needvideo = FALSE;
10637 int needtext = FALSE;
10638 int debug = sip_debug_test_pvt(p);
10639 int min_audio_packet_size = 0;
10640 int min_video_packet_size = 0;
10641 int min_text_packet_size = 0;
10642
10643 char codecbuf[SIPBUFSIZE];
10644 char buf[SIPBUFSIZE];
10645 char dummy_answer[256];
10646
10647
10648 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10649
10650 if (!p->rtp) {
10651 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10652 return AST_FAILURE;
10653 }
10654
10655
10656
10657
10658 if (!p->sessionid) {
10659 p->sessionid = (int)ast_random();
10660 p->sessionversion = p->sessionid;
10661 } else {
10662 if (oldsdp == FALSE)
10663 p->sessionversion++;
10664 }
10665
10666 if (add_audio) {
10667 doing_directmedia = (p->redirip.sin_addr.s_addr && p->redircodecs) ? TRUE : FALSE;
10668
10669 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10670 if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
10671 ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
10672 } else if (p->vrtp) {
10673 needvideo = TRUE;
10674 ast_debug(2, "This call needs video offers!\n");
10675 } else {
10676 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10677 }
10678 }
10679
10680 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10681 if (sipdebug_text)
10682 ast_verbose("We think we can do text\n");
10683 if (p->trtp) {
10684 if (sipdebug_text) {
10685 ast_verbose("And we have a text rtp object\n");
10686 }
10687 needtext = TRUE;
10688 ast_debug(2, "This call needs text offers! \n");
10689 } else {
10690 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10691 }
10692 }
10693 }
10694
10695 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10696
10697 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));
10698 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10699
10700 if (add_audio) {
10701 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
10702 hold = "a=recvonly\r\n";
10703 doing_directmedia = FALSE;
10704 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
10705 hold = "a=inactive\r\n";
10706 doing_directmedia = FALSE;
10707 } else {
10708 hold = "a=sendrecv\r\n";
10709 }
10710
10711 capability = p->jointcapability;
10712
10713
10714 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
10715 p->novideo ? "True" : "False", p->notext ? "True" : "False");
10716 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10717
10718 if (doing_directmedia) {
10719 capability &= p->redircodecs;
10720 ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
10721 }
10722
10723
10724 if (capability & AST_FORMAT_AUDIO_MASK)
10725 needaudio = TRUE;
10726
10727 if (debug)
10728 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
10729
10730
10731
10732 if (needvideo) {
10733 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10734
10735
10736 if (p->maxcallbitrate)
10737 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10738 if (debug)
10739 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));
10740 }
10741
10742
10743
10744 if (needtext) {
10745 if (sipdebug_text)
10746 ast_verbose("Lets set up the text sdp\n");
10747
10748 if (p->tredirip.sin_addr.s_addr) {
10749 tdest.sin_addr = p->tredirip.sin_addr;
10750 tdest.sin_port = p->tredirip.sin_port;
10751 } else {
10752 tdest.sin_addr = p->ourip.sin_addr;
10753 tdest.sin_port = tsin.sin_port;
10754 }
10755 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10756 if (debug)
10757 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
10758
10759 }
10760
10761
10762
10763
10764
10765
10766 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777 if (capability & p->prefcodec) {
10778 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10779
10780 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10781 alreadysent |= codec;
10782 }
10783
10784
10785 for (x = 0; x < 32; x++) {
10786 int codec;
10787
10788 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10789 break;
10790
10791 if (!(capability & codec))
10792 continue;
10793
10794 if (alreadysent & codec)
10795 continue;
10796
10797 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10798 alreadysent |= codec;
10799 }
10800
10801
10802 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10803 if (!(capability & x))
10804 continue;
10805
10806 if (alreadysent & x)
10807 continue;
10808
10809 if (x & AST_FORMAT_AUDIO_MASK)
10810 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10811 else if (x & AST_FORMAT_VIDEO_MASK)
10812 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10813 else if (x & AST_FORMAT_TEXT_MASK)
10814 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10815 }
10816
10817
10818 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10819 if (!(p->jointnoncodeccapability & x))
10820 continue;
10821
10822 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10823 }
10824
10825 ast_debug(3, "-- Done with adding codecs to SDP\n");
10826
10827 if (!p->owner || !ast_internal_timing_enabled(p->owner))
10828 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10829
10830 if (min_audio_packet_size)
10831 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10832
10833
10834 if (min_video_packet_size)
10835 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10836
10837
10838 if (min_text_packet_size)
10839 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10840
10841 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10842 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10843 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10844 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10845 }
10846
10847 if (add_t38) {
10848
10849 ast_udptl_get_us(p->udptl, &udptlsin);
10850
10851
10852 if (p->udptlredirip.sin_addr.s_addr) {
10853 udptldest.sin_port = p->udptlredirip.sin_port;
10854 udptldest.sin_addr = p->udptlredirip.sin_addr;
10855 } else {
10856 udptldest.sin_addr = p->ourip.sin_addr;
10857 udptldest.sin_port = udptlsin.sin_port;
10858 }
10859
10860 if (debug)
10861 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10862
10863
10864
10865
10866 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10867
10868 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10869 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10870 if (p->t38.our_parms.fill_bit_removal) {
10871 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10872 }
10873 if (p->t38.our_parms.transcoding_mmr) {
10874 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10875 }
10876 if (p->t38.our_parms.transcoding_jbig) {
10877 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10878 }
10879 switch (p->t38.our_parms.rate_management) {
10880 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10881 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10882 break;
10883 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10884 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10885 break;
10886 }
10887 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10888 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10889 case UDPTL_ERROR_CORRECTION_NONE:
10890 break;
10891 case UDPTL_ERROR_CORRECTION_FEC:
10892 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10893 break;
10894 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10895 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10896 break;
10897 }
10898 }
10899
10900 if (needaudio)
10901 ast_str_append(&m_audio, 0, "\r\n");
10902 if (needvideo)
10903 ast_str_append(&m_video, 0, "\r\n");
10904 if (needtext)
10905 ast_str_append(&m_text, 0, "\r\n");
10906
10907 add_header(resp, "Content-Type", "application/sdp");
10908 add_content(resp, version);
10909 add_content(resp, owner);
10910 add_content(resp, subject);
10911 add_content(resp, connection);
10912 if (needvideo)
10913 add_content(resp, bandwidth);
10914 add_content(resp, session_time);
10915 if (needaudio) {
10916 add_content(resp, m_audio->str);
10917 add_content(resp, a_audio->str);
10918 add_content(resp, hold);
10919 } else if (p->offered_media[SDP_AUDIO].offered) {
10920 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10921 add_content(resp, dummy_answer);
10922 }
10923 if (needvideo) {
10924 add_content(resp, m_video->str);
10925 add_content(resp, a_video->str);
10926 add_content(resp, hold);
10927 } else if (p->offered_media[SDP_VIDEO].offered) {
10928 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10929 add_content(resp, dummy_answer);
10930 }
10931 if (needtext) {
10932 add_content(resp, m_text->str);
10933 add_content(resp, a_text->str);
10934 add_content(resp, hold);
10935 } else if (p->offered_media[SDP_TEXT].offered) {
10936 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10937 add_content(resp, dummy_answer);
10938 }
10939 if (add_t38) {
10940 add_content(resp, m_modem->str);
10941 add_content(resp, a_modem->str);
10942 } else if (p->offered_media[SDP_IMAGE].offered) {
10943 add_content(resp, "m=image 0 udptl t38\r\n");
10944 }
10945
10946
10947 p->lastrtprx = p->lastrtptx = time(NULL);
10948
10949 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10950
10951 return AST_SUCCESS;
10952 }
10953
10954
10955 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10956 {
10957 struct sip_request resp;
10958 int seqno;
10959
10960 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10961 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10962 return -1;
10963 }
10964 respprep(&resp, p, msg, req);
10965 if (p->udptl) {
10966 add_sdp(&resp, p, 0, 0, 1);
10967 } else
10968 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10969 if (retrans && !p->pendinginvite)
10970 p->pendinginvite = seqno;
10971 return send_response(p, &resp, retrans, seqno);
10972 }
10973
10974
10975 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10976 {
10977
10978
10979
10980 struct ast_str *duplicate = dst->data;
10981 struct ast_str *duplicate_content = dst->content;
10982
10983
10984
10985 memcpy(dst, src, sizeof(*dst));
10986 dst->data = duplicate;
10987 dst->content = duplicate_content;
10988
10989
10990 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10991 return;
10992 ast_str_copy_string(&dst->data, src->data);
10993
10994
10995 if (src->content) {
10996 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10997 return;
10998 ast_str_copy_string(&dst->content, src->content);
10999 }
11000 }
11001
11002
11003
11004
11005 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
11006 {
11007 struct sip_request resp;
11008 int seqno;
11009 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
11010 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11011 return -1;
11012 }
11013 respprep(&resp, p, msg, req);
11014 if (p->rtp) {
11015 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11016 ast_debug(1, "Setting framing from config on incoming call\n");
11017 ast_rtp_codec_setpref(p->rtp, &p->prefs);
11018 }
11019 try_suggested_sip_codec(p);
11020 if (p->t38.state == T38_ENABLED) {
11021 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
11022 } else {
11023 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
11024 }
11025 } else
11026 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
11027 if (reliable && !p->pendinginvite)
11028 p->pendinginvite = seqno;
11029 return send_response(p, &resp, reliable, seqno);
11030 }
11031
11032
11033 static int determine_firstline_parts(struct sip_request *req)
11034 {
11035 char *e = ast_skip_blanks(req->data->str);
11036 char *local_rlPart1;
11037
11038 if (!*e)
11039 return -1;
11040 req->rlPart1 = e - req->data->str;
11041 local_rlPart1 = e;
11042 e = ast_skip_nonblanks(e);
11043 if (*e)
11044 *e++ = '\0';
11045
11046 e = ast_skip_blanks(e);
11047 if ( !*e )
11048 return -1;
11049 ast_trim_blanks(e);
11050
11051 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
11052 if (strlen(e) < 3)
11053 return -1;
11054 req->rlPart2 = e - req->data->str;
11055 } else {
11056 if ( *e == '<' ) {
11057 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
11058 e++;
11059 if (!*e)
11060 return -1;
11061 }
11062 req->rlPart2 = e - req->data->str;
11063 e = ast_skip_nonblanks(e);
11064 if (*e)
11065 *e++ = '\0';
11066 e = ast_skip_blanks(e);
11067 if (strcasecmp(e, "SIP/2.0") ) {
11068 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
11069 return -1;
11070 }
11071 }
11072 return 1;
11073 }
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
11089 {
11090 struct sip_request req;
11091
11092 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
11093
11094 add_header(&req, "Allow", ALLOWED_METHODS);
11095 add_supported_header(p, &req);
11096 if (sipdebug) {
11097 if (oldsdp == TRUE)
11098 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11099 else
11100 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11101 }
11102
11103 if (p->do_history)
11104 append_history(p, "ReInv", "Re-invite sent");
11105 memset(p->offered_media, 0, sizeof(p->offered_media));
11106
11107 if (t38version)
11108 add_sdp(&req, p, oldsdp, FALSE, TRUE);
11109 else
11110 add_sdp(&req, p, oldsdp, TRUE, FALSE);
11111
11112
11113 initialize_initreq(p, &req);
11114 p->lastinvite = p->ocseq;
11115 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11116
11117 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11118 }
11119
11120
11121 static char *remove_uri_parameters(char *uri)
11122 {
11123 char *atsign;
11124 atsign = strchr(uri, '@');
11125 if (!atsign)
11126 atsign = uri;
11127 atsign = strchr(atsign, ';');
11128 if (atsign)
11129 *atsign = '\0';
11130 return uri;
11131 }
11132
11133
11134 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
11135 {
11136 char stripped[SIPBUFSIZE];
11137 char *c;
11138
11139 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
11140 c = get_in_brackets(stripped);
11141
11142 c = remove_uri_parameters(c);
11143 if (!ast_strlen_zero(c))
11144 ast_string_field_set(p, uri, c);
11145
11146 }
11147
11148
11149 static void build_contact(struct sip_pvt *p)
11150 {
11151 char tmp[SIPBUFSIZE];
11152 char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 1);
11153 int ourport = ntohs(p->ourip.sin_port);
11154
11155
11156 if (!sip_standard_port(p->socket.type, ourport)) {
11157 if (p->socket.type == SIP_TRANSPORT_UDP)
11158 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
11159 else
11160 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
11161 } else {
11162 if (p->socket.type == SIP_TRANSPORT_UDP)
11163 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
11164 else
11165 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
11166 }
11167 }
11168
11169
11170 static void build_rpid(struct sip_pvt *p)
11171 {
11172 int send_pres_tags = TRUE;
11173 const char *privacy=NULL;
11174 const char *screen=NULL;
11175 char buf[256];
11176 const char *clid = default_callerid;
11177 const char *clin = NULL;
11178 const char *fromdomain;
11179
11180 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
11181 return;
11182
11183 if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
11184 clid = p->owner->cid.cid_num;
11185 if (p->owner && p->owner->cid.cid_name)
11186 clin = p->owner->cid.cid_name;
11187 if (ast_strlen_zero(clin))
11188 clin = clid;
11189
11190 switch (p->callingpres) {
11191 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11192 privacy = "off";
11193 screen = "no";
11194 break;
11195 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11196 privacy = "off";
11197 screen = "yes";
11198 break;
11199 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11200 privacy = "off";
11201 screen = "no";
11202 break;
11203 case AST_PRES_ALLOWED_NETWORK_NUMBER:
11204 privacy = "off";
11205 screen = "yes";
11206 break;
11207 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11208 privacy = "full";
11209 screen = "no";
11210 break;
11211 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11212 privacy = "full";
11213 screen = "yes";
11214 break;
11215 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11216 privacy = "full";
11217 screen = "no";
11218 break;
11219 case AST_PRES_PROHIB_NETWORK_NUMBER:
11220 privacy = "full";
11221 screen = "yes";
11222 break;
11223 case AST_PRES_NUMBER_NOT_AVAILABLE:
11224 send_pres_tags = FALSE;
11225 break;
11226 default:
11227 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
11228 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
11229 privacy = "full";
11230 else
11231 privacy = "off";
11232 screen = "no";
11233 break;
11234 }
11235
11236 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
11237
11238 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
11239 if (send_pres_tags)
11240 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
11241 ast_string_field_set(p, rpid, buf);
11242
11243 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
11244 S_OR(p->fromuser, clid),
11245 fromdomain, p->tag);
11246 }
11247
11248
11249 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
11250 {
11251 struct ast_str *invite = ast_str_alloca(256);
11252 char from[256];
11253 char to[256];
11254 char tmp_n[SIPBUFSIZE/2];
11255 char tmp_l[SIPBUFSIZE/2];
11256 const char *l = NULL;
11257 const char *n = NULL;
11258 const char *d = NULL;
11259 const char *urioptions = "";
11260 int ourport;
11261
11262 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
11263 const char *s = p->username;
11264
11265
11266
11267
11268
11269
11270 if (*s == '+')
11271 s++;
11272 for (; *s; s++) {
11273 if (!strchr(AST_DIGIT_ANYNUM, *s) )
11274 break;
11275 }
11276
11277 if (!*s)
11278 urioptions = ";user=phone";
11279 }
11280
11281
11282 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
11283
11284 d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
11285 if (p->owner) {
11286 l = p->owner->cid.cid_num;
11287 n = p->owner->cid.cid_name;
11288 }
11289
11290 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
11291 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
11292 l = CALLERID_UNKNOWN;
11293 n = l;
11294 d = FROMDOMAIN_INVALID;
11295 }
11296 if (ast_strlen_zero(l))
11297 l = default_callerid;
11298 if (ast_strlen_zero(n))
11299 n = l;
11300
11301 if (!ast_strlen_zero(p->fromuser))
11302 l = p->fromuser;
11303 else
11304 ast_string_field_set(p, fromuser, l);
11305
11306
11307 if (!ast_strlen_zero(p->fromname))
11308 n = p->fromname;
11309 else
11310 ast_string_field_set(p, fromname, n);
11311
11312 if (sip_cfg.pedanticsipchecking) {
11313 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11314 n = tmp_n;
11315 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
11316 l = tmp_l;
11317 }
11318
11319 ourport = ntohs(p->ourip.sin_port);
11320 if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
11321 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
11322 else
11323 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
11324
11325
11326 if (!ast_strlen_zero(p->fullcontact)) {
11327
11328 ast_str_append(&invite, 0, "%s", p->fullcontact);
11329 } else {
11330
11331 ast_str_append(&invite, 0, "sip:");
11332 if (!ast_strlen_zero(p->username)) {
11333 n = p->username;
11334 if (sip_cfg.pedanticsipchecking) {
11335 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11336 n = tmp_n;
11337 }
11338 ast_str_append(&invite, 0, "%s@", n);
11339 }
11340 ast_str_append(&invite, 0, "%s", p->tohost);
11341 if (p->portinuri)
11342 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
11343 ast_str_append(&invite, 0, "%s", urioptions);
11344 }
11345
11346
11347 if (p->options && !ast_strlen_zero(p->options->uri_options))
11348 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
11349
11350
11351
11352
11353 ast_string_field_set(p, uri, invite->str);
11354
11355 if (!ast_strlen_zero(p->todnid)) {
11356
11357 if (!strchr(p->todnid, '@')) {
11358
11359 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11360 } else {
11361 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11362 }
11363 } else {
11364 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
11365
11366 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
11367 } else if (p->options && p->options->vxml_url) {
11368
11369 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
11370 } else
11371 snprintf(to, sizeof(to), "<%s>", p->uri);
11372 }
11373
11374 init_req(req, sipmethod, p->uri);
11375
11376 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
11377
11378 add_header(req, "Via", p->via);
11379 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11380
11381
11382
11383
11384 add_route(req, p->route);
11385
11386
11387 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
11388 build_rpid(p);
11389 add_header(req, "From", p->rpid_from);
11390 } else
11391 add_header(req, "From", from);
11392 add_header(req, "To", to);
11393 ast_string_field_set(p, exten, l);
11394 build_contact(p);
11395 add_header(req, "Contact", p->our_contact);
11396 add_header(req, "Call-ID", p->callid);
11397 add_header(req, "CSeq", tmp_n);
11398 if (!ast_strlen_zero(global_useragent))
11399 add_header(req, "User-Agent", global_useragent);
11400 if (!ast_strlen_zero(p->rpid))
11401 add_header(req, "Remote-Party-ID", p->rpid);
11402 }
11403
11404
11405
11406
11407
11408
11409
11410
11411 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
11412 {
11413 struct sip_request req;
11414 struct ast_variable *var;
11415
11416 req.method = sipmethod;
11417 if (init) {
11418 p->branch ^= ast_random();
11419 p->invite_branch = p->branch;
11420 build_via(p);
11421 }
11422 if (init > 1)
11423 initreqprep(&req, p, sipmethod);
11424 else
11425
11426 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
11427
11428 if (p->options && p->options->auth)
11429 add_header(&req, p->options->authheader, p->options->auth);
11430 append_date(&req);
11431 if (sipmethod == SIP_REFER) {
11432 if (p->refer) {
11433 char buf[SIPBUFSIZE];
11434 if (!ast_strlen_zero(p->refer->refer_to))
11435 add_header(&req, "Refer-To", p->refer->refer_to);
11436 if (!ast_strlen_zero(p->refer->referred_by)) {
11437 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
11438 add_header(&req, "Referred-By", buf);
11439 }
11440 }
11441 } else if (sipmethod == SIP_SUBSCRIBE) {
11442 char buf[SIPBUFSIZE];
11443
11444 add_header(&req, "Event", "message-summary");
11445 add_header(&req, "Accept", "application/simple-message-summary");
11446 snprintf(buf, sizeof(buf), "%d", mwi_expiry);
11447 add_header(&req, "Expires", buf);
11448 }
11449
11450
11451
11452 if (p->options && !ast_strlen_zero(p->options->replaces)) {
11453 add_header(&req, "Replaces", p->options->replaces);
11454 add_header(&req, "Require", "replaces");
11455 }
11456
11457
11458 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
11459 char i2astr[10];
11460
11461 if (!p->stimer->st_interval)
11462 p->stimer->st_interval = st_get_se(p, TRUE);
11463
11464 p->stimer->st_active = TRUE;
11465
11466 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11467 add_header(&req, "Session-Expires", i2astr);
11468 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11469 add_header(&req, "Min-SE", i2astr);
11470 }
11471
11472 add_header(&req, "Allow", ALLOWED_METHODS);
11473 add_supported_header(p, &req);
11474
11475 if(p->notify_headers) {
11476 char buf[512];
11477 for (var = p->notify_headers; var; var = var->next) {
11478 ast_copy_string(buf, var->value, sizeof(buf));
11479 add_header(&req, var->name, ast_unescape_semicolon(buf));
11480 }
11481 }
11482 if (p->options && p->options->addsipheaders && p->owner) {
11483 struct ast_channel *chan = p->owner;
11484 struct varshead *headp;
11485
11486 ast_channel_lock(chan);
11487
11488 headp = &chan->varshead;
11489
11490 if (!headp)
11491 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11492 else {
11493 const struct ast_var_t *current;
11494 AST_LIST_TRAVERSE(headp, current, entries) {
11495
11496 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11497 char *content, *end;
11498 const char *header = ast_var_value(current);
11499 char *headdup = ast_strdupa(header);
11500
11501
11502 if (*headdup == '"')
11503 headdup++;
11504 if ((content = strchr(headdup, ':'))) {
11505 *content++ = '\0';
11506 content = ast_skip_blanks(content);
11507
11508 end = content + strlen(content) -1;
11509 if (*end == '"')
11510 *end = '\0';
11511
11512 add_header(&req, headdup, content);
11513 if (sipdebug)
11514 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11515 }
11516 }
11517 }
11518 }
11519
11520 ast_channel_unlock(chan);
11521 }
11522 if (sdp) {
11523 memset(p->offered_media, 0, sizeof(p->offered_media));
11524 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11525 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11526 add_sdp(&req, p, FALSE, FALSE, TRUE);
11527 } else if (p->rtp)
11528 add_sdp(&req, p, FALSE, TRUE, FALSE);
11529 }
11530
11531 if (!p->initreq.headers || init > 2)
11532 initialize_initreq(p, &req);
11533 p->lastinvite = p->ocseq;
11534 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11535 }
11536
11537
11538 static int sip_subscribe_mwi_do(const void *data)
11539 {
11540 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11541
11542 if (!mwi) {
11543 return -1;
11544 }
11545
11546 mwi->resub = -1;
11547 __sip_subscribe_mwi_do(mwi);
11548 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11549
11550 return 0;
11551 }
11552
11553
11554 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11555 {
11556
11557 if (!mwi->dnsmgr) {
11558 char transport[MAXHOSTNAMELEN];
11559 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11560 ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11561 }
11562
11563
11564 if (mwi->call) {
11565 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11566 return 0;
11567 }
11568
11569
11570 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11571 return -1;
11572 }
11573
11574 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11575
11576 if (!mwi->us.sin_port && mwi->portno) {
11577 mwi->us.sin_port = htons(mwi->portno);
11578 }
11579
11580
11581 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11582 dialog_unlink_all(mwi->call, TRUE, TRUE);
11583 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11584 return 0;
11585 }
11586
11587 if (!mwi->dnsmgr && mwi->portno) {
11588 mwi->call->sa.sin_port = htons(mwi->portno);
11589 mwi->call->recv.sin_port = htons(mwi->portno);
11590 } else {
11591 mwi->portno = ntohs(mwi->call->sa.sin_port);
11592 }
11593
11594
11595 if (!ast_strlen_zero(mwi->authuser)) {
11596 ast_string_field_set(mwi->call, peername, mwi->authuser);
11597 ast_string_field_set(mwi->call, authname, mwi->authuser);
11598 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11599 } else {
11600 ast_string_field_set(mwi->call, peername, mwi->username);
11601 ast_string_field_set(mwi->call, authname, mwi->username);
11602 ast_string_field_set(mwi->call, fromuser, mwi->username);
11603 }
11604 ast_string_field_set(mwi->call, username, mwi->username);
11605 if (!ast_strlen_zero(mwi->secret)) {
11606 ast_string_field_set(mwi->call, peersecret, mwi->secret);
11607 }
11608 set_socket_transport(&mwi->call->socket, mwi->transport);
11609 mwi->call->socket.port = htons(mwi->portno);
11610 ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11611 build_contact(mwi->call);
11612 build_via(mwi->call);
11613 build_callid_pvt(mwi->call);
11614 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11615
11616
11617 mwi->call->mwi = ASTOBJ_REF(mwi);
11618
11619
11620 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11621
11622 return 0;
11623 }
11624
11625 static int find_calling_channel(struct ast_channel *c, void *data) {
11626 struct sip_pvt *p = data;
11627
11628 return (c->pbx &&
11629 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11630 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11631 }
11632
11633
11634 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11635 {
11636 struct ast_str *tmp = ast_str_alloca(4000);
11637 char from[256], to[256];
11638 char *c, *mfrom, *mto;
11639 struct sip_request req;
11640 char hint[AST_MAX_EXTENSION];
11641 char *statestring = "terminated";
11642 const struct cfsubscription_types *subscriptiontype;
11643 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11644 char *pidfstate = "--";
11645 char *pidfnote= "Ready";
11646
11647 memset(from, 0, sizeof(from));
11648 memset(to, 0, sizeof(to));
11649
11650 switch (state) {
11651 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11652 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11653 local_state = NOTIFY_INUSE;
11654 pidfstate = "busy";
11655 pidfnote = "Ringing";
11656 break;
11657 case AST_EXTENSION_RINGING:
11658 statestring = "early";
11659 local_state = NOTIFY_INUSE;
11660 pidfstate = "busy";
11661 pidfnote = "Ringing";
11662 break;
11663 case AST_EXTENSION_INUSE:
11664 statestring = "confirmed";
11665 local_state = NOTIFY_INUSE;
11666 pidfstate = "busy";
11667 pidfnote = "On the phone";
11668 break;
11669 case AST_EXTENSION_BUSY:
11670 statestring = "confirmed";
11671 local_state = NOTIFY_CLOSED;
11672 pidfstate = "busy";
11673 pidfnote = "On the phone";
11674 break;
11675 case AST_EXTENSION_UNAVAILABLE:
11676 statestring = "terminated";
11677 local_state = NOTIFY_CLOSED;
11678 pidfstate = "away";
11679 pidfnote = "Unavailable";
11680 break;
11681 case AST_EXTENSION_ONHOLD:
11682 statestring = "confirmed";
11683 local_state = NOTIFY_CLOSED;
11684 pidfstate = "busy";
11685 pidfnote = "On hold";
11686 break;
11687 case AST_EXTENSION_NOT_INUSE:
11688 default:
11689
11690 break;
11691 }
11692
11693 subscriptiontype = find_subscription_type(p->subscribed);
11694
11695
11696 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11697 char *hint2 = hint, *individual_hint = NULL;
11698 int hint_count = 0, unavailable_count = 0;
11699
11700 while ((individual_hint = strsep(&hint2, "&"))) {
11701 hint_count++;
11702
11703 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11704 unavailable_count++;
11705 }
11706
11707
11708
11709
11710 if (hint_count > 0 && hint_count == unavailable_count) {
11711 local_state = NOTIFY_CLOSED;
11712 pidfstate = "away";
11713 pidfnote = "Not online";
11714 }
11715 }
11716
11717 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11718 c = get_in_brackets(from);
11719 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11720 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11721 return -1;
11722 }
11723
11724 mfrom = remove_uri_parameters(c);
11725
11726 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11727 c = get_in_brackets(to);
11728 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11729 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11730 return -1;
11731 }
11732 mto = remove_uri_parameters(c);
11733
11734 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11735
11736
11737 add_header(&req, "Event", subscriptiontype->event);
11738 add_header(&req, "Content-Type", subscriptiontype->mediatype);
11739 switch(state) {
11740 case AST_EXTENSION_DEACTIVATED:
11741 if (timeout)
11742 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11743 else {
11744 add_header(&req, "Subscription-State", "terminated;reason=probation");
11745 add_header(&req, "Retry-After", "60");
11746 }
11747 break;
11748 case AST_EXTENSION_REMOVED:
11749 add_header(&req, "Subscription-State", "terminated;reason=noresource");
11750 break;
11751 default:
11752 if (p->expiry)
11753 add_header(&req, "Subscription-State", "active");
11754 else
11755 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11756 }
11757 switch (p->subscribed) {
11758 case XPIDF_XML:
11759 case CPIM_PIDF_XML:
11760 ast_str_append(&tmp, 0,
11761 "<?xml version=\"1.0\"?>\n"
11762 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11763 "<presence>\n");
11764 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11765 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11766 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11767 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11768 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11769 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11770 break;
11771 case PIDF_XML:
11772 ast_str_append(&tmp, 0,
11773 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11774 "<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);
11775 ast_str_append(&tmp, 0, "<pp:person><status>\n");
11776 if (pidfstate[0] != '-')
11777 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11778 ast_str_append(&tmp, 0, "</status></pp:person>\n");
11779 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote);
11780 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten);
11781 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11782 if (pidfstate[0] == 'b')
11783 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11784 else
11785 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11786 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11787 break;
11788 case DIALOG_INFO_XML:
11789 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11790 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);
11791 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11792 const char *local_display = p->exten;
11793 char *local_target = mto;
11794
11795
11796
11797
11798 if (sip_cfg.notifycid) {
11799 struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11800
11801 if (caller) {
11802 int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11803 local_target = alloca(need);
11804 snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11805 if (!(ast_strlen_zero(caller->cid.cid_name))) {
11806 local_display = ast_strdupa(caller->cid.cid_name);
11807 }
11808 ast_channel_unlock(caller);
11809 caller = NULL;
11810 }
11811
11812
11813 if (sip_cfg.pedanticsipchecking) {
11814 ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
11815 p->exten, p->callid, p->theirtag, p->tag);
11816 } else {
11817 ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
11818 p->exten, p->callid);
11819 }
11820 ast_str_append(&tmp, 0,
11821 "<remote>\n"
11822
11823
11824 "<identity display=\"%s\">%s</identity>\n"
11825 "<target uri=\"%s\"/>\n"
11826 "</remote>\n"
11827 "<local>\n"
11828 "<identity>%s</identity>\n"
11829 "<target uri=\"%s\"/>\n"
11830 "</local>\n",
11831 local_display, local_target, local_target, mto, mto);
11832 } else {
11833 ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
11834 }
11835 } else {
11836 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11837 }
11838 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11839 if (state == AST_EXTENSION_ONHOLD) {
11840 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11841 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11842 "</target>\n</local>\n", mto);
11843 }
11844 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11845 break;
11846 case NONE:
11847 default:
11848 break;
11849 }
11850
11851 add_content(&req, tmp->str);
11852
11853 p->pendinginvite = p->ocseq;
11854
11855 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11856 }
11857
11858
11859
11860
11861
11862
11863
11864 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11865 {
11866 struct sip_request req;
11867 struct ast_str *out = ast_str_alloca(500);
11868 int ourport = ntohs(p->ourip.sin_port);
11869 const char *exten = S_OR(vmexten, default_vmexten);
11870
11871 initreqprep(&req, p, SIP_NOTIFY);
11872 add_header(&req, "Event", "message-summary");
11873 add_header(&req, "Content-Type", default_notifymime);
11874 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11875
11876 if (!ast_strlen_zero(p->fromdomain)) {
11877 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11878 } else if (!sip_standard_port(p->socket.type, ourport)) {
11879 if (p->socket.type == SIP_TRANSPORT_UDP) {
11880 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11881 } else {
11882 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));
11883 }
11884 } else {
11885 if (p->socket.type == SIP_TRANSPORT_UDP) {
11886 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11887 } else {
11888 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));
11889 }
11890 }
11891
11892
11893
11894 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11895 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11896
11897 if (p->subscribed) {
11898 if (p->expiry)
11899 add_header(&req, "Subscription-State", "active");
11900 else
11901 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11902 }
11903
11904 add_content(&req, out->str);
11905
11906 if (!p->initreq.headers)
11907 initialize_initreq(p, &req);
11908 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11909 }
11910
11911
11912 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11913 {
11914 struct sip_request req;
11915 char tmp[SIPBUFSIZE/2];
11916
11917 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11918 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11919 add_header(&req, "Event", tmp);
11920 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11921 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11922 add_header(&req, "Allow", ALLOWED_METHODS);
11923 add_supported_header(p, &req);
11924
11925 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11926 add_content(&req, tmp);
11927
11928 if (!p->initreq.headers)
11929 initialize_initreq(p, &req);
11930
11931 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11932 }
11933
11934
11935 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11936 struct sip_request req;
11937 struct ast_variable *var, *newvar;
11938
11939 initreqprep(&req, p, SIP_NOTIFY);
11940
11941
11942 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11943 add_header(&req, newvar->name, newvar->value);
11944 for (var = vars; var; var = var->next) {
11945 char buf[512];
11946
11947 if (!strcasecmp(var->name, "Content-Length")) {
11948 ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11949 continue;
11950 }
11951
11952 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
11953 ast_copy_string(buf, var->value, sizeof(buf));
11954 add_header(&req, var->name, ast_unescape_semicolon(buf));
11955 newvar->next = ast_variable_new(var->name, var->value, "");
11956 newvar = newvar->next;
11957 }
11958
11959 if (!p->initreq.headers) {
11960 initialize_initreq(p, &req);
11961 }
11962
11963 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11964 }
11965
11966 static int manager_sipnotify(struct mansession *s, const struct message *m)
11967 {
11968 const char *channame = astman_get_header(m, "Channel");
11969 struct ast_variable *vars = astman_get_variables(m);
11970 struct sip_pvt *p;
11971
11972 if (ast_strlen_zero(channame)) {
11973 astman_send_error(s, m, "SIPNotify requires a channel name");
11974 return 0;
11975 }
11976
11977 if (!strncasecmp(channame, "sip/", 4)) {
11978 channame += 4;
11979 }
11980
11981 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11982 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11983 return 0;
11984 }
11985
11986 if (create_addr(p, channame, NULL, 0)) {
11987
11988 dialog_unlink_all(p, TRUE, TRUE);
11989 dialog_unref(p, "unref dialog inside for loop" );
11990
11991 astman_send_error(s, m, "Could not create address");
11992 return 0;
11993 }
11994
11995
11996 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11997
11998
11999 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
12000 build_via(p);
12001 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
12002 build_callid_pvt(p);
12003 ao2_t_link(dialogs, p, "Linking in new name");
12004 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
12005 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
12006
12007 if (!transmit_notify_custom(p, vars)) {
12008 astman_send_ack(s, m, "Notify Sent");
12009 } else {
12010 astman_send_error(s, m, "Unable to send notify");
12011 }
12012 ast_variables_destroy(vars);
12013 return 0;
12014 }
12015
12016 static char mandescr_sipnotify[] =
12017 "Description: Sends a SIP Notify event\n"
12018 "All parameters for this event must be specified in the body of this request\n"
12019 "via multiple Variable: name=value sequences.\n"
12020 "Variables: \n"
12021 " *Channel: <peername> Peer to receive the notify. Required.\n"
12022 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
12023 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
12024
12025 static const struct _map_x_s regstatestrings[] = {
12026 { REG_STATE_FAILED, "Failed" },
12027 { REG_STATE_UNREGISTERED, "Unregistered"},
12028 { REG_STATE_REGSENT, "Request Sent"},
12029 { REG_STATE_AUTHSENT, "Auth. Sent"},
12030 { REG_STATE_REGISTERED, "Registered"},
12031 { REG_STATE_REJECTED, "Rejected"},
12032 { REG_STATE_TIMEOUT, "Timeout"},
12033 { REG_STATE_NOAUTH, "No Authentication"},
12034 { -1, NULL }
12035 };
12036
12037
12038 static const char *regstate2str(enum sipregistrystate regstate)
12039 {
12040 return map_x_s(regstatestrings, regstate, "Unknown");
12041 }
12042
12043
12044
12045
12046
12047
12048
12049 static int sip_reregister(const void *data)
12050 {
12051
12052 struct sip_registry *r= (struct sip_registry *) data;
12053
12054
12055 if (!r)
12056 return 0;
12057
12058 if (r->call && r->call->do_history)
12059 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
12060
12061
12062 if (sipdebug)
12063 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
12064
12065 r->expire = -1;
12066 r->expiry = r->configured_expiry;
12067 __sip_do_register(r);
12068 registry_unref(r, "unref the re-register scheduled event");
12069 return 0;
12070 }
12071
12072
12073 static int __sip_do_register(struct sip_registry *r)
12074 {
12075 int res;
12076
12077 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
12078 return res;
12079 }
12080
12081
12082
12083
12084
12085
12086
12087 static int sip_reg_timeout(const void *data)
12088 {
12089
12090
12091 struct sip_registry *r = (struct sip_registry *)data;
12092 struct sip_pvt *p;
12093 int res;
12094
12095
12096 if (!r)
12097 return 0;
12098
12099 if (r->dnsmgr) {
12100
12101 ast_dnsmgr_refresh(r->dnsmgr);
12102 }
12103
12104 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
12105
12106
12107
12108
12109 if (r->call) {
12110
12111
12112 p = r->call;
12113 sip_pvt_lock(p);
12114 pvt_set_needdestroy(p, "registration timeout");
12115
12116 __sip_pretend_ack(p);
12117 sip_pvt_unlock(p);
12118
12119
12120
12121 if (p->registry)
12122 p->registry = registry_unref(p->registry, "p->registry unreffed");
12123 r->call = dialog_unref(r->call, "unrefing r->call");
12124 }
12125
12126 r->timeout = -1;
12127 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
12128
12129
12130
12131 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
12132 r->regstate = REG_STATE_FAILED;
12133 } else {
12134 r->regstate = REG_STATE_UNREGISTERED;
12135 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
12136 }
12137 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));
12138 registry_unref(r, "unreffing registry_unref r");
12139 return 0;
12140 }
12141
12142
12143
12144
12145 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
12146 {
12147 struct sip_request req;
12148 char from[256];
12149 char to[256];
12150 char tmp[80];
12151 char addr[80];
12152 struct sip_pvt *p;
12153 struct sip_peer *peer = NULL;
12154 int res;
12155 char *fromdomain;
12156 char *domainport = NULL;
12157
12158
12159 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
12160 if (r) {
12161 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
12162 }
12163 return 0;
12164 }
12165
12166 if (r->dnsmgr == NULL) {
12167 char transport[MAXHOSTNAMELEN];
12168 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
12169 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
12170 ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
12171 if (peer) {
12172 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
12173 }
12174 }
12175
12176 if (r->call) {
12177 if (!auth) {
12178 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
12179 return 0;
12180 } else {
12181 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
12182 make_our_tag(p->tag, sizeof(p->tag));
12183 ast_string_field_set(p, theirtag, NULL);
12184 }
12185 } else {
12186
12187 if (!r->callid_valid) {
12188 build_callid_registry(r, internip.sin_addr, default_fromdomain);
12189 r->callid_valid = TRUE;
12190 }
12191
12192 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
12193 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
12194 return 0;
12195 }
12196
12197 if (p->do_history)
12198 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
12199
12200
12201 if (!r->us.sin_port && r->portno)
12202 r->us.sin_port = htons(r->portno);
12203
12204
12205 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
12206
12207
12208 dialog_unlink_all(p, TRUE, TRUE);
12209 p = dialog_unref(p, "unref dialog after unlink_all");
12210 if (r->timeout > -1) {
12211 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12212 registry_unref(_data, "del for REPLACE of registry ptr"),
12213 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
12214 registry_addref(r,"add for REPLACE registry ptr"));
12215 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
12216 } else {
12217 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
12218 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);
12219 }
12220 r->regattempts++;
12221 return 0;
12222 }
12223
12224
12225 ast_string_field_set(r, callid, p->callid);
12226 if (!r->dnsmgr && r->portno) {
12227 p->sa.sin_port = htons(r->portno);
12228 p->recv.sin_port = htons(r->portno);
12229 } else {
12230 r->portno = ntohs(p->sa.sin_port);
12231 }
12232 ast_set_flag(&p->flags[0], SIP_OUTGOING);
12233 r->call = dialog_ref(p, "copying dialog into registry r->call");
12234 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
12235 if (!ast_strlen_zero(r->secret)) {
12236 ast_string_field_set(p, peersecret, r->secret);
12237 }
12238 if (!ast_strlen_zero(r->md5secret))
12239 ast_string_field_set(p, peermd5secret, r->md5secret);
12240
12241
12242 if (!ast_strlen_zero(r->authuser)) {
12243 ast_string_field_set(p, peername, r->authuser);
12244 ast_string_field_set(p, authname, r->authuser);
12245 } else if (!ast_strlen_zero(r->username)) {
12246 ast_string_field_set(p, peername, r->username);
12247 ast_string_field_set(p, authname, r->username);
12248 ast_string_field_set(p, fromuser, r->username);
12249 }
12250 if (!ast_strlen_zero(r->username))
12251 ast_string_field_set(p, username, r->username);
12252
12253 if (!ast_strlen_zero(r->callback))
12254 ast_string_field_set(p, exten, r->callback);
12255
12256
12257 set_socket_transport(&p->socket, r->transport);
12258 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
12259 p->socket.port = sip_tcp_desc.local_address.sin_port;
12260 }
12261
12262
12263
12264
12265
12266
12267 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
12268 build_contact(p);
12269 }
12270
12271
12272 if (auth == NULL) {
12273 if (r->timeout > -1)
12274 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
12275 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12276 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
12277 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
12278 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
12279 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
12280 }
12281
12282 if ((fromdomain = strchr(r->username, '@'))) {
12283
12284 fromdomain++ ;
12285
12286 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
12287 if (!ast_strlen_zero(p->theirtag))
12288 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
12289 else
12290 snprintf(to, sizeof(to), "<sip:%s>", r->username);
12291
12292
12293
12294 if (ast_strlen_zero(p->fromdomain)) {
12295 ast_string_field_set(p, fromdomain, fromdomain);
12296 }
12297 } else {
12298 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
12299 if (!ast_strlen_zero(p->theirtag))
12300 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
12301 else
12302 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
12303 }
12304
12305
12306
12307 if (!ast_strlen_zero(p->fromdomain)) {
12308 domainport = strrchr(p->fromdomain, ':');
12309 if (domainport) {
12310 *domainport++ = '\0';
12311 if (ast_strlen_zero(domainport))
12312 domainport = NULL;
12313 }
12314 if (domainport) {
12315 if (atoi(domainport) != STANDARD_SIP_PORT)
12316 snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
12317 else
12318 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
12319 } else {
12320 if (r->portno && r->portno != STANDARD_SIP_PORT)
12321 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
12322 else
12323 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
12324 }
12325 } else {
12326 if (r->portno && r->portno != STANDARD_SIP_PORT)
12327 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
12328 else
12329 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
12330 }
12331 ast_string_field_set(p, uri, addr);
12332
12333 p->branch ^= ast_random();
12334
12335 init_req(&req, sipmethod, addr);
12336
12337
12338 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
12339 p->ocseq = r->ocseq;
12340
12341 build_via(p);
12342 add_header(&req, "Via", p->via);
12343 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
12344 add_header(&req, "From", from);
12345 add_header(&req, "To", to);
12346 add_header(&req, "Call-ID", p->callid);
12347 add_header(&req, "CSeq", tmp);
12348 if (!ast_strlen_zero(global_useragent))
12349 add_header(&req, "User-Agent", global_useragent);
12350
12351
12352 if (auth)
12353 add_header(&req, authheader, auth);
12354 else if (!ast_strlen_zero(r->nonce)) {
12355 char digest[1024];
12356
12357
12358
12359
12360
12361
12362 if (sipdebug)
12363 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
12364 ast_string_field_set(p, realm, r->realm);
12365 ast_string_field_set(p, nonce, r->nonce);
12366 ast_string_field_set(p, domain, r->domain);
12367 ast_string_field_set(p, opaque, r->opaque);
12368 ast_string_field_set(p, qop, r->qop);
12369 p->noncecount = ++r->noncecount;
12370
12371 memset(digest, 0, sizeof(digest));
12372 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
12373 add_header(&req, "Authorization", digest);
12374 else
12375 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
12376
12377 }
12378
12379 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
12380 add_header(&req, "Expires", tmp);
12381 add_header(&req, "Contact", p->our_contact);
12382
12383 initialize_initreq(p, &req);
12384 if (sip_debug_test_pvt(p)) {
12385 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
12386 }
12387 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
12388 r->regattempts++;
12389 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
12390 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12391 dialog_unref(p, "p is finished here at the end of transmit_register");
12392 return res;
12393 }
12394
12395
12396 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
12397 {
12398 struct sip_request req;
12399
12400 reqprep(&req, p, SIP_MESSAGE, 0, 1);
12401 add_text(&req, text);
12402 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12403 }
12404
12405
12406 static int sip_refer_allocate(struct sip_pvt *p)
12407 {
12408 p->refer = ast_calloc(1, sizeof(struct sip_refer));
12409 return p->refer ? 1 : 0;
12410 }
12411
12412
12413
12414
12415
12416
12417 static int transmit_refer(struct sip_pvt *p, const char *dest)
12418 {
12419 struct sip_request req = {
12420 .headers = 0,
12421 };
12422 char from[256];
12423 const char *of;
12424 char *c;
12425 char referto[256];
12426 char *ttag, *ftag;
12427 char *theirtag = ast_strdupa(p->theirtag);
12428 int use_tls=FALSE;
12429
12430 if (sipdebug)
12431 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
12432
12433
12434 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12435 of = get_header(&p->initreq, "To");
12436 ttag = theirtag;
12437 ftag = p->tag;
12438 } else {
12439 of = get_header(&p->initreq, "From");
12440 ftag = theirtag;
12441 ttag = p->tag;
12442 }
12443
12444 ast_copy_string(from, of, sizeof(from));
12445 of = get_in_brackets(from);
12446 ast_string_field_set(p, from, of);
12447 if (!strncasecmp(of, "sip:", 4)) {
12448 of += 4;
12449 }else if (!strncasecmp(of, "sips:", 5)) {
12450 of += 5;
12451 use_tls = TRUE;
12452 } else {
12453 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
12454 }
12455
12456 if ((c = strchr(dest, '@')))
12457 c = NULL;
12458 else if ((c = strchr(of, '@')))
12459 *c++ = '\0';
12460 if (c)
12461 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12462 else
12463 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12464
12465
12466 sip_refer_allocate(p);
12467 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12468 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12469 p->refer->status = REFER_SENT;
12470
12471 reqprep(&req, p, SIP_REFER, 0, 1);
12472
12473 add_header(&req, "Refer-To", referto);
12474 add_header(&req, "Allow", ALLOWED_METHODS);
12475 add_supported_header(p, &req);
12476 if (!ast_strlen_zero(p->our_contact))
12477 add_header(&req, "Referred-By", p->our_contact);
12478
12479 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489 }
12490
12491
12492
12493 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12494 {
12495 struct sip_request req;
12496
12497 reqprep(&req, p, SIP_INFO, 0, 1);
12498 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12499 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12500 }
12501
12502
12503 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12504 {
12505 struct sip_request req;
12506
12507 reqprep(&req, p, SIP_INFO, 0, 1);
12508 add_vidupdate(&req);
12509 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12510 }
12511
12512
12513
12514
12515 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12516 {
12517 struct sip_request resp;
12518
12519 if (sipmethod == SIP_ACK)
12520 p->invitestate = INV_CONFIRMED;
12521
12522 reqprep(&resp, p, sipmethod, seqno, newbranch);
12523 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
12524 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12525
12526 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12527 }
12528
12529
12530 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12531 {
12532 if (code == WWW_AUTH) {
12533 *header = "WWW-Authenticate";
12534 *respheader = "Authorization";
12535 } else if (code == PROXY_AUTH) {
12536 *header = "Proxy-Authenticate";
12537 *respheader = "Proxy-Authorization";
12538 } else {
12539 ast_verbose("-- wrong response code %d\n", code);
12540 *header = *respheader = "Invalid";
12541 }
12542 }
12543
12544
12545 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12546 {
12547 struct sip_request resp;
12548
12549 reqprep(&resp, p, sipmethod, seqno, newbranch);
12550 if (!ast_strlen_zero(p->realm)) {
12551 char digest[1024];
12552
12553 memset(digest, 0, sizeof(digest));
12554 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12555 char *dummy, *response;
12556 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
12557 auth_headers(code, &dummy, &response);
12558 add_header(&resp, response, digest);
12559 } else
12560 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12561 }
12562
12563
12564 if (sipmethod == SIP_BYE) {
12565 char buf[10];
12566
12567 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12568 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12569 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12570 }
12571
12572 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12573 }
12574
12575
12576 static void destroy_association(struct sip_peer *peer)
12577 {
12578 int realtimeregs = ast_check_realtime("sipregs");
12579 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12580
12581 if (!sip_cfg.ignore_regexpire) {
12582 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12583 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12584 } else {
12585 ast_db_del("SIP/Registry", peer->name);
12586 }
12587 }
12588 }
12589
12590 static void set_socket_transport(struct sip_socket *socket, int transport)
12591 {
12592
12593 if (socket->type != transport) {
12594 socket->fd = -1;
12595 socket->type = transport;
12596 if (socket->tcptls_session) {
12597 ao2_ref(socket->tcptls_session, -1);
12598 socket->tcptls_session = NULL;
12599 }
12600 }
12601 }
12602
12603
12604 static int expire_register(const void *data)
12605 {
12606 struct sip_peer *peer = (struct sip_peer *)data;
12607
12608 if (!peer)
12609 return 0;
12610
12611 peer->expire = -1;
12612 peer->portinuri = 0;
12613
12614 destroy_association(peer);
12615 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12616
12617 if (peer->socket.tcptls_session) {
12618 ao2_ref(peer->socket.tcptls_session, -1);
12619 peer->socket.tcptls_session = NULL;
12620 }
12621
12622 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12623 register_peer_exten(peer, FALSE);
12624 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12625
12626
12627
12628
12629 if (peer->is_realtime)
12630 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12631
12632 if (peer->selfdestruct ||
12633 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12634 unlink_peer_from_tables(peer);
12635 } else if (peer->addr.sin_addr.s_addr) {
12636
12637
12638
12639 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12640 }
12641
12642
12643
12644 memset(&peer->addr, 0, sizeof(peer->addr));
12645
12646 unref_peer(peer, "removing peer ref for expire_register");
12647
12648 return 0;
12649 }
12650
12651
12652 static int sip_poke_peer_s(const void *data)
12653 {
12654 struct sip_peer *peer = (struct sip_peer *)data;
12655 struct sip_peer *foundpeer;
12656
12657 peer->pokeexpire = -1;
12658
12659 foundpeer = ao2_find(peers, peer, OBJ_POINTER);
12660 if (!foundpeer) {
12661 unref_peer(peer, "removing poke peer ref");
12662 return 0;
12663 } else if (foundpeer->name != peer->name) {
12664 unref_peer(foundpeer, "removing above peer ref");
12665 unref_peer(peer, "removing poke peer ref");
12666 return 0;
12667 }
12668
12669 unref_peer(foundpeer, "removing above peer ref");
12670 sip_poke_peer(peer, 0);
12671 unref_peer(peer, "removing poke peer ref");
12672
12673 return 0;
12674 }
12675
12676
12677 static void reg_source_db(struct sip_peer *peer)
12678 {
12679 char data[256];
12680 struct in_addr in;
12681 int expire;
12682 int port;
12683 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12684
12685 if (peer->rt_fromcontact)
12686 return;
12687 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12688 return;
12689
12690 scan = data;
12691 addr = strsep(&scan, ":");
12692 port_str = strsep(&scan, ":");
12693 expiry_str = strsep(&scan, ":");
12694 username = strsep(&scan, ":");
12695 contact = scan;
12696
12697 if (!inet_aton(addr, &in))
12698 return;
12699
12700 if (port_str)
12701 port = atoi(port_str);
12702 else
12703 return;
12704
12705 if (expiry_str)
12706 expire = atoi(expiry_str);
12707 else
12708 return;
12709
12710 if (username)
12711 ast_string_field_set(peer, username, username);
12712 if (contact)
12713 ast_string_field_set(peer, fullcontact, contact);
12714
12715 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12716 peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12717
12718 memset(&peer->addr, 0, sizeof(peer->addr));
12719 peer->addr.sin_family = AF_INET;
12720 peer->addr.sin_addr = in;
12721 peer->addr.sin_port = htons(port);
12722 if (sipsock < 0) {
12723
12724 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12725 unref_peer(_data, "removing poke peer ref"),
12726 unref_peer(peer, "removing poke peer ref"),
12727 ref_peer(peer, "adding poke peer ref"));
12728 } else {
12729 sip_poke_peer(peer, 0);
12730 }
12731 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12732 unref_peer(_data, "remove registration ref"),
12733 unref_peer(peer, "remove registration ref"),
12734 ref_peer(peer, "add registration ref"));
12735 register_peer_exten(peer, TRUE);
12736 }
12737
12738
12739 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12740 {
12741 char contact[SIPBUFSIZE];
12742 char *c;
12743
12744
12745 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12746 c = get_in_brackets(contact);
12747
12748
12749 ast_string_field_set(pvt, fullcontact, c);
12750
12751
12752 ast_string_field_set(pvt, okcontacturi, c);
12753
12754
12755
12756 return TRUE;
12757 }
12758
12759 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12760 {
12761 struct hostent *hp;
12762 struct ast_hostent ahp;
12763 int port = STANDARD_SIP_PORT;
12764 char *host, *pt, *transport;
12765 char contact_buf[256];
12766 char *contact;
12767
12768
12769 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12770 contact = contact_buf;
12771
12772
12773
12774
12775
12776
12777
12778
12779 if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12780 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12781 }
12782
12783
12784 if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12785 port = port_str2int(pt, STANDARD_TLS_PORT);
12786 } else {
12787 port = port_str2int(pt, STANDARD_SIP_PORT);
12788 }
12789
12790
12791
12792
12793
12794
12795
12796
12797 hp = ast_gethostbyname(host, &ahp);
12798 if (!hp) {
12799 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12800 return -1;
12801 }
12802 sin->sin_family = AF_INET;
12803 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12804 sin->sin_port = htons(port);
12805
12806 return 0;
12807 }
12808
12809
12810 static int set_address_from_contact(struct sip_pvt *pvt)
12811 {
12812 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12813
12814
12815
12816 pvt->sa = pvt->recv;
12817 return 0;
12818 }
12819
12820 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12821 }
12822
12823
12824 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12825 {
12826 char contact[SIPBUFSIZE];
12827 char data[SIPBUFSIZE];
12828 const char *expires = get_header(req, "Expires");
12829 int expire = atoi(expires);
12830 char *curi, *host, *pt, *transport;
12831 int port;
12832 int transport_type;
12833 const char *useragent;
12834 struct hostent *hp;
12835 struct ast_hostent ahp;
12836 struct sockaddr_in oldsin, testsin;
12837 char *firstcuri = NULL;
12838 int start = 0;
12839 int wildcard_found = 0;
12840 int single_binding_found = 0;
12841
12842 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12843
12844 if (ast_strlen_zero(expires)) {
12845 char *s = strcasestr(contact, ";expires=");
12846 if (s) {
12847 expires = strsep(&s, ";");
12848 if (sscanf(expires + 9, "%30d", &expire) != 1)
12849 expire = default_expiry;
12850 } else {
12851
12852 expire = default_expiry;
12853 }
12854 }
12855
12856 copy_socket_data(&pvt->socket, &req->socket);
12857
12858 do {
12859
12860 curi = contact;
12861 if (strchr(contact, '<') == NULL)
12862 strsep(&curi, ";");
12863 curi = get_in_brackets(contact);
12864 if (!firstcuri) {
12865 firstcuri = ast_strdupa(curi);
12866 }
12867
12868 if (!strcasecmp(curi, "*")) {
12869 wildcard_found = 1;
12870 } else {
12871 single_binding_found = 1;
12872 }
12873
12874 if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
12875
12876
12877 return PARSE_REGISTER_FAILED;
12878 }
12879
12880 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12881 } while (!ast_strlen_zero(contact));
12882 curi = firstcuri;
12883
12884
12885
12886
12887
12888 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12889
12890 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12891 pvt->expiry = ast_sched_when(sched, peer->expire);
12892 return PARSE_REGISTER_QUERY;
12893 } else if (!strcasecmp(curi, "*") || !expire) {
12894
12895 AST_SCHED_DEL_UNREF(sched, peer->expire,
12896 unref_peer(peer, "remove register expire ref"));
12897 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12898 expire_register(ref_peer(peer,"add ref for explicit expire_register"));
12899 return PARSE_REGISTER_UPDATE;
12900 }
12901
12902
12903 ast_string_field_set(peer, fullcontact, curi);
12904
12905
12906 ast_string_field_build(pvt, our_contact, "<%s>", curi);
12907
12908
12909 if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12910 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12911 }
12912
12913
12914
12915 peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12916
12917
12918 if ((transport_type = get_transport_str2enum(transport))) {
12919
12920
12921
12922
12923 port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12924 } else {
12925 port = port_str2int(pt, STANDARD_SIP_PORT);
12926 transport_type = pvt->socket.type;
12927 }
12928
12929
12930
12931
12932 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12933 set_socket_transport(&peer->socket, transport_type);
12934 }
12935
12936 oldsin = peer->addr;
12937
12938
12939 if (peer->addr.sin_addr.s_addr && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
12940 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12941 }
12942
12943 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12944
12945 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12946
12947
12948 hp = ast_gethostbyname(host, &ahp);
12949 if (!hp) {
12950 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12951 ast_string_field_set(peer, fullcontact, "");
12952 ast_string_field_set(pvt, our_contact, "");
12953 return PARSE_REGISTER_FAILED;
12954 }
12955 peer->addr.sin_family = AF_INET;
12956 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12957 peer->addr.sin_port = htons(port);
12958 } else {
12959
12960
12961 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12962 peer->addr = pvt->recv;
12963 }
12964
12965
12966 memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12967 if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12968 ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12969 ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12970 ast_string_field_set(peer, fullcontact, "");
12971 ast_string_field_set(pvt, our_contact, "");
12972 return PARSE_REGISTER_DENIED;
12973 }
12974
12975
12976
12977
12978 if ((peer->socket.type == pvt->socket.type) &&
12979 (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12980 (peer->addr.sin_port == pvt->recv.sin_port)){
12981
12982 copy_socket_data(&peer->socket, &pvt->socket);
12983 }
12984
12985
12986 if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12987 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12988 }
12989
12990
12991 peer->sipoptions = pvt->sipoptions;
12992
12993 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12994 ast_string_field_set(peer, username, curi);
12995
12996 AST_SCHED_DEL_UNREF(sched, peer->expire,
12997 unref_peer(peer, "remove register expire ref"));
12998
12999 if (expire > max_expiry)
13000 expire = max_expiry;
13001 if (expire < min_expiry)
13002 expire = min_expiry;
13003 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13004 peer->expire = -1;
13005 } else {
13006 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
13007 ref_peer(peer, "add registration ref"));
13008 if (peer->expire == -1) {
13009 unref_peer(peer, "remote registration ref");
13010 }
13011 }
13012 pvt->expiry = expire;
13013 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);
13014
13015
13016
13017
13018 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
13019 ast_db_put("SIP/Registry", peer->name, data);
13020 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));
13021
13022
13023 if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
13024 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));
13025 }
13026 sip_poke_peer(peer, 0);
13027 register_peer_exten(peer, 1);
13028
13029
13030 useragent = get_header(req, "User-Agent");
13031 if (strcasecmp(useragent, peer->useragent)) {
13032 ast_string_field_set(peer, useragent, useragent);
13033 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
13034 }
13035 return PARSE_REGISTER_UPDATE;
13036 }
13037
13038
13039 static void free_old_route(struct sip_route *route)
13040 {
13041 struct sip_route *next;
13042
13043 while (route) {
13044 next = route->next;
13045 ast_free(route);
13046 route = next;
13047 }
13048 }
13049
13050
13051 static void list_route(struct sip_route *route)
13052 {
13053 if (!route)
13054 ast_verbose("list_route: no route\n");
13055 else {
13056 for (;route; route = route->next)
13057 ast_verbose("list_route: hop: <%s>\n", route->hop);
13058 }
13059 }
13060
13061
13062 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
13063 {
13064 struct sip_route *thishop, *head, *tail;
13065 int start = 0;
13066 int len;
13067 const char *rr, *contact, *c;
13068
13069
13070 if (p->route && p->route_persistant) {
13071 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
13072 return;
13073 }
13074
13075 if (p->route) {
13076 free_old_route(p->route);
13077 p->route = NULL;
13078 }
13079
13080
13081 p->route_persistant = 1;
13082
13083
13084
13085
13086
13087
13088 head = NULL;
13089 tail = head;
13090
13091 for (;;) {
13092
13093 rr = __get_header(req, "Record-Route", &start);
13094 if (*rr == '\0')
13095 break;
13096 for (; (rr = strchr(rr, '<')) ; rr += len) {
13097 ++rr;
13098 len = strcspn(rr, ">") + 1;
13099
13100 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13101
13102 ast_copy_string(thishop->hop, rr, len);
13103 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
13104
13105 if (backwards) {
13106
13107 thishop->next = head;
13108 head = thishop;
13109
13110 if (!tail)
13111 tail = thishop;
13112 } else {
13113 thishop->next = NULL;
13114
13115 if (tail)
13116 tail->next = thishop;
13117 else
13118 head = thishop;
13119 tail = thishop;
13120 }
13121 }
13122 }
13123 }
13124
13125
13126 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
13127
13128
13129 contact = get_header(req, "Contact");
13130 if (!ast_strlen_zero(contact)) {
13131 ast_debug(2, "build_route: Contact hop: %s\n", contact);
13132
13133 c = strchr(contact, '<');
13134 if (c) {
13135
13136 ++c;
13137 len = strcspn(c, ">") + 1;
13138 } else {
13139
13140 c = contact;
13141 len = strlen(contact) + 1;
13142 }
13143 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13144
13145 ast_copy_string(thishop->hop, c, len);
13146 thishop->next = NULL;
13147
13148 if (tail)
13149 tail->next = thishop;
13150 else
13151 head = thishop;
13152 }
13153 }
13154 }
13155
13156
13157 p->route = head;
13158
13159
13160 if (sip_debug_test_pvt(p))
13161 list_route(p->route);
13162 }
13163
13164
13165
13166
13167
13168
13169
13170 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
13171 {
13172 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
13173 ast_string_field_build(p, randdata, "%08lx", ast_random());
13174 p->stalenonce = 0;
13175 }
13176 }
13177
13178 AST_THREADSTORAGE(check_auth_buf);
13179 #define CHECK_AUTH_BUF_INITLEN 256
13180
13181
13182
13183
13184
13185
13186 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
13187 const char *secret, const char *md5secret, int sipmethod,
13188 char *uri, enum xmittype reliable, int ignore)
13189 {
13190 const char *response;
13191 char *reqheader, *respheader;
13192 const char *authtoken;
13193 char a1_hash[256];
13194 char resp_hash[256]="";
13195 char *c;
13196 int wrongnonce = FALSE;
13197 int good_response;
13198 const char *usednonce = p->randdata;
13199 struct ast_str *buf;
13200 int res;
13201
13202
13203 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
13204 struct x {
13205 const char *key;
13206 const char *s;
13207 } *i, keys[] = {
13208 [K_RESP] = { "response=", "" },
13209 [K_URI] = { "uri=", "" },
13210 [K_USER] = { "username=", "" },
13211 [K_NONCE] = { "nonce=", "" },
13212 [K_LAST] = { NULL, NULL}
13213 };
13214
13215
13216 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
13217 return AUTH_SUCCESSFUL;
13218
13219
13220
13221 response = "401 Unauthorized";
13222
13223
13224
13225
13226
13227 auth_headers(WWW_AUTH, &respheader, &reqheader);
13228
13229 authtoken = get_header(req, reqheader);
13230 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13231
13232
13233 if (!reliable) {
13234
13235
13236 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13237
13238 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13239 }
13240 return AUTH_CHALLENGE_SENT;
13241 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13242
13243 set_nonce_randdata(p, 1);
13244 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13245
13246 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13247 return AUTH_CHALLENGE_SENT;
13248 }
13249
13250
13251
13252
13253
13254
13255 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
13256 return AUTH_SECRET_FAILED;
13257
13258
13259 res = ast_str_set(&buf, 0, "%s", authtoken);
13260
13261 if (res == AST_DYNSTR_BUILD_FAILED)
13262 return AUTH_SECRET_FAILED;
13263
13264 c = buf->str;
13265
13266 while(c && *(c = ast_skip_blanks(c)) ) {
13267 for (i = keys; i->key != NULL; i++) {
13268 const char *separator = ",";
13269
13270 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
13271 continue;
13272
13273 c += strlen(i->key);
13274 if (*c == '"') {
13275 c++;
13276 separator = "\"";
13277 }
13278 i->s = c;
13279 strsep(&c, separator);
13280 break;
13281 }
13282 if (i->key == NULL)
13283 strsep(&c, " ,");
13284 }
13285
13286
13287 if (strcmp(username, keys[K_USER].s)) {
13288 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
13289 username, keys[K_USER].s);
13290
13291 return AUTH_USERNAME_MISMATCH;
13292 }
13293
13294
13295
13296 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
13297 wrongnonce = TRUE;
13298 usednonce = keys[K_NONCE].s;
13299 } else {
13300 p->stalenonce = 1;
13301 }
13302
13303 if (!ast_strlen_zero(md5secret))
13304 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
13305 else {
13306 char a1[256];
13307 snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
13308 ast_md5_hash(a1_hash, a1);
13309 }
13310
13311
13312 {
13313 char a2[256];
13314 char a2_hash[256];
13315 char resp[256];
13316
13317 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
13318 S_OR(keys[K_URI].s, uri));
13319 ast_md5_hash(a2_hash, a2);
13320 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
13321 ast_md5_hash(resp_hash, resp);
13322 }
13323
13324 good_response = keys[K_RESP].s &&
13325 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
13326 if (wrongnonce) {
13327 if (good_response) {
13328 if (sipdebug)
13329 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
13330
13331 set_nonce_randdata(p, 0);
13332 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
13333 } else {
13334
13335 if (!req->ignore) {
13336 if (sipdebug)
13337 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
13338 set_nonce_randdata(p, 1);
13339 } else {
13340 if (sipdebug)
13341 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
13342 }
13343 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13344 }
13345
13346
13347 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13348 return AUTH_CHALLENGE_SENT;
13349 }
13350 if (good_response) {
13351 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
13352 return AUTH_SUCCESSFUL;
13353 }
13354
13355
13356
13357
13358
13359
13360 return AUTH_SECRET_FAILED;
13361 }
13362
13363
13364 static void sip_peer_hold(struct sip_pvt *p, int hold)
13365 {
13366 struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
13367
13368 if (!peer)
13369 return;
13370
13371
13372 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
13373
13374
13375 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13376 unref_peer(peer, "sip_peer_hold: from find_peer operation");
13377
13378 return;
13379 }
13380
13381
13382 static void mwi_event_cb(const struct ast_event *event, void *userdata)
13383 {
13384 struct sip_peer *peer = userdata;
13385
13386 ao2_lock(peer);
13387 sip_send_mwi_to_peer(peer, event, 0);
13388 ao2_unlock(peer);
13389 }
13390
13391
13392
13393
13394 static int cb_extensionstate(char *context, char* exten, int state, void *data)
13395 {
13396 struct sip_pvt *p = data;
13397
13398 sip_pvt_lock(p);
13399
13400 switch(state) {
13401 case AST_EXTENSION_DEACTIVATED:
13402 case AST_EXTENSION_REMOVED:
13403 if (p->autokillid > -1 && sip_cancel_destroy(p))
13404 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13405 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13406 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
13407 p->stateid = -1;
13408 p->subscribed = NONE;
13409 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
13410 break;
13411 default:
13412 p->laststate = state;
13413 break;
13414 }
13415 if (p->subscribed != NONE) {
13416 if (!p->pendinginvite) {
13417 transmit_state_notify(p, state, 1, FALSE);
13418 } else {
13419
13420
13421 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13422 }
13423 }
13424 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
13425 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
13426
13427 sip_pvt_unlock(p);
13428
13429 return 0;
13430 }
13431
13432
13433
13434
13435 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
13436 {
13437
13438
13439 const char *response = "401 Unauthorized";
13440 const char *reqheader = "Authorization";
13441 const char *respheader = "WWW-Authenticate";
13442 const char *authtoken;
13443 struct ast_str *buf;
13444 char *c;
13445
13446
13447 enum keys { K_NONCE, K_LAST };
13448 struct x {
13449 const char *key;
13450 const char *s;
13451 } *i, keys[] = {
13452 [K_NONCE] = { "nonce=", "" },
13453 [K_LAST] = { NULL, NULL}
13454 };
13455
13456 authtoken = get_header(req, reqheader);
13457 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13458
13459
13460 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13461
13462 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13463 return;
13464 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13465
13466 set_nonce_randdata(p, 1);
13467 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13468
13469 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13470 return;
13471 }
13472
13473 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13474 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13475 return;
13476 }
13477
13478
13479 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
13480 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13481 return;
13482 }
13483
13484 c = buf->str;
13485
13486 while (c && *(c = ast_skip_blanks(c))) {
13487 for (i = keys; i->key != NULL; i++) {
13488 const char *separator = ",";
13489
13490 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13491 continue;
13492 }
13493
13494 c += strlen(i->key);
13495 if (*c == '"') {
13496 c++;
13497 separator = "\"";
13498 }
13499 i->s = c;
13500 strsep(&c, separator);
13501 break;
13502 }
13503 if (i->key == NULL) {
13504 strsep(&c, " ,");
13505 }
13506 }
13507
13508
13509 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13510 if (!req->ignore) {
13511 set_nonce_randdata(p, 1);
13512 }
13513 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13514
13515
13516 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13517 } else {
13518 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13519 }
13520 }
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536 static char *terminate_uri(char *uri)
13537 {
13538 char *t = uri;
13539 while (*t && *t > ' ' && *t != ';')
13540 t++;
13541 *t = '\0';
13542 return uri;
13543 }
13544
13545
13546
13547
13548
13549
13550 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13551 struct sip_request *req, char *uri)
13552 {
13553 enum check_auth_result res = AUTH_NOT_FOUND;
13554 struct sip_peer *peer;
13555 char tmp[256];
13556 char *name, *c;
13557 char *domain;
13558
13559 terminate_uri(uri);
13560
13561 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13562 if (sip_cfg.pedanticsipchecking)
13563 ast_uri_decode(tmp);
13564
13565 c = get_in_brackets(tmp);
13566 c = remove_uri_parameters(c);
13567
13568 if (!strncasecmp(c, "sip:", 4)) {
13569 name = c + 4;
13570 } else if (!strncasecmp(c, "sips:", 5)) {
13571 name = c + 5;
13572 } else {
13573 name = c;
13574 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13575 }
13576
13577
13578
13579
13580
13581 if ((c = strchr(name, '@'))) {
13582 *c++ = '\0';
13583 domain = c;
13584 if ((c = strchr(domain, ':')))
13585 *c = '\0';
13586 if (!AST_LIST_EMPTY(&domain_list)) {
13587 if (!check_sip_domain(domain, NULL, 0)) {
13588 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13589 return AUTH_UNKNOWN_DOMAIN;
13590 }
13591 }
13592 }
13593 c = strchr(name, ';');
13594 if (c)
13595 *c = '\0';
13596
13597 ast_string_field_set(p, exten, name);
13598 build_contact(p);
13599 if (req->ignore) {
13600
13601 const char *expires = get_header(req, "Expires");
13602 int expire = atoi(expires);
13603
13604 if (ast_strlen_zero(expires)) {
13605 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13606 expire = atoi(expires + 9);
13607 }
13608 }
13609 if (!ast_strlen_zero(expires) && expire == 0) {
13610 transmit_response_with_date(p, "200 OK", req);
13611 return 0;
13612 }
13613 }
13614 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13615 if (!(peer && ast_apply_ha(peer->ha, sin))) {
13616
13617 if (peer) {
13618 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13619 peer = NULL;
13620 res = AUTH_ACL_FAILED;
13621 } else
13622 res = AUTH_NOT_FOUND;
13623 }
13624
13625 if (peer) {
13626
13627
13628 if (p->rtp) {
13629 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13630 p->autoframing = peer->autoframing;
13631 }
13632 if (!peer->host_dynamic) {
13633 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13634 res = AUTH_PEER_NOT_DYNAMIC;
13635 } else {
13636 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13637 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13638 transmit_response(p, "100 Trying", req);
13639 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13640 if (sip_cancel_destroy(p))
13641 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13642
13643 if (check_request_transport(peer, req)) {
13644 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13645 transmit_response_with_date(p, "403 Forbidden", req);
13646 res = AUTH_BAD_TRANSPORT;
13647 } else {
13648
13649
13650
13651 switch (parse_register_contact(p, peer, req)) {
13652 case PARSE_REGISTER_DENIED:
13653 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13654 transmit_response_with_date(p, "603 Denied", req);
13655 peer->lastmsgssent = -1;
13656 res = 0;
13657 break;
13658 case PARSE_REGISTER_FAILED:
13659 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13660 transmit_response_with_date(p, "400 Bad Request", req);
13661 peer->lastmsgssent = -1;
13662 res = 0;
13663 break;
13664 case PARSE_REGISTER_QUERY:
13665 ast_string_field_set(p, fullcontact, peer->fullcontact);
13666 transmit_response_with_date(p, "200 OK", req);
13667 peer->lastmsgssent = -1;
13668 res = 0;
13669 break;
13670 case PARSE_REGISTER_UPDATE:
13671 ast_string_field_set(p, fullcontact, peer->fullcontact);
13672 update_peer(peer, p->expiry);
13673
13674 transmit_response_with_date(p, "200 OK", req);
13675 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13676 peer->lastmsgssent = -1;
13677 res = 0;
13678 break;
13679 }
13680 }
13681
13682 }
13683 }
13684 }
13685 if (!peer && sip_cfg.autocreatepeer) {
13686
13687 peer = temp_peer(name);
13688 if (peer) {
13689 ao2_t_link(peers, peer, "link peer into peer table");
13690 if (peer->addr.sin_addr.s_addr) {
13691 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13692 }
13693
13694 if (sip_cancel_destroy(p))
13695 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13696 switch (parse_register_contact(p, peer, req)) {
13697 case PARSE_REGISTER_DENIED:
13698 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13699 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13700 peer->lastmsgssent = -1;
13701 res = 0;
13702 break;
13703 case PARSE_REGISTER_FAILED:
13704 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13705 transmit_response_with_date(p, "400 Bad Request", req);
13706 peer->lastmsgssent = -1;
13707 res = 0;
13708 break;
13709 case PARSE_REGISTER_QUERY:
13710 ast_string_field_set(p, fullcontact, peer->fullcontact);
13711 transmit_response_with_date(p, "200 OK", req);
13712 peer->lastmsgssent = -1;
13713 res = 0;
13714 break;
13715 case PARSE_REGISTER_UPDATE:
13716 ast_string_field_set(p, fullcontact, peer->fullcontact);
13717
13718 transmit_response_with_date(p, "200 OK", req);
13719 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));
13720 peer->lastmsgssent = -1;
13721 res = 0;
13722 break;
13723 }
13724 }
13725 }
13726 if (!peer && sip_cfg.alwaysauthreject && ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING)) {
13727
13728
13729
13730 transmit_response(p, "100 Trying", req);
13731
13732 sched_yield();
13733 }
13734 if (!res) {
13735 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13736 }
13737 if (res < 0) {
13738 switch (res) {
13739 case AUTH_SECRET_FAILED:
13740
13741 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13742 if (global_authfailureevents)
13743 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",
13744 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13745 break;
13746 case AUTH_USERNAME_MISMATCH:
13747
13748
13749
13750
13751 case AUTH_NOT_FOUND:
13752 case AUTH_PEER_NOT_DYNAMIC:
13753 case AUTH_ACL_FAILED:
13754 if (sip_cfg.alwaysauthreject) {
13755 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13756 if (global_authfailureevents) {
13757 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",
13758 name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13759 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13760 }
13761 } else {
13762
13763 if (res == AUTH_PEER_NOT_DYNAMIC) {
13764 transmit_response(p, "403 Forbidden", &p->initreq);
13765 if (global_authfailureevents) {
13766 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13767 "ChannelType: SIP\r\n"
13768 "Peer: SIP/%s\r\n"
13769 "PeerStatus: Rejected\r\n"
13770 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13771 "Address: %s\r\n"
13772 "Port: %d\r\n",
13773 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13774 }
13775 } else {
13776 transmit_response(p, "404 Not found", &p->initreq);
13777 if (global_authfailureevents) {
13778 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13779 "ChannelType: SIP\r\n"
13780 "Peer: SIP/%s\r\n"
13781 "PeerStatus: Rejected\r\n"
13782 "Cause: %s\r\n"
13783 "Address: %s\r\n"
13784 "Port: %d\r\n",
13785 name,
13786 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13787 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13788 }
13789 }
13790 }
13791 break;
13792 case AUTH_BAD_TRANSPORT:
13793 default:
13794 break;
13795 }
13796 }
13797 if (peer)
13798 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13799
13800 return res;
13801 }
13802
13803
13804 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13805
13806 if (!strcmp(reason, "unknown")) {
13807 ast_string_field_set(p, redircause, "UNKNOWN");
13808 } else if (!strcmp(reason, "user-busy")) {
13809 ast_string_field_set(p, redircause, "BUSY");
13810 } else if (!strcmp(reason, "no-answer")) {
13811 ast_string_field_set(p, redircause, "NOANSWER");
13812 } else if (!strcmp(reason, "unavailable")) {
13813 ast_string_field_set(p, redircause, "UNREACHABLE");
13814 } else if (!strcmp(reason, "unconditional")) {
13815 ast_string_field_set(p, redircause, "UNCONDITIONAL");
13816 } else if (!strcmp(reason, "time-of-day")) {
13817 ast_string_field_set(p, redircause, "UNKNOWN");
13818 } else if (!strcmp(reason, "do-not-disturb")) {
13819 ast_string_field_set(p, redircause, "UNKNOWN");
13820 } else if (!strcmp(reason, "deflection")) {
13821 ast_string_field_set(p, redircause, "UNKNOWN");
13822 } else if (!strcmp(reason, "follow-me")) {
13823 ast_string_field_set(p, redircause, "UNKNOWN");
13824 } else if (!strcmp(reason, "out-of-service")) {
13825 ast_string_field_set(p, redircause, "UNREACHABLE");
13826 } else if (!strcmp(reason, "away")) {
13827 ast_string_field_set(p, redircause, "UNREACHABLE");
13828 } else {
13829 ast_string_field_set(p, redircause, "UNKNOWN");
13830 }
13831 }
13832
13833
13834 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13835 {
13836 char tmp[256], *exten, *rexten, *rdomain;
13837 char *params, *reason = NULL;
13838 struct sip_request *req;
13839
13840 req = oreq ? oreq : &p->initreq;
13841
13842 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13843 if (ast_strlen_zero(tmp))
13844 return 0;
13845
13846
13847
13848
13849 params = strchr(tmp, ';');
13850
13851 exten = get_in_brackets(tmp);
13852 if (!strncasecmp(exten, "sip:", 4)) {
13853 exten += 4;
13854 } else if (!strncasecmp(exten, "sips:", 5)) {
13855 exten += 5;
13856 } else {
13857 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
13858 return -1;
13859 }
13860
13861
13862 if (params) {
13863 *params = '\0';
13864 params++;
13865 while (*params == ';' || *params == ' ')
13866 params++;
13867
13868 if ((reason = strcasestr(params, "reason="))) {
13869 reason+=7;
13870
13871 if (*reason == '"')
13872 ast_strip_quoted(reason, "\"", "\"");
13873 if (!ast_strlen_zero(reason)) {
13874 sip_set_redirstr(p, reason);
13875 if (p->owner) {
13876 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13877 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13878 }
13879 }
13880 }
13881 }
13882
13883 rdomain = exten;
13884 rexten = strsep(&rdomain, "@");
13885 if (p->owner)
13886 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13887
13888 if (sip_debug_test_pvt(p))
13889 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13890
13891 ast_string_field_set(p, rdnis, rexten);
13892
13893 return 0;
13894 }
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13909 {
13910 char tmp[256] = "", *uri, *a;
13911 char tmpf[256] = "", *from = NULL;
13912 struct sip_request *req;
13913 char *colon;
13914 char *decoded_uri;
13915
13916 req = oreq;
13917 if (!req)
13918 req = &p->initreq;
13919
13920
13921 if (req->rlPart2)
13922 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13923
13924 if (sip_cfg.pedanticsipchecking)
13925 ast_uri_decode(tmp);
13926
13927 uri = get_in_brackets(tmp);
13928
13929 if (!strncasecmp(uri, "sip:", 4)) {
13930 uri += 4;
13931 } else if (!strncasecmp(uri, "sips:", 5)) {
13932 uri += 5;
13933 } else {
13934 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
13935 return -1;
13936 }
13937
13938
13939
13940
13941
13942 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13943 if (!ast_strlen_zero(tmpf)) {
13944 if (sip_cfg.pedanticsipchecking)
13945 ast_uri_decode(tmpf);
13946 from = get_in_brackets(tmpf);
13947 }
13948
13949 if (!ast_strlen_zero(from)) {
13950 if (!strncasecmp(from, "sip:", 4)) {
13951 from += 4;
13952 } else if (!strncasecmp(from, "sips:", 5)) {
13953 from += 5;
13954 } else {
13955 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
13956 return -1;
13957 }
13958 if ((a = strchr(from, '@')))
13959 *a++ = '\0';
13960 else
13961 a = from;
13962 from = strsep(&from, ";");
13963 a = strsep(&a, ";");
13964 ast_string_field_set(p, fromdomain, a);
13965 }
13966
13967
13968
13969
13970 if ((a = strchr(uri, '@'))) {
13971 *a++ = '\0';
13972 } else {
13973 a = uri;
13974 uri = "s";
13975 }
13976 colon = strchr(a, ':');
13977 if (colon)
13978 *colon = '\0';
13979
13980 uri = strsep(&uri, ";");
13981 a = strsep(&a, ";");
13982
13983 ast_string_field_set(p, domain, a);
13984
13985 if (!AST_LIST_EMPTY(&domain_list)) {
13986 char domain_context[AST_MAX_EXTENSION];
13987
13988 domain_context[0] = '\0';
13989 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13990 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13991 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13992 return -2;
13993 }
13994 }
13995
13996
13997 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13998 ast_string_field_set(p, context, domain_context);
13999 }
14000
14001
14002 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
14003 ast_string_field_set(p, context, p->subscribecontext);
14004
14005 if (sip_debug_test_pvt(p))
14006 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
14007
14008
14009
14010 decoded_uri = ast_strdupa(uri);
14011 ast_uri_decode(decoded_uri);
14012
14013
14014 if (req->method == SIP_SUBSCRIBE) {
14015 char hint[AST_MAX_EXTENSION];
14016 int which = 0;
14017 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
14018 (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
14019 if (!oreq) {
14020 ast_string_field_set(p, exten, which ? decoded_uri : uri);
14021 }
14022 return 0;
14023 } else {
14024 return -1;
14025 }
14026 } else {
14027 int which = 0;
14028
14029
14030
14031 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) ||
14032 (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) && (which = 1)) ||
14033 !strcmp(decoded_uri, ast_pickup_ext())) {
14034 if (!oreq) {
14035 ast_string_field_set(p, exten, which ? decoded_uri : uri);
14036 }
14037 return 0;
14038 }
14039 }
14040
14041
14042 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
14043 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
14044 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
14045 return 1;
14046 }
14047
14048 return -1;
14049 }
14050
14051
14052
14053
14054 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
14055 {
14056 struct sip_pvt *sip_pvt_ptr;
14057 struct sip_pvt tmp_dialog = {
14058 .callid = callid,
14059 };
14060
14061 if (totag)
14062 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
14063
14064
14065
14066 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
14067 if (sip_pvt_ptr) {
14068
14069 sip_pvt_lock(sip_pvt_ptr);
14070 if (sip_cfg.pedanticsipchecking) {
14071 unsigned char frommismatch = 0, tomismatch = 0;
14072
14073 if (ast_strlen_zero(fromtag)) {
14074 sip_pvt_unlock(sip_pvt_ptr);
14075 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
14076 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14077 return NULL;
14078 }
14079
14080 if (ast_strlen_zero(totag)) {
14081 sip_pvt_unlock(sip_pvt_ptr);
14082 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
14083 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14084 return NULL;
14085 }
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
14101 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
14102
14103 if (frommismatch || tomismatch) {
14104 sip_pvt_unlock(sip_pvt_ptr);
14105 if (frommismatch) {
14106 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
14107 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
14108 fromtag, sip_pvt_ptr->theirtag);
14109 }
14110 if (tomismatch) {
14111 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
14112 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
14113 totag, sip_pvt_ptr->tag);
14114 }
14115 return NULL;
14116 }
14117 }
14118
14119 if (totag)
14120 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
14121 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
14122 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
14123
14124
14125 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
14126 sip_pvt_unlock(sip_pvt_ptr);
14127 usleep(1);
14128 sip_pvt_lock(sip_pvt_ptr);
14129 }
14130 }
14131
14132 return sip_pvt_ptr;
14133 }
14134
14135
14136
14137
14138
14139
14140
14141
14142 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
14143 {
14144
14145 const char *p_referred_by = NULL;
14146 char *h_refer_to = NULL;
14147 char *h_referred_by = NULL;
14148 char *refer_to;
14149 const char *p_refer_to;
14150 char *referred_by_uri = NULL;
14151 char *ptr;
14152 struct sip_request *req = NULL;
14153 const char *transfer_context = NULL;
14154 struct sip_refer *referdata;
14155
14156
14157 req = outgoing_req;
14158 referdata = transferer->refer;
14159
14160 if (!req)
14161 req = &transferer->initreq;
14162
14163 p_refer_to = get_header(req, "Refer-To");
14164 if (ast_strlen_zero(p_refer_to)) {
14165 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
14166 return -2;
14167 }
14168 h_refer_to = ast_strdupa(p_refer_to);
14169 refer_to = get_in_brackets(h_refer_to);
14170 if (sip_cfg.pedanticsipchecking)
14171 ast_uri_decode(refer_to);
14172
14173 if (!strncasecmp(refer_to, "sip:", 4)) {
14174 refer_to += 4;
14175 } else if (!strncasecmp(refer_to, "sips:", 5)) {
14176 refer_to += 5;
14177 } else {
14178 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
14179 return -3;
14180 }
14181
14182
14183 p_referred_by = get_header(req, "Referred-By");
14184
14185
14186 if (transferer->owner) {
14187 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
14188 if (peer) {
14189 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
14190 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
14191 }
14192 }
14193
14194 if (!ast_strlen_zero(p_referred_by)) {
14195 char *lessthan;
14196 h_referred_by = ast_strdupa(p_referred_by);
14197 if (sip_cfg.pedanticsipchecking)
14198 ast_uri_decode(h_referred_by);
14199
14200
14201 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
14202 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
14203 *(lessthan - 1) = '\0';
14204 }
14205
14206 referred_by_uri = get_in_brackets(h_referred_by);
14207 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
14208 referred_by_uri += 4;
14209 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
14210 referred_by_uri += 5;
14211 } else {
14212 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
14213 referred_by_uri = NULL;
14214 }
14215 }
14216
14217
14218 if ((ptr = strcasestr(refer_to, "replaces="))) {
14219 char *to = NULL, *from = NULL;
14220
14221
14222 referdata->attendedtransfer = 1;
14223 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
14224 ast_uri_decode(referdata->replaces_callid);
14225 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
14226 *ptr++ = '\0';
14227 }
14228
14229 if (ptr) {
14230
14231 to = strcasestr(ptr, "to-tag=");
14232 from = strcasestr(ptr, "from-tag=");
14233 }
14234
14235
14236 if (to) {
14237 ptr = to + 7;
14238 if ((to = strchr(ptr, '&')))
14239 *to = '\0';
14240 if ((to = strchr(ptr, ';')))
14241 *to = '\0';
14242 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
14243 }
14244
14245 if (from) {
14246 ptr = from + 9;
14247 if ((to = strchr(ptr, '&')))
14248 *to = '\0';
14249 if ((to = strchr(ptr, ';')))
14250 *to = '\0';
14251 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
14252 }
14253
14254 if (!strcmp(referdata->replaces_callid, transferer->callid) &&
14255 (!sip_cfg.pedanticsipchecking ||
14256 (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
14257 !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
14258 ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
14259 return -4;
14260 }
14261
14262 if (!sip_cfg.pedanticsipchecking)
14263 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
14264 else
14265 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>" );
14266 }
14267
14268 if ((ptr = strchr(refer_to, '@'))) {
14269 char *urioption = NULL, *domain;
14270 *ptr++ = '\0';
14271
14272 if ((urioption = strchr(ptr, ';')))
14273 *urioption++ = '\0';
14274
14275 domain = ptr;
14276 if ((ptr = strchr(domain, ':')))
14277 *ptr = '\0';
14278
14279
14280 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
14281 if (urioption)
14282 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
14283 }
14284
14285 if ((ptr = strchr(refer_to, ';')))
14286 *ptr = '\0';
14287 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
14288
14289 if (referred_by_uri) {
14290 if ((ptr = strchr(referred_by_uri, ';')))
14291 *ptr = '\0';
14292 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
14293 } else {
14294 referdata->referred_by[0] = '\0';
14295 }
14296
14297
14298 if (transferer->owner)
14299 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
14300
14301
14302 if (ast_strlen_zero(transfer_context)) {
14303 transfer_context = S_OR(transferer->owner->macrocontext,
14304 S_OR(transferer->context, sip_cfg.default_context));
14305 }
14306
14307 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
14308
14309
14310 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
14311 if (sip_debug_test_pvt(transferer)) {
14312 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
14313 }
14314
14315 return 0;
14316 }
14317 if (sip_debug_test_pvt(transferer))
14318 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
14319
14320
14321 return -1;
14322 }
14323
14324
14325
14326
14327
14328 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
14329 {
14330 char tmp[256] = "", *c, *a;
14331 struct sip_request *req = oreq ? oreq : &p->initreq;
14332 struct sip_refer *referdata = NULL;
14333 const char *transfer_context = NULL;
14334
14335 if (!p->refer && !sip_refer_allocate(p))
14336 return -1;
14337
14338 referdata = p->refer;
14339
14340 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
14341 c = get_in_brackets(tmp);
14342
14343 if (sip_cfg.pedanticsipchecking)
14344 ast_uri_decode(c);
14345
14346 if (!strncasecmp(c, "sip:", 4)) {
14347 c += 4;
14348 } else if (!strncasecmp(c, "sips:", 5)) {
14349 c += 5;
14350 } else {
14351 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
14352 return -1;
14353 }
14354
14355 if ((a = strchr(c, ';')))
14356 *a = '\0';
14357
14358 if ((a = strchr(c, '@'))) {
14359 *a++ = '\0';
14360 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
14361 }
14362
14363 if (sip_debug_test_pvt(p))
14364 ast_verbose("Looking for %s in %s\n", c, p->context);
14365
14366 if (p->owner)
14367 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
14368
14369
14370 if (ast_strlen_zero(transfer_context)) {
14371 transfer_context = S_OR(p->owner->macrocontext,
14372 S_OR(p->context, sip_cfg.default_context));
14373 }
14374 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
14375
14376 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
14377 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
14378 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
14379 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
14380 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
14381
14382 ast_string_field_set(p, context, transfer_context);
14383 return 0;
14384 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
14385 return 1;
14386 }
14387
14388 return -1;
14389 }
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
14402 {
14403 char via[256];
14404 char *cur, *opts;
14405
14406 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14407
14408
14409 opts = strchr(via, ',');
14410 if (opts)
14411 *opts = '\0';
14412
14413
14414 opts = strchr(via, ';');
14415 if (!opts)
14416 return;
14417 *opts++ = '\0';
14418 while ( (cur = strsep(&opts, ";")) ) {
14419 if (!strncmp(cur, "rport=", 6)) {
14420 int port = strtol(cur+6, NULL, 10);
14421
14422 p->ourip.sin_port = ntohs(port);
14423 } else if (!strncmp(cur, "received=", 9)) {
14424 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
14425 ;
14426 }
14427 }
14428 }
14429
14430
14431 static void check_via(struct sip_pvt *p, struct sip_request *req)
14432 {
14433 char via[512];
14434 char *c, *pt, *maddr;
14435 struct hostent *hp;
14436 struct ast_hostent ahp;
14437
14438 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14439
14440
14441 c = strchr(via, ',');
14442 if (c)
14443 *c = '\0';
14444
14445
14446 c = strstr(via, ";rport");
14447 if (c && (c[6] != '='))
14448 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
14449
14450
14451 maddr = strstr(via, "maddr=");
14452 if (maddr) {
14453 maddr += 6;
14454 c = maddr + strspn(maddr, "0123456789.");
14455 *c = '\0';
14456 }
14457
14458 c = strchr(via, ';');
14459 if (c)
14460 *c = '\0';
14461
14462 c = strchr(via, ' ');
14463 if (c) {
14464 *c = '\0';
14465 c = ast_skip_blanks(c+1);
14466 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
14467 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
14468 return;
14469 }
14470 pt = strchr(c, ':');
14471 if (pt)
14472 *pt++ = '\0';
14473
14474 if (maddr)
14475 c = maddr;
14476 hp = ast_gethostbyname(c, &ahp);
14477 if (!hp) {
14478 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
14479 return;
14480 }
14481 memset(&p->sa, 0, sizeof(p->sa));
14482 p->sa.sin_family = AF_INET;
14483 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
14484 p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
14485
14486 if (sip_debug_test_pvt(p)) {
14487 const struct sockaddr_in *dst = sip_real_dst(p);
14488 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
14489 }
14490 }
14491 }
14492
14493
14494 static char *get_calleridname(const char *input, char *output, size_t outputsize)
14495 {
14496 const char *end = strchr(input, '<');
14497 const char *tmp = strchr(input, '"');
14498 int bytes = 0;
14499 int maxbytes = outputsize - 1;
14500
14501 if (!end || end == input)
14502 return NULL;
14503
14504 end--;
14505
14506 if (tmp && tmp <= end) {
14507
14508
14509
14510 end = strchr(tmp+1, '"');
14511 if (!end)
14512 return NULL;
14513 bytes = (int) (end - tmp);
14514
14515 if (bytes > maxbytes)
14516 bytes = maxbytes;
14517 ast_copy_string(output, tmp + 1, bytes);
14518 } else {
14519
14520
14521 input = ast_skip_blanks(input);
14522
14523 while(*end && *end < 33 && end > input)
14524 end--;
14525 if (end >= input) {
14526 bytes = (int) (end - input) + 2;
14527
14528 if (bytes > maxbytes)
14529 bytes = maxbytes;
14530 ast_copy_string(output, input, bytes);
14531 } else
14532 return NULL;
14533 }
14534 return output;
14535 }
14536
14537
14538
14539
14540
14541 static int get_rpid_num(const char *input, char *output, int maxlen)
14542 {
14543 char *start;
14544 char *end;
14545
14546 start = strchr(input, ':');
14547 if (!start) {
14548 output[0] = '\0';
14549 return 0;
14550 }
14551 start++;
14552
14553
14554 ast_copy_string(output, start, maxlen);
14555 output[maxlen-1] = '\0';
14556
14557 end = strchr(output, '@');
14558 if (end)
14559 *end = '\0';
14560 else
14561 output[0] = '\0';
14562 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
14563 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14564
14565 return 0;
14566 }
14567
14568
14569
14570 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14571 {
14572
14573 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14574 char *tmp = ast_strdupa(rpid_num);
14575 if (!ast_strlen_zero(calleridname))
14576 ast_string_field_set(p, cid_name, calleridname);
14577 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14578 ast_shrink_phone_number(tmp);
14579 ast_string_field_set(p, cid_num, tmp);
14580 }
14581 }
14582
14583
14584 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14585 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14586 struct sip_peer **authpeer,
14587 enum xmittype reliable,
14588 char *rpid_num, char *calleridname, char *uri2)
14589 {
14590 enum check_auth_result res;
14591 int debug=sip_debug_test_addr(sin);
14592 struct sip_peer *peer;
14593
14594 if (sipmethod == SIP_SUBSCRIBE) {
14595
14596
14597
14598 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14599 } else {
14600
14601 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14602
14603
14604 if (!peer) {
14605 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14606 }
14607 }
14608
14609 if (!peer) {
14610 if (debug)
14611 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14612 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14613 return AUTH_DONT_KNOW;
14614 }
14615 if (!ast_apply_ha(peer->ha, sin)) {
14616 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14617 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14618 return AUTH_ACL_FAILED;
14619 }
14620 if (debug)
14621 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14622 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14623
14624
14625
14626 if (p->rtp) {
14627 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14628 p->autoframing = peer->autoframing;
14629 }
14630
14631
14632 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14633 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14634
14635 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14636 p->t38_maxdatagram = peer->t38_maxdatagram;
14637 set_t38_capabilities(p);
14638 }
14639
14640
14641
14642 if (p->sipoptions)
14643 peer->sipoptions = p->sipoptions;
14644
14645 replace_cid(p, rpid_num, calleridname);
14646 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14647
14648 ast_string_field_set(p, peersecret, peer->secret);
14649 ast_string_field_set(p, peermd5secret, peer->md5secret);
14650 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14651 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14652 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14653 ast_string_field_set(p, parkinglot, peer->parkinglot);
14654 if (peer->callingpres)
14655 p->callingpres = peer->callingpres;
14656 if (peer->maxms && peer->lastms)
14657 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14658 else
14659 p->timer_t1 = peer->timer_t1;
14660
14661
14662 if (peer->timer_b)
14663 p->timer_b = peer->timer_b;
14664 else
14665 p->timer_b = 64 * p->timer_t1;
14666
14667 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14668
14669 ast_string_field_set(p, peersecret, NULL);
14670 ast_string_field_set(p, peermd5secret, NULL);
14671 }
14672 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14673 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14674 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14675
14676 if (peer->call_limit)
14677 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14678 ast_string_field_set(p, peername, peer->name);
14679 ast_string_field_set(p, authname, peer->name);
14680
14681 if (sipmethod == SIP_INVITE) {
14682
14683 p->chanvars = copy_vars(peer->chanvars);
14684 }
14685
14686 if (authpeer) {
14687 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14688 (*authpeer) = peer;
14689 }
14690
14691 if (!ast_strlen_zero(peer->username)) {
14692 ast_string_field_set(p, username, peer->username);
14693
14694
14695 ast_string_field_set(p, authname, peer->username);
14696 }
14697 if (!ast_strlen_zero(peer->cid_num)) {
14698 char *tmp = ast_strdupa(peer->cid_num);
14699 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14700 ast_shrink_phone_number(tmp);
14701 ast_string_field_set(p, cid_num, tmp);
14702 }
14703 if (!ast_strlen_zero(peer->cid_name))
14704 ast_string_field_set(p, cid_name, peer->cid_name);
14705 ast_string_field_set(p, fullcontact, peer->fullcontact);
14706 if (!ast_strlen_zero(peer->context))
14707 ast_string_field_set(p, context, peer->context);
14708 ast_string_field_set(p, peersecret, peer->secret);
14709 ast_string_field_set(p, peermd5secret, peer->md5secret);
14710 ast_string_field_set(p, language, peer->language);
14711 ast_string_field_set(p, accountcode, peer->accountcode);
14712 p->amaflags = peer->amaflags;
14713 p->callgroup = peer->callgroup;
14714 p->pickupgroup = peer->pickupgroup;
14715 p->capability = peer->capability;
14716 p->prefs = peer->prefs;
14717 p->jointcapability = peer->capability;
14718 if (p->peercapability)
14719 p->jointcapability &= p->peercapability;
14720 p->maxcallbitrate = peer->maxcallbitrate;
14721 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14722 (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14723 !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14724 p->vrtp) {
14725 ast_rtp_destroy(p->vrtp);
14726 p->vrtp = NULL;
14727 }
14728 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14729 ast_rtp_destroy(p->trtp);
14730 p->trtp = NULL;
14731 }
14732 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14733 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14734 p->noncodeccapability |= AST_RTP_DTMF;
14735 else
14736 p->noncodeccapability &= ~AST_RTP_DTMF;
14737 p->jointnoncodeccapability = p->noncodeccapability;
14738 }
14739 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14740 return res;
14741 }
14742
14743
14744
14745
14746
14747
14748
14749 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14750 int sipmethod, char *uri, enum xmittype reliable,
14751 struct sockaddr_in *sin, struct sip_peer **authpeer)
14752 {
14753 char from[256];
14754 char *dummy;
14755 char *domain;
14756 char *of;
14757 char rpid_num[50];
14758 const char *rpid;
14759 enum check_auth_result res;
14760 char calleridname[50];
14761 char *uri2 = ast_strdupa(uri);
14762
14763 terminate_uri(uri2);
14764
14765 ast_copy_string(from, get_header(req, "From"), sizeof(from));
14766 if (sip_cfg.pedanticsipchecking)
14767 ast_uri_decode(from);
14768
14769 memset(calleridname, 0, sizeof(calleridname));
14770 get_calleridname(from, calleridname, sizeof(calleridname));
14771 if (calleridname[0])
14772 ast_string_field_set(p, cid_name, calleridname);
14773
14774 rpid = get_header(req, "Remote-Party-ID");
14775 memset(rpid_num, 0, sizeof(rpid_num));
14776 if (!ast_strlen_zero(rpid))
14777 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14778
14779 of = get_in_brackets(from);
14780 if (ast_strlen_zero(p->exten)) {
14781 char *t = uri2;
14782 if (!strncasecmp(t, "sip:", 4))
14783 t+= 4;
14784 else if (!strncasecmp(t, "sips:", 5))
14785 t += 5;
14786 ast_string_field_set(p, exten, t);
14787 t = strchr(p->exten, '@');
14788 if (t)
14789 *t = '\0';
14790 if (ast_strlen_zero(p->our_contact))
14791 build_contact(p);
14792 }
14793
14794 ast_string_field_set(p, from, of);
14795
14796
14797 if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14798 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14799 }
14800
14801 if (ast_strlen_zero(of)) {
14802
14803
14804
14805
14806
14807
14808 of = domain;
14809 } else {
14810 char *tmp = ast_strdupa(of);
14811
14812
14813
14814 tmp = strsep(&tmp, ";");
14815 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14816 ast_shrink_phone_number(tmp);
14817 ast_string_field_set(p, cid_num, tmp);
14818 }
14819
14820 if (global_match_auth_username) {
14821
14822
14823
14824
14825
14826
14827
14828
14829 const char *hdr = get_header(req, "Authorization");
14830 if (ast_strlen_zero(hdr))
14831 hdr = get_header(req, "Proxy-Authorization");
14832
14833 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14834 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14835 of = from;
14836 of = strsep(&of, "\"");
14837 }
14838 }
14839
14840 res = check_peer_ok(p, of, req, sipmethod, sin,
14841 authpeer, reliable, rpid_num, calleridname, uri2);
14842 if (res != AUTH_DONT_KNOW)
14843 return res;
14844
14845
14846 if (sip_cfg.allowguest) {
14847 replace_cid(p, rpid_num, calleridname);
14848 res = AUTH_SUCCESSFUL;
14849 } else if (sip_cfg.alwaysauthreject)
14850 res = AUTH_FAKE_AUTH;
14851 else
14852 res = AUTH_SECRET_FAILED;
14853
14854
14855 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14856 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14857 }
14858
14859 return res;
14860 }
14861
14862
14863
14864
14865 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14866 {
14867 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14868 }
14869
14870
14871 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14872 {
14873 int x;
14874 int y;
14875
14876 buf[0] = '\0';
14877
14878 y = len - strlen(buf) - 5;
14879 if (y < 0)
14880 y = 0;
14881 for (x = 0; x < req->lines; x++) {
14882 char *line = REQ_OFFSET_TO_STR(req, line[x]);
14883 strncat(buf, line, y);
14884 y -= strlen(line) + 1;
14885 if (y < 0)
14886 y = 0;
14887 if (y != 0 && addnewline)
14888 strcat(buf, "\n");
14889 }
14890 return 0;
14891 }
14892
14893
14894
14895
14896
14897 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14898 {
14899 char buf[1400];
14900 struct ast_frame f;
14901 const char *content_type = get_header(req, "Content-Type");
14902
14903 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
14904 transmit_response(p, "415 Unsupported Media Type", req);
14905 if (!p->owner)
14906 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14907 return;
14908 }
14909
14910 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14911 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14912 transmit_response(p, "202 Accepted", req);
14913 if (!p->owner)
14914 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14915 return;
14916 }
14917
14918 if (p->owner) {
14919 if (sip_debug_test_pvt(p))
14920 ast_verbose("SIP Text message received: '%s'\n", buf);
14921 memset(&f, 0, sizeof(f));
14922 f.frametype = AST_FRAME_TEXT;
14923 f.subclass = 0;
14924 f.offset = 0;
14925 f.data.ptr = buf;
14926 f.datalen = strlen(buf) + 1;
14927 ast_queue_frame(p->owner, &f);
14928 transmit_response(p, "202 Accepted", req);
14929 return;
14930 }
14931
14932
14933 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);
14934 transmit_response(p, "405 Method Not Allowed", req);
14935 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14936 return;
14937 }
14938
14939
14940 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14941 {
14942 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14943 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14944 char ilimits[40];
14945 char iused[40];
14946 int showall = FALSE;
14947 struct ao2_iterator i;
14948 struct sip_peer *peer;
14949
14950 switch (cmd) {
14951 case CLI_INIT:
14952 e->command = "sip show inuse";
14953 e->usage =
14954 "Usage: sip show inuse [all]\n"
14955 " List all SIP devices usage counters and limits.\n"
14956 " Add option \"all\" to show all devices, not only those with a limit.\n";
14957 return NULL;
14958 case CLI_GENERATE:
14959 return NULL;
14960 }
14961
14962 if (a->argc < 3)
14963 return CLI_SHOWUSAGE;
14964
14965 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
14966 showall = TRUE;
14967
14968 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14969
14970 i = ao2_iterator_init(peers, 0);
14971 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14972 ao2_lock(peer);
14973 if (peer->call_limit)
14974 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14975 else
14976 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14977 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14978 if (showall || peer->call_limit)
14979 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14980 ao2_unlock(peer);
14981 unref_peer(peer, "toss iterator pointer");
14982 }
14983 ao2_iterator_destroy(&i);
14984
14985 return CLI_SUCCESS;
14986 #undef FORMAT
14987 #undef FORMAT2
14988 }
14989
14990
14991
14992 static char *transfermode2str(enum transfermodes mode)
14993 {
14994 if (mode == TRANSFER_OPENFORALL)
14995 return "open";
14996 else if (mode == TRANSFER_CLOSED)
14997 return "closed";
14998 return "strict";
14999 }
15000
15001 static struct _map_x_s natmodes[] = {
15002 { SIP_NAT_NEVER, "No"},
15003 { SIP_NAT_ROUTE, "Route"},
15004 { SIP_NAT_ALWAYS, "Always"},
15005 { SIP_NAT_RFC3581, "RFC3581"},
15006 { -1, NULL},
15007 };
15008
15009
15010 static const char *nat2str(int nat)
15011 {
15012 return map_x_s(natmodes, nat, "Unknown");
15013 }
15014
15015 #ifdef NOTUSED
15016
15017
15018
15019
15020 static struct _map_x_s natcfgmodes[] = {
15021 { SIP_NAT_NEVER, "never"},
15022 { SIP_NAT_ROUTE, "route"},
15023 { SIP_NAT_ALWAYS, "yes"},
15024 { SIP_NAT_RFC3581, "no"},
15025 { -1, NULL},
15026 };
15027
15028
15029 static const char *nat2strconfig(int nat)
15030 {
15031 return map_x_s(natcfgmodes, nat, "Unknown");
15032 }
15033 #endif
15034
15035
15036
15037
15038
15039
15040
15041 static struct _map_x_s stmodes[] = {
15042 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
15043 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
15044 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
15045 { -1, NULL},
15046 };
15047
15048 static const char *stmode2str(enum st_mode m)
15049 {
15050 return map_x_s(stmodes, m, "Unknown");
15051 }
15052
15053 static enum st_mode str2stmode(const char *s)
15054 {
15055 return map_s_x(stmodes, s, -1);
15056 }
15057
15058
15059 static struct _map_x_s strefreshers[] = {
15060 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
15061 { SESSION_TIMER_REFRESHER_UAC, "uac"},
15062 { SESSION_TIMER_REFRESHER_UAS, "uas"},
15063 { -1, NULL},
15064 };
15065
15066 static const char *strefresher2str(enum st_refresher r)
15067 {
15068 return map_x_s(strefreshers, r, "Unknown");
15069 }
15070
15071 static enum st_refresher str2strefresher(const char *s)
15072 {
15073 return map_s_x(strefreshers, s, -1);
15074 }
15075
15076
15077 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
15078 {
15079 int res = 0;
15080 if (peer->maxms) {
15081 if (peer->lastms < 0) {
15082 ast_copy_string(status, "UNREACHABLE", statuslen);
15083 } else if (peer->lastms > peer->maxms) {
15084 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
15085 res = 1;
15086 } else if (peer->lastms) {
15087 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
15088 res = 1;
15089 } else {
15090 ast_copy_string(status, "UNKNOWN", statuslen);
15091 }
15092 } else {
15093 ast_copy_string(status, "Unmonitored", statuslen);
15094
15095 res = -1;
15096 }
15097 return res;
15098 }
15099
15100
15101
15102
15103
15104
15105 static const char *cli_yesno(int x)
15106 {
15107 return x ? "Yes" : "No";
15108 }
15109
15110
15111 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15112 {
15113 struct sip_threadinfo *th;
15114 struct ao2_iterator i;
15115
15116 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
15117 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
15118
15119 switch (cmd) {
15120 case CLI_INIT:
15121 e->command = "sip show tcp";
15122 e->usage =
15123 "Usage: sip show tcp\n"
15124 " Lists all active TCP/TLS sessions.\n";
15125 return NULL;
15126 case CLI_GENERATE:
15127 return NULL;
15128 }
15129
15130 if (a->argc != 3)
15131 return CLI_SHOWUSAGE;
15132
15133 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
15134 i = ao2_iterator_init(threadt, 0);
15135 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
15136 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr),
15137 ntohs(th->tcptls_session->remote_address.sin_port),
15138 get_transport(th->type),
15139 (th->tcptls_session->client ? "Client" : "Server"));
15140 ao2_t_ref(th, -1, "decrement ref from iterator");
15141 }
15142 ao2_iterator_destroy(&i);
15143 return CLI_SUCCESS;
15144 #undef FORMAT
15145 #undef FORMAT2
15146 }
15147
15148
15149 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15150 {
15151 regex_t regexbuf;
15152 int havepattern = FALSE;
15153 struct ao2_iterator user_iter;
15154 struct sip_peer *user;
15155
15156 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
15157
15158 switch (cmd) {
15159 case CLI_INIT:
15160 e->command = "sip show users";
15161 e->usage =
15162 "Usage: sip show users [like <pattern>]\n"
15163 " Lists all known SIP users.\n"
15164 " Optional regular expression pattern is used to filter the user list.\n";
15165 return NULL;
15166 case CLI_GENERATE:
15167 return NULL;
15168 }
15169
15170 switch (a->argc) {
15171 case 5:
15172 if (!strcasecmp(a->argv[3], "like")) {
15173 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
15174 return CLI_SHOWUSAGE;
15175 havepattern = TRUE;
15176 } else
15177 return CLI_SHOWUSAGE;
15178 case 3:
15179 break;
15180 default:
15181 return CLI_SHOWUSAGE;
15182 }
15183
15184 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
15185
15186 user_iter = ao2_iterator_init(peers, 0);
15187 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
15188 ao2_lock(user);
15189 if (!(user->type & SIP_TYPE_USER)) {
15190 ao2_unlock(user);
15191 unref_peer(user, "sip show users");
15192 continue;
15193 }
15194
15195 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
15196 ao2_unlock(user);
15197 unref_peer(user, "sip show users");
15198 continue;
15199 }
15200
15201 ast_cli(a->fd, FORMAT, user->name,
15202 user->secret,
15203 user->accountcode,
15204 user->context,
15205 cli_yesno(user->ha != NULL),
15206 nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
15207 ao2_unlock(user);
15208 unref_peer(user, "sip show users");
15209 }
15210 ao2_iterator_destroy(&user_iter);
15211
15212 if (havepattern)
15213 regfree(®exbuf);
15214
15215 return CLI_SUCCESS;
15216 #undef FORMAT
15217 }
15218
15219
15220 static char mandescr_show_registry[] =
15221 "Description: Lists all registration requests and status\n"
15222 "Registrations will follow as separate events. followed by a final event called\n"
15223 "RegistrationsComplete.\n"
15224 "Variables: \n"
15225 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
15226
15227
15228 static int manager_show_registry(struct mansession *s, const struct message *m)
15229 {
15230 const char *id = astman_get_header(m, "ActionID");
15231 char idtext[256] = "";
15232 int total = 0;
15233
15234 if (!ast_strlen_zero(id))
15235 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15236
15237 astman_send_listack(s, m, "Registrations will follow", "start");
15238
15239 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
15240 ASTOBJ_RDLOCK(iterator);
15241 astman_append(s,
15242 "Event: RegistryEntry\r\n"
15243 "%s"
15244 "Host: %s\r\n"
15245 "Port: %d\r\n"
15246 "Username: %s\r\n"
15247 "Refresh: %d\r\n"
15248 "State: %s\r\n"
15249 "RegistrationTime: %ld\r\n"
15250 "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
15251 iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
15252 ASTOBJ_UNLOCK(iterator);
15253 total++;
15254 } while(0));
15255
15256 astman_append(s,
15257 "Event: RegistrationsComplete\r\n"
15258 "EventList: Complete\r\n"
15259 "ListItems: %d\r\n"
15260 "%s"
15261 "\r\n", total, idtext);
15262
15263 return 0;
15264 }
15265
15266 static char mandescr_show_peers[] =
15267 "Description: Lists SIP peers in text format with details on current status.\n"
15268 "Peerlist will follow as separate events, followed by a final event called\n"
15269 "PeerlistComplete.\n"
15270 "Variables: \n"
15271 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
15272
15273
15274
15275 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
15276 {
15277 const char *id = astman_get_header(m, "ActionID");
15278 const char *a[] = {"sip", "show", "peers"};
15279 char idtext[256] = "";
15280 int total = 0;
15281
15282 if (!ast_strlen_zero(id))
15283 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15284
15285 astman_send_listack(s, m, "Peer status list will follow", "start");
15286
15287 _sip_show_peers(-1, &total, s, m, 3, a);
15288
15289 astman_append(s,
15290 "Event: PeerlistComplete\r\n"
15291 "EventList: Complete\r\n"
15292 "ListItems: %d\r\n"
15293 "%s"
15294 "\r\n", total, idtext);
15295 return 0;
15296 }
15297
15298
15299 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15300 {
15301 switch (cmd) {
15302 case CLI_INIT:
15303 e->command = "sip show peers";
15304 e->usage =
15305 "Usage: sip show peers [like <pattern>]\n"
15306 " Lists all known SIP peers.\n"
15307 " Optional regular expression pattern is used to filter the peer list.\n";
15308 return NULL;
15309 case CLI_GENERATE:
15310 return NULL;
15311 }
15312
15313 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
15314 }
15315
15316 int peercomparefunc(const void *a, const void *b);
15317
15318 int peercomparefunc(const void *a, const void *b)
15319 {
15320 struct sip_peer **ap = (struct sip_peer **)a;
15321 struct sip_peer **bp = (struct sip_peer **)b;
15322 return strcmp((*ap)->name, (*bp)->name);
15323 }
15324
15325
15326
15327 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
15328 {
15329 regex_t regexbuf;
15330 int havepattern = FALSE;
15331 struct sip_peer *peer;
15332 struct ao2_iterator i;
15333
15334
15335 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
15336 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
15337
15338 char name[256];
15339 int total_peers = 0;
15340 int peers_mon_online = 0;
15341 int peers_mon_offline = 0;
15342 int peers_unmon_offline = 0;
15343 int peers_unmon_online = 0;
15344 const char *id;
15345 char idtext[256] = "";
15346 int realtimepeers;
15347 int objcount = ao2_container_count(peers);
15348 struct sip_peer **peerarray;
15349 int k;
15350
15351
15352 realtimepeers = ast_check_realtime("sippeers");
15353 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
15354
15355 if (s) {
15356 id = astman_get_header(m, "ActionID");
15357 if (!ast_strlen_zero(id))
15358 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15359 }
15360
15361 switch (argc) {
15362 case 5:
15363 if (!strcasecmp(argv[3], "like")) {
15364 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
15365 return CLI_SHOWUSAGE;
15366 havepattern = TRUE;
15367 } else
15368 return CLI_SHOWUSAGE;
15369 case 3:
15370 break;
15371 default:
15372 return CLI_SHOWUSAGE;
15373 }
15374
15375 if (!s)
15376 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
15377
15378
15379 i = ao2_iterator_init(peers, 0);
15380 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15381 ao2_lock(peer);
15382
15383 if (!(peer->type & SIP_TYPE_PEER)) {
15384 ao2_unlock(peer);
15385 unref_peer(peer, "unref peer because it's actually a user");
15386 continue;
15387 }
15388
15389 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
15390 objcount--;
15391 ao2_unlock(peer);
15392 unref_peer(peer, "toss iterator peer ptr before continue");
15393 continue;
15394 }
15395
15396 peerarray[total_peers++] = peer;
15397 ao2_unlock(peer);
15398 }
15399 ao2_iterator_destroy(&i);
15400
15401 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
15402
15403 for(k=0; k < total_peers; k++) {
15404 char status[20] = "";
15405 char srch[2000];
15406 char pstatus;
15407 peer = peerarray[k];
15408
15409 ao2_lock(peer);
15410 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
15411 ao2_unlock(peer);
15412 peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr before continue");
15413 continue;
15414 }
15415
15416 if (!ast_strlen_zero(peer->username) && !s)
15417 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
15418 else
15419 ast_copy_string(name, peer->name, sizeof(name));
15420
15421 pstatus = peer_status(peer, status, sizeof(status));
15422 if (pstatus == 1)
15423 peers_mon_online++;
15424 else if (pstatus == 0)
15425 peers_mon_offline++;
15426 else {
15427 if (peer->addr.sin_port == 0)
15428 peers_unmon_offline++;
15429 else
15430 peers_unmon_online++;
15431 }
15432
15433 snprintf(srch, sizeof(srch), FORMAT, name,
15434 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15435 peer->host_dynamic ? " D " : " ",
15436 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
15437 peer->ha ? " A " : " ",
15438 ntohs(peer->addr.sin_port), status,
15439 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15440
15441 if (!s) {
15442 ast_cli(fd, FORMAT, name,
15443 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15444 peer->host_dynamic ? " D " : " ",
15445 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
15446 peer->ha ? " A " : " ",
15447
15448 ntohs(peer->addr.sin_port), status,
15449 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15450 } else {
15451
15452 astman_append(s,
15453 "Event: PeerEntry\r\n%s"
15454 "Channeltype: SIP\r\n"
15455 "ObjectName: %s\r\n"
15456 "ChanObjectType: peer\r\n"
15457 "IPaddress: %s\r\n"
15458 "IPport: %d\r\n"
15459 "Dynamic: %s\r\n"
15460 "Natsupport: %s\r\n"
15461 "VideoSupport: %s\r\n"
15462 "TextSupport: %s\r\n"
15463 "ACL: %s\r\n"
15464 "Status: %s\r\n"
15465 "RealtimeDevice: %s\r\n\r\n",
15466 idtext,
15467 peer->name,
15468 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
15469 ntohs(peer->addr.sin_port),
15470 peer->host_dynamic ? "yes" : "no",
15471 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
15472 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
15473 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
15474 peer->ha ? "yes" : "no",
15475 status,
15476 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
15477 }
15478 ao2_unlock(peer);
15479 peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr");
15480 }
15481
15482 if (!s)
15483 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
15484 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
15485
15486 if (havepattern)
15487 regfree(®exbuf);
15488
15489 if (total)
15490 *total = total_peers;
15491
15492 ast_free(peerarray);
15493
15494 return CLI_SUCCESS;
15495 #undef FORMAT
15496 #undef FORMAT2
15497 }
15498
15499 static int peer_dump_func(void *userobj, void *arg, int flags)
15500 {
15501 struct sip_peer *peer = userobj;
15502 int refc = ao2_t_ref(userobj, 0, "");
15503 int *fd = arg;
15504
15505 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
15506 peer->name, 0, refc);
15507 return 0;
15508 }
15509
15510 static int dialog_dump_func(void *userobj, void *arg, int flags)
15511 {
15512 struct sip_pvt *pvt = userobj;
15513 int refc = ao2_t_ref(userobj, 0, "");
15514 int *fd = arg;
15515
15516 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
15517 pvt->callid, 0, refc);
15518 return 0;
15519 }
15520
15521
15522
15523 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15524 {
15525 char tmp[256];
15526
15527 switch (cmd) {
15528 case CLI_INIT:
15529 e->command = "sip show objects";
15530 e->usage =
15531 "Usage: sip show objects\n"
15532 " Lists status of known SIP objects\n";
15533 return NULL;
15534 case CLI_GENERATE:
15535 return NULL;
15536 }
15537
15538 if (a->argc != 3)
15539 return CLI_SHOWUSAGE;
15540 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15541 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
15542 ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
15543 ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers_by_ip");
15544 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15545 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
15546 ast_cli(a->fd, "-= Dialog objects:\n\n");
15547 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
15548 return CLI_SUCCESS;
15549 }
15550
15551 static void print_group(int fd, ast_group_t group, int crlf)
15552 {
15553 char buf[256];
15554 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15555 }
15556
15557
15558 static struct _map_x_s dtmfstr[] = {
15559 { SIP_DTMF_RFC2833, "rfc2833" },
15560 { SIP_DTMF_INFO, "info" },
15561 { SIP_DTMF_SHORTINFO, "shortinfo" },
15562 { SIP_DTMF_INBAND, "inband" },
15563 { SIP_DTMF_AUTO, "auto" },
15564 { -1, NULL },
15565 };
15566
15567
15568 static const char *dtmfmode2str(int mode)
15569 {
15570 return map_x_s(dtmfstr, mode, "<error>");
15571 }
15572
15573
15574 static int str2dtmfmode(const char *str)
15575 {
15576 return map_s_x(dtmfstr, str, -1);
15577 }
15578
15579 static struct _map_x_s insecurestr[] = {
15580 { SIP_INSECURE_PORT, "port" },
15581 { SIP_INSECURE_INVITE, "invite" },
15582 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15583 { 0, "no" },
15584 { -1, NULL },
15585 };
15586
15587
15588 static const char *insecure2str(int mode)
15589 {
15590 return map_x_s(insecurestr, mode, "<error>");
15591 }
15592
15593
15594
15595
15596 static void cleanup_stale_contexts(char *new, char *old)
15597 {
15598 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15599
15600 while ((oldcontext = strsep(&old, "&"))) {
15601 stalecontext = '\0';
15602 ast_copy_string(newlist, new, sizeof(newlist));
15603 stringp = newlist;
15604 while ((newcontext = strsep(&stringp, "&"))) {
15605 if (!strcmp(newcontext, oldcontext)) {
15606
15607 stalecontext = '\0';
15608 break;
15609 } else if (strcmp(newcontext, oldcontext)) {
15610 stalecontext = oldcontext;
15611 }
15612
15613 }
15614 if (stalecontext)
15615 ast_context_destroy(ast_context_find(stalecontext), "SIP");
15616 }
15617 }
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
15632 {
15633 struct sip_pvt *dialog = dialogobj;
15634 time_t *t = arg;
15635
15636 if (sip_pvt_trylock(dialog)) {
15637
15638
15639 return 0;
15640 }
15641
15642
15643 check_rtp_timeout(dialog, *t);
15644
15645
15646
15647
15648 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15649
15650 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15651 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15652 sip_pvt_unlock(dialog);
15653 return 0;
15654 }
15655
15656 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15657 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15658 sip_pvt_unlock(dialog);
15659 return 0;
15660 }
15661
15662 sip_pvt_unlock(dialog);
15663
15664
15665 dialog_unlink_all(dialog, TRUE, FALSE);
15666 return 0;
15667 }
15668
15669 sip_pvt_unlock(dialog);
15670
15671 return 0;
15672 }
15673
15674
15675
15676 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15677 {
15678 struct sip_peer *peer, *pi;
15679 int prunepeer = FALSE;
15680 int multi = FALSE;
15681 char *name = NULL;
15682 regex_t regexbuf;
15683 int havepattern = 0;
15684 struct ao2_iterator i;
15685 static char *choices[] = { "all", "like", NULL };
15686 char *cmplt;
15687
15688 if (cmd == CLI_INIT) {
15689 e->command = "sip prune realtime [peer|all]";
15690 e->usage =
15691 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15692 " Prunes object(s) from the cache.\n"
15693 " Optional regular expression pattern is used to filter the objects.\n";
15694 return NULL;
15695 } else if (cmd == CLI_GENERATE) {
15696 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15697 cmplt = ast_cli_complete(a->word, choices, a->n);
15698 if (!cmplt)
15699 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15700 return cmplt;
15701 }
15702 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15703 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15704 return NULL;
15705 }
15706 switch (a->argc) {
15707 case 4:
15708 name = a->argv[3];
15709
15710 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15711 return CLI_SHOWUSAGE;
15712 prunepeer = TRUE;
15713 if (!strcasecmp(name, "all")) {
15714 multi = TRUE;
15715 name = NULL;
15716 }
15717
15718 break;
15719 case 5:
15720
15721 name = a->argv[4];
15722 if (!strcasecmp(a->argv[3], "peer"))
15723 prunepeer = TRUE;
15724 else if (!strcasecmp(a->argv[3], "like")) {
15725 prunepeer = TRUE;
15726 multi = TRUE;
15727 } else
15728 return CLI_SHOWUSAGE;
15729 if (!strcasecmp(name, "like"))
15730 return CLI_SHOWUSAGE;
15731 if (!multi && !strcasecmp(name, "all")) {
15732 multi = TRUE;
15733 name = NULL;
15734 }
15735 break;
15736 case 6:
15737 name = a->argv[5];
15738 multi = TRUE;
15739
15740 if (strcasecmp(a->argv[4], "like"))
15741 return CLI_SHOWUSAGE;
15742 if (!strcasecmp(a->argv[3], "peer")) {
15743 prunepeer = TRUE;
15744 } else
15745 return CLI_SHOWUSAGE;
15746 break;
15747 default:
15748 return CLI_SHOWUSAGE;
15749 }
15750
15751 if (multi && name) {
15752 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB)) {
15753 return CLI_SHOWUSAGE;
15754 }
15755 havepattern = 1;
15756 }
15757
15758 if (multi) {
15759 if (prunepeer) {
15760 int pruned = 0;
15761
15762 i = ao2_iterator_init(peers, 0);
15763 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15764 ao2_lock(pi);
15765 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
15766 unref_peer(pi, "toss iterator peer ptr before continue");
15767 ao2_unlock(pi);
15768 continue;
15769 };
15770 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15771 pi->the_mark = 1;
15772 pruned++;
15773 }
15774 ao2_unlock(pi);
15775 unref_peer(pi, "toss iterator peer ptr");
15776 }
15777 ao2_iterator_destroy(&i);
15778 if (pruned) {
15779 unlink_marked_peers_from_tables();
15780 ast_cli(a->fd, "%d peers pruned.\n", pruned);
15781 } else
15782 ast_cli(a->fd, "No peers found to prune.\n");
15783 }
15784 } else {
15785 if (prunepeer) {
15786 struct sip_peer tmp;
15787 ast_copy_string(tmp.name, name, sizeof(tmp.name));
15788 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15789 if (peer->addr.sin_addr.s_addr) {
15790 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15791 }
15792 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15793 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15794
15795 ao2_t_link(peers, peer, "link peer into peer table");
15796 if (peer->addr.sin_addr.s_addr) {
15797 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15798 }
15799
15800 } else
15801 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15802 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15803 } else
15804 ast_cli(a->fd, "Peer '%s' not found.\n", name);
15805 }
15806 }
15807
15808 if (havepattern) {
15809 regfree(®exbuf);
15810 }
15811
15812 return CLI_SUCCESS;
15813 }
15814
15815
15816 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15817 {
15818 int x, codec;
15819
15820 for(x = 0; x < 32 ; x++) {
15821 codec = ast_codec_pref_index(pref, x);
15822 if (!codec)
15823 break;
15824 ast_cli(fd, "%s", ast_getformatname(codec));
15825 ast_cli(fd, ":%d", pref->framing[x]);
15826 if (x < 31 && ast_codec_pref_index(pref, x + 1))
15827 ast_cli(fd, ",");
15828 }
15829 if (!x)
15830 ast_cli(fd, "none");
15831 }
15832
15833
15834 static const char *domain_mode_to_text(const enum domain_mode mode)
15835 {
15836 switch (mode) {
15837 case SIP_DOMAIN_AUTO:
15838 return "[Automatic]";
15839 case SIP_DOMAIN_CONFIG:
15840 return "[Configured]";
15841 }
15842
15843 return "";
15844 }
15845
15846
15847 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15848 {
15849 struct domain *d;
15850 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15851
15852 switch (cmd) {
15853 case CLI_INIT:
15854 e->command = "sip show domains";
15855 e->usage =
15856 "Usage: sip show domains\n"
15857 " Lists all configured SIP local domains.\n"
15858 " Asterisk only responds to SIP messages to local domains.\n";
15859 return NULL;
15860 case CLI_GENERATE:
15861 return NULL;
15862 }
15863
15864 if (AST_LIST_EMPTY(&domain_list)) {
15865 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15866 return CLI_SUCCESS;
15867 } else {
15868 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15869 AST_LIST_LOCK(&domain_list);
15870 AST_LIST_TRAVERSE(&domain_list, d, list)
15871 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15872 domain_mode_to_text(d->mode));
15873 AST_LIST_UNLOCK(&domain_list);
15874 ast_cli(a->fd, "\n");
15875 return CLI_SUCCESS;
15876 }
15877 }
15878 #undef FORMAT
15879
15880 static char mandescr_show_peer[] =
15881 "Description: Show one SIP peer with details on current status.\n"
15882 "Variables: \n"
15883 " Peer: <name> The peer name you want to check.\n"
15884 " ActionID: <id> Optional action ID for this AMI transaction.\n";
15885
15886
15887 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15888 {
15889 const char *a[4];
15890 const char *peer;
15891
15892 peer = astman_get_header(m, "Peer");
15893 if (ast_strlen_zero(peer)) {
15894 astman_send_error(s, m, "Peer: <name> missing.");
15895 return 0;
15896 }
15897 a[0] = "sip";
15898 a[1] = "show";
15899 a[2] = "peer";
15900 a[3] = peer;
15901
15902 _sip_show_peer(1, -1, s, m, 4, a);
15903 astman_append(s, "\r\n\r\n" );
15904 return 0;
15905 }
15906
15907
15908 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15909 {
15910 switch (cmd) {
15911 case CLI_INIT:
15912 e->command = "sip show peer";
15913 e->usage =
15914 "Usage: sip show peer <name> [load]\n"
15915 " Shows all details on one SIP peer and the current status.\n"
15916 " Option \"load\" forces lookup of peer in realtime storage.\n";
15917 return NULL;
15918 case CLI_GENERATE:
15919 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15920 }
15921 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15922 }
15923
15924
15925 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15926 {
15927 struct sip_peer *peer;
15928 int load_realtime;
15929
15930 if (argc < 4)
15931 return CLI_SHOWUSAGE;
15932
15933 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15934 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15935 sip_poke_peer(peer, 1);
15936 unref_peer(peer, "qualify: done with peer");
15937 } else if (type == 0) {
15938 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15939 } else {
15940 astman_send_error(s, m, "Peer not found");
15941 }
15942 return CLI_SUCCESS;
15943 }
15944
15945
15946 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15947 {
15948 const char *a[4];
15949 const char *peer;
15950
15951 peer = astman_get_header(m, "Peer");
15952 if (ast_strlen_zero(peer)) {
15953 astman_send_error(s, m, "Peer: <name> missing.");
15954 return 0;
15955 }
15956 a[0] = "sip";
15957 a[1] = "qualify";
15958 a[2] = "peer";
15959 a[3] = peer;
15960
15961 _sip_qualify_peer(1, -1, s, m, 4, a);
15962 astman_append(s, "\r\n\r\n" );
15963 return 0;
15964 }
15965
15966
15967 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15968 {
15969 switch (cmd) {
15970 case CLI_INIT:
15971 e->command = "sip qualify peer";
15972 e->usage =
15973 "Usage: sip qualify peer <name> [load]\n"
15974 " Requests a response from one SIP peer and the current status.\n"
15975 " Option \"load\" forces lookup of peer in realtime storage.\n";
15976 return NULL;
15977 case CLI_GENERATE:
15978 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15979 }
15980 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15981 }
15982
15983
15984 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15985 {
15986 struct sip_mailbox *mailbox;
15987
15988 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15989 ast_str_append(mailbox_str, 0, "%s%s%s%s",
15990 mailbox->mailbox,
15991 ast_strlen_zero(mailbox->context) ? "" : "@",
15992 S_OR(mailbox->context, ""),
15993 AST_LIST_NEXT(mailbox, entry) ? "," : "");
15994 }
15995 }
15996
15997 static struct _map_x_s faxecmodes[] = {
15998 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
15999 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
16000 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
16001 { -1, NULL},
16002 };
16003
16004 static const char *faxec2str(int faxec)
16005 {
16006 return map_x_s(faxecmodes, faxec, "Unknown");
16007 }
16008
16009
16010 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
16011 {
16012 char status[30] = "";
16013 char cbuf[256];
16014 struct sip_peer *peer;
16015 char codec_buf[512];
16016 struct ast_codec_pref *pref;
16017 struct ast_variable *v;
16018 struct sip_auth *auth;
16019 int x = 0, codec = 0, load_realtime;
16020 int realtimepeers;
16021
16022 realtimepeers = ast_check_realtime("sippeers");
16023
16024 if (argc < 4)
16025 return CLI_SHOWUSAGE;
16026
16027 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
16028 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
16029
16030 if (s) {
16031 if (peer) {
16032 const char *id = astman_get_header(m, "ActionID");
16033
16034 astman_append(s, "Response: Success\r\n");
16035 if (!ast_strlen_zero(id))
16036 astman_append(s, "ActionID: %s\r\n", id);
16037 } else {
16038 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
16039 astman_send_error(s, m, cbuf);
16040 return CLI_SUCCESS;
16041 }
16042 }
16043 if (peer && type==0 ) {
16044 struct ast_str *mailbox_str = ast_str_alloca(512);
16045 ast_cli(fd, "\n\n");
16046 ast_cli(fd, " * Name : %s\n", peer->name);
16047 if (realtimepeers) {
16048 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
16049 }
16050 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
16051 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
16052 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
16053 for (auth = peer->auth; auth; auth = auth->next) {
16054 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
16055 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
16056 }
16057 ast_cli(fd, " Context : %s\n", peer->context);
16058 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
16059 ast_cli(fd, " Language : %s\n", peer->language);
16060 if (!ast_strlen_zero(peer->accountcode))
16061 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
16062 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
16063 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
16064 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
16065 if (!ast_strlen_zero(peer->fromuser))
16066 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
16067 if (!ast_strlen_zero(peer->fromdomain))
16068 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
16069 ast_cli(fd, " Callgroup : ");
16070 print_group(fd, peer->callgroup, 0);
16071 ast_cli(fd, " Pickupgroup : ");
16072 print_group(fd, peer->pickupgroup, 0);
16073 peer_mailboxes_to_str(&mailbox_str, peer);
16074 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
16075 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
16076 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
16077 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
16078 if (peer->busy_level)
16079 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
16080 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
16081 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
16082 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
16083 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
16084 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16085 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
16086 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
16087 ast_cli(fd, " T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16088 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16089 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
16090 ast_cli(fd, " DirectMedia : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
16091 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
16092 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
16093 ast_cli(fd, " Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
16094 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
16095 ast_cli(fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16096 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
16097 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
16098 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16099 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16100 ast_cli(fd, " Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16101 if (peer->outboundproxy)
16102 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
16103 peer->outboundproxy->force ? "(forced)" : "");
16104
16105
16106 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16107 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
16108 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
16109 ast_cli(fd, " ToHost : %s\n", peer->tohost);
16110 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));
16111 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
16112 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
16113 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
16114 if (!ast_strlen_zero(global_regcontext))
16115 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
16116 ast_cli(fd, " Def. Username: %s\n", peer->username);
16117 ast_cli(fd, " SIP Options : ");
16118 if (peer->sipoptions) {
16119 int lastoption = -1;
16120 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16121 if (sip_options[x].id != lastoption) {
16122 if (peer->sipoptions & sip_options[x].id)
16123 ast_cli(fd, "%s ", sip_options[x].text);
16124 lastoption = x;
16125 }
16126 }
16127 } else
16128 ast_cli(fd, "(none)");
16129
16130 ast_cli(fd, "\n");
16131 ast_cli(fd, " Codecs : ");
16132 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16133 ast_cli(fd, "%s\n", codec_buf);
16134 ast_cli(fd, " Codec Order : (");
16135 print_codec_to_cli(fd, &peer->prefs);
16136 ast_cli(fd, ")\n");
16137
16138 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
16139 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
16140 ast_cli(fd, " Status : ");
16141 peer_status(peer, status, sizeof(status));
16142 ast_cli(fd, "%s\n", status);
16143 ast_cli(fd, " Useragent : %s\n", peer->useragent);
16144 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
16145 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
16146 if (peer->chanvars) {
16147 ast_cli(fd, " Variables :\n");
16148 for (v = peer->chanvars ; v ; v = v->next)
16149 ast_cli(fd, " %s = %s\n", v->name, v->value);
16150 }
16151
16152 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
16153 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
16154 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
16155 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
16156 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
16157 ast_cli(fd, "\n");
16158 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
16159 } else if (peer && type == 1) {
16160 char buffer[256];
16161 struct ast_str *mailbox_str = ast_str_alloca(512);
16162 astman_append(s, "Channeltype: SIP\r\n");
16163 astman_append(s, "ObjectName: %s\r\n", peer->name);
16164 astman_append(s, "ChanObjectType: peer\r\n");
16165 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
16166 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
16167 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
16168 astman_append(s, "Context: %s\r\n", peer->context);
16169 astman_append(s, "Language: %s\r\n", peer->language);
16170 if (!ast_strlen_zero(peer->accountcode))
16171 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
16172 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
16173 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
16174 if (!ast_strlen_zero(peer->fromuser))
16175 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
16176 if (!ast_strlen_zero(peer->fromdomain))
16177 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
16178 astman_append(s, "Callgroup: ");
16179 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
16180 astman_append(s, "Pickupgroup: ");
16181 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
16182 peer_mailboxes_to_str(&mailbox_str, peer);
16183 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
16184 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
16185 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
16186 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
16187 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
16188 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
16189 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
16190 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
16191 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
16192 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16193 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
16194 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
16195 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16196 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16197 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
16198 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
16199 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
16200 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
16201 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
16202 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16203 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
16204 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
16205 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
16206 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
16207 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
16208
16209
16210 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16211 astman_append(s, "ToHost: %s\r\n", peer->tohost);
16212 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));
16213 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));
16214 astman_append(s, "Default-Username: %s\r\n", peer->username);
16215 if (!ast_strlen_zero(global_regcontext))
16216 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
16217 astman_append(s, "Codecs: ");
16218 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16219 astman_append(s, "%s\r\n", codec_buf);
16220 astman_append(s, "CodecOrder: ");
16221 pref = &peer->prefs;
16222 for(x = 0; x < 32 ; x++) {
16223 codec = ast_codec_pref_index(pref, x);
16224 if (!codec)
16225 break;
16226 astman_append(s, "%s", ast_getformatname(codec));
16227 if (x < 31 && ast_codec_pref_index(pref, x+1))
16228 astman_append(s, ",");
16229 }
16230
16231 astman_append(s, "\r\n");
16232 astman_append(s, "Status: ");
16233 peer_status(peer, status, sizeof(status));
16234 astman_append(s, "%s\r\n", status);
16235 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
16236 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
16237 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
16238 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
16239 if (peer->chanvars) {
16240 for (v = peer->chanvars ; v ; v = v->next) {
16241 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
16242 }
16243 }
16244
16245 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
16246
16247 } else {
16248 ast_cli(fd, "Peer %s not found.\n", argv[3]);
16249 ast_cli(fd, "\n");
16250 }
16251
16252 return CLI_SUCCESS;
16253 }
16254
16255
16256 static char *complete_sip_user(const char *word, int state)
16257 {
16258 char *result = NULL;
16259 int wordlen = strlen(word);
16260 int which = 0;
16261 struct ao2_iterator user_iter;
16262 struct sip_peer *user;
16263
16264 user_iter = ao2_iterator_init(peers, 0);
16265 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
16266 ao2_lock(user);
16267 if (!(user->type & SIP_TYPE_USER)) {
16268 ao2_unlock(user);
16269 unref_peer(user, "complete sip user");
16270 continue;
16271 }
16272
16273 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
16274 result = ast_strdup(user->name);
16275 }
16276 ao2_unlock(user);
16277 unref_peer(user, "complete sip user");
16278 if (result) {
16279 break;
16280 }
16281 }
16282 ao2_iterator_destroy(&user_iter);
16283 return result;
16284 }
16285
16286 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
16287 {
16288 if (pos == 3)
16289 return complete_sip_user(word, state);
16290
16291 return NULL;
16292 }
16293
16294
16295 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16296 {
16297 char cbuf[256];
16298 struct sip_peer *user;
16299 struct ast_variable *v;
16300 int load_realtime;
16301
16302 switch (cmd) {
16303 case CLI_INIT:
16304 e->command = "sip show user";
16305 e->usage =
16306 "Usage: sip show user <name> [load]\n"
16307 " Shows all details on one SIP user and the current status.\n"
16308 " Option \"load\" forces lookup of peer in realtime storage.\n";
16309 return NULL;
16310 case CLI_GENERATE:
16311 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
16312 }
16313
16314 if (a->argc < 4)
16315 return CLI_SHOWUSAGE;
16316
16317
16318 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
16319
16320 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
16321 ao2_lock(user);
16322 ast_cli(a->fd, "\n\n");
16323 ast_cli(a->fd, " * Name : %s\n", user->name);
16324 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
16325 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
16326 ast_cli(a->fd, " Context : %s\n", user->context);
16327 ast_cli(a->fd, " Language : %s\n", user->language);
16328 if (!ast_strlen_zero(user->accountcode))
16329 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
16330 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
16331 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
16332 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
16333 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
16334 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
16335 ast_cli(a->fd, " Callgroup : ");
16336 print_group(a->fd, user->callgroup, 0);
16337 ast_cli(a->fd, " Pickupgroup : ");
16338 print_group(a->fd, user->pickupgroup, 0);
16339 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
16340 ast_cli(a->fd, " ACL : %s\n", cli_yesno(user->ha != NULL));
16341 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
16342 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
16343 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
16344 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
16345
16346 ast_cli(a->fd, " Codec Order : (");
16347 print_codec_to_cli(a->fd, &user->prefs);
16348 ast_cli(a->fd, ")\n");
16349
16350 ast_cli(a->fd, " Auto-Framing: %s \n", cli_yesno(user->autoframing));
16351 if (user->chanvars) {
16352 ast_cli(a->fd, " Variables :\n");
16353 for (v = user->chanvars ; v ; v = v->next)
16354 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
16355 }
16356
16357 ast_cli(a->fd, "\n");
16358
16359 ao2_unlock(user);
16360 unref_peer(user, "sip show user");
16361 } else {
16362 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
16363 ast_cli(a->fd, "\n");
16364 }
16365
16366 return CLI_SUCCESS;
16367 }
16368
16369
16370 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16371 {
16372 struct ast_str *cbuf;
16373 struct ast_cb_names cbnames = {9, { "retrans_pkt",
16374 "__sip_autodestruct",
16375 "expire_register",
16376 "auto_congest",
16377 "sip_reg_timeout",
16378 "sip_poke_peer_s",
16379 "sip_poke_noanswer",
16380 "sip_reregister",
16381 "sip_reinvite_retry"},
16382 { retrans_pkt,
16383 __sip_autodestruct,
16384 expire_register,
16385 auto_congest,
16386 sip_reg_timeout,
16387 sip_poke_peer_s,
16388 sip_poke_noanswer,
16389 sip_reregister,
16390 sip_reinvite_retry}};
16391
16392 switch (cmd) {
16393 case CLI_INIT:
16394 e->command = "sip show sched";
16395 e->usage =
16396 "Usage: sip show sched\n"
16397 " Shows stats on what's in the sched queue at the moment\n";
16398 return NULL;
16399 case CLI_GENERATE:
16400 return NULL;
16401 }
16402
16403 cbuf = ast_str_alloca(2048);
16404
16405 ast_cli(a->fd, "\n");
16406 ast_sched_report(sched, &cbuf, &cbnames);
16407 ast_cli(a->fd, "%s", cbuf->str);
16408
16409 return CLI_SUCCESS;
16410 }
16411
16412
16413 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16414 {
16415 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
16416 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
16417 char host[80];
16418 char tmpdat[256];
16419 struct ast_tm tm;
16420 int counter = 0;
16421
16422 switch (cmd) {
16423 case CLI_INIT:
16424 e->command = "sip show registry";
16425 e->usage =
16426 "Usage: sip show registry\n"
16427 " Lists all registration requests and status.\n";
16428 return NULL;
16429 case CLI_GENERATE:
16430 return NULL;
16431 }
16432
16433 if (a->argc != 3)
16434 return CLI_SHOWUSAGE;
16435 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
16436
16437 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
16438 ASTOBJ_RDLOCK(iterator);
16439 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16440 if (iterator->regtime.tv_sec) {
16441 ast_localtime(&iterator->regtime, &tm, NULL);
16442 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
16443 } else
16444 tmpdat[0] = '\0';
16445 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
16446 ASTOBJ_UNLOCK(iterator);
16447 counter++;
16448 } while(0));
16449 ast_cli(a->fd, "%d SIP registrations.\n", counter);
16450 return CLI_SUCCESS;
16451 #undef FORMAT
16452 #undef FORMAT2
16453 }
16454
16455
16456
16457
16458
16459 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16460 {
16461 struct sip_peer *peer;
16462 int load_realtime = 0;
16463
16464 switch (cmd) {
16465 case CLI_INIT:
16466 e->command = "sip unregister";
16467 e->usage =
16468 "Usage: sip unregister <peer>\n"
16469 " Unregister (force expiration) a SIP peer from the registry\n";
16470 return NULL;
16471 case CLI_GENERATE:
16472 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
16473 }
16474
16475 if (a->argc != 3)
16476 return CLI_SHOWUSAGE;
16477
16478 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
16479 if (peer->expire > 0) {
16480 AST_SCHED_DEL_UNREF(sched, peer->expire,
16481 unref_peer(peer, "remove register expire ref"));
16482 expire_register(ref_peer(peer, "ref for expire_register"));
16483 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
16484 } else {
16485 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
16486 }
16487 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
16488 } else {
16489 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
16490 }
16491
16492 return CLI_SUCCESS;
16493 }
16494
16495
16496 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
16497 {
16498 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
16499 #define FORMAT "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u\n"
16500 struct sip_pvt *cur = __cur;
16501 unsigned int rxcount, txcount, rxploss, txploss;
16502 char durbuf[10];
16503 int duration;
16504 int durh, durm, durs;
16505 struct ast_channel *c = cur->owner;
16506 struct __show_chan_arg *arg = __arg;
16507 int fd = arg->fd;
16508
16509
16510 if (cur->subscribed != NONE)
16511 return 0;
16512
16513 if (!cur->rtp) {
16514 if (sipdebug)
16515 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");
16516 return 0;
16517 }
16518 rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
16519 txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
16520 rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
16521 txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
16522
16523
16524 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16525 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16526 durh = duration / 3600;
16527 durm = (duration % 3600) / 60;
16528 durs = duration % 60;
16529 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16530 } else {
16531 durbuf[0] = '\0';
16532 }
16533
16534 ast_cli(fd, FORMAT,
16535 ast_inet_ntoa(cur->sa.sin_addr),
16536 cur->callid,
16537 durbuf,
16538 rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
16539 rxcount > (unsigned int) 100000 ? "K":" ",
16540 rxploss,
16541 (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
16542 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
16543 txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
16544 txcount > (unsigned int) 100000 ? "K":" ",
16545 txploss,
16546 txcount > 0 ? (double) txploss / txcount * 100 : 0,
16547 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
16548 );
16549 arg->numchans++;
16550
16551 return 0;
16552 }
16553
16554
16555 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16556 {
16557 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16558
16559 switch (cmd) {
16560 case CLI_INIT:
16561 e->command = "sip show channelstats";
16562 e->usage =
16563 "Usage: sip show channelstats\n"
16564 " Lists all currently active SIP channel's RTCP statistics.\n"
16565 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
16566 return NULL;
16567 case CLI_GENERATE:
16568 return NULL;
16569 }
16570
16571 if (a->argc != 3)
16572 return CLI_SHOWUSAGE;
16573
16574 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16575
16576 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16577 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
16578 return CLI_SUCCESS;
16579 }
16580 #undef FORMAT
16581 #undef FORMAT2
16582
16583
16584 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16585 {
16586 int realtimepeers;
16587 int realtimeregs;
16588 char codec_buf[SIPBUFSIZE];
16589 const char *msg;
16590
16591 switch (cmd) {
16592 case CLI_INIT:
16593 e->command = "sip show settings";
16594 e->usage =
16595 "Usage: sip show settings\n"
16596 " Provides detailed list of the configuration of the SIP channel.\n";
16597 return NULL;
16598 case CLI_GENERATE:
16599 return NULL;
16600 }
16601
16602
16603 realtimepeers = ast_check_realtime("sippeers");
16604 realtimeregs = ast_check_realtime("sipregs");
16605
16606 if (a->argc != 3)
16607 return CLI_SHOWUSAGE;
16608 ast_cli(a->fd, "\n\nGlobal Settings:\n");
16609 ast_cli(a->fd, "----------------\n");
16610 ast_cli(a->fd, " UDP SIP Port: %d\n", ntohs(bindaddr.sin_port));
16611 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16612 ast_cli(a->fd, " TCP SIP Port: ");
16613 if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16614 ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16615 ast_cli(a->fd, " TCP Bindaddress: %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16616 } else {
16617 ast_cli(a->fd, "Disabled\n");
16618 }
16619 ast_cli(a->fd, " TLS SIP Port: ");
16620 if (default_tls_cfg.enabled != FALSE) {
16621 ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16622 ast_cli(a->fd, " TLS Bindaddress: %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16623 } else {
16624 ast_cli(a->fd, "Disabled\n");
16625 }
16626 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16627 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16628 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16629 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(sip_cfg.autocreatepeer));
16630 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
16631 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(sip_cfg.allowguest));
16632 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16633 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16634 ast_cli(a->fd, " Allow promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16635 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
16636 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16637 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
16638 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
16639 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16640 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16641 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16642 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(sip_cfg.directrtpsetup));
16643 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
16644 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16645 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16646 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
16647 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(sip_cfg.regextenonqualify));
16648 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
16649 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
16650 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
16651 ast_cli(a->fd, " Call Events: %s\n", sip_cfg.callevents ? "On" : "Off");
16652 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
16653
16654 ast_cli(a->fd, " T.38 support: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16655 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16656 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
16657
16658 if (!realtimepeers && !realtimeregs)
16659 ast_cli(a->fd, " SIP realtime: Disabled\n" );
16660 else
16661 ast_cli(a->fd, " SIP realtime: Enabled\n" );
16662 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
16663 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16664 ast_cli(a->fd, "---------------------------\n");
16665 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
16666 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
16667 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
16668 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
16669 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
16670 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
16671 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
16672 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
16673 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16674 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16675 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
16676 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
16677 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
16678 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16679
16680 ast_cli(a->fd, "\nNetwork Settings:\n");
16681 ast_cli(a->fd, "---------------------------\n");
16682
16683 if (localaddr == NULL)
16684 msg = "Disabled, no localnet list";
16685 else if (externip.sin_addr.s_addr == 0)
16686 msg = "Disabled, externip is 0.0.0.0";
16687 else if (stunaddr.sin_addr.s_addr != 0)
16688 msg = "Enabled using STUN";
16689 else if (!ast_strlen_zero(externhost))
16690 msg = "Enabled using externhost";
16691 else
16692 msg = "Enabled using externip";
16693 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
16694 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
16695 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16696 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
16697 {
16698 struct ast_ha *d;
16699 const char *prefix = "Localnet:";
16700 char buf[INET_ADDRSTRLEN];
16701
16702 for (d = localaddr; d ; prefix = "", d = d->next) {
16703 ast_cli(a->fd, " %-24s%s/%s\n",
16704 prefix, ast_inet_ntoa(d->netaddr),
16705 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16706 }
16707 }
16708 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16709
16710 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16711 ast_cli(a->fd, "---------------------------\n");
16712 ast_cli(a->fd, " Codecs: ");
16713 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16714 ast_cli(a->fd, "%s\n", codec_buf);
16715 ast_cli(a->fd, " Codec Order: ");
16716 print_codec_to_cli(a->fd, &default_prefs);
16717 ast_cli(a->fd, "\n");
16718 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
16719 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16720 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(sip_cfg.compactheaders));
16721 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16722 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16723 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16724 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
16725 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(sip_cfg.srvlookup));
16726 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16727 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
16728 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
16729 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
16730 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
16731 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
16732 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(sip_cfg.notifyringing));
16733 if (sip_cfg.notifyringing) {
16734 ast_cli(a->fd, " Include CID: %s%s\n",
16735 cli_yesno(sip_cfg.notifycid),
16736 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16737 }
16738 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(sip_cfg.notifyhold));
16739 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
16740 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
16741 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
16742 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16743 sip_cfg.outboundproxy.force ? "(forced)" : "");
16744 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
16745 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
16746 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
16747 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
16748 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
16749 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
16750 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
16751 ast_cli(a->fd, " No premature media: %s\n", global_prematuremediafilter ? "Yes" : "No");
16752
16753 ast_cli(a->fd, "\nDefault Settings:\n");
16754 ast_cli(a->fd, "-----------------\n");
16755 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
16756 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
16757 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
16758 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16759 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16760 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
16761 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16762 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" );
16763 ast_cli(a->fd, " Language: %s\n", default_language);
16764 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
16765 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
16766 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
16767 ast_cli(a->fd, " Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16768
16769 if (realtimepeers || realtimeregs) {
16770 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16771 ast_cli(a->fd, "----------------------\n");
16772 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
16773 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
16774 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16775 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16776 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16777 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16778 ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
16779 }
16780 ast_cli(a->fd, "\n----\n");
16781 return CLI_SUCCESS;
16782 }
16783
16784 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16785 {
16786 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
16787 char host[80];
16788
16789 switch (cmd) {
16790 case CLI_INIT:
16791 e->command = "sip show mwi";
16792 e->usage =
16793 "Usage: sip show mwi\n"
16794 " Provides a list of MWI subscriptions and status.\n";
16795 return NULL;
16796 case CLI_GENERATE:
16797 return NULL;
16798 }
16799
16800 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16801
16802 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16803 ASTOBJ_RDLOCK(iterator);
16804 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16805 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16806 ASTOBJ_UNLOCK(iterator);
16807 } while(0));
16808
16809 return CLI_SUCCESS;
16810 #undef FORMAT
16811 }
16812
16813
16814
16815 static const char *subscription_type2str(enum subscriptiontype subtype)
16816 {
16817 int i;
16818
16819 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16820 if (subscription_types[i].type == subtype) {
16821 return subscription_types[i].text;
16822 }
16823 }
16824 return subscription_types[0].text;
16825 }
16826
16827
16828 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16829 {
16830 int i;
16831
16832 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16833 if (subscription_types[i].type == subtype) {
16834 return &subscription_types[i];
16835 }
16836 }
16837 return &subscription_types[0];
16838 }
16839
16840
16841
16842
16843
16844
16845
16846
16847 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
16848 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
16849 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
16850 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
16851
16852
16853 static int show_channels_cb(void *__cur, void *__arg, int flags)
16854 {
16855 struct sip_pvt *cur = __cur;
16856 struct __show_chan_arg *arg = __arg;
16857 const struct sockaddr_in *dst = sip_real_dst(cur);
16858
16859
16860 if (cur->subscribed == NONE && !arg->subscriptions) {
16861
16862 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16863 char formatbuf[SIPBUFSIZE/2];
16864
16865 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
16866 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16867 cur->callid,
16868 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16869 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16870 cur->needdestroy ? "(d)" : "",
16871 cur->lastmsg ,
16872 referstatus
16873 );
16874 arg->numchans++;
16875 }
16876 if (cur->subscribed != NONE && arg->subscriptions) {
16877 struct ast_str *mailbox_str = ast_str_alloca(512);
16878 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16879 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16880 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16881 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16882 cur->callid,
16883
16884 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16885 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
16886 subscription_type2str(cur->subscribed),
16887 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16888 cur->expiry
16889 );
16890 arg->numchans++;
16891 }
16892 return 0;
16893 }
16894
16895
16896
16897
16898
16899
16900 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16901 {
16902 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16903
16904
16905 if (cmd == CLI_INIT) {
16906 e->command = "sip show {channels|subscriptions}";
16907 e->usage =
16908 "Usage: sip show channels\n"
16909 " Lists all currently active SIP calls (dialogs).\n"
16910 "Usage: sip show subscriptions\n"
16911 " Lists active SIP subscriptions.\n";
16912 return NULL;
16913 } else if (cmd == CLI_GENERATE)
16914 return NULL;
16915
16916 if (a->argc != e->args)
16917 return CLI_SHOWUSAGE;
16918 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16919 if (!arg.subscriptions)
16920 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16921 else
16922 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16923
16924
16925 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16926
16927
16928 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16929 (arg.subscriptions ? "subscription" : "dialog"),
16930 ESS(arg.numchans));
16931 return CLI_SUCCESS;
16932 #undef FORMAT
16933 #undef FORMAT2
16934 #undef FORMAT3
16935 }
16936
16937
16938
16939
16940
16941
16942 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16943 {
16944 int which=0;
16945 struct sip_pvt *cur;
16946 char *c = NULL;
16947 int wordlen = strlen(word);
16948 struct ao2_iterator i;
16949
16950 if (pos != 3) {
16951 return NULL;
16952 }
16953
16954 i = ao2_iterator_init(dialogs, 0);
16955 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16956 sip_pvt_lock(cur);
16957 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16958 c = ast_strdup(cur->callid);
16959 sip_pvt_unlock(cur);
16960 dialog_unref(cur, "drop ref in iterator loop break");
16961 break;
16962 }
16963 sip_pvt_unlock(cur);
16964 dialog_unref(cur, "drop ref in iterator loop");
16965 }
16966 ao2_iterator_destroy(&i);
16967 return c;
16968 }
16969
16970
16971
16972 static char *complete_sip_peer(const char *word, int state, int flags2)
16973 {
16974 char *result = NULL;
16975 int wordlen = strlen(word);
16976 int which = 0;
16977 struct ao2_iterator i = ao2_iterator_init(peers, 0);
16978 struct sip_peer *peer;
16979
16980 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16981
16982 if (!strncasecmp(word, peer->name, wordlen) &&
16983 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16984 ++which > state)
16985 result = ast_strdup(peer->name);
16986 unref_peer(peer, "toss iterator peer ptr before break");
16987 if (result) {
16988 break;
16989 }
16990 }
16991 ao2_iterator_destroy(&i);
16992 return result;
16993 }
16994
16995
16996 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16997 {
16998 char *result = NULL;
16999 int wordlen = strlen(word);
17000 int which = 0;
17001 struct ao2_iterator i;
17002 struct sip_peer *peer;
17003
17004 i = ao2_iterator_init(peers, 0);
17005 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17006 if (!strncasecmp(word, peer->name, wordlen) &&
17007 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
17008 ++which > state && peer->expire > 0)
17009 result = ast_strdup(peer->name);
17010 if (result) {
17011 unref_peer(peer, "toss iterator peer ptr before break");
17012 break;
17013 }
17014 unref_peer(peer, "toss iterator peer ptr");
17015 }
17016 ao2_iterator_destroy(&i);
17017 return result;
17018 }
17019
17020
17021 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
17022 {
17023 if (pos == 3)
17024 return complete_sipch(line, word, pos, state);
17025
17026 return NULL;
17027 }
17028
17029
17030 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
17031 {
17032 if (pos == 3) {
17033 return complete_sip_peer(word, state, 0);
17034 }
17035
17036 return NULL;
17037 }
17038
17039
17040 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
17041 {
17042 if (pos == 2)
17043 return complete_sip_registered_peer(word, state, 0);
17044
17045 return NULL;
17046 }
17047
17048
17049 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
17050 {
17051 char *c = NULL;
17052
17053 if (pos == 2) {
17054 int which = 0;
17055 char *cat = NULL;
17056 int wordlen = strlen(word);
17057
17058
17059
17060 if (!notify_types)
17061 return NULL;
17062
17063 while ( (cat = ast_category_browse(notify_types, cat)) ) {
17064 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
17065 c = ast_strdup(cat);
17066 break;
17067 }
17068 }
17069 return c;
17070 }
17071
17072 if (pos > 2)
17073 return complete_sip_peer(word, state, 0);
17074
17075 return NULL;
17076 }
17077
17078
17079 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17080 {
17081 struct sip_pvt *cur;
17082 size_t len;
17083 int found = 0;
17084 struct ao2_iterator i;
17085
17086 switch (cmd) {
17087 case CLI_INIT:
17088 e->command = "sip show channel";
17089 e->usage =
17090 "Usage: sip show channel <call-id>\n"
17091 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
17092 return NULL;
17093 case CLI_GENERATE:
17094 return complete_sipch(a->line, a->word, a->pos, a->n);
17095 }
17096
17097 if (a->argc != 4)
17098 return CLI_SHOWUSAGE;
17099 len = strlen(a->argv[3]);
17100
17101 i = ao2_iterator_init(dialogs, 0);
17102 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17103 sip_pvt_lock(cur);
17104
17105 if (!strncasecmp(cur->callid, a->argv[3], len)) {
17106 char formatbuf[SIPBUFSIZE/2];
17107 ast_cli(a->fd, "\n");
17108 if (cur->subscribed != NONE)
17109 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
17110 else
17111 ast_cli(a->fd, " * SIP Call\n");
17112 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
17113 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
17114 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
17115 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
17116 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
17117 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
17118 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
17119 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
17120 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
17121 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
17122 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
17123 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
17124 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
17125 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
17126 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
17127 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)" );
17128 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
17129 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
17130 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
17131 if (!ast_strlen_zero(cur->username))
17132 ast_cli(a->fd, " Username: %s\n", cur->username);
17133 if (!ast_strlen_zero(cur->peername))
17134 ast_cli(a->fd, " Peername: %s\n", cur->peername);
17135 if (!ast_strlen_zero(cur->uri))
17136 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
17137 if (!ast_strlen_zero(cur->cid_num))
17138 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
17139 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
17140 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
17141 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
17142 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
17143 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
17144 ast_cli(a->fd, " SIP Options: ");
17145 if (cur->sipoptions) {
17146 int x;
17147 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17148 if (cur->sipoptions & sip_options[x].id)
17149 ast_cli(a->fd, "%s ", sip_options[x].text);
17150 }
17151 ast_cli(a->fd, "\n");
17152 } else
17153 ast_cli(a->fd, "(none)\n");
17154
17155 if (!cur->stimer)
17156 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
17157 else {
17158 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
17159 if (cur->stimer->st_active == TRUE) {
17160 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
17161 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
17162 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
17163 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
17164 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
17165 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
17166 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
17167 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
17168 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
17169 }
17170 }
17171
17172 ast_cli(a->fd, "\n\n");
17173
17174 found++;
17175 }
17176
17177 sip_pvt_unlock(cur);
17178
17179 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
17180 }
17181 ao2_iterator_destroy(&i);
17182
17183 if (!found)
17184 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17185
17186 return CLI_SUCCESS;
17187 }
17188
17189
17190 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17191 {
17192 struct sip_pvt *cur;
17193 size_t len;
17194 int found = 0;
17195 struct ao2_iterator i;
17196
17197 switch (cmd) {
17198 case CLI_INIT:
17199 e->command = "sip show history";
17200 e->usage =
17201 "Usage: sip show history <call-id>\n"
17202 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
17203 return NULL;
17204 case CLI_GENERATE:
17205 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
17206 }
17207
17208 if (a->argc != 4)
17209 return CLI_SHOWUSAGE;
17210
17211 if (!recordhistory)
17212 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
17213
17214 len = strlen(a->argv[3]);
17215
17216 i = ao2_iterator_init(dialogs, 0);
17217 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17218 sip_pvt_lock(cur);
17219 if (!strncasecmp(cur->callid, a->argv[3], len)) {
17220 struct sip_history *hist;
17221 int x = 0;
17222
17223 ast_cli(a->fd, "\n");
17224 if (cur->subscribed != NONE)
17225 ast_cli(a->fd, " * Subscription\n");
17226 else
17227 ast_cli(a->fd, " * SIP Call\n");
17228 if (cur->history)
17229 AST_LIST_TRAVERSE(cur->history, hist, list)
17230 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
17231 if (x == 0)
17232 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
17233 found++;
17234 }
17235 sip_pvt_unlock(cur);
17236 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
17237 }
17238 ao2_iterator_destroy(&i);
17239
17240 if (!found)
17241 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17242
17243 return CLI_SUCCESS;
17244 }
17245
17246
17247 static void sip_dump_history(struct sip_pvt *dialog)
17248 {
17249 int x = 0;
17250 struct sip_history *hist;
17251 static int errmsg = 0;
17252
17253 if (!dialog)
17254 return;
17255
17256 if (!option_debug && !sipdebug) {
17257 if (!errmsg) {
17258 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
17259 errmsg = 1;
17260 }
17261 return;
17262 }
17263
17264 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
17265 if (dialog->subscribed)
17266 ast_debug(1, " * Subscription\n");
17267 else
17268 ast_debug(1, " * SIP Call\n");
17269 if (dialog->history)
17270 AST_LIST_TRAVERSE(dialog->history, hist, list)
17271 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
17272 if (!x)
17273 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
17274 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
17275 }
17276
17277
17278
17279 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
17280 {
17281 char buf[1024];
17282 unsigned int event;
17283 const char *c = get_header(req, "Content-Type");
17284
17285
17286 if (!strcasecmp(c, "application/dtmf-relay") ||
17287 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
17288 unsigned int duration = 0;
17289
17290 if (!p->owner) {
17291 transmit_response(p, "481 Call leg/transaction does not exist", req);
17292 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17293 return;
17294 }
17295
17296
17297 if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
17298 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
17299 transmit_response(p, "200 OK", req);
17300 return;
17301 } else {
17302 ast_copy_string(buf, c, sizeof(buf));
17303 }
17304
17305 if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
17306 duration = atoi(c);
17307 if (!duration)
17308 duration = 100;
17309
17310
17311 if (ast_strlen_zero(buf)) {
17312 transmit_response(p, "200 OK", req);
17313 return;
17314 }
17315
17316 if (buf[0] == '*')
17317 event = 10;
17318 else if (buf[0] == '#')
17319 event = 11;
17320 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
17321 event = 12 + buf[0] - 'A';
17322 else if (buf[0] == '!')
17323 event = 16;
17324 else
17325 event = atoi(buf);
17326 if (event == 16) {
17327
17328 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
17329 ast_queue_frame(p->owner, &f);
17330 if (sipdebug)
17331 ast_verbose("* DTMF-relay event received: FLASH\n");
17332 } else {
17333
17334 struct ast_frame f = { AST_FRAME_DTMF, };
17335 if (event < 10) {
17336 f.subclass = '0' + event;
17337 } else if (event < 11) {
17338 f.subclass = '*';
17339 } else if (event < 12) {
17340 f.subclass = '#';
17341 } else if (event < 16) {
17342 f.subclass = 'A' + (event - 12);
17343 }
17344 f.len = duration;
17345 ast_queue_frame(p->owner, &f);
17346 if (sipdebug)
17347 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
17348 }
17349 transmit_response(p, "200 OK", req);
17350 return;
17351 } else if (!strcasecmp(c, "application/dtmf")) {
17352
17353 unsigned int duration = 0;
17354
17355 if (!p->owner) {
17356 transmit_response(p, "481 Call leg/transaction does not exist", req);
17357 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17358 return;
17359 }
17360
17361 get_msg_text(buf, sizeof(buf), req, TRUE);
17362 duration = 100;
17363
17364 if (ast_strlen_zero(buf)) {
17365 transmit_response(p, "200 OK", req);
17366 return;
17367 }
17368 event = atoi(buf);
17369 if (event == 16) {
17370
17371 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
17372 ast_queue_frame(p->owner, &f);
17373 if (sipdebug)
17374 ast_verbose("* DTMF-relay event received: FLASH\n");
17375 } else {
17376
17377 struct ast_frame f = { AST_FRAME_DTMF, };
17378 if (event < 10) {
17379 f.subclass = '0' + event;
17380 } else if (event < 11) {
17381 f.subclass = '*';
17382 } else if (event < 12) {
17383 f.subclass = '#';
17384 } else if (event < 16) {
17385 f.subclass = 'A' + (event - 12);
17386 }
17387 f.len = duration;
17388 ast_queue_frame(p->owner, &f);
17389 if (sipdebug)
17390 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
17391 }
17392 transmit_response(p, "200 OK", req);
17393 return;
17394
17395 } else if (!strcasecmp(c, "application/media_control+xml")) {
17396
17397 if (p->owner)
17398 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
17399 transmit_response(p, "200 OK", req);
17400 return;
17401 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
17402
17403 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
17404 if (p->owner && p->owner->cdr)
17405 ast_cdr_setuserfield(p->owner, c);
17406 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
17407 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
17408 transmit_response(p, "200 OK", req);
17409 } else {
17410 transmit_response(p, "403 Forbidden", req);
17411 }
17412 return;
17413 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
17414
17415
17416
17417
17418
17419
17420
17421 struct ast_call_feature *feat;
17422 int j;
17423 struct ast_frame f = { AST_FRAME_DTMF, };
17424
17425 ast_rdlock_call_features();
17426 feat = ast_find_call_feature("automon");
17427 if (!feat || ast_strlen_zero(feat->exten)) {
17428 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
17429
17430 transmit_response(p, "403 Forbidden", req);
17431 ast_unlock_call_features();
17432 return;
17433 }
17434
17435 f.len = 100;
17436 for (j=0; j < strlen(feat->exten); j++) {
17437 f.subclass = feat->exten[j];
17438 ast_queue_frame(p->owner, &f);
17439 if (sipdebug)
17440 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
17441 }
17442 ast_unlock_call_features();
17443
17444 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
17445 transmit_response(p, "200 OK", req);
17446 return;
17447 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
17448
17449 transmit_response(p, "200 OK", req);
17450 return;
17451 }
17452
17453
17454
17455
17456 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
17457 transmit_response(p, "415 Unsupported media type", req);
17458 return;
17459 }
17460
17461
17462 static char *sip_do_debug_ip(int fd, char *arg)
17463 {
17464 struct hostent *hp;
17465 struct ast_hostent ahp;
17466 int port = 0;
17467 char *p;
17468
17469 p = arg;
17470 strsep(&p, ":");
17471 if (p)
17472 port = atoi(p);
17473 hp = ast_gethostbyname(arg, &ahp);
17474 if (hp == NULL)
17475 return CLI_SHOWUSAGE;
17476
17477 debugaddr.sin_family = AF_INET;
17478 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
17479 debugaddr.sin_port = htons(port);
17480 if (port == 0)
17481 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
17482 else
17483 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
17484
17485 sipdebug |= sip_debug_console;
17486
17487 return CLI_SUCCESS;
17488 }
17489
17490
17491 static char *sip_do_debug_peer(int fd, char *arg)
17492 {
17493 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
17494 if (!peer)
17495 ast_cli(fd, "No such peer '%s'\n", arg);
17496 else if (peer->addr.sin_addr.s_addr == 0)
17497 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
17498 else {
17499 debugaddr.sin_family = AF_INET;
17500 debugaddr.sin_addr = peer->addr.sin_addr;
17501 debugaddr.sin_port = peer->addr.sin_port;
17502 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
17503 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
17504 sipdebug |= sip_debug_console;
17505 }
17506 if (peer)
17507 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
17508 return CLI_SUCCESS;
17509 }
17510
17511
17512 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17513 {
17514 int oldsipdebug = sipdebug & sip_debug_console;
17515 char *what;
17516
17517 if (cmd == CLI_INIT) {
17518 e->command = "sip set debug {on|off|ip|peer}";
17519 e->usage =
17520 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17521 " Globally disables dumping of SIP packets,\n"
17522 " or enables it either globally or for a (single)\n"
17523 " IP address or registered peer.\n";
17524 return NULL;
17525 } else if (cmd == CLI_GENERATE) {
17526 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
17527 return complete_sip_peer(a->word, a->n, 0);
17528 return NULL;
17529 }
17530
17531 what = a->argv[e->args-1];
17532 if (a->argc == e->args) {
17533 if (!strcasecmp(what, "on")) {
17534 sipdebug |= sip_debug_console;
17535 sipdebug_text = 1;
17536 memset(&debugaddr, 0, sizeof(debugaddr));
17537 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17538 return CLI_SUCCESS;
17539 } else if (!strcasecmp(what, "off")) {
17540 sipdebug &= ~sip_debug_console;
17541 sipdebug_text = 0;
17542 ast_cli(a->fd, "SIP Debugging Disabled\n");
17543 return CLI_SUCCESS;
17544 }
17545 } else if (a->argc == e->args +1) {
17546 if (!strcasecmp(what, "ip"))
17547 return sip_do_debug_ip(a->fd, a->argv[e->args]);
17548 else if (!strcasecmp(what, "peer"))
17549 return sip_do_debug_peer(a->fd, a->argv[e->args]);
17550 }
17551 return CLI_SHOWUSAGE;
17552 }
17553
17554
17555 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17556 {
17557 struct ast_variable *varlist;
17558 int i;
17559
17560 switch (cmd) {
17561 case CLI_INIT:
17562 e->command = "sip notify";
17563 e->usage =
17564 "Usage: sip notify <type> <peer> [<peer>...]\n"
17565 " Send a NOTIFY message to a SIP peer or peers\n"
17566 " Message types are defined in sip_notify.conf\n";
17567 return NULL;
17568 case CLI_GENERATE:
17569 return complete_sipnotify(a->line, a->word, a->pos, a->n);
17570 }
17571
17572 if (a->argc < 4)
17573 return CLI_SHOWUSAGE;
17574
17575 if (!notify_types) {
17576 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17577 return CLI_FAILURE;
17578 }
17579
17580 varlist = ast_variable_browse(notify_types, a->argv[2]);
17581
17582 if (!varlist) {
17583 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17584 return CLI_FAILURE;
17585 }
17586
17587 for (i = 3; i < a->argc; i++) {
17588 struct sip_pvt *p;
17589
17590 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17591 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17592 return CLI_FAILURE;
17593 }
17594
17595 if (create_addr(p, a->argv[i], NULL, 1)) {
17596
17597 dialog_unlink_all(p, TRUE, TRUE);
17598 dialog_unref(p, "unref dialog inside for loop" );
17599
17600 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17601 continue;
17602 }
17603
17604
17605 ast_set_flag(&p->flags[0], SIP_OUTGOING);
17606
17607
17608 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17609 build_via(p);
17610 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17611 build_callid_pvt(p);
17612 ao2_t_link(dialogs, p, "Linking in new name");
17613 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17614 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17615 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17616 transmit_notify_custom(p, varlist);
17617 }
17618
17619 return CLI_SUCCESS;
17620 }
17621
17622
17623 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17624 {
17625 switch (cmd) {
17626 case CLI_INIT:
17627 e->command = "sip set history {on|off}";
17628 e->usage =
17629 "Usage: sip set history {on|off}\n"
17630 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17631 " Use 'sip show history' to view the history of a call number.\n";
17632 return NULL;
17633 case CLI_GENERATE:
17634 return NULL;
17635 }
17636
17637 if (a->argc != e->args)
17638 return CLI_SHOWUSAGE;
17639
17640 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17641 recordhistory = TRUE;
17642 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17643 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17644 recordhistory = FALSE;
17645 ast_cli(a->fd, "SIP History Recording Disabled\n");
17646 } else {
17647 return CLI_SHOWUSAGE;
17648 }
17649 return CLI_SUCCESS;
17650 }
17651
17652
17653 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17654 {
17655 char *header, *respheader;
17656 char digest[1024];
17657
17658 p->authtries++;
17659 auth_headers(code, &header, &respheader);
17660 memset(digest, 0, sizeof(digest));
17661 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17662
17663
17664 if (sip_debug_test_pvt(p) && p->registry)
17665 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17666
17667 return -1;
17668 }
17669 if (p->do_history)
17670 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17671 if (sip_debug_test_pvt(p) && p->registry)
17672 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17673 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
17674 }
17675
17676
17677 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17678 {
17679 char *header, *respheader;
17680 char digest[1024];
17681
17682 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17683 return -2;
17684
17685 p->authtries++;
17686 auth_headers(code, &header, &respheader);
17687 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17688 memset(digest, 0, sizeof(digest));
17689 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17690
17691 return -1;
17692 }
17693
17694 p->options->auth = digest;
17695 p->options->authheader = respheader;
17696 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
17697 }
17698
17699
17700
17701
17702
17703 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
17704 {
17705 char tmp[512];
17706 char *c;
17707 char oldnonce[256];
17708
17709
17710 const struct x {
17711 const char *key;
17712 const ast_string_field *field;
17713 } *i, keys[] = {
17714 { "realm=", &p->realm },
17715 { "nonce=", &p->nonce },
17716 { "opaque=", &p->opaque },
17717 { "qop=", &p->qop },
17718 { "domain=", &p->domain },
17719 { NULL, 0 },
17720 };
17721
17722 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17723 if (ast_strlen_zero(tmp))
17724 return -1;
17725 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17726 ast_log(LOG_WARNING, "missing Digest.\n");
17727 return -1;
17728 }
17729 c = tmp + strlen("Digest ");
17730 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17731 while (c && *(c = ast_skip_blanks(c))) {
17732 for (i = keys; i->key != NULL; i++) {
17733 char *src, *separator;
17734 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17735 continue;
17736
17737 c += strlen(i->key);
17738 if (*c == '"') {
17739 src = ++c;
17740 separator = "\"";
17741 } else {
17742 src = c;
17743 separator = ",";
17744 }
17745 strsep(&c, separator);
17746 ast_string_field_ptr_set(p, i->field, src);
17747 break;
17748 }
17749 if (i->key == NULL)
17750 strsep(&c, ",");
17751 }
17752
17753 if (strcmp(p->nonce, oldnonce))
17754 p->noncecount = 0;
17755
17756
17757 if (p->registry) {
17758 struct sip_registry *r = p->registry;
17759
17760 if (strcmp(r->nonce, p->nonce)) {
17761 ast_string_field_set(r, realm, p->realm);
17762 ast_string_field_set(r, nonce, p->nonce);
17763 ast_string_field_set(r, domain, p->domain);
17764 ast_string_field_set(r, opaque, p->opaque);
17765 ast_string_field_set(r, qop, p->qop);
17766 r->noncecount = 0;
17767 }
17768 }
17769 return build_reply_digest(p, sipmethod, digest, digest_len);
17770 }
17771
17772
17773
17774
17775
17776
17777 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17778 {
17779 char a1[256];
17780 char a2[256];
17781 char a1_hash[256];
17782 char a2_hash[256];
17783 char resp[256];
17784 char resp_hash[256];
17785 char uri[256];
17786 char opaque[256] = "";
17787 char cnonce[80];
17788 const char *username;
17789 const char *secret;
17790 const char *md5secret;
17791 struct sip_auth *auth = NULL;
17792
17793 if (!ast_strlen_zero(p->domain))
17794 ast_copy_string(uri, p->domain, sizeof(uri));
17795 else if (!ast_strlen_zero(p->uri))
17796 ast_copy_string(uri, p->uri, sizeof(uri));
17797 else
17798 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17799
17800 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17801
17802
17803 if(!(auth = find_realm_authentication(p->peerauth, p->realm)))
17804 auth = find_realm_authentication(authl, p->realm);
17805
17806 if (auth) {
17807 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17808 username = auth->username;
17809 secret = auth->secret;
17810 md5secret = auth->md5secret;
17811 if (sipdebug)
17812 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17813 } else {
17814
17815 username = p->authname;
17816 secret = p->relatedpeer
17817 && !ast_strlen_zero(p->relatedpeer->remotesecret)
17818 ? p->relatedpeer->remotesecret : p->peersecret;
17819 md5secret = p->peermd5secret;
17820 }
17821 if (ast_strlen_zero(username))
17822 return -1;
17823
17824
17825 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17826 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17827 if (!ast_strlen_zero(md5secret))
17828 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17829 else
17830 ast_md5_hash(a1_hash, a1);
17831 ast_md5_hash(a2_hash, a2);
17832
17833 p->noncecount++;
17834 if (!ast_strlen_zero(p->qop))
17835 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17836 else
17837 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17838 ast_md5_hash(resp_hash, resp);
17839
17840
17841 if (!ast_strlen_zero(p->opaque)) {
17842 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17843 }
17844
17845
17846 if (!ast_strlen_zero(p->qop))
17847 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);
17848 else
17849 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);
17850
17851 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17852
17853 return 0;
17854 }
17855
17856
17857 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
17858 {
17859 struct sip_pvt *p;
17860 const char *content = NULL;
17861 AST_DECLARE_APP_ARGS(args,
17862 AST_APP_ARG(header);
17863 AST_APP_ARG(number);
17864 );
17865 int i, number, start = 0;
17866
17867 if (ast_strlen_zero(data)) {
17868 ast_log(LOG_WARNING, "This function requires a header name.\n");
17869 return -1;
17870 }
17871
17872 ast_channel_lock(chan);
17873 if (!IS_SIP_TECH(chan->tech)) {
17874 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17875 ast_channel_unlock(chan);
17876 return -1;
17877 }
17878
17879 AST_STANDARD_APP_ARGS(args, data);
17880 if (!args.number) {
17881 number = 1;
17882 } else {
17883 sscanf(args.number, "%30d", &number);
17884 if (number < 1)
17885 number = 1;
17886 }
17887
17888 p = chan->tech_pvt;
17889
17890
17891 if (!p) {
17892 ast_channel_unlock(chan);
17893 return -1;
17894 }
17895
17896 for (i = 0; i < number; i++)
17897 content = __get_header(&p->initreq, args.header, &start);
17898
17899 if (ast_strlen_zero(content)) {
17900 ast_channel_unlock(chan);
17901 return -1;
17902 }
17903
17904 ast_copy_string(buf, content, len);
17905 ast_channel_unlock(chan);
17906
17907 return 0;
17908 }
17909
17910 static struct ast_custom_function sip_header_function = {
17911 .name = "SIP_HEADER",
17912 .read = func_header_read,
17913 };
17914
17915
17916 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17917 {
17918 if (ast_strlen_zero(data)) {
17919 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17920 return -1;
17921 }
17922 if (check_sip_domain(data, NULL, 0))
17923 ast_copy_string(buf, data, len);
17924 else
17925 buf[0] = '\0';
17926 return 0;
17927 }
17928
17929 static struct ast_custom_function checksipdomain_function = {
17930 .name = "CHECKSIPDOMAIN",
17931 .read = func_check_sipdomain,
17932 };
17933
17934
17935 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17936 {
17937 struct sip_peer *peer;
17938 char *colname;
17939
17940 if ((colname = strchr(data, ':'))) {
17941 static int deprecation_warning = 0;
17942 *colname++ = '\0';
17943 if (deprecation_warning++ % 10 == 0)
17944 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
17945 } else if ((colname = strchr(data, ',')))
17946 *colname++ = '\0';
17947 else
17948 colname = "ip";
17949
17950 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17951 return -1;
17952
17953 if (!strcasecmp(colname, "ip")) {
17954 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17955 } else if (!strcasecmp(colname, "port")) {
17956 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17957 } else if (!strcasecmp(colname, "status")) {
17958 peer_status(peer, buf, len);
17959 } else if (!strcasecmp(colname, "language")) {
17960 ast_copy_string(buf, peer->language, len);
17961 } else if (!strcasecmp(colname, "regexten")) {
17962 ast_copy_string(buf, peer->regexten, len);
17963 } else if (!strcasecmp(colname, "limit")) {
17964 snprintf(buf, len, "%d", peer->call_limit);
17965 } else if (!strcasecmp(colname, "busylevel")) {
17966 snprintf(buf, len, "%d", peer->busy_level);
17967 } else if (!strcasecmp(colname, "curcalls")) {
17968 snprintf(buf, len, "%d", peer->inUse);
17969 } else if (!strcasecmp(colname, "accountcode")) {
17970 ast_copy_string(buf, peer->accountcode, len);
17971 } else if (!strcasecmp(colname, "callgroup")) {
17972 ast_print_group(buf, len, peer->callgroup);
17973 } else if (!strcasecmp(colname, "pickupgroup")) {
17974 ast_print_group(buf, len, peer->pickupgroup);
17975 } else if (!strcasecmp(colname, "useragent")) {
17976 ast_copy_string(buf, peer->useragent, len);
17977 } else if (!strcasecmp(colname, "mailbox")) {
17978 struct ast_str *mailbox_str = ast_str_alloca(512);
17979 peer_mailboxes_to_str(&mailbox_str, peer);
17980 ast_copy_string(buf, mailbox_str->str, len);
17981 } else if (!strcasecmp(colname, "context")) {
17982 ast_copy_string(buf, peer->context, len);
17983 } else if (!strcasecmp(colname, "expire")) {
17984 snprintf(buf, len, "%d", peer->expire);
17985 } else if (!strcasecmp(colname, "dynamic")) {
17986 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17987 } else if (!strcasecmp(colname, "callerid_name")) {
17988 ast_copy_string(buf, peer->cid_name, len);
17989 } else if (!strcasecmp(colname, "callerid_num")) {
17990 ast_copy_string(buf, peer->cid_num, len);
17991 } else if (!strcasecmp(colname, "codecs")) {
17992 ast_getformatname_multiple(buf, len -1, peer->capability);
17993 } else if (!strncasecmp(colname, "chanvar[", 8)) {
17994 char *chanvar=colname + 8;
17995 struct ast_variable *v;
17996
17997 chanvar = strsep(&chanvar, "]");
17998 for (v = peer->chanvars ; v ; v = v->next) {
17999 if (!strcasecmp(v->name, chanvar)) {
18000 ast_copy_string(buf, v->value, len);
18001 }
18002 }
18003 } else if (!strncasecmp(colname, "codec[", 6)) {
18004 char *codecnum;
18005 int codec = 0;
18006
18007 codecnum = colname + 6;
18008 codecnum = strsep(&codecnum, "]");
18009 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
18010 ast_copy_string(buf, ast_getformatname(codec), len);
18011 } else {
18012 buf[0] = '\0';
18013 }
18014 } else {
18015 buf[0] = '\0';
18016 }
18017
18018 unref_peer(peer, "unref_peer from function_sippeer, just before return");
18019
18020 return 0;
18021 }
18022
18023
18024 static struct ast_custom_function sippeer_function = {
18025 .name = "SIPPEER",
18026 .read = function_sippeer,
18027 };
18028
18029
18030 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
18031 {
18032 struct sip_pvt *p;
18033 static int deprecated = 0;
18034
18035 *buf = 0;
18036
18037 if (!data) {
18038 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
18039 return -1;
18040 }
18041
18042 ast_channel_lock(chan);
18043 if (!IS_SIP_TECH(chan->tech)) {
18044 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
18045 ast_channel_unlock(chan);
18046 return -1;
18047 }
18048
18049 if (deprecated++ % 20 == 0) {
18050
18051 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
18052 }
18053
18054 p = chan->tech_pvt;
18055
18056
18057 if (!p) {
18058 ast_channel_unlock(chan);
18059 return -1;
18060 }
18061
18062 if (!strcasecmp(data, "peerip")) {
18063 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
18064 } else if (!strcasecmp(data, "recvip")) {
18065 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
18066 } else if (!strcasecmp(data, "from")) {
18067 ast_copy_string(buf, p->from, len);
18068 } else if (!strcasecmp(data, "uri")) {
18069 ast_copy_string(buf, p->uri, len);
18070 } else if (!strcasecmp(data, "useragent")) {
18071 ast_copy_string(buf, p->useragent, len);
18072 } else if (!strcasecmp(data, "peername")) {
18073 ast_copy_string(buf, p->peername, len);
18074 } else if (!strcasecmp(data, "t38passthrough")) {
18075 if (p->t38.state == T38_DISABLED) {
18076 ast_copy_string(buf, "0", len);
18077 } else {
18078 ast_copy_string(buf, "1", len);
18079 }
18080 } else {
18081 ast_channel_unlock(chan);
18082 return -1;
18083 }
18084 ast_channel_unlock(chan);
18085
18086 return 0;
18087 }
18088
18089
18090 static struct ast_custom_function sipchaninfo_function = {
18091 .name = "SIPCHANINFO",
18092 .read = function_sipchaninfo_read,
18093 };
18094
18095
18096
18097
18098
18099
18100
18101 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
18102 {
18103 char tmp[SIPBUFSIZE];
18104 char *s, *e, *t, *trans;
18105 char *domain;
18106 enum sip_transport transport = SIP_TRANSPORT_UDP;
18107
18108 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
18109 if ((t = strchr(tmp, ',')))
18110 *t = '\0';
18111
18112 s = get_in_brackets(tmp);
18113 if ((trans = strcasestr(s, ";transport="))) do {
18114 trans += 11;
18115
18116 if ((e = strchr(trans, ';')))
18117 *e = '\0';
18118
18119 if (!strncasecmp(trans, "tcp", 3))
18120 transport = SIP_TRANSPORT_TCP;
18121 else if (!strncasecmp(trans, "tls", 3))
18122 transport = SIP_TRANSPORT_TLS;
18123 else {
18124 if (strncasecmp(trans, "udp", 3))
18125 ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
18126
18127 transport = SIP_TRANSPORT_UDP;
18128 }
18129 } while(0);
18130 s = remove_uri_parameters(s);
18131
18132 if (p->socket.tcptls_session) {
18133 ao2_ref(p->socket.tcptls_session, -1);
18134 p->socket.tcptls_session = NULL;
18135 }
18136
18137 set_socket_transport(&p->socket, transport);
18138
18139 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
18140 char *host = NULL;
18141 if (!strncasecmp(s, "sip:", 4))
18142 s += 4;
18143 else if (!strncasecmp(s, "sips:", 5))
18144 s += 5;
18145 e = strchr(s, '/');
18146 if (e)
18147 *e = '\0';
18148 if ((host = strchr(s, '@'))) {
18149 *host++ = '\0';
18150 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
18151 if (p->owner)
18152 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
18153 } else {
18154 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
18155 if (p->owner)
18156 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
18157 }
18158 } else {
18159 e = strchr(tmp, '@');
18160 if (e) {
18161 *e++ = '\0';
18162 domain = e;
18163 } else {
18164
18165 domain = tmp;
18166 }
18167 e = strchr(tmp, '/');
18168 if (e)
18169 *e = '\0';
18170
18171 if (!strncasecmp(s, "sip:", 4))
18172 s += 4;
18173 else if (!strncasecmp(s, "sips:", 5))
18174 s += 5;
18175 e = strchr(s, ';');
18176 if (e)
18177 *e = '\0';
18178 ast_uri_decode(s);
18179 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
18180 if (p->owner) {
18181 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
18182 ast_string_field_set(p->owner, call_forward, s);
18183 }
18184 }
18185 }
18186
18187
18188
18189
18190
18191
18192 static void check_pendings(struct sip_pvt *p)
18193 {
18194 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18195
18196 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
18197 p->invitestate = INV_CANCELLED;
18198 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
18199
18200
18201 } else {
18202
18203
18204 if (p->pendinginvite)
18205 return;
18206
18207 if (p->owner) {
18208 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
18209 }
18210
18211 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
18212 }
18213 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
18214 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18215 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
18216
18217 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
18218 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
18219 } else {
18220 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
18221
18222 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
18223 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
18224 }
18225 }
18226 }
18227
18228
18229
18230
18231
18232 static int sip_reinvite_retry(const void *data)
18233 {
18234 struct sip_pvt *p = (struct sip_pvt *) data;
18235 struct ast_channel *owner;
18236
18237 sip_pvt_lock(p);
18238 while ((owner = p->owner) && ast_channel_trylock(owner)) {
18239 sip_pvt_unlock(p);
18240 usleep(1);
18241 sip_pvt_lock(p);
18242 }
18243 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18244 p->waitid = -1;
18245 check_pendings(p);
18246 sip_pvt_unlock(p);
18247 if (owner) {
18248 ast_channel_unlock(owner);
18249 }
18250 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
18251 return 0;
18252 }
18253
18254
18255
18256 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18257 {
18258 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
18259 int res = 0;
18260 int xmitres = 0;
18261 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
18262 char *p_hdrval;
18263 int rtn;
18264
18265 if (reinvite)
18266 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
18267 else
18268 ast_debug(4, "SIP response %d to standard invite\n", resp);
18269
18270 if (p->alreadygone) {
18271 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
18272 return;
18273 }
18274
18275
18276
18277 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"));
18278
18279
18280
18281
18282 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
18283 resp = 183;
18284
18285
18286 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
18287 p->invitestate = INV_PROCEEDING;
18288
18289
18290 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
18291 p->invitestate = INV_COMPLETED;
18292
18293
18294 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
18295 p->pendinginvite = 0;
18296
18297 switch (resp) {
18298 case 100:
18299 case 101:
18300 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18301 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18302 check_pendings(p);
18303 break;
18304
18305 case 180:
18306 case 182:
18307 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18308 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18309 if (!req->ignore && p->owner) {
18310 ast_queue_control(p->owner, AST_CONTROL_RINGING);
18311 if (p->owner->_state != AST_STATE_UP) {
18312 ast_setstate(p->owner, AST_STATE_RINGING);
18313 }
18314 }
18315 if (find_sdp(req)) {
18316 if (p->invitestate != INV_CANCELLED)
18317 p->invitestate = INV_EARLY_MEDIA;
18318 res = process_sdp(p, req, SDP_T38_NONE);
18319 if (!req->ignore && p->owner) {
18320
18321 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18322 }
18323 }
18324 check_pendings(p);
18325 break;
18326
18327 case 183:
18328 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18329 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18330 if (find_sdp(req)) {
18331 if (p->invitestate != INV_CANCELLED)
18332 p->invitestate = INV_EARLY_MEDIA;
18333 res = process_sdp(p, req, SDP_T38_NONE);
18334 if (!req->ignore && p->owner) {
18335
18336 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18337 }
18338 } else {
18339
18340
18341
18342
18343 if (!req->ignore && p->owner) {
18344 ast_queue_control(p->owner, AST_CONTROL_RINGING);
18345 }
18346 }
18347 check_pendings(p);
18348 break;
18349
18350 case 200:
18351 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18352 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18353 p->authtries = 0;
18354 if (find_sdp(req)) {
18355 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
18356 if (!reinvite)
18357
18358
18359 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18360 }
18361
18362
18363
18364
18365 if (outgoing) {
18366 update_call_counter(p, DEC_CALL_RINGING);
18367 parse_ok_contact(p, req);
18368
18369 if (!reinvite)
18370 build_route(p, req, 1);
18371
18372 if(set_address_from_contact(p)) {
18373
18374
18375 if (!p->route && !req->ignore)
18376 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18377 }
18378
18379 }
18380
18381 if (!req->ignore && p->owner) {
18382 if (!reinvite) {
18383 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
18384 if (sip_cfg.callevents)
18385 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
18386 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
18387 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
18388 } else {
18389 ast_queue_frame(p->owner, &ast_null_frame);
18390 }
18391 } else {
18392
18393
18394
18395 if (!req->ignore)
18396 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18397 }
18398
18399
18400 if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
18401 p_hdrval = (char*)get_header(req, "Session-Expires");
18402 if (!ast_strlen_zero(p_hdrval)) {
18403
18404 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
18405 int tmp_st_interval = 0;
18406 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
18407 if (rtn != 0) {
18408 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18409 }
18410 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
18411 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
18412 p->stimer->st_ref = tmp_st_ref;
18413 }
18414 if (tmp_st_interval) {
18415 p->stimer->st_interval = tmp_st_interval;
18416 }
18417 p->stimer->st_active = TRUE;
18418 p->stimer->st_active_peer_ua = TRUE;
18419 start_session_timer(p);
18420 } else {
18421
18422 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
18423 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
18424 p->stimer->st_active_peer_ua = FALSE;
18425 start_session_timer(p);
18426 }
18427 }
18428 }
18429
18430
18431
18432 p->invitestate = INV_TERMINATED;
18433 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18434 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
18435 check_pendings(p);
18436 break;
18437
18438 case 407:
18439 case 401:
18440
18441 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18442 if (p->options)
18443 p->options->auth_type = resp;
18444
18445
18446 ast_string_field_set(p, theirtag, NULL);
18447 if (!req->ignore) {
18448 if (p->authtries < MAX_AUTHTRIES)
18449 p->invitestate = INV_CALLING;
18450 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
18451 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
18452 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
18453 sip_alreadygone(p);
18454 if (p->owner)
18455 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18456 }
18457 }
18458 break;
18459
18460 case 403:
18461
18462 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18463 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
18464 if (!req->ignore && p->owner)
18465 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18466 pvt_set_needdestroy(p, "received 403 response");
18467 sip_alreadygone(p);
18468 break;
18469
18470 case 404:
18471 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18472 if (p->owner && !req->ignore)
18473 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18474 sip_alreadygone(p);
18475 break;
18476
18477 case 408:
18478 case 481:
18479
18480 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
18481 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18482 if (p->owner)
18483 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18484 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18485 break;
18486
18487 case 422:
18488 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18489 ast_string_field_set(p, theirtag, NULL);
18490 proc_422_rsp(p, req);
18491 break;
18492
18493 case 428:
18494 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18495 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
18496 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
18497 if (p->owner)
18498 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18499 break;
18500
18501
18502
18503 case 487:
18504
18505
18506
18507 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18508 if (p->owner && !req->ignore) {
18509 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
18510 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
18511 } else if (!req->ignore) {
18512 update_call_counter(p, DEC_CALL_LIMIT);
18513 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
18514 pvt_set_needdestroy(p, "received 487 response");
18515 sip_alreadygone(p);
18516 }
18517 break;
18518 case 415:
18519 case 488:
18520 case 606:
18521 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18522 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
18523 change_t38_state(p, T38_DISABLED);
18524
18525 ast_rtp_set_rtptimers_onhold(p->rtp);
18526
18527
18528 transmit_reinvite_with_sdp(p, FALSE, FALSE);
18529 } else {
18530
18531 if (p->owner && !req->ignore)
18532 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18533 pvt_set_needdestroy(p, "received 488 response");
18534
18535 if (!reinvite)
18536 sip_alreadygone(p);
18537 }
18538 break;
18539 case 491:
18540 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18541 if (p->owner && !req->ignore) {
18542 if (p->owner->_state != AST_STATE_UP) {
18543 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18544 pvt_set_needdestroy(p, "received 491 response");
18545 } else {
18546
18547
18548
18549 int wait;
18550
18551
18552 if (p->outgoing_call) {
18553 wait = 2100 + ast_random() % 2000;
18554 } else {
18555 wait = ast_random() % 2000;
18556 }
18557 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."));
18558 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);
18559 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
18560 }
18561 }
18562 break;
18563
18564 case 501:
18565 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18566 if (p->owner)
18567 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18568 break;
18569 }
18570 if (xmitres == XMIT_ERROR)
18571 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
18572 }
18573
18574
18575
18576
18577 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18578 {
18579 switch (resp) {
18580 case 200:
18581
18582 if (p->owner) {
18583 if (!p->refer) {
18584 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
18585 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
18586 } else {
18587 ast_debug(4, "Got OK on REFER Notify message\n");
18588 }
18589 } else {
18590 if (p->subscribed == NONE) {
18591 ast_debug(4, "Got 200 accepted on NOTIFY\n");
18592 pvt_set_needdestroy(p, "received 200 response");
18593 }
18594 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18595
18596 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18597 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18598 }
18599 }
18600 break;
18601 case 401:
18602 case 407:
18603 if (!p->notify_headers) {
18604 break;
18605 }
18606 ast_string_field_set(p, theirtag, NULL);
18607 if (ast_strlen_zero(p->authname)) {
18608 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));
18609 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18610 }
18611 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18612 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18613 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18614 }
18615 break;
18616 }
18617 }
18618
18619
18620 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18621 {
18622 if (!p->mwi) {
18623 return;
18624 }
18625
18626 switch (resp) {
18627 case 200:
18628 ast_debug(3, "Got 200 OK on subscription for MWI\n");
18629 if (p->options) {
18630 ast_free(p->options);
18631 p->options = NULL;
18632 }
18633 p->mwi->subscribed = 1;
18634 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18635 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18636 }
18637 break;
18638 case 401:
18639 case 407:
18640 ast_string_field_set(p, theirtag, NULL);
18641 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18642 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18643 p->mwi->call = NULL;
18644 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18645 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18646 }
18647 break;
18648 case 403:
18649 transmit_response_with_date(p, "200 OK", req);
18650 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18651 p->mwi->call = NULL;
18652 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18653 pvt_set_needdestroy(p, "received 403 response");
18654 sip_alreadygone(p);
18655 break;
18656 case 404:
18657 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18658 p->mwi->call = NULL;
18659 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18660 pvt_set_needdestroy(p, "received 404 response");
18661 break;
18662 case 481:
18663 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18664 p->mwi->call = NULL;
18665 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18666 pvt_set_needdestroy(p, "received 481 response");
18667 break;
18668 case 500:
18669 case 501:
18670 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18671 p->mwi->call = NULL;
18672 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18673 pvt_set_needdestroy(p, "received 500/501 response");
18674 break;
18675 }
18676 }
18677
18678
18679
18680
18681 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18682 {
18683
18684 if (!p->refer)
18685 return;
18686
18687 switch (resp) {
18688 case 202:
18689
18690
18691 p->refer->status = REFER_ACCEPTED;
18692
18693 ast_debug(3, "Got 202 accepted on transfer\n");
18694
18695 break;
18696
18697 case 401:
18698 case 407:
18699 if (ast_strlen_zero(p->authname)) {
18700 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18701 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18702 pvt_set_needdestroy(p, "unable to authenticate REFER");
18703 }
18704 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18705 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18706 p->refer->status = REFER_NOAUTH;
18707 pvt_set_needdestroy(p, "failed to authenticat REFER");
18708 }
18709 break;
18710 case 481:
18711
18712
18713
18714
18715 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18716 if (p->owner)
18717 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18718 pvt_set_needdestroy(p, "received 481 response");
18719 break;
18720
18721 case 500:
18722 case 501:
18723
18724
18725 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18726 pvt_set_needdestroy(p, "received 500/501 response");
18727 p->refer->status = REFER_FAILED;
18728 break;
18729 case 603:
18730 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18731 p->refer->status = REFER_FAILED;
18732 pvt_set_needdestroy(p, "received 603 response");
18733 break;
18734 }
18735 }
18736
18737
18738 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18739 {
18740 int expires, expires_ms;
18741 struct sip_registry *r;
18742 r=p->registry;
18743
18744 switch (resp) {
18745 case 401:
18746 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18747 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18748 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18749 }
18750 break;
18751 case 403:
18752 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18753 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18754 r->regstate = REG_STATE_NOAUTH;
18755 pvt_set_needdestroy(p, "received 403 response");
18756 break;
18757 case 404:
18758 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18759 pvt_set_needdestroy(p, "received 404 response");
18760 if (r->call)
18761 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18762 r->regstate = REG_STATE_REJECTED;
18763 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18764 break;
18765 case 407:
18766 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18767 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18768 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18769 }
18770 break;
18771 case 408:
18772
18773 if (r) {
18774 r->regattempts = 0;
18775 } else {
18776 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18777 }
18778 break;
18779 case 423:
18780 r->expiry = atoi(get_header(req, "Min-Expires"));
18781 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);
18782 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18783 if (r->call) {
18784 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18785 pvt_set_needdestroy(p, "received 423 response");
18786 }
18787 if (r->expiry > max_expiry) {
18788 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18789 r->expiry = r->configured_expiry;
18790 r->regstate = REG_STATE_REJECTED;
18791 } else {
18792 r->regstate = REG_STATE_UNREGISTERED;
18793 transmit_register(r, SIP_REGISTER, NULL, NULL);
18794 }
18795 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));
18796 break;
18797 case 479:
18798 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18799 pvt_set_needdestroy(p, "received 479 response");
18800 if (r->call)
18801 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18802 r->regstate = REG_STATE_REJECTED;
18803 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18804 break;
18805 case 200:
18806 if (!r) {
18807 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));
18808 pvt_set_needdestroy(p, "received erroneous 200 response");
18809 return 0;
18810 }
18811
18812 r->regstate = REG_STATE_REGISTERED;
18813 r->regtime = ast_tvnow();
18814 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18815 r->regattempts = 0;
18816 ast_debug(1, "Registration successful\n");
18817 if (r->timeout > -1) {
18818 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18819 }
18820 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18821 if (r->call)
18822 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18823 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18824
18825 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18826
18827
18828
18829
18830
18831
18832 expires = 0;
18833
18834
18835 if (!ast_strlen_zero(get_header(req, "Contact"))) {
18836 const char *contact = NULL;
18837 const char *tmptmp = NULL;
18838 int start = 0;
18839 for(;;) {
18840 contact = __get_header(req, "Contact", &start);
18841
18842 if(!ast_strlen_zero(contact)) {
18843 if( (tmptmp=strstr(contact, p->our_contact))) {
18844 contact=tmptmp;
18845 break;
18846 }
18847 } else
18848 break;
18849 }
18850 tmptmp = strcasestr(contact, "expires=");
18851 if (tmptmp) {
18852 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18853 expires = 0;
18854 }
18855
18856 }
18857 if (!expires)
18858 expires=atoi(get_header(req, "expires"));
18859 if (!expires)
18860 expires=default_expiry;
18861
18862 expires_ms = expires * 1000;
18863 if (expires <= EXPIRY_GUARD_LIMIT)
18864 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18865 else
18866 expires_ms -= EXPIRY_GUARD_SECS * 1000;
18867 if (sipdebug)
18868 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
18869
18870 r->refresh= (int) expires_ms / 1000;
18871
18872
18873 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
18874 registry_unref(_data,"unref in REPLACE del fail"),
18875 registry_unref(r,"unref in REPLACE add fail"),
18876 registry_addref(r,"The Addition side of REPLACE"));
18877 }
18878 return 1;
18879 }
18880
18881
18882 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18883 {
18884 struct sip_peer *peer = p->relatedpeer ;
18885 int statechanged, is_reachable, was_reachable;
18886 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18887
18888
18889
18890
18891
18892
18893 if (pingtime < 1)
18894 pingtime = 1;
18895
18896
18897
18898
18899
18900 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18901 is_reachable = pingtime <= peer->maxms;
18902 statechanged = peer->lastms == 0
18903 || was_reachable != is_reachable;
18904
18905 peer->lastms = pingtime;
18906 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18907 if (statechanged) {
18908 const char *s = is_reachable ? "Reachable" : "Lagged";
18909 char str_lastms[20];
18910 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18911
18912 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18913 peer->name, s, pingtime, peer->maxms);
18914 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18915 if (sip_cfg.peer_rtupdate) {
18916 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18917 }
18918 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18919 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18920 peer->name, s, pingtime);
18921 if (is_reachable && sip_cfg.regextenonqualify)
18922 register_peer_exten(peer, TRUE);
18923 }
18924
18925 pvt_set_needdestroy(p, "got OPTIONS response");
18926
18927
18928 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18929 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18930 sip_poke_peer_s, peer,
18931 unref_peer(_data, "removing poke peer ref"),
18932 unref_peer(peer, "removing poke peer ref"),
18933 ref_peer(peer, "adding poke peer ref"));
18934 }
18935
18936
18937 static void stop_media_flows(struct sip_pvt *p)
18938 {
18939
18940 if (p->rtp)
18941 ast_rtp_stop(p->rtp);
18942 if (p->vrtp)
18943 ast_rtp_stop(p->vrtp);
18944 if (p->trtp)
18945 ast_rtp_stop(p->trtp);
18946 if (p->udptl)
18947 ast_udptl_stop(p->udptl);
18948 }
18949
18950
18951
18952 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18953 {
18954 struct ast_channel *owner;
18955 int sipmethod;
18956 int res = 1;
18957 const char *c = get_header(req, "Cseq");
18958
18959 char *c_copy = ast_strdupa(c);
18960
18961 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18962
18963 if (!msg)
18964 msg = "";
18965
18966 sipmethod = find_sip_method(msg);
18967
18968 owner = p->owner;
18969 if (owner)
18970 owner->hangupcause = hangup_sip2cause(resp);
18971
18972 if (p->socket.type == SIP_TRANSPORT_UDP) {
18973 int ack_res;
18974
18975
18976 if ((resp >= 100) && (resp <= 199)) {
18977 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18978 } else {
18979 ack_res = __sip_ack(p, seqno, 0, sipmethod);
18980 }
18981
18982 if (ack_res == FALSE) {
18983 append_history(p, "Ignore", "Ignoring this retransmit\n");
18984 return;
18985 }
18986 }
18987
18988
18989 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
18990 p->pendinginvite = 0;
18991
18992
18993 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18994 char tag[128];
18995
18996 gettag(req, "To", tag, sizeof(tag));
18997 ast_string_field_set(p, theirtag, tag);
18998 }
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
19015 pvt_set_needdestroy(p, "received 4XX response to a BYE");
19016 return;
19017 }
19018
19019 if (p->relatedpeer && p->method == SIP_OPTIONS) {
19020
19021
19022
19023 if (resp != 100)
19024 handle_response_peerpoke(p, resp, req);
19025 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
19026 switch(resp) {
19027 case 100:
19028 case 101:
19029 case 183:
19030 case 180:
19031 case 182:
19032 if (sipmethod == SIP_INVITE)
19033 handle_response_invite(p, resp, rest, req, seqno);
19034 break;
19035 case 200:
19036 p->authtries = 0;
19037 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19038
19039
19040
19041 } else if (sipmethod == SIP_INVITE) {
19042 handle_response_invite(p, resp, rest, req, seqno);
19043 } else if (sipmethod == SIP_NOTIFY) {
19044 handle_response_notify(p, resp, rest, req, seqno);
19045 } else if (sipmethod == SIP_REGISTER) {
19046 res = handle_response_register(p, resp, rest, req, seqno);
19047 } else if (sipmethod == SIP_SUBSCRIBE) {
19048 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19049 handle_response_subscribe(p, resp, rest, req, seqno);
19050 } else if (sipmethod == SIP_BYE) {
19051 pvt_set_needdestroy(p, "received 200 response");
19052 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19053 }
19054 break;
19055 case 202:
19056 if (sipmethod == SIP_REFER)
19057 handle_response_refer(p, resp, rest, req, seqno);
19058 break;
19059 case 401:
19060 case 407:
19061 if (sipmethod == SIP_INVITE)
19062 handle_response_invite(p, resp, rest, req, seqno);
19063 else if (sipmethod == SIP_NOTIFY)
19064 handle_response_notify(p, resp, rest, req, seqno);
19065 else if (sipmethod == SIP_REFER)
19066 handle_response_refer(p, resp, rest, req, seqno);
19067 else if (sipmethod == SIP_SUBSCRIBE)
19068 handle_response_subscribe(p, resp, rest, req, seqno);
19069 else if (p->registry && sipmethod == SIP_REGISTER)
19070 res = handle_response_register(p, resp, rest, req, seqno);
19071 else if (sipmethod == SIP_BYE) {
19072 if (p->options)
19073 p->options->auth_type = resp;
19074 if (ast_strlen_zero(p->authname)) {
19075 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
19076 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
19077 pvt_set_needdestroy(p, "unable to authenticate BYE");
19078 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
19079 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19080 pvt_set_needdestroy(p, "failed to authenticate BYE");
19081 }
19082 } else {
19083 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
19084 pvt_set_needdestroy(p, "received 407 response");
19085 }
19086 break;
19087 case 403:
19088 if (sipmethod == SIP_INVITE)
19089 handle_response_invite(p, resp, rest, req, seqno);
19090 else if (sipmethod == SIP_SUBSCRIBE)
19091 handle_response_subscribe(p, resp, rest, req, seqno);
19092 else if (p->registry && sipmethod == SIP_REGISTER)
19093 res = handle_response_register(p, resp, rest, req, seqno);
19094 else {
19095 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
19096 pvt_set_needdestroy(p, "received 403 response");
19097 }
19098 break;
19099 case 404:
19100 if (p->registry && sipmethod == SIP_REGISTER)
19101 res = handle_response_register(p, resp, rest, req, seqno);
19102 else if (sipmethod == SIP_INVITE)
19103 handle_response_invite(p, resp, rest, req, seqno);
19104 else if (sipmethod == SIP_SUBSCRIBE)
19105 handle_response_subscribe(p, resp, rest, req, seqno);
19106 else if (owner)
19107 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19108 break;
19109 case 423:
19110 if (sipmethod == SIP_REGISTER)
19111 res = handle_response_register(p, resp, rest, req, seqno);
19112 break;
19113 case 408:
19114 if (sipmethod == SIP_INVITE)
19115 handle_response_invite(p, resp, rest, req, seqno);
19116 else if (sipmethod == SIP_REGISTER)
19117 res = handle_response_register(p, resp, rest, req, seqno);
19118 else if (sipmethod == SIP_BYE) {
19119 pvt_set_needdestroy(p, "received 408 response");
19120 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
19121 } else {
19122 if (owner)
19123 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19124 pvt_set_needdestroy(p, "received 408 response");
19125 }
19126 break;
19127
19128 case 422:
19129 if (sipmethod == SIP_INVITE) {
19130 handle_response_invite(p, resp, rest, req, seqno);
19131 }
19132 break;
19133
19134 case 481:
19135 if (sipmethod == SIP_INVITE) {
19136 handle_response_invite(p, resp, rest, req, seqno);
19137 } else if (sipmethod == SIP_REFER) {
19138 handle_response_refer(p, resp, rest, req, seqno);
19139 } else if (sipmethod == SIP_SUBSCRIBE) {
19140 handle_response_subscribe(p, resp, rest, req, seqno);
19141 } else if (sipmethod == SIP_NOTIFY) {
19142 pvt_set_needdestroy(p, "received 481 response");
19143 } else if (sipmethod == SIP_BYE) {
19144
19145
19146 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19147 } else if (sipmethod == SIP_CANCEL) {
19148
19149
19150 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19151 } else {
19152 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19153
19154 }
19155 break;
19156 case 487:
19157 if (sipmethod == SIP_INVITE)
19158 handle_response_invite(p, resp, rest, req, seqno);
19159 break;
19160 case 415:
19161 case 488:
19162 case 606:
19163 if (sipmethod == SIP_INVITE)
19164 handle_response_invite(p, resp, rest, req, seqno);
19165 break;
19166 case 491:
19167 if (sipmethod == SIP_INVITE)
19168 handle_response_invite(p, resp, rest, req, seqno);
19169 else {
19170 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
19171 pvt_set_needdestroy(p, "received 491 response");
19172 }
19173 break;
19174 case 501:
19175 if (sipmethod == SIP_INVITE)
19176 handle_response_invite(p, resp, rest, req, seqno);
19177 else if (sipmethod == SIP_REFER)
19178 handle_response_refer(p, resp, rest, req, seqno);
19179 else
19180 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
19181 break;
19182 case 603:
19183 if (sipmethod == SIP_REFER) {
19184 handle_response_refer(p, resp, rest, req, seqno);
19185 break;
19186 }
19187
19188 default:
19189 if ((resp >= 300) && (resp < 700)) {
19190
19191 if ((resp != 487))
19192 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
19193
19194 if (sipmethod == SIP_INVITE)
19195 stop_media_flows(p);
19196
19197
19198 switch(resp) {
19199 case 300:
19200 case 301:
19201 case 302:
19202 case 305:
19203 parse_moved_contact(p, req);
19204
19205 case 486:
19206 case 600:
19207 case 603:
19208 if (p->owner)
19209 ast_queue_control(p->owner, AST_CONTROL_BUSY);
19210 break;
19211 case 482:
19212
19213
19214
19215
19216
19217 if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
19218 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
19219 ast_string_field_build(p->owner, call_forward,
19220 "Local/%s@%s", p->username, p->context);
19221 }
19222
19223 case 480:
19224 case 404:
19225 case 410:
19226 case 400:
19227 case 500:
19228 if (sipmethod == SIP_REFER) {
19229 handle_response_refer(p, resp, rest, req, seqno);
19230 break;
19231 } else if (sipmethod == SIP_SUBSCRIBE) {
19232 handle_response_subscribe(p, resp, rest, req, seqno);
19233 break;
19234 }
19235
19236 case 502:
19237 case 503:
19238 case 504:
19239 if (owner)
19240 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19241 break;
19242 default:
19243
19244 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
19245 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
19246 break;
19247 }
19248
19249 if (sipmethod == SIP_INVITE)
19250 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19251 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
19252 sip_alreadygone(p);
19253 if (!p->owner) {
19254 pvt_set_needdestroy(p, "transaction completed");
19255 }
19256 } else if ((resp >= 100) && (resp < 200)) {
19257 if (sipmethod == SIP_INVITE) {
19258 if (!req->ignore && sip_cancel_destroy(p))
19259 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19260 if (find_sdp(req))
19261 process_sdp(p, req, SDP_T38_NONE);
19262 if (p->owner) {
19263
19264 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19265 }
19266 }
19267 } else
19268 ast_log(LOG_NOTICE, "Don't 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));
19269 }
19270 } else {
19271
19272
19273 if (req->debug)
19274 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
19275
19276 if (sipmethod == SIP_INVITE && resp == 200) {
19277
19278
19279 char tag[128];
19280
19281 gettag(req, "To", tag, sizeof(tag));
19282 ast_string_field_set(p, theirtag, tag);
19283 }
19284
19285 switch(resp) {
19286 case 200:
19287 if (sipmethod == SIP_INVITE) {
19288 handle_response_invite(p, resp, rest, req, seqno);
19289 } else if (sipmethod == SIP_CANCEL) {
19290 ast_debug(1, "Got 200 OK on CANCEL\n");
19291
19292
19293 } else if (sipmethod == SIP_NOTIFY) {
19294
19295 if (p->owner) {
19296 if (p->refer) {
19297 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
19298 } else
19299 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
19300
19301 } else {
19302 if (!p->subscribed && !p->refer) {
19303 pvt_set_needdestroy(p, "transaction completed");
19304 }
19305 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
19306
19307 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
19308 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
19309 }
19310 }
19311 } else if (sipmethod == SIP_BYE) {
19312 pvt_set_needdestroy(p, "transaction completed");
19313 } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19314
19315
19316 ;
19317 }
19318 break;
19319 case 202:
19320 if (sipmethod == SIP_REFER)
19321 handle_response_refer(p, resp, rest, req, seqno);
19322 break;
19323 case 401:
19324 case 407:
19325 if (sipmethod == SIP_REFER)
19326 handle_response_refer(p, resp, rest, req, seqno);
19327 else if (sipmethod == SIP_INVITE)
19328 handle_response_invite(p, resp, rest, req, seqno);
19329 else if (sipmethod == SIP_BYE) {
19330 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
19331 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19332 pvt_set_needdestroy(p, "failed to authenticate BYE");
19333 }
19334 }
19335 break;
19336 case 481:
19337 if (sipmethod == SIP_INVITE) {
19338
19339 handle_response_invite(p, resp, rest, req, seqno);
19340 } else if (sipmethod == SIP_BYE) {
19341 pvt_set_needdestroy(p, "received 481 response");
19342 } else if (sipmethod == SIP_NOTIFY) {
19343 pvt_set_needdestroy(p, "received 481 response");
19344 } else if (sipdebug) {
19345 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
19346 }
19347 break;
19348 case 501:
19349 if (sipmethod == SIP_INVITE)
19350 handle_response_invite(p, resp, rest, req, seqno);
19351 else if (sipmethod == SIP_REFER)
19352 handle_response_refer(p, resp, rest, req, seqno);
19353 break;
19354 case 603:
19355 if (sipmethod == SIP_REFER) {
19356 handle_response_refer(p, resp, rest, req, seqno);
19357 break;
19358 }
19359
19360 default:
19361 if ((resp >= 100) && (resp < 200)) {
19362 if (sipmethod == SIP_INVITE) {
19363 if (!req->ignore && sip_cancel_destroy(p))
19364 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19365 }
19366 }
19367 if ((resp >= 300) && (resp < 700)) {
19368 if ((resp != 487))
19369 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
19370 switch(resp) {
19371 case 415:
19372 case 488:
19373 case 603:
19374 case 500:
19375 case 502:
19376 case 503:
19377 case 504:
19378
19379
19380 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
19381 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19382 break;
19383 }
19384 }
19385 break;
19386 }
19387 }
19388 }
19389
19390
19391
19392
19393
19394
19395
19396 static void *sip_park_thread(void *stuff)
19397 {
19398 struct ast_channel *transferee, *transferer;
19399 struct sip_dual *d;
19400 struct sip_request req = {0,};
19401 int ext;
19402 int res;
19403
19404 d = stuff;
19405 transferee = d->chan1;
19406 transferer = d->chan2;
19407 copy_request(&req, &d->req);
19408
19409 if (!transferee || !transferer) {
19410 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
19411 deinit_req(&d->req);
19412 ast_free(d);
19413 return NULL;
19414 }
19415 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
19416
19417 ast_channel_lock(transferee);
19418 if (ast_do_masquerade(transferee)) {
19419 ast_log(LOG_WARNING, "Masquerade failed.\n");
19420 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
19421 ast_channel_unlock(transferee);
19422 deinit_req(&d->req);
19423 ast_free(d);
19424 return NULL;
19425 }
19426 ast_channel_unlock(transferee);
19427
19428 res = ast_park_call(transferee, transferer, 0, &ext);
19429
19430
19431 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
19432 if (!res) {
19433 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
19434 } else {
19435
19436 sprintf(buf, "Call parked on extension '%d'", ext);
19437 transmit_message_with_text(transferer->tech_pvt, buf);
19438 }
19439 #endif
19440
19441
19442
19443 if (!res) {
19444
19445 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
19446 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
19447 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19448 ast_hangup(transferer);
19449 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
19450 } else {
19451 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
19452 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
19453 ast_debug(1, "SIP Call parked failed \n");
19454
19455 }
19456 deinit_req(&d->req);
19457 ast_free(d);
19458 return NULL;
19459 }
19460
19461
19462
19463
19464 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
19465 {
19466 struct sip_dual *d;
19467 struct ast_channel *transferee, *transferer;
19468
19469 pthread_t th;
19470
19471 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
19472 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
19473 if ((!transferer) || (!transferee)) {
19474 if (transferee) {
19475 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19476 ast_hangup(transferee);
19477 }
19478 if (transferer) {
19479 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19480 ast_hangup(transferer);
19481 }
19482 return -1;
19483 }
19484
19485
19486 transferee->readformat = chan1->readformat;
19487 transferee->writeformat = chan1->writeformat;
19488
19489
19490 ast_channel_masquerade(transferee, chan1);
19491
19492
19493 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
19494 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
19495 transferee->priority = chan1->priority;
19496
19497
19498
19499
19500
19501 transferer->readformat = chan2->readformat;
19502 transferer->writeformat = chan2->writeformat;
19503 if (!ast_strlen_zero(chan2->parkinglot))
19504 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
19505
19506
19507
19508
19509 while (ast_channel_trylock(chan2)) {
19510 struct sip_pvt *pvt = chan2->tech_pvt;
19511 sip_pvt_unlock(pvt);
19512 usleep(1);
19513 sip_pvt_lock(pvt);
19514 }
19515 ast_channel_masquerade(transferer, chan2);
19516 ast_channel_unlock(chan2);
19517
19518
19519 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
19520 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
19521 transferer->priority = chan2->priority;
19522
19523 ast_channel_lock(transferer);
19524 if (ast_do_masquerade(transferer)) {
19525 ast_log(LOG_WARNING, "Masquerade failed :(\n");
19526 ast_channel_unlock(transferer);
19527 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19528 ast_hangup(transferer);
19529 return -1;
19530 }
19531 ast_channel_unlock(transferer);
19532 if (!transferer || !transferee) {
19533 if (!transferer) {
19534 ast_debug(1, "No transferer channel, giving up parking\n");
19535 }
19536 if (!transferee) {
19537 ast_debug(1, "No transferee channel, giving up parking\n");
19538 }
19539 return -1;
19540 }
19541 if (!(d = ast_calloc(1, sizeof(*d)))) {
19542 return -1;
19543 }
19544
19545
19546 copy_request(&d->req, req);
19547 d->chan1 = transferee;
19548 d->chan2 = transferer;
19549 d->seqno = seqno;
19550 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
19551
19552 deinit_req(&d->req);
19553 ast_free(d);
19554
19555 return -1;
19556 }
19557 return 0;
19558 }
19559
19560
19561
19562
19563
19564 static void *sip_pickup_thread(void *stuff)
19565 {
19566 struct ast_channel *chan;
19567 chan = stuff;
19568
19569 if (ast_pickup_call(chan)) {
19570 chan->hangupcause = AST_CAUSE_CALL_REJECTED;
19571 } else {
19572 chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19573 }
19574 ast_hangup(chan);
19575 chan = NULL;
19576 return NULL;
19577 }
19578
19579
19580
19581
19582 static int sip_pickup(struct ast_channel *chan)
19583 {
19584 pthread_t threadid;
19585
19586 if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
19587 ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
19588 return -1;
19589 }
19590 ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
19591 return 0;
19592 }
19593
19594
19595
19596
19597
19598 static void ast_quiet_chan(struct ast_channel *chan)
19599 {
19600 if (chan && chan->_state == AST_STATE_UP) {
19601 if (ast_test_flag(chan, AST_FLAG_MOH))
19602 ast_moh_stop(chan);
19603 else if (chan->generatordata)
19604 ast_deactivate_generator(chan);
19605 }
19606 }
19607
19608
19609
19610 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
19611 {
19612 int res = 0;
19613 struct ast_channel *peera = NULL,
19614 *peerb = NULL,
19615 *peerc = NULL,
19616 *peerd = NULL;
19617
19618
19619
19620
19621 ast_debug(4, "Sip transfer:--------------------\n");
19622 if (transferer->chan1)
19623 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
19624 else
19625 ast_debug(4, "-- No transferer first channel - odd??? \n");
19626 if (target->chan1)
19627 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19628 else
19629 ast_debug(4, "-- No target first channel ---\n");
19630 if (transferer->chan2)
19631 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19632 else
19633 ast_debug(4, "-- No bridged call to transferee\n");
19634 if (target->chan2)
19635 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)");
19636 else
19637 ast_debug(4, "-- No target second channel ---\n");
19638 ast_debug(4, "-- END Sip transfer:--------------------\n");
19639 if (transferer->chan2) {
19640 peera = transferer->chan1;
19641 peerb = target->chan1;
19642 peerc = transferer->chan2;
19643 peerd = target->chan2;
19644 ast_debug(3, "SIP transfer: Four channels to handle\n");
19645 } else if (target->chan2) {
19646 peera = target->chan1;
19647 peerb = transferer->chan1;
19648 peerc = target->chan2;
19649 peerd = transferer->chan2;
19650 ast_debug(3, "SIP transfer: Three channels to handle\n");
19651 }
19652
19653 if (peera && peerb && peerc && (peerb != peerc)) {
19654 ast_quiet_chan(peera);
19655 ast_quiet_chan(peerb);
19656 ast_quiet_chan(peerc);
19657 if (peerd)
19658 ast_quiet_chan(peerd);
19659
19660 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19661 if (ast_channel_masquerade(peerb, peerc)) {
19662 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19663 res = -1;
19664 } else
19665 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19666 return res;
19667 } else {
19668 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19669 if (transferer->chan1)
19670 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19671 if (target->chan1)
19672 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19673 return -1;
19674 }
19675 return 0;
19676 }
19677
19678
19679
19680
19681
19682
19683 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19684 {
19685 const char *thetag;
19686
19687 if (!tagbuf)
19688 return NULL;
19689 tagbuf[0] = '\0';
19690 thetag = get_header(req, header);
19691 thetag = strcasestr(thetag, ";tag=");
19692 if (thetag) {
19693 thetag += 5;
19694 ast_copy_string(tagbuf, thetag, tagbufsize);
19695 return strsep(&tagbuf, ";");
19696 }
19697 return NULL;
19698 }
19699
19700
19701 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19702 {
19703
19704
19705 int res = 0;
19706 const char *event = get_header(req, "Event");
19707 char *eventid = NULL;
19708 char *sep;
19709
19710 if( (sep = strchr(event, ';')) ) {
19711 *sep++ = '\0';
19712 eventid = sep;
19713 }
19714
19715 if (sipdebug)
19716 ast_debug(2, "Got NOTIFY Event: %s\n", event);
19717
19718 if (!strcmp(event, "refer")) {
19719
19720
19721
19722
19723
19724 char buf[1024];
19725 char *cmd, *code;
19726 int respcode;
19727 int success = TRUE;
19728
19729
19730
19731
19732
19733
19734
19735
19736 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19737
19738 transmit_response(p, "400 Bad request", req);
19739 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19740 return -1;
19741 }
19742
19743
19744 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19745 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19746 transmit_response(p, "400 Bad request", req);
19747 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19748 return -1;
19749 }
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19772 cmd = ast_skip_blanks(buf);
19773 code = cmd;
19774
19775 while(*code && (*code > 32)) {
19776 code++;
19777 }
19778 *code++ = '\0';
19779 code = ast_skip_blanks(code);
19780 sep = code;
19781 sep++;
19782 while(*sep && (*sep > 32)) {
19783 sep++;
19784 }
19785 *sep++ = '\0';
19786 respcode = atoi(code);
19787 switch (respcode) {
19788 case 100:
19789 case 101:
19790
19791 break;
19792 case 183:
19793
19794 break;
19795 case 200:
19796
19797 break;
19798 case 301:
19799 case 302:
19800
19801 success = FALSE;
19802 break;
19803 case 503:
19804
19805 success = FALSE;
19806 break;
19807 case 603:
19808
19809 success = FALSE;
19810 break;
19811 }
19812 if (!success) {
19813 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19814 }
19815
19816
19817 transmit_response(p, "200 OK", req);
19818 } else if (p->mwi && !strcmp(event, "message-summary")) {
19819 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19820
19821 if (!ast_strlen_zero(c)) {
19822 char *old = strsep(&c, " ");
19823 char *new = strsep(&old, "/");
19824 struct ast_event *event;
19825
19826 if ((event = ast_event_new(AST_EVENT_MWI,
19827 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19828 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19829 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19830 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19831 AST_EVENT_IE_END))) {
19832 ast_event_queue_and_cache(event);
19833 }
19834 }
19835
19836 transmit_response(p, "200 OK", req);
19837 } else if (!strcmp(event, "keep-alive")) {
19838
19839
19840 transmit_response(p, "200 OK", req);
19841 } else {
19842
19843 transmit_response(p, "489 Bad event", req);
19844 res = -1;
19845 }
19846
19847 if (!p->lastinvite)
19848 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19849
19850 return res;
19851 }
19852
19853
19854
19855
19856 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19857 {
19858 int res;
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870 if (p->lastinvite) {
19871
19872 transmit_response_with_allow(p, "200 OK", req, 0);
19873 return 0;
19874 }
19875
19876 res = get_destination(p, req);
19877 build_contact(p);
19878
19879 if (ast_strlen_zero(p->context))
19880 ast_string_field_set(p, context, sip_cfg.default_context);
19881
19882 if (ast_shutting_down())
19883 transmit_response_with_allow(p, "503 Unavailable", req, 0);
19884 else if (res < 0)
19885 transmit_response_with_allow(p, "404 Not Found", req, 0);
19886 else
19887 transmit_response_with_allow(p, "200 OK", req, 0);
19888
19889
19890
19891 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19892
19893 return res;
19894 }
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19906 {
19907 int earlyreplace = 0;
19908 int oneleggedreplace = 0;
19909 struct ast_channel *c = p->owner;
19910 struct ast_channel *replacecall = p->refer->refer_call->owner;
19911 struct ast_channel *targetcall;
19912
19913 struct ast_channel *test;
19914
19915
19916 if (replacecall->_state == AST_STATE_RING)
19917 earlyreplace = 1;
19918
19919
19920 if (!(targetcall = ast_bridged_channel(replacecall))) {
19921
19922 if (!earlyreplace) {
19923 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19924 oneleggedreplace = 1;
19925 }
19926 }
19927 if (targetcall && targetcall->_state == AST_STATE_RINGING)
19928 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19929
19930 if (targetcall)
19931 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
19932 else
19933 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
19934
19935 if (req->ignore) {
19936 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19937
19938
19939
19940 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19941
19942 if (c) {
19943 *nounlock = 1;
19944 ast_channel_unlock(c);
19945 }
19946 ast_channel_unlock(replacecall);
19947 sip_pvt_unlock(p->refer->refer_call);
19948 return 1;
19949 }
19950 if (!c) {
19951
19952 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
19953 transmit_response_reliable(p, "503 Service Unavailable", req);
19954 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19955 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19956 ast_channel_unlock(replacecall);
19957 sip_pvt_unlock(p->refer->refer_call);
19958 return 1;
19959 }
19960 append_history(p, "Xfer", "INVITE/Replace received");
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972 transmit_response(p, "100 Trying", req);
19973 ast_setstate(c, AST_STATE_RING);
19974
19975
19976
19977
19978
19979 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19980
19981 ast_setstate(c, AST_STATE_UP);
19982
19983
19984 ast_quiet_chan(replacecall);
19985 ast_quiet_chan(targetcall);
19986 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19987
19988
19989 if (! earlyreplace && ! oneleggedreplace )
19990 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19991
19992
19993 if(ast_channel_masquerade(replacecall, c))
19994 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19995 else
19996 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19997
19998
19999 if (ast_do_masquerade(replacecall)) {
20000 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
20001 }
20002
20003 if (earlyreplace || oneleggedreplace ) {
20004 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20005 }
20006
20007 ast_setstate(c, AST_STATE_DOWN);
20008 ast_debug(4, "After transfer:----------------------------\n");
20009 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
20010 if (replacecall)
20011 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
20012 if (p->owner) {
20013 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
20014 test = ast_bridged_channel(p->owner);
20015 if (test)
20016 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
20017 else
20018 ast_debug(4, " -- No call bridged to C->owner \n");
20019 } else
20020 ast_debug(4, " -- No channel yet \n");
20021 ast_debug(4, "End After transfer:----------------------------\n");
20022
20023
20024 ast_channel_unlock(replacecall);
20025 ast_channel_unlock(c);
20026 sip_pvt_unlock(p->refer->refer_call);
20027 sip_pvt_unlock(p);
20028 *nounlock = 1;
20029
20030
20031 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
20032 ast_hangup(c);
20033 sip_pvt_lock(p);
20034
20035 return 0;
20036 }
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055 static int sip_uri_params_cmp(const char *input1, const char *input2)
20056 {
20057 char *params1 = NULL;
20058 char *params2 = NULL;
20059 char *pos1;
20060 char *pos2;
20061 int zerolength1 = 0;
20062 int zerolength2 = 0;
20063 int maddrmatch = 0;
20064 int ttlmatch = 0;
20065 int usermatch = 0;
20066 int methodmatch = 0;
20067
20068 if (ast_strlen_zero(input1)) {
20069 zerolength1 = 1;
20070 } else {
20071 params1 = ast_strdupa(input1);
20072 }
20073 if (ast_strlen_zero(input2)) {
20074 zerolength2 = 1;
20075 } else {
20076 params2 = ast_strdupa(input2);
20077 }
20078
20079
20080
20081
20082 if (zerolength1 && zerolength2) {
20083 return 0;
20084 }
20085
20086 for (pos1 = strsep(¶ms1, ";"); pos1; pos1 = strsep(¶ms1, ";")) {
20087 char *value1 = pos1;
20088 char *name1 = strsep(&value1, "=");
20089 char *params2dup = NULL;
20090 int matched = 0;
20091 if (!value1) {
20092 value1 = "";
20093 }
20094
20095
20096
20097
20098 if (!zerolength2) {
20099 params2dup = ast_strdupa(params2);
20100 }
20101 for (pos2 = strsep(¶ms2dup, ";"); pos2; pos2 = strsep(¶ms2dup, ";")) {
20102 char *name2 = pos2;
20103 char *value2 = strchr(pos2, '=');
20104 if (!value2) {
20105 value2 = "";
20106 } else {
20107 *value2++ = '\0';
20108 }
20109 if (!strcasecmp(name1, name2)) {
20110 if (strcasecmp(value1, value2)) {
20111 goto fail;
20112 } else {
20113 matched = 1;
20114 break;
20115 }
20116 }
20117 }
20118
20119 if (!strcasecmp(name1, "maddr")) {
20120 if (matched) {
20121 maddrmatch = 1;
20122 } else {
20123 goto fail;
20124 }
20125 } else if (!strcasecmp(name1, "ttl")) {
20126 if (matched) {
20127 ttlmatch = 1;
20128 } else {
20129 goto fail;
20130 }
20131 } else if (!strcasecmp(name1, "user")) {
20132 if (matched) {
20133 usermatch = 1;
20134 } else {
20135 goto fail;
20136 }
20137 } else if (!strcasecmp(name1, "method")) {
20138 if (matched) {
20139 methodmatch = 1;
20140 } else {
20141 goto fail;
20142 }
20143 }
20144 }
20145
20146
20147
20148
20149
20150 for (pos2 = strsep(¶ms2, ";"); pos2; pos2 = strsep(¶ms2, ";")) {
20151 char *value2 = pos2;
20152 char *name2 = strsep(&value2, "=");
20153 if (!value2) {
20154 value2 = "";
20155 }
20156 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
20157 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
20158 (!strcasecmp(name2, "user") && !usermatch) ||
20159 (!strcasecmp(name2, "method") && !methodmatch)) {
20160 goto fail;
20161 }
20162 }
20163 return 0;
20164
20165 fail:
20166 return 1;
20167 }
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180 static int sip_uri_headers_cmp(const char *input1, const char *input2)
20181 {
20182 char *headers1 = NULL;
20183 char *headers2 = NULL;
20184 int zerolength1 = 0;
20185 int zerolength2 = 0;
20186 int different = 0;
20187 char *header1;
20188
20189 if (ast_strlen_zero(input1)) {
20190 zerolength1 = 1;
20191 } else {
20192 headers1 = ast_strdupa(input1);
20193 }
20194
20195 if (ast_strlen_zero(input2)) {
20196 zerolength2 = 1;
20197 } else {
20198 headers2 = ast_strdupa(input2);
20199 }
20200
20201 if ((zerolength1 && !zerolength2) ||
20202 (zerolength2 && !zerolength1))
20203 return 1;
20204
20205 if (zerolength1 && zerolength2)
20206 return 0;
20207
20208
20209
20210
20211
20212 if (strlen(headers1) != strlen(headers2)) {
20213 return 1;
20214 }
20215
20216 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
20217 if (!strcasestr(headers2, header1)) {
20218 different = 1;
20219 break;
20220 }
20221 }
20222
20223 return different;
20224 }
20225
20226 static int sip_uri_cmp(const char *input1, const char *input2)
20227 {
20228 char *uri1 = ast_strdupa(input1);
20229 char *uri2 = ast_strdupa(input2);
20230 char *host1;
20231 char *host2;
20232 char *params1;
20233 char *params2;
20234 char *headers1;
20235 char *headers2;
20236
20237
20238
20239
20240 strsep(&uri1, ":");
20241 strsep(&uri2, ":");
20242
20243 if ((host1 = strchr(uri1, '@'))) {
20244 *host1++ = '\0';
20245 }
20246 if ((host2 = strchr(uri2, '@'))) {
20247 *host2++ = '\0';
20248 }
20249
20250
20251
20252
20253 if ((host1 && !host2) ||
20254 (host2 && !host1) ||
20255 (host1 && host2 && strcmp(uri1, uri2))) {
20256 return 1;
20257 }
20258
20259 if (!host1)
20260 host1 = uri1;
20261 if (!host2)
20262 host2 = uri2;
20263
20264
20265
20266
20267
20268 if ((params1 = strchr(host1, ';'))) {
20269 *params1++ = '\0';
20270 }
20271 if ((params2 = strchr(host2, ';'))) {
20272 *params2++ = '\0';
20273 }
20274
20275
20276
20277
20278 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
20279 *headers1++ = '\0';
20280 }
20281 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
20282 *headers2++ = '\0';
20283 }
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295 if (strcasecmp(host1, host2)) {
20296 return 1;
20297 }
20298
20299
20300 if (sip_uri_headers_cmp(headers1, headers2)) {
20301 return 1;
20302 }
20303
20304
20305 return sip_uri_params_cmp(params1, params2);
20306 }
20307
20308
20309 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
20310 {
20311 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
20312 struct ast_app *pickup = pbx_findapp("Pickup");
20313
20314 if (!pickup) {
20315 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
20316 return -1;
20317 }
20318
20319 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
20320
20321 ast_debug(2, "About to call Pickup(%s)\n", str->str);
20322
20323
20324
20325
20326 pbx_exec(channel, pickup, str->str);
20327
20328 return 0;
20329 }
20330
20331
20332 static int sip_t38_abort(const void *data)
20333 {
20334 struct sip_pvt *p = (struct sip_pvt *) data;
20335
20336 sip_pvt_lock(p);
20337
20338
20339
20340
20341
20342 if (p->t38id != -1) {
20343 change_t38_state(p, T38_DISABLED);
20344 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
20345 p->t38id = -1;
20346 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
20347 }
20348 sip_pvt_unlock(p);
20349 return 0;
20350 }
20351
20352
20353
20354
20355
20356
20357
20358 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)
20359 {
20360 int res = 1;
20361 int gotdest;
20362 const char *p_replaces;
20363 char *replace_id = NULL;
20364 int refer_locked = 0;
20365 const char *required;
20366 unsigned int required_profile = 0;
20367 struct ast_channel *c = NULL;
20368 int reinvite = 0;
20369 int rtn;
20370
20371 const char *p_uac_se_hdr;
20372 const char *p_uac_min_se;
20373 int uac_max_se = -1;
20374 int uac_min_se = -1;
20375 int st_active = FALSE;
20376 int st_interval = 0;
20377 enum st_refresher st_ref;
20378 int dlg_min_se = -1;
20379 struct {
20380 char exten[AST_MAX_EXTENSION];
20381 char context[AST_MAX_CONTEXT];
20382 } pickup = {
20383 .exten = "",
20384 };
20385 st_ref = SESSION_TIMER_REFRESHER_AUTO;
20386
20387
20388 if (!p->sipoptions) {
20389 const char *supported = get_header(req, "Supported");
20390 if (!ast_strlen_zero(supported))
20391 parse_sip_options(p, supported);
20392 }
20393
20394
20395 required = get_header(req, "Require");
20396 if (!ast_strlen_zero(required)) {
20397 required_profile = parse_sip_options(NULL, required);
20398 if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
20399
20400 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
20401 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
20402 p->invitestate = INV_COMPLETED;
20403 if (!p->lastinvite)
20404 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20405 res = -1;
20406 goto request_invite_cleanup;
20407 }
20408 }
20409
20410
20411
20412 p->sipoptions |= required_profile;
20413 p->reqsipoptions = required_profile;
20414
20415
20416 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
20417
20418
20419
20420
20421
20422 int different;
20423 char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
20424 char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
20425 if (sip_cfg.pedanticsipchecking)
20426 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
20427 else
20428 different = strcmp(initial_rlPart2, this_rlPart2);
20429 if (!different) {
20430 transmit_response(p, "482 Loop Detected", req);
20431 p->invitestate = INV_COMPLETED;
20432 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20433 res = 0;
20434 goto request_invite_cleanup;
20435 } else {
20436
20437
20438
20439
20440
20441
20442
20443 char *uri = ast_strdupa(this_rlPart2);
20444 char *at = strchr(uri, '@');
20445 char *peerorhost;
20446 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
20447 transmit_response(p, "100 Trying", req);
20448 if (at) {
20449 *at = '\0';
20450 }
20451
20452 if ((peerorhost = strchr(uri, ':'))) {
20453 *peerorhost++ = '\0';
20454 }
20455 ast_string_field_set(p, theirtag, NULL);
20456
20457
20458 ast_string_field_set(p->owner, call_forward, peerorhost);
20459 ast_queue_control(p->owner, AST_CONTROL_BUSY);
20460 res = 0;
20461 goto request_invite_cleanup;
20462 }
20463 }
20464
20465 if (!req->ignore && p->pendinginvite) {
20466 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477 __sip_ack(p, p->pendinginvite, 1, 0);
20478 } else {
20479
20480 p->glareinvite = seqno;
20481 if (p->rtp && find_sdp(req)) {
20482 struct sockaddr_in sin;
20483 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
20484 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
20485 } else {
20486 ast_rtp_set_alt_peer(p->rtp, &sin);
20487 }
20488 if (p->vrtp) {
20489 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
20490 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
20491 } else {
20492 ast_rtp_set_alt_peer(p->vrtp, &sin);
20493 }
20494 }
20495 }
20496 transmit_response_reliable(p, "491 Request Pending", req);
20497 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
20498
20499 res = 0;
20500 goto request_invite_cleanup;
20501 }
20502 }
20503
20504 p_replaces = get_header(req, "Replaces");
20505 if (!ast_strlen_zero(p_replaces)) {
20506
20507 char *ptr;
20508 char *fromtag = NULL;
20509 char *totag = NULL;
20510 char *start, *to;
20511 int error = 0;
20512
20513 if (p->owner) {
20514 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
20515 transmit_response_reliable(p, "400 Bad request", req);
20516
20517 res = -1;
20518 goto request_invite_cleanup;
20519 }
20520
20521 if (sipdebug)
20522 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
20523
20524 replace_id = ast_strdupa(p_replaces);
20525 ast_uri_decode(replace_id);
20526
20527 if (!p->refer && !sip_refer_allocate(p)) {
20528 transmit_response_reliable(p, "500 Server Internal Error", req);
20529 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
20530 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20531 p->invitestate = INV_COMPLETED;
20532 res = -1;
20533 goto request_invite_cleanup;
20534 }
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545 replace_id = ast_skip_blanks(replace_id);
20546
20547 start = replace_id;
20548 while ( (ptr = strsep(&start, ";")) ) {
20549 ptr = ast_skip_blanks(ptr);
20550 if ( (to = strcasestr(ptr, "to-tag=") ) )
20551 totag = to + 7;
20552 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
20553 fromtag = to + 9;
20554 fromtag = strsep(&fromtag, "&");
20555 }
20556 }
20557
20558 if (sipdebug)
20559 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
20560 replace_id,
20561 fromtag ? fromtag : "<no from tag>",
20562 totag ? totag : "<no to tag>");
20563
20564
20565
20566
20567
20568 if (strncmp(replace_id, "pickup-", 7) == 0) {
20569 struct sip_pvt *subscription = NULL;
20570 replace_id += 7;
20571
20572 if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20573 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
20574 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20575 error = 1;
20576 } else {
20577 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
20578 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
20579 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
20580 sip_pvt_unlock(subscription);
20581 if (subscription->owner) {
20582 ast_channel_unlock(subscription->owner);
20583 }
20584 }
20585 }
20586
20587
20588 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20589 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
20590 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20591 error = 1;
20592 } else {
20593 refer_locked = 1;
20594 }
20595
20596
20597
20598
20599
20600 if (p->refer->refer_call == p) {
20601 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
20602 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
20603 transmit_response_reliable(p, "400 Bad request", req);
20604 error = 1;
20605 }
20606
20607 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
20608
20609 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
20610
20611 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
20612 error = 1;
20613 }
20614
20615 if (!error && ast_strlen_zero(pickup.exten) && 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) {
20616 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20617 transmit_response_reliable(p, "603 Declined (Replaces)", req);
20618 error = 1;
20619 }
20620
20621 if (error) {
20622 append_history(p, "Xfer", "INVITE/Replace Failed.");
20623 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20624 sip_pvt_unlock(p);
20625 if (p->refer->refer_call) {
20626 sip_pvt_unlock(p->refer->refer_call);
20627 if (p->refer->refer_call->owner) {
20628 ast_channel_unlock(p->refer->refer_call->owner);
20629 }
20630 }
20631 refer_locked = 0;
20632 p->invitestate = INV_COMPLETED;
20633 res = -1;
20634 goto request_invite_cleanup;
20635 }
20636 }
20637
20638
20639
20640
20641 if (!req->ignore) {
20642 int newcall = (p->initreq.headers ? TRUE : FALSE);
20643
20644 if (sip_cancel_destroy(p))
20645 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20646
20647 p->pendinginvite = seqno;
20648 check_via(p, req);
20649
20650 copy_request(&p->initreq, req);
20651 if (sipdebug)
20652 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20653 if (!p->owner) {
20654 if (debug)
20655 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20656 if (newcall)
20657 append_history(p, "Invite", "New call: %s", p->callid);
20658 parse_ok_contact(p, req);
20659 } else {
20660 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
20661
20662 if (find_sdp(req)) {
20663 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20664 transmit_response_reliable(p, "488 Not acceptable here", req);
20665 if (!p->lastinvite)
20666 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20667 res = -1;
20668 goto request_invite_cleanup;
20669 }
20670 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20671 } else {
20672 p->jointcapability = p->capability;
20673 ast_debug(1, "Hm.... No sdp for the moment\n");
20674
20675
20676
20677 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
20678 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
20679
20680 ast_queue_frame(p->owner, &ast_null_frame);
20681 change_hold_state(p, req, FALSE, 0);
20682 }
20683 }
20684 if (p->do_history)
20685 append_history(p, "ReInv", "Re-invite received");
20686 }
20687 } else if (debug)
20688 ast_verbose("Ignoring this INVITE request\n");
20689
20690 if (!p->lastinvite && !req->ignore && !p->owner) {
20691
20692
20693 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20694 if (res == AUTH_CHALLENGE_SENT) {
20695 p->invitestate = INV_COMPLETED;
20696 res = 0;
20697 goto request_invite_cleanup;
20698 }
20699 if (res < 0) {
20700 if (res == AUTH_FAKE_AUTH) {
20701 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20702 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20703 } else {
20704 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20705 transmit_response_reliable(p, "403 Forbidden", req);
20706 }
20707 p->invitestate = INV_COMPLETED;
20708 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20709 ast_string_field_set(p, theirtag, NULL);
20710 res = 0;
20711 goto request_invite_cleanup;
20712 }
20713
20714
20715 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20716 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20717 p->t38_maxdatagram = global_t38_maxdatagram;
20718 set_t38_capabilities(p);
20719 } else {
20720
20721 ast_debug(1, "UDPTL creation failed on dialog.\n");
20722 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20723 }
20724 }
20725
20726 req->authenticated = 1;
20727
20728
20729 if (find_sdp(req)) {
20730 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20731
20732 transmit_response_reliable(p, "488 Not acceptable here", req);
20733 p->invitestate = INV_COMPLETED;
20734 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20735 ast_debug(1, "No compatible codecs for this SIP call.\n");
20736 res = -1;
20737 goto request_invite_cleanup;
20738 }
20739 } else {
20740 p->jointcapability = p->capability;
20741 ast_debug(2, "No SDP in Invite, third party call control\n");
20742 }
20743
20744
20745
20746 if (p->owner)
20747 ast_queue_frame(p->owner, &ast_null_frame);
20748
20749
20750
20751 if (ast_strlen_zero(p->context))
20752 ast_string_field_set(p, context, sip_cfg.default_context);
20753
20754
20755
20756 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20757 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20758 if (res < 0) {
20759 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20760 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20761 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20762 p->invitestate = INV_COMPLETED;
20763 }
20764 res = 0;
20765 goto request_invite_cleanup;
20766 }
20767 gotdest = get_destination(p, NULL);
20768 get_rdnis(p, NULL);
20769 extract_uri(p, req);
20770 build_contact(p);
20771
20772 if (p->rtp) {
20773 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20774 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20775 }
20776
20777 if (!replace_id && gotdest) {
20778 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20779 transmit_response_reliable(p, "484 Address Incomplete", req);
20780 else {
20781 char *decoded_exten = ast_strdupa(p->exten);
20782
20783 transmit_response_reliable(p, "404 Not Found", req);
20784 ast_uri_decode(decoded_exten);
20785 ast_log(LOG_NOTICE, "Call from '%s' to extension"
20786 " '%s' rejected because extension not found in context '%s'.\n",
20787 S_OR(p->username, p->peername), decoded_exten, p->context);
20788 }
20789 p->invitestate = INV_COMPLETED;
20790 update_call_counter(p, DEC_CALL_LIMIT);
20791 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20792 res = 0;
20793 goto request_invite_cleanup;
20794 } else {
20795
20796
20797
20798 if (ast_strlen_zero(p->exten))
20799 ast_string_field_set(p, exten, "s");
20800
20801
20802 make_our_tag(p->tag, sizeof(p->tag));
20803
20804
20805 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20806 *recount = 1;
20807
20808
20809 build_route(p, req, 0);
20810
20811 if (c) {
20812
20813 ast_channel_lock(c);
20814 }
20815 }
20816 } else {
20817 if (sipdebug) {
20818 if (!req->ignore)
20819 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20820 else
20821 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20822 }
20823 if (!req->ignore)
20824 reinvite = 1;
20825 c = p->owner;
20826 }
20827
20828
20829 if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
20830
20831
20832 ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
20833
20834
20835 if (!p->stimer)
20836 sip_st_alloc(p);
20837
20838
20839 p_uac_se_hdr = get_header(req, "Session-Expires");
20840 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20841 if (rtn != 0) {
20842 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20843 p->invitestate = INV_COMPLETED;
20844 if (!p->lastinvite) {
20845 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20846 }
20847 res = -1;
20848 goto request_invite_cleanup;
20849 }
20850
20851
20852 p_uac_min_se = get_header(req, "Min-SE");
20853 if (!ast_strlen_zero(p_uac_min_se)) {
20854 rtn = parse_minse(p_uac_min_se, &uac_min_se);
20855 if (rtn != 0) {
20856 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20857 p->invitestate = INV_COMPLETED;
20858 if (!p->lastinvite) {
20859 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20860 }
20861 res = -1;
20862 goto request_invite_cleanup;
20863 }
20864 }
20865
20866 dlg_min_se = st_get_se(p, FALSE);
20867 switch (st_get_mode(p, 1)) {
20868 case SESSION_TIMER_MODE_ACCEPT:
20869 case SESSION_TIMER_MODE_ORIGINATE:
20870 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20871 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20872 p->invitestate = INV_COMPLETED;
20873 if (!p->lastinvite) {
20874 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20875 }
20876 res = -1;
20877 goto request_invite_cleanup;
20878 }
20879
20880 p->stimer->st_active_peer_ua = TRUE;
20881 st_active = TRUE;
20882 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20883 st_ref = st_get_refresher(p);
20884 }
20885
20886 if (uac_max_se > 0) {
20887 int dlg_max_se = st_get_se(p, TRUE);
20888 if (dlg_max_se >= uac_min_se) {
20889 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20890 } else {
20891 st_interval = uac_max_se;
20892 }
20893 } else {
20894
20895 st_interval = global_max_se;
20896 }
20897 break;
20898
20899 case SESSION_TIMER_MODE_REFUSE:
20900 if (p->reqsipoptions & SIP_OPT_TIMER) {
20901 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20902 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20903 p->invitestate = INV_COMPLETED;
20904 if (!p->lastinvite) {
20905 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20906 }
20907 res = -1;
20908 goto request_invite_cleanup;
20909 }
20910 break;
20911
20912 default:
20913 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
20914 break;
20915 }
20916 } else {
20917
20918
20919
20920 switch (st_get_mode(p, 1)) {
20921 case SESSION_TIMER_MODE_ORIGINATE:
20922 st_active = TRUE;
20923 st_interval = st_get_se(p, TRUE);
20924 st_ref = SESSION_TIMER_REFRESHER_UAS;
20925 p->stimer->st_active_peer_ua = FALSE;
20926 break;
20927
20928 default:
20929 break;
20930 }
20931 }
20932
20933 if (reinvite == 0) {
20934
20935 if (st_active == TRUE) {
20936 p->stimer->st_active = TRUE;
20937 p->stimer->st_interval = st_interval;
20938 p->stimer->st_ref = st_ref;
20939 start_session_timer(p);
20940 }
20941 } else {
20942 if (p->stimer->st_active == TRUE) {
20943
20944
20945
20946 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20947
20948
20949 if (st_interval > 0) {
20950 p->stimer->st_interval = st_interval;
20951 p->stimer->st_ref = st_ref;
20952 }
20953
20954 restart_session_timer(p);
20955 if (p->stimer->st_expirys > 0) {
20956 p->stimer->st_expirys--;
20957 }
20958 }
20959 }
20960
20961 if (!req->ignore && p)
20962 p->lastinvite = seqno;
20963
20964 if (c && replace_id) {
20965 if (!ast_strlen_zero(pickup.exten)) {
20966 append_history(p, "Xfer", "INVITE/Replace received");
20967
20968
20969 transmit_response(p, "100 Trying", req);
20970 p->invitestate = INV_PROCEEDING;
20971 ast_setstate(c, AST_STATE_RING);
20972
20973
20974 ast_channel_unlock(c);
20975 *nounlock = 1;
20976
20977
20978
20979
20980
20981
20982 sip_pvt_unlock(p);
20983 do_magic_pickup(c, pickup.exten, pickup.context);
20984
20985 ast_hangup(c);
20986 sip_pvt_lock(p);
20987
20988 res = 0;
20989 goto request_invite_cleanup;
20990 } else {
20991
20992 if (sipdebug)
20993 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20994 res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20995 refer_locked = 0;
20996 goto request_invite_cleanup;
20997 }
20998 }
20999
21000
21001 if (c) {
21002 enum ast_channel_state c_state = c->_state;
21003
21004 if (c_state != AST_STATE_UP && reinvite &&
21005 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015 c_state = AST_STATE_UP;
21016 }
21017
21018 switch(c_state) {
21019 case AST_STATE_DOWN:
21020 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
21021 transmit_provisional_response(p, "100 Trying", req, 0);
21022 p->invitestate = INV_PROCEEDING;
21023 ast_setstate(c, AST_STATE_RING);
21024 if (strcmp(p->exten, ast_pickup_ext())) {
21025 enum ast_pbx_result result;
21026
21027 result = ast_pbx_start(c);
21028
21029 switch(result) {
21030 case AST_PBX_FAILED:
21031 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
21032 p->invitestate = INV_COMPLETED;
21033 transmit_response_reliable(p, "503 Unavailable", req);
21034 break;
21035 case AST_PBX_CALL_LIMIT:
21036 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
21037 p->invitestate = INV_COMPLETED;
21038 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
21039 break;
21040 case AST_PBX_SUCCESS:
21041
21042 break;
21043 }
21044
21045 if (result) {
21046
21047
21048 ast_channel_unlock(c);
21049 *nounlock = 1;
21050 sip_pvt_unlock(p);
21051 ast_hangup(c);
21052 sip_pvt_lock(p);
21053 c = NULL;
21054 }
21055 } else {
21056 if (sip_pickup(c)) {
21057 ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
21058 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
21059 sip_alreadygone(p);
21060 c->hangupcause = AST_CAUSE_FAILURE;
21061
21062
21063 ast_channel_unlock(c);
21064 *nounlock = 1;
21065
21066 p->invitestate = INV_COMPLETED;
21067 sip_pvt_unlock(p);
21068 ast_hangup(c);
21069 sip_pvt_lock(p);
21070 c = NULL;
21071 }
21072 }
21073 break;
21074 case AST_STATE_RING:
21075 transmit_provisional_response(p, "100 Trying", req, 0);
21076 p->invitestate = INV_PROCEEDING;
21077 break;
21078 case AST_STATE_RINGING:
21079 transmit_provisional_response(p, "180 Ringing", req, 0);
21080 p->invitestate = INV_PROCEEDING;
21081 break;
21082 case AST_STATE_UP:
21083 ast_debug(2, "%s: This call is UP.... \n", c->name);
21084
21085 transmit_response(p, "100 Trying", req);
21086
21087 if (p->t38.state == T38_PEER_REINVITE) {
21088 if (p->t38id > -1) {
21089
21090 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
21091 }
21092 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."));
21093 } else if (p->t38.state == T38_ENABLED) {
21094 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21095 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
21096 } else if (p->t38.state == T38_DISABLED) {
21097
21098 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21099 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
21100 }
21101
21102 p->invitestate = INV_TERMINATED;
21103 break;
21104 default:
21105 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
21106 transmit_response(p, "100 Trying", req);
21107 break;
21108 }
21109 } else {
21110 if (p && (p->autokillid == -1)) {
21111 const char *msg;
21112
21113 if (!p->jointcapability)
21114 msg = "488 Not Acceptable Here (codec error)";
21115 else {
21116 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
21117 msg = "503 Unavailable";
21118 }
21119 transmit_response_reliable(p, msg, req);
21120 p->invitestate = INV_COMPLETED;
21121 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21122 }
21123 }
21124
21125 request_invite_cleanup:
21126
21127 if (refer_locked && p->refer && p->refer->refer_call) {
21128 sip_pvt_unlock(p->refer->refer_call);
21129 if (p->refer->refer_call->owner) {
21130 ast_channel_unlock(p->refer->refer_call->owner);
21131 }
21132 }
21133
21134 return res;
21135 }
21136
21137
21138
21139 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
21140 {
21141 struct sip_dual target;
21142
21143 int res = 0;
21144 struct sip_pvt *targetcall_pvt;
21145
21146
21147 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
21148 transferer->refer->replaces_callid_fromtag))) {
21149 if (transferer->refer->localtransfer) {
21150
21151
21152
21153 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
21154 append_history(transferer, "Xfer", "Refer failed");
21155 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21156 transferer->refer->status = REFER_FAILED;
21157 return -1;
21158 }
21159
21160 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
21161 return 0;
21162 }
21163
21164
21165 append_history(transferer, "Xfer", "Refer accepted");
21166 if (!targetcall_pvt->owner) {
21167 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
21168
21169 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
21170 append_history(transferer, "Xfer", "Refer failed");
21171 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21172 transferer->refer->status = REFER_FAILED;
21173 sip_pvt_unlock(targetcall_pvt);
21174 if (targetcall_pvt)
21175 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
21176 return -1;
21177 }
21178
21179
21180 target.chan1 = targetcall_pvt->owner;
21181 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
21182
21183 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
21184
21185 if (target.chan2)
21186 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
21187 else if (target.chan1->_state != AST_STATE_RING)
21188 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
21189 else
21190 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
21191 }
21192
21193
21194 if (sipdebug) {
21195 if (current->chan2)
21196 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
21197 else
21198 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
21199 }
21200
21201 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21202
21203
21204 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",
21205 transferer->owner->name,
21206 transferer->owner->uniqueid,
21207 transferer->callid,
21208 target.chan1->name,
21209 target.chan1->uniqueid);
21210 res = attempt_transfer(current, &target);
21211 sip_pvt_unlock(targetcall_pvt);
21212 if (res) {
21213
21214 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
21215 append_history(transferer, "Xfer", "Refer failed");
21216 if (targetcall_pvt->owner)
21217 ast_channel_unlock(targetcall_pvt->owner);
21218 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21219 } else {
21220
21221 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
21222
21223
21224 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
21225 append_history(transferer, "Xfer", "Refer succeeded");
21226 transferer->refer->status = REFER_200OK;
21227 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
21228 ast_waitstream(target.chan2, "");
21229 }
21230 if (targetcall_pvt->owner) {
21231 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
21232 ast_channel_unlock(targetcall_pvt->owner);
21233 }
21234 ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
21235 if (target.chan2) {
21236 ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
21237 }
21238 }
21239 if (targetcall_pvt)
21240 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
21241 return 1;
21242 }
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
21309 {
21310 struct sip_dual current;
21311
21312
21313 int res = 0;
21314 current.req.data = NULL;
21315
21316 if (req->debug)
21317 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");
21318
21319 if (!p->owner) {
21320
21321
21322 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
21323 transmit_response(p, "603 Declined (No dialog)", req);
21324 if (!req->ignore) {
21325 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
21326 sip_alreadygone(p);
21327 pvt_set_needdestroy(p, "outside of dialog");
21328 }
21329 return 0;
21330 }
21331
21332
21333
21334 if (p->allowtransfer == TRANSFER_CLOSED ) {
21335
21336 transmit_response(p, "603 Declined (policy)", req);
21337 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
21338
21339 return 0;
21340 }
21341
21342 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
21343
21344 transmit_response(p, "491 Request pending", req);
21345 append_history(p, "Xfer", "Refer failed. Request pending.");
21346 return 0;
21347 }
21348
21349
21350 if (!p->refer && !sip_refer_allocate(p)) {
21351 transmit_response(p, "500 Internal Server Error", req);
21352 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
21353 return -3;
21354 }
21355
21356 res = get_refer_info(p, req);
21357
21358 p->refer->status = REFER_SENT;
21359
21360 if (res != 0) {
21361 switch (res) {
21362 case -2:
21363 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
21364 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
21365 if (req->debug)
21366 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
21367 break;
21368 case -3:
21369 transmit_response(p, "603 Declined (Non sip: uri)", req);
21370 append_history(p, "Xfer", "Refer failed. Non SIP uri");
21371 if (req->debug)
21372 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
21373 break;
21374 default:
21375
21376 transmit_response(p, "202 Accepted", req);
21377 append_history(p, "Xfer", "Refer failed. Bad extension.");
21378 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
21379 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21380 if (req->debug)
21381 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
21382 break;
21383 }
21384 return 0;
21385 }
21386 if (ast_strlen_zero(p->context))
21387 ast_string_field_set(p, context, sip_cfg.default_context);
21388
21389
21390 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
21391 p->refer->localtransfer = 1;
21392 if (sipdebug)
21393 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
21394 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
21395
21396 p->refer->localtransfer = 1;
21397 } else if (sipdebug)
21398 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
21399
21400
21401
21402 if (req->ignore)
21403 return res;
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431 current.chan1 = p->owner;
21432
21433
21434 current.chan2 = ast_bridged_channel(current.chan1);
21435
21436 if (sipdebug)
21437 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>");
21438
21439 if (!current.chan2 && !p->refer->attendedtransfer) {
21440
21441
21442
21443 if (sipdebug)
21444 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
21445 p->refer->status = REFER_FAILED;
21446 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
21447 transmit_response(p, "603 Declined", req);
21448 return -1;
21449 }
21450
21451 if (current.chan2) {
21452 if (sipdebug)
21453 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
21454
21455 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
21456 }
21457
21458 ast_set_flag(&p->flags[0], SIP_GOTREFER);
21459
21460
21461 transmit_response(p, "202 Accepted", req);
21462
21463
21464 if (p->refer->attendedtransfer) {
21465 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
21466 return res;
21467
21468 if (sipdebug)
21469 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
21470
21471 }
21472
21473
21474
21475 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
21476
21477 *nounlock = 1;
21478 ast_channel_unlock(current.chan1);
21479 copy_request(¤t.req, req);
21480 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21481 p->refer->status = REFER_200OK;
21482 append_history(p, "Xfer", "REFER to call parking.");
21483 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",
21484 current.chan1->name,
21485 current.chan1->uniqueid,
21486 p->callid,
21487 current.chan2->name,
21488 current.chan2->uniqueid,
21489 p->refer->refer_to);
21490 if (sipdebug)
21491 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
21492 if ((res = sip_park(current.chan2, current.chan1, req, seqno))) {
21493 transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
21494 }
21495 return res;
21496 }
21497
21498
21499 if (current.chan1 && current.chan2) {
21500 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
21501 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
21502 }
21503 if (current.chan2) {
21504 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
21505 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
21506 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
21507
21508 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
21509
21510 if (p->refer->referred_by)
21511 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
21512 }
21513
21514 if (!ast_strlen_zero(p->refer->replaces_callid)) {
21515 char tempheader[SIPBUFSIZE];
21516 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
21517 p->refer->replaces_callid_totag ? ";to-tag=" : "",
21518 p->refer->replaces_callid_totag,
21519 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
21520 p->refer->replaces_callid_fromtag);
21521 if (current.chan2)
21522 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
21523 }
21524
21525
21526 *nounlock = 1;
21527 ast_channel_unlock(current.chan1);
21528
21529
21530
21531
21532 if (!p->refer->attendedtransfer)
21533 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
21534
21535
21536
21537
21538
21539 if (!current.chan2) {
21540
21541
21542
21543
21544
21545
21546
21547 p->refer->status = REFER_FAILED;
21548 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
21549 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21550 append_history(p, "Xfer", "Refer failed (only bridged calls).");
21551 return -1;
21552 }
21553 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21554
21555
21556
21557
21558
21559
21560 ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
21561 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
21562
21563 if (!res) {
21564 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",
21565 current.chan1->name,
21566 current.chan1->uniqueid,
21567 p->callid,
21568 current.chan2->name,
21569 current.chan2->uniqueid,
21570 p->refer->refer_to, p->refer->refer_to_context);
21571
21572 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21573 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
21574 if (p->refer->localtransfer)
21575 p->refer->status = REFER_200OK;
21576 if (p->owner)
21577 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21578 append_history(p, "Xfer", "Refer succeeded.");
21579 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21580
21581
21582 res = 0;
21583 } else {
21584 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21585 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21586 append_history(p, "Xfer", "Refer failed.");
21587
21588 p->refer->status = REFER_FAILED;
21589 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
21590 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21591 res = -1;
21592 }
21593 return res;
21594 }
21595
21596
21597 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
21598 {
21599
21600 check_via(p, req);
21601 sip_alreadygone(p);
21602
21603
21604
21605
21606
21607
21608 if (p->invitestate == INV_TERMINATED)
21609 __sip_pretend_ack(p);
21610 else
21611 p->invitestate = INV_CANCELLED;
21612
21613 if (p->owner && p->owner->_state == AST_STATE_UP) {
21614
21615 transmit_response(p, "200 OK", req);
21616 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
21617 return 0;
21618 }
21619
21620 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
21621 update_call_counter(p, DEC_CALL_LIMIT);
21622
21623 stop_media_flows(p);
21624 if (p->owner)
21625 ast_queue_hangup(p->owner);
21626 else
21627 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21628 if (p->initreq.len > 0) {
21629 struct sip_pkt *pkt, *prev_pkt;
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21642 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21643 AST_SCHED_DEL(sched, pkt->retransid);
21644 UNLINK(pkt, p->packets, prev_pkt);
21645 dialog_unref(pkt->owner, "unref packet->owner from dialog");
21646 if (pkt->data) {
21647 ast_free(pkt->data);
21648 }
21649 ast_free(pkt);
21650 break;
21651 }
21652 }
21653 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21654 transmit_response(p, "200 OK", req);
21655 return 1;
21656 } else {
21657 transmit_response(p, "481 Call Leg Does Not Exist", req);
21658 return 0;
21659 }
21660 }
21661
21662 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21663 {
21664 struct sip_pvt *p = chan->tech_pvt;
21665 char *all = "", *parse = ast_strdupa(preparse);
21666 int res = 0;
21667 AST_DECLARE_APP_ARGS(args,
21668 AST_APP_ARG(param);
21669 AST_APP_ARG(type);
21670 AST_APP_ARG(field);
21671 );
21672 AST_STANDARD_APP_ARGS(args, parse);
21673
21674
21675 if (!IS_SIP_TECH(chan->tech)) {
21676 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21677 return 0;
21678 }
21679
21680 memset(buf, 0, buflen);
21681
21682 if (p == NULL) {
21683 return -1;
21684 }
21685
21686 if (!strcasecmp(args.param, "peerip")) {
21687 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21688 } else if (!strcasecmp(args.param, "recvip")) {
21689 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21690 } else if (!strcasecmp(args.param, "from")) {
21691 ast_copy_string(buf, p->from, buflen);
21692 } else if (!strcasecmp(args.param, "uri")) {
21693 ast_copy_string(buf, p->uri, buflen);
21694 } else if (!strcasecmp(args.param, "useragent")) {
21695 ast_copy_string(buf, p->useragent, buflen);
21696 } else if (!strcasecmp(args.param, "peername")) {
21697 ast_copy_string(buf, p->peername, buflen);
21698 } else if (!strcasecmp(args.param, "t38passthrough")) {
21699 ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21700 } else if (!strcasecmp(args.param, "rtpdest")) {
21701 struct sockaddr_in sin;
21702 struct ast_rtp *stream = NULL;
21703
21704 if (ast_strlen_zero(args.type))
21705 args.type = "audio";
21706
21707 if (!strcasecmp(args.type, "audio")) {
21708 stream = p->rtp;
21709 } else if (!strcasecmp(args.type, "video")) {
21710 stream = p->vrtp;
21711 } else if (!strcasecmp(args.type, "text")) {
21712 stream = p->trtp;
21713 } else {
21714 return -1;
21715 }
21716
21717 if (!stream) {
21718 return -1;
21719 }
21720
21721 ast_rtp_get_peer(stream, &sin);
21722 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21723 } else if (!strcasecmp(args.param, "rtpqos")) {
21724 struct ast_rtp_quality qos;
21725 struct ast_rtp *rtp = p->rtp;
21726
21727 memset(&qos, 0, sizeof(qos));
21728
21729 if (ast_strlen_zero(args.type))
21730 args.type = "audio";
21731 if (ast_strlen_zero(args.field))
21732 args.field = "all";
21733
21734 if (!strcasecmp(args.type, "AUDIO")) {
21735 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21736 } else if (!strcasecmp(args.type, "VIDEO")) {
21737 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21738 } else if (!strcasecmp(args.type, "TEXT")) {
21739 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21740 } else {
21741 return -1;
21742 }
21743
21744 if (!strcasecmp(args.field, "local_ssrc"))
21745 snprintf(buf, buflen, "%u", qos.local_ssrc);
21746 else if (!strcasecmp(args.field, "local_lostpackets"))
21747 snprintf(buf, buflen, "%u", qos.local_lostpackets);
21748 else if (!strcasecmp(args.field, "local_jitter"))
21749 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21750 else if (!strcasecmp(args.field, "local_count"))
21751 snprintf(buf, buflen, "%u", qos.local_count);
21752 else if (!strcasecmp(args.field, "remote_ssrc"))
21753 snprintf(buf, buflen, "%u", qos.remote_ssrc);
21754 else if (!strcasecmp(args.field, "remote_lostpackets"))
21755 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21756 else if (!strcasecmp(args.field, "remote_jitter"))
21757 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21758 else if (!strcasecmp(args.field, "remote_count"))
21759 snprintf(buf, buflen, "%u", qos.remote_count);
21760 else if (!strcasecmp(args.field, "rtt"))
21761 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21762 else if (!strcasecmp(args.field, "all"))
21763 ast_copy_string(buf, all, buflen);
21764 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21765 ;
21766 else {
21767 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21768 return -1;
21769 }
21770 } else {
21771 res = -1;
21772 }
21773 return res;
21774 }
21775
21776
21777 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21778 {
21779 struct ast_channel *c=NULL;
21780 int res;
21781 struct ast_channel *bridged_to;
21782
21783
21784 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21785 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21786 }
21787
21788 __sip_pretend_ack(p);
21789
21790 p->invitestate = INV_TERMINATED;
21791
21792 copy_request(&p->initreq, req);
21793 if (sipdebug)
21794 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21795 check_via(p, req);
21796 sip_alreadygone(p);
21797
21798
21799 if (p->do_history || p->owner) {
21800 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21801 char *videoqos, *textqos;
21802
21803
21804
21805
21806 while (bridge && ast_channel_trylock(bridge)) {
21807 ast_channel_unlock(p->owner);
21808 do {
21809
21810 sip_pvt_unlock(p);
21811 usleep(1);
21812 sip_pvt_lock(p);
21813 } while (p->owner && ast_channel_trylock(p->owner));
21814 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21815 }
21816
21817 if (p->rtp) {
21818 if (p->do_history) {
21819 char *audioqos,
21820 *audioqos_jitter,
21821 *audioqos_loss,
21822 *audioqos_rtt;
21823
21824 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21825 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21826 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21827 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21828
21829 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21830 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21831 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21832 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21833 }
21834
21835 if (p->owner) {
21836 ast_rtp_set_vars(p->owner, p->rtp);
21837 }
21838 }
21839
21840 if (bridge) {
21841 struct sip_pvt *q = bridge->tech_pvt;
21842
21843 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21844 ast_rtp_set_vars(bridge, q->rtp);
21845 ast_channel_unlock(bridge);
21846 }
21847
21848 if (p->vrtp) {
21849 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21850 if (p->do_history)
21851 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21852 if (p->owner)
21853 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21854 }
21855
21856 if (p->trtp) {
21857 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21858 if (p->do_history)
21859 append_history(p, "RTCPtext", "Quality:%s", textqos);
21860 if (p->owner)
21861 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21862 }
21863 }
21864
21865 stop_media_flows(p);
21866 stop_session_timer(p);
21867
21868 if (!ast_strlen_zero(get_header(req, "Also"))) {
21869 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
21870 ast_inet_ntoa(p->recv.sin_addr));
21871 if (ast_strlen_zero(p->context))
21872 ast_string_field_set(p, context, sip_cfg.default_context);
21873 res = get_also_info(p, req);
21874 if (!res) {
21875 c = p->owner;
21876 if (c) {
21877 bridged_to = ast_bridged_channel(c);
21878 if (bridged_to) {
21879
21880 ast_queue_control(c, AST_CONTROL_UNHOLD);
21881 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21882 } else
21883 ast_queue_hangup(p->owner);
21884 }
21885 } else {
21886 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21887 if (p->owner)
21888 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21889 }
21890 } else if (p->owner) {
21891 ast_queue_hangup(p->owner);
21892 ast_debug(3, "Received bye, issuing owner hangup\n");
21893 } else {
21894 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21895 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21896 }
21897 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21898 transmit_response(p, "200 OK", req);
21899
21900 return 1;
21901 }
21902
21903
21904 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21905 {
21906 if (!req->ignore) {
21907 if (req->debug)
21908 ast_verbose("Receiving message!\n");
21909 receive_message(p, req);
21910 } else
21911 transmit_response(p, "202 Accepted", req);
21912 return 1;
21913 }
21914
21915 static void add_peer_mwi_subs(struct sip_peer *peer)
21916 {
21917 struct sip_mailbox *mailbox;
21918
21919 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21920 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21921 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21922 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21923 AST_EVENT_IE_END);
21924 }
21925 }
21926
21927
21928 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21929 {
21930 int gotdest = 0;
21931 int res = 0;
21932 int firststate = AST_EXTENSION_REMOVED;
21933 struct sip_peer *authpeer = NULL;
21934 const char *eventheader = get_header(req, "Event");
21935 int resubscribe = (p->subscribed != NONE) && !req->ignore;
21936 char *temp, *event;
21937
21938 if (p->initreq.headers) {
21939
21940 if (p->initreq.method != SIP_SUBSCRIBE) {
21941
21942
21943 transmit_response(p, "403 Forbidden (within dialog)", req);
21944
21945 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);
21946 return 0;
21947 } else if (req->debug) {
21948 if (resubscribe)
21949 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21950 else
21951 ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
21952 }
21953 }
21954
21955
21956
21957
21958 if (!sip_cfg.allowsubscribe) {
21959 transmit_response(p, "403 Forbidden (policy)", req);
21960 pvt_set_needdestroy(p, "forbidden");
21961 return 0;
21962 }
21963
21964 if (!req->ignore && !resubscribe) {
21965 const char *to = get_header(req, "To");
21966 char totag[128];
21967
21968
21969 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21970 if (req->debug)
21971 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21972 transmit_response(p, "481 Subscription does not exist", req);
21973 pvt_set_needdestroy(p, "subscription does not exist");
21974 return 0;
21975 }
21976
21977
21978 if (req->debug)
21979 ast_verbose("Creating new subscription\n");
21980
21981 copy_request(&p->initreq, req);
21982 if (sipdebug)
21983 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21984 check_via(p, req);
21985 build_route(p, req, 0);
21986 } else if (req->debug && req->ignore)
21987 ast_verbose("Ignoring this SUBSCRIBE request\n");
21988
21989
21990 if (ast_strlen_zero(eventheader)) {
21991 transmit_response(p, "489 Bad Event", req);
21992 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21993 pvt_set_needdestroy(p, "unknown event package in subscribe");
21994 return 0;
21995 }
21996
21997 if ( (strchr(eventheader, ';'))) {
21998 event = ast_strdupa(eventheader);
21999 temp = strchr(event, ';');
22000 *temp = '\0';
22001
22002 } else
22003 event = (char *) eventheader;
22004
22005
22006
22007
22008 if (p->subscribed == NONE || resubscribe) {
22009 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
22010
22011
22012 if (res == AUTH_CHALLENGE_SENT)
22013 return 0;
22014 if (res < 0) {
22015 if (res == AUTH_FAKE_AUTH) {
22016 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22017 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
22018 } else {
22019 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
22020 transmit_response_reliable(p, "403 Forbidden", req);
22021 }
22022
22023 pvt_set_needdestroy(p, "authentication failed");
22024 return 0;
22025 }
22026 }
22027
22028
22029
22030
22031
22032
22033
22034 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
22035 transmit_response(p, "403 Forbidden (policy)", req);
22036 pvt_set_needdestroy(p, "subscription not allowed");
22037 if (authpeer)
22038 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
22039 return 0;
22040 }
22041
22042 if (strcmp(event, "message-summary")) {
22043
22044 gotdest = get_destination(p, NULL);
22045 }
22046
22047
22048 parse_ok_contact(p, req);
22049
22050 build_contact(p);
22051 if (gotdest) {
22052 transmit_response(p, "404 Not Found", req);
22053 pvt_set_needdestroy(p, "subscription target not found");
22054 if (authpeer)
22055 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
22056 return 0;
22057 }
22058
22059
22060 if (ast_strlen_zero(p->tag))
22061 make_our_tag(p->tag, sizeof(p->tag));
22062
22063 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
22064 unsigned int pidf_xml;
22065 const char *accept;
22066 int start = 0;
22067 enum subscriptiontype subscribed = NONE;
22068 const char *unknown_acceptheader = NULL;
22069
22070 if (authpeer)
22071 authpeer = unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
22072
22073
22074
22075 accept = __get_header(req, "Accept", &start);
22076 while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
22077 pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
22078
22079
22080
22081 if (pidf_xml && strstr(p->useragent, "Polycom")) {
22082 subscribed = XPIDF_XML;
22083 } else if (pidf_xml) {
22084 subscribed = PIDF_XML;
22085 } else if (strstr(accept, "application/dialog-info+xml")) {
22086 subscribed = DIALOG_INFO_XML;
22087
22088 } else if (strstr(accept, "application/cpim-pidf+xml")) {
22089 subscribed = CPIM_PIDF_XML;
22090 } else if (strstr(accept, "application/xpidf+xml")) {
22091 subscribed = XPIDF_XML;
22092 } else {
22093 unknown_acceptheader = accept;
22094 }
22095
22096 accept = __get_header(req, "Accept", &start);
22097 }
22098
22099 if (!start) {
22100 if (p->subscribed == NONE) {
22101 transmit_response(p, "489 Bad Event", req);
22102 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
22103 "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
22104 "'%s', subscribeuri: '%s'\n",
22105 p->stateid,
22106 p->laststate,
22107 p->dialogver,
22108 p->subscribecontext,
22109 p->subscribeuri);
22110 pvt_set_needdestroy(p, "no Accept header");
22111 return 0;
22112 }
22113
22114
22115 } else if (subscribed == NONE) {
22116
22117 char mybuf[200];
22118 if (!ast_strlen_zero(unknown_acceptheader)) {
22119 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
22120 } else {
22121 snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
22122 }
22123 transmit_response(p, mybuf, req);
22124 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
22125 "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
22126 "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
22127 unknown_acceptheader,
22128 (int)p->subscribed,
22129 p->stateid,
22130 p->laststate,
22131 p->dialogver,
22132 p->subscribecontext,
22133 p->subscribeuri);
22134 pvt_set_needdestroy(p, "unrecognized format");
22135 return 0;
22136 } else {
22137 p->subscribed = subscribed;
22138 }
22139 } else if (!strcmp(event, "message-summary")) {
22140 int start = 0;
22141 int found_supported = 0;
22142 const char *acceptheader;
22143
22144 acceptheader = __get_header(req, "Accept", &start);
22145 while (!found_supported && !ast_strlen_zero(acceptheader)) {
22146 found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
22147 if (!found_supported && (option_debug > 2)) {
22148 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
22149 }
22150 acceptheader = __get_header(req, "Accept", &start);
22151 }
22152 if (start && !found_supported) {
22153
22154 transmit_response(p, "406 Not Acceptable", req);
22155 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
22156 pvt_set_needdestroy(p, "unknown format");
22157 if (authpeer)
22158 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
22159 return 0;
22160 }
22161
22162
22163
22164
22165
22166
22167 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
22168 transmit_response(p, "404 Not found (no mailbox)", req);
22169 pvt_set_needdestroy(p, "received 404 response");
22170 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
22171 if (authpeer)
22172 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
22173 return 0;
22174 }
22175
22176 p->subscribed = MWI_NOTIFICATION;
22177 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
22178 add_peer_mwi_subs(authpeer);
22179 }
22180 if (authpeer->mwipvt && authpeer->mwipvt != p) {
22181
22182 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
22183 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
22184
22185 }
22186 if (authpeer->mwipvt)
22187 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
22188 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
22189 if (p->relatedpeer)
22190 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
22191 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
22192
22193 } else {
22194 transmit_response(p, "489 Bad Event", req);
22195 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
22196 pvt_set_needdestroy(p, "unknown event package");
22197 if (authpeer)
22198 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
22199 return 0;
22200 }
22201
22202
22203 if (authpeer) {
22204 authpeer = unref_peer(authpeer, "unref pointer into (*authpeer)");
22205 }
22206
22207
22208 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
22209 if (p->stateid > -1) {
22210 ast_extension_state_del(p->stateid, cb_extensionstate);
22211
22212 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
22213 }
22214 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
22215 }
22216
22217 if (!req->ignore && p)
22218 p->lastinvite = seqno;
22219 if (p && !p->needdestroy) {
22220 p->expiry = atoi(get_header(req, "Expires"));
22221
22222
22223 if (p->expiry > max_expiry)
22224 p->expiry = max_expiry;
22225 if (p->expiry < min_expiry && p->expiry > 0)
22226 p->expiry = min_expiry;
22227
22228 if (sipdebug) {
22229 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
22230 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
22231 else
22232 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
22233 }
22234 if (p->autokillid > -1 && sip_cancel_destroy(p))
22235 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22236 if (p->expiry > 0)
22237 sip_scheddestroy(p, (p->expiry + 10) * 1000);
22238
22239 if (p->subscribed == MWI_NOTIFICATION) {
22240 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22241 transmit_response(p, "200 OK", req);
22242 if (p->relatedpeer) {
22243 ao2_lock(p->relatedpeer);
22244 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
22245 ao2_unlock(p->relatedpeer);
22246 }
22247 } else {
22248
22249 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
22250
22251 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));
22252 transmit_response(p, "404 Not found", req);
22253 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
22254 return 0;
22255 }
22256 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22257 transmit_response(p, "200 OK", req);
22258 transmit_state_notify(p, firststate, 1, FALSE);
22259 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
22260
22261 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
22262
22263
22264 }
22265 if (!p->expiry) {
22266 pvt_set_needdestroy(p, "forcing expiration");
22267 }
22268 }
22269 return 1;
22270 }
22271
22272
22273 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
22274 {
22275 enum check_auth_result res;
22276
22277
22278
22279 if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
22280 ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
22281 return -1;
22282 }
22283
22284
22285 copy_request(&p->initreq, req);
22286 if (sipdebug)
22287 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22288 check_via(p, req);
22289 if ((res = register_verify(p, sin, req, e)) < 0) {
22290 const char *reason;
22291
22292 switch (res) {
22293 case AUTH_SECRET_FAILED:
22294 reason = "Wrong password";
22295 break;
22296 case AUTH_USERNAME_MISMATCH:
22297 reason = "Username/auth name mismatch";
22298 break;
22299 case AUTH_NOT_FOUND:
22300 reason = "No matching peer found";
22301 break;
22302 case AUTH_UNKNOWN_DOMAIN:
22303 reason = "Not a local domain";
22304 break;
22305 case AUTH_PEER_NOT_DYNAMIC:
22306 reason = "Peer is not supposed to register";
22307 break;
22308 case AUTH_ACL_FAILED:
22309 reason = "Device does not match ACL";
22310 break;
22311 case AUTH_BAD_TRANSPORT:
22312 reason = "Device not configured to use this transport type";
22313 break;
22314 default:
22315 reason = "Unknown failure";
22316 break;
22317 }
22318 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
22319 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
22320 reason);
22321 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
22322 } else {
22323 req->authenticated = 1;
22324 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
22325 }
22326
22327 if (res < 1) {
22328
22329
22330 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22331 }
22332 return res;
22333 }
22334
22335
22336
22337
22338
22339
22340
22341
22342 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
22343 {
22344
22345
22346 const char *cmd;
22347 const char *cseq;
22348 const char *useragent;
22349 const char *via;
22350 const char *callid;
22351 int via_pos = 0;
22352 int seqno;
22353 int len;
22354 int respid;
22355 int res = 0;
22356 int debug = sip_debug_test_pvt(p);
22357 char *e;
22358 int error = 0;
22359 int oldmethod = p->method;
22360 int acked = 0;
22361
22362
22363
22364
22365 cseq = get_header(req, "Cseq");
22366 cmd = REQ_OFFSET_TO_STR(req, header[0]);
22367
22368 via = __get_header(req, "Via", &via_pos);
22369
22370 callid = get_header(req, "Call-ID");
22371
22372
22373 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
22374 ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
22375 error = 1;
22376 }
22377 if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
22378 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
22379 error = 1;
22380 }
22381 if (error) {
22382 if (!p->initreq.headers) {
22383 pvt_set_needdestroy(p, "no headers");
22384 }
22385 return -1;
22386 }
22387
22388
22389 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
22390 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
22391
22392
22393 useragent = get_header(req, "User-Agent");
22394 if (!ast_strlen_zero(useragent))
22395 ast_string_field_set(p, useragent, useragent);
22396
22397
22398 if (req->method == SIP_RESPONSE) {
22399
22400
22401
22402
22403
22404
22405 if (ast_strlen_zero(e)) {
22406 return 0;
22407 }
22408 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
22409 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
22410 return 0;
22411 }
22412 if (respid <= 0) {
22413 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
22414 return 0;
22415 }
22416
22417
22418
22419 if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
22420 ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
22421 return 0;
22422 }
22423 if (p->ocseq && (p->ocseq < seqno)) {
22424 if (option_debug)
22425 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
22426 return -1;
22427 } else {
22428 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
22429 extract_uri(p, req);
22430 }
22431 handle_response(p, respid, e + len, req, seqno);
22432 }
22433 return 0;
22434 }
22435
22436
22437
22438
22439
22440 p->method = req->method;
22441 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
22442
22443 if (p->icseq && (p->icseq > seqno) ) {
22444 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
22445 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
22446 } else {
22447 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
22448 if (req->method != SIP_ACK)
22449 transmit_response(p, "500 Server error", req);
22450 return -1;
22451 }
22452 } else if (p->icseq &&
22453 p->icseq == seqno &&
22454 req->method != SIP_ACK &&
22455 (p->method != SIP_CANCEL || p->alreadygone)) {
22456
22457
22458
22459 req->ignore = 1;
22460 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
22461 }
22462
22463 if (seqno >= p->icseq)
22464
22465
22466
22467 p->icseq = seqno;
22468
22469
22470 if (ast_strlen_zero(p->theirtag)) {
22471 char tag[128];
22472
22473 gettag(req, "From", tag, sizeof(tag));
22474 ast_string_field_set(p, theirtag, tag);
22475 }
22476 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
22477
22478 if (sip_cfg.pedanticsipchecking) {
22479
22480
22481
22482
22483 if (!p->initreq.headers && req->has_to_tag) {
22484
22485 if (!req->ignore && req->method == SIP_INVITE) {
22486 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
22487
22488 } else if (req->method != SIP_ACK) {
22489 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22490 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22491 } else {
22492 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
22493 }
22494 return res;
22495 }
22496 }
22497
22498 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
22499 transmit_response(p, "400 Bad request", req);
22500 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22501 return -1;
22502 }
22503
22504
22505 switch (p->method) {
22506 case SIP_OPTIONS:
22507 res = handle_request_options(p, req);
22508 break;
22509 case SIP_INVITE:
22510 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
22511 break;
22512 case SIP_REFER:
22513 res = handle_request_refer(p, req, debug, seqno, nounlock);
22514 break;
22515 case SIP_CANCEL:
22516 res = handle_request_cancel(p, req);
22517 break;
22518 case SIP_BYE:
22519 res = handle_request_bye(p, req);
22520 break;
22521 case SIP_MESSAGE:
22522 res = handle_request_message(p, req);
22523 break;
22524 case SIP_SUBSCRIBE:
22525 res = handle_request_subscribe(p, req, sin, seqno, e);
22526 break;
22527 case SIP_REGISTER:
22528 res = handle_request_register(p, req, sin, e);
22529 break;
22530 case SIP_INFO:
22531 if (req->debug)
22532 ast_verbose("Receiving INFO!\n");
22533 if (!req->ignore)
22534 handle_request_info(p, req);
22535 else
22536 transmit_response(p, "200 OK", req);
22537 break;
22538 case SIP_NOTIFY:
22539 res = handle_request_notify(p, req, sin, seqno, e);
22540 break;
22541 case SIP_ACK:
22542
22543 if (seqno == p->pendinginvite) {
22544 p->invitestate = INV_TERMINATED;
22545 p->pendinginvite = 0;
22546 acked = __sip_ack(p, seqno, 1 , 0);
22547 if (find_sdp(req)) {
22548 if (process_sdp(p, req, SDP_T38_NONE))
22549 return -1;
22550 }
22551 check_pendings(p);
22552 } else if (p->glareinvite == seqno) {
22553
22554 p->glareinvite = 0;
22555 acked = __sip_ack(p, seqno, 1, 0);
22556 }
22557 if (!acked) {
22558
22559
22560 p->method = oldmethod;
22561 }
22562 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
22563 pvt_set_needdestroy(p, "unmatched ACK");
22564 }
22565 break;
22566 default:
22567 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
22568 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
22569 cmd, ast_inet_ntoa(p->sa.sin_addr));
22570
22571 if (!p->initreq.headers) {
22572 pvt_set_needdestroy(p, "unimplemented method");
22573 }
22574 break;
22575 }
22576 return res;
22577 }
22578
22579 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
22580 {
22581 struct sip_request *req;
22582
22583 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
22584 if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
22585
22586 if (option_debug) {
22587 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22588 }
22589 }
22590 ast_free(req);
22591 }
22592 }
22593
22594 static int scheduler_process_request_queue(const void *data)
22595 {
22596 struct sip_pvt *p = (struct sip_pvt *) data;
22597 int recount = 0;
22598 int nounlock = 0;
22599 int lockretry;
22600
22601 for (lockretry = 10; lockretry > 0; lockretry--) {
22602 sip_pvt_lock(p);
22603
22604
22605
22606 if (!p->owner || !ast_channel_trylock(p->owner)) {
22607 break;
22608 }
22609
22610 if (lockretry != 1) {
22611 sip_pvt_unlock(p);
22612
22613 usleep(1);
22614 }
22615 }
22616
22617 if (!lockretry) {
22618 int retry = !AST_LIST_EMPTY(&p->request_queue);
22619
22620
22621
22622
22623
22624
22625 sip_pvt_unlock(p);
22626 if (!retry) {
22627 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22628 }
22629 return retry;
22630 };
22631
22632 process_request_queue(p, &recount, &nounlock);
22633 p->request_queue_sched_id = -1;
22634
22635 if (p->owner && !nounlock) {
22636 ast_channel_unlock(p->owner);
22637 }
22638 sip_pvt_unlock(p);
22639
22640 if (recount) {
22641 ast_update_use_count();
22642 }
22643
22644 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22645
22646 return 0;
22647 }
22648
22649 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
22650 {
22651 struct sip_request *newreq;
22652
22653 if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
22654 return -1;
22655 }
22656
22657 copy_request(newreq, req);
22658 AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
22659 if (p->request_queue_sched_id == -1) {
22660 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) {
22661 dialog_unref(p, "Decrement refcount due to sched_add failure");
22662 }
22663 }
22664
22665 return 0;
22666 }
22667
22668
22669
22670
22671
22672
22673 static int sipsock_read(int *id, int fd, short events, void *ignore)
22674 {
22675 struct sip_request req;
22676 struct sockaddr_in sin = { 0, };
22677 int res;
22678 socklen_t len = sizeof(sin);
22679 static char readbuf[65535];
22680
22681 memset(&req, 0, sizeof(req));
22682 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
22683 if (res < 0) {
22684 #if !defined(__FreeBSD__)
22685 if (errno == EAGAIN)
22686 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
22687 else
22688 #endif
22689 if (errno != ECONNREFUSED)
22690 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
22691 return 1;
22692 }
22693
22694 readbuf[res] = '\0';
22695
22696 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22697 return 1;
22698 }
22699
22700 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22701 return -1;
22702 }
22703
22704
22705 req.len = ast_str_strlen(req.data);
22706 req.socket.fd = sipsock;
22707 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22708 req.socket.tcptls_session = NULL;
22709 req.socket.port = bindaddr.sin_port;
22710
22711 handle_request_do(&req, &sin);
22712 deinit_req(&req);
22713
22714 return 1;
22715 }
22716
22717
22718
22719
22720
22721 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
22722 {
22723 struct sip_pvt *p;
22724 int recount = 0;
22725 int nounlock = 0;
22726 int lockretry;
22727
22728 if (sip_debug_test_addr(sin))
22729 req->debug = 1;
22730 if (sip_cfg.pedanticsipchecking)
22731 req->len = lws2sws(req->data->str, req->len);
22732 if (req->debug) {
22733 ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n",
22734 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
22735 ntohs(sin->sin_port), req->data->str);
22736 }
22737
22738 if (parse_request(req) == -1) {
22739 ast_str_reset(req->data);
22740 return 1;
22741 }
22742 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22743
22744 if (req->debug)
22745 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22746
22747 if (req->headers < 2) {
22748 ast_str_reset(req->data);
22749 return 1;
22750 }
22751
22752
22753 for (lockretry = 10; lockretry > 0; lockretry--) {
22754 ast_mutex_lock(&netlock);
22755
22756
22757 p = find_call(req, sin, req->method);
22758 if (p == NULL) {
22759 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22760 ast_mutex_unlock(&netlock);
22761 return 1;
22762 }
22763
22764 copy_socket_data(&p->socket, &req->socket);
22765
22766
22767
22768 if (!p->owner || !ast_channel_trylock(p->owner))
22769 break;
22770
22771 if (lockretry != 1) {
22772 sip_pvt_unlock(p);
22773 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop");
22774 ast_mutex_unlock(&netlock);
22775
22776 usleep(1);
22777 }
22778 }
22779 p->recv = *sin;
22780
22781
22782 if (p->owner) {
22783 req->authenticated = 1;
22784 }
22785
22786 if (p->do_history)
22787 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22788
22789 if (!lockretry) {
22790 if (!queue_request(p, req)) {
22791
22792 sip_pvt_unlock(p);
22793 ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22794 ast_mutex_unlock(&netlock);
22795 return 1;
22796 }
22797
22798 if (p->owner)
22799 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 ??? - "));
22800 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22801 if (req->method != SIP_ACK)
22802 transmit_response(p, "503 Server error", req);
22803
22804 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22805 sip_pvt_unlock(p);
22806 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry");
22807 ast_mutex_unlock(&netlock);
22808 return 1;
22809 }
22810
22811
22812
22813
22814 if (!AST_LIST_EMPTY(&p->request_queue)) {
22815 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"));
22816 process_request_queue(p, &recount, &nounlock);
22817 }
22818
22819 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22820
22821 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22822 }
22823
22824 if (recount)
22825 ast_update_use_count();
22826
22827 if (p->owner && !nounlock)
22828 ast_channel_unlock(p->owner);
22829 sip_pvt_unlock(p);
22830 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
22831 ast_mutex_unlock(&netlock);
22832 return 1;
22833 }
22834
22835
22836
22837
22838
22839
22840
22841 static int sip_standard_port(enum sip_transport type, int port)
22842 {
22843 if (type & SIP_TRANSPORT_TLS)
22844 return port == STANDARD_TLS_PORT;
22845 else
22846 return port == STANDARD_SIP_PORT;
22847 }
22848
22849 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22850 {
22851 struct sip_threadinfo *th = obj;
22852 struct sockaddr_in *s = arg;
22853
22854 if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22855 return CMP_MATCH | CMP_STOP;
22856 }
22857
22858 return 0;
22859 }
22860
22861
22862
22863
22864
22865
22866 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22867 {
22868 struct sip_threadinfo *th;
22869 struct ast_tcptls_session_instance *tcptls_instance = NULL;
22870
22871 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22872 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22873 ao2_t_ref(th, -1, "decrement ref from callback");
22874 }
22875 return tcptls_instance;
22876 }
22877
22878
22879 static int sip_prepare_socket(struct sip_pvt *p)
22880 {
22881 struct sip_socket *s = &p->socket;
22882 static const char name[] = "SIP socket";
22883 struct sip_threadinfo *th = NULL;
22884 struct ast_tcptls_session_instance *tcptls_session;
22885 struct ast_tcptls_session_args tmp_ca = {
22886 .name = name,
22887 .accept_fd = -1,
22888 };
22889 struct ast_tcptls_session_args *ca;
22890
22891
22892 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22893 return s->fd;
22894 }
22895 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22896 (s->tcptls_session) &&
22897 (s->tcptls_session->fd != -1)) {
22898 return s->tcptls_session->fd;
22899 }
22900
22901
22902
22903
22904 if (p->outboundproxy && p->outboundproxy->transport) {
22905 s->type = p->outboundproxy->transport;
22906 }
22907
22908 if (s->type == SIP_TRANSPORT_UDP) {
22909 s->fd = sipsock;
22910 return s->fd;
22911 }
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923 tmp_ca.remote_address = *(sip_real_dst(p));
22924 if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22925 s->fd = tcptls_session->fd;
22926 if (s->tcptls_session) {
22927 ao2_ref(s->tcptls_session, -1);
22928 s->tcptls_session = NULL;
22929 }
22930 s->tcptls_session = tcptls_session;
22931 return s->fd;
22932
22933 } else if (s->tcptls_session) {
22934 return s->fd;
22935 }
22936
22937
22938
22939 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22940 !(ca->name = ast_strdup(name))) {
22941 goto create_tcptls_session_fail;
22942 }
22943 ca->accept_fd = -1;
22944 ca->remote_address = *(sip_real_dst(p));
22945
22946 if (s->type == SIP_TRANSPORT_TLS) {
22947 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22948 goto create_tcptls_session_fail;
22949 }
22950 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22951
22952 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22953 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22954 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22955 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22956
22957 goto create_tcptls_session_fail;
22958 }
22959
22960
22961 if (!ast_strlen_zero(p->tohost)) {
22962 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22963 }
22964 }
22965
22966 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22967 goto create_tcptls_session_fail;
22968 }
22969
22970 s->fd = s->tcptls_session->fd;
22971
22972
22973
22974
22975
22976 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22977 goto create_tcptls_session_fail;
22978
22979 }
22980
22981
22982 ao2_ref(s->tcptls_session, +1);
22983
22984 if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22985 ast_debug(1, "Unable to launch '%s'.", ca->name);
22986 ao2_ref(s->tcptls_session, -1);
22987 goto create_tcptls_session_fail;
22988 }
22989
22990 return s->fd;
22991
22992 create_tcptls_session_fail:
22993 if (ca) {
22994 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22995 }
22996 if (s->tcptls_session) {
22997 close(tcptls_session->fd);
22998 s->fd = tcptls_session->fd = -1;
22999 ao2_ref(s->tcptls_session, -1);
23000 s->tcptls_session = NULL;
23001 }
23002 if (th) {
23003 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
23004 }
23005
23006 return -1;
23007 }
23008
23009
23010
23011
23012
23013 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
23014 {
23015 char *port;
23016
23017 if ((*hostname = strstr(line, "://"))) {
23018 *hostname += 3;
23019
23020 if (!strncasecmp(line, "tcp", 3))
23021 *transport = SIP_TRANSPORT_TCP;
23022 else if (!strncasecmp(line, "tls", 3))
23023 *transport = SIP_TRANSPORT_TLS;
23024 else if (!strncasecmp(line, "udp", 3))
23025 *transport = SIP_TRANSPORT_UDP;
23026 else
23027 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
23028 } else {
23029 *hostname = line;
23030 *transport = SIP_TRANSPORT_UDP;
23031 }
23032
23033 if ((line = strrchr(*hostname, '@')))
23034 line++;
23035 else
23036 line = *hostname;
23037
23038 if ((port = strrchr(line, ':'))) {
23039 *port++ = '\0';
23040
23041 if (!sscanf(port, "%5u", portnum)) {
23042 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
23043 port = NULL;
23044 }
23045 }
23046
23047 if (!port) {
23048 if (*transport & SIP_TRANSPORT_TLS) {
23049 *portnum = STANDARD_TLS_PORT;
23050 } else {
23051 *portnum = STANDARD_SIP_PORT;
23052 }
23053 }
23054
23055 return 0;
23056 }
23057
23058
23059
23060
23061
23062
23063 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
23064 {
23065 struct sip_mailbox *mailbox;
23066
23067 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23068 struct ast_event *event;
23069 event = ast_event_get_cached(AST_EVENT_MWI,
23070 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
23071 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
23072 AST_EVENT_IE_END);
23073 if (!event)
23074 continue;
23075 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
23076 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
23077 ast_event_destroy(event);
23078 }
23079
23080 return (*new || *old) ? 0 : 1;
23081 }
23082
23083
23084 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
23085 {
23086
23087 struct sip_pvt *p;
23088 int newmsgs = 0, oldmsgs = 0;
23089
23090 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
23091 return 0;
23092
23093
23094 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
23095 return 0;
23096
23097 if (event) {
23098 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
23099 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
23100 } else if (!cache_only) {
23101 struct ast_str *mailbox_str = ast_str_alloca(512);
23102 peer_mailboxes_to_str(&mailbox_str, peer);
23103 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
23104 } else {
23105 get_cached_mwi(peer, &newmsgs, &oldmsgs);
23106 }
23107
23108 if (peer->mwipvt) {
23109
23110 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
23111 } else {
23112
23113 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
23114 return -1;
23115
23116
23117
23118
23119 set_socket_transport(&p->socket, 0);
23120 if (create_addr_from_peer(p, peer)) {
23121
23122 dialog_unlink_all(p, TRUE, TRUE);
23123 dialog_unref(p, "unref dialog p just created via sip_alloc");
23124
23125 return 0;
23126 }
23127
23128 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23129 build_via(p);
23130 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23131 build_callid_pvt(p);
23132 ao2_t_link(dialogs, p, "Linking in under new name");
23133
23134 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23135 }
23136
23137
23138 ast_set_flag(&p->flags[0], SIP_OUTGOING);
23139
23140 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
23141 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
23142 return 0;
23143 }
23144
23145
23146 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
23147 {
23148
23149 if (!dialog->rtp || !dialog->owner)
23150 return;
23151
23152
23153 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
23154 return;
23155
23156
23157 if (dialog->t38.state == T38_ENABLED)
23158 return;
23159
23160
23161 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
23162 return;
23163
23164
23165 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
23166 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
23167
23168 dialog->lastrtptx = time(NULL);
23169 ast_rtp_sendcng(dialog->rtp, 0);
23170 }
23171
23172
23173
23174
23175
23176
23177
23178
23179 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
23180 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
23181
23182
23183 struct sockaddr_in sin;
23184 ast_rtp_get_peer(dialog->rtp, &sin);
23185 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
23186 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
23187
23188 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
23189 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
23190 sip_pvt_unlock(dialog);
23191 usleep(1);
23192 sip_pvt_lock(dialog);
23193 }
23194 if (!dialog->owner) {
23195 return;
23196 }
23197 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
23198 dialog->owner->name, (long) (t - dialog->lastrtprx));
23199
23200 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
23201 ast_channel_unlock(dialog->owner);
23202
23203
23204
23205
23206 ast_rtp_set_rtptimeout(dialog->rtp, 0);
23207 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
23208 if (dialog->vrtp) {
23209 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
23210 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
23211 }
23212 }
23213 }
23214 }
23215 }
23216
23217
23218
23219
23220
23221 static void *do_monitor(void *data)
23222 {
23223 int res;
23224 time_t t;
23225 int reloading;
23226
23227
23228 if (sipsock > -1)
23229 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
23230
23231
23232 for(;;) {
23233
23234 ast_mutex_lock(&sip_reload_lock);
23235 reloading = sip_reloading;
23236 sip_reloading = FALSE;
23237 ast_mutex_unlock(&sip_reload_lock);
23238 if (reloading) {
23239 ast_verb(1, "Reloading SIP\n");
23240 sip_do_reload(sip_reloadreason);
23241
23242
23243 if (sipsock > -1) {
23244 if (sipsock_read_id)
23245 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
23246 else
23247 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
23248 } else if (sipsock_read_id) {
23249 ast_io_remove(io, sipsock_read_id);
23250 sipsock_read_id = NULL;
23251 }
23252 }
23253
23254
23255 t = time(NULL);
23256
23257
23258
23259
23260 ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
23261 "callback to remove dialogs w/needdestroy");
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273 pthread_testcancel();
23274
23275 res = ast_sched_wait(sched);
23276 if ((res < 0) || (res > 1000))
23277 res = 1000;
23278 res = ast_io_wait(io, res);
23279 if (res > 20)
23280 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
23281 ast_mutex_lock(&monlock);
23282 res = ast_sched_runq(sched);
23283 if (res >= 20)
23284 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
23285 ast_mutex_unlock(&monlock);
23286 }
23287
23288
23289 return NULL;
23290 }
23291
23292
23293 static int restart_monitor(void)
23294 {
23295
23296 if (monitor_thread == AST_PTHREADT_STOP)
23297 return 0;
23298 ast_mutex_lock(&monlock);
23299 if (monitor_thread == pthread_self()) {
23300 ast_mutex_unlock(&monlock);
23301 ast_log(LOG_WARNING, "Cannot kill myself\n");
23302 return -1;
23303 }
23304 if (monitor_thread != AST_PTHREADT_NULL) {
23305
23306 pthread_kill(monitor_thread, SIGURG);
23307 } else {
23308
23309 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
23310 ast_mutex_unlock(&monlock);
23311 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
23312 return -1;
23313 }
23314 }
23315 ast_mutex_unlock(&monlock);
23316 return 0;
23317 }
23318
23319
23320
23321 static void restart_session_timer(struct sip_pvt *p)
23322 {
23323 if (!p->stimer) {
23324 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
23325 return;
23326 }
23327
23328 if (p->stimer->st_active == TRUE) {
23329 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23330 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23331 dialog_unref(p, "Removing session timer ref"));
23332 start_session_timer(p);
23333 }
23334 }
23335
23336
23337
23338 static void stop_session_timer(struct sip_pvt *p)
23339 {
23340 if (!p->stimer) {
23341 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
23342 return;
23343 }
23344
23345 if (p->stimer->st_active == TRUE) {
23346 p->stimer->st_active = FALSE;
23347 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23348 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23349 dialog_unref(p, "removing session timer ref"));
23350 }
23351 }
23352
23353
23354
23355 static void start_session_timer(struct sip_pvt *p)
23356 {
23357 if (!p->stimer) {
23358 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
23359 return;
23360 }
23361
23362 if (p->stimer->st_schedid > -1) {
23363
23364 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23365 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23366 dialog_unref(p, "unref stimer->st_schedid from dialog"));
23367 }
23368
23369 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
23370 dialog_ref(p, "adding session timer ref"));
23371 if (p->stimer->st_schedid < 0) {
23372 dialog_unref(p, "removing session timer ref");
23373 ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
23374 } else {
23375 p->stimer->st_active = TRUE;
23376 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
23377 }
23378 }
23379
23380
23381
23382 static int proc_session_timer(const void *vp)
23383 {
23384 struct sip_pvt *p = (struct sip_pvt *) vp;
23385 int sendreinv = FALSE;
23386 int res = 0;
23387
23388 if (!p->stimer) {
23389 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
23390 goto return_unref;
23391 }
23392
23393 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
23394
23395 if (!p->owner) {
23396 goto return_unref;
23397 }
23398
23399 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
23400 goto return_unref;
23401 }
23402
23403 switch (p->stimer->st_ref) {
23404 case SESSION_TIMER_REFRESHER_UAC:
23405 if (p->outgoing_call == TRUE) {
23406 sendreinv = TRUE;
23407 }
23408 break;
23409 case SESSION_TIMER_REFRESHER_UAS:
23410 if (p->outgoing_call != TRUE) {
23411 sendreinv = TRUE;
23412 }
23413 break;
23414 default:
23415 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
23416 goto return_unref;
23417 }
23418
23419 if (sendreinv == TRUE) {
23420 res = 1;
23421 transmit_reinvite_with_sdp(p, FALSE, TRUE);
23422 } else {
23423 p->stimer->st_expirys++;
23424 if (p->stimer->st_expirys >= 2) {
23425 if (p->stimer->quit_flag) {
23426 goto return_unref;
23427 }
23428 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
23429 sip_pvt_lock(p);
23430 while (p->owner && ast_channel_trylock(p->owner)) {
23431 sip_pvt_unlock(p);
23432 usleep(1);
23433 if (p->stimer && p->stimer->quit_flag) {
23434 goto return_unref;
23435 }
23436 sip_pvt_lock(p);
23437 }
23438
23439 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
23440 ast_channel_unlock(p->owner);
23441 sip_pvt_unlock(p);
23442 }
23443 }
23444
23445 return_unref:
23446 if (!res) {
23447
23448 if (p->stimer) {
23449 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23450 p->stimer->st_schedid = -1;
23451 stop_session_timer(p);
23452 }
23453
23454
23455
23456 dialog_unref(p, "removing session timer ref");
23457 }
23458
23459 return res;
23460 }
23461
23462
23463
23464 int parse_minse (const char *p_hdrval, int *const p_interval)
23465 {
23466 if (ast_strlen_zero(p_hdrval)) {
23467 ast_log(LOG_WARNING, "Null Min-SE header\n");
23468 return -1;
23469 }
23470
23471 *p_interval = 0;
23472 p_hdrval = ast_skip_blanks(p_hdrval);
23473 if (!sscanf(p_hdrval, "%30d", p_interval)) {
23474 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23475 return -1;
23476 }
23477
23478 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
23479 return 0;
23480 }
23481
23482
23483
23484 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
23485 {
23486 char *p_token;
23487 int ref_idx;
23488 char *p_se_hdr;
23489
23490 if (ast_strlen_zero(p_hdrval)) {
23491 ast_log(LOG_WARNING, "Null Session-Expires header\n");
23492 return -1;
23493 }
23494
23495 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
23496 *p_interval = 0;
23497
23498 p_se_hdr = ast_strdupa(p_hdrval);
23499 p_se_hdr = ast_skip_blanks(p_se_hdr);
23500
23501 while ((p_token = strsep(&p_se_hdr, ";"))) {
23502 p_token = ast_skip_blanks(p_token);
23503 if (!sscanf(p_token, "%30d", p_interval)) {
23504 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
23505 return -1;
23506 }
23507
23508 ast_debug(2, "Session-Expires: %d\n", *p_interval);
23509
23510 if (!p_se_hdr)
23511 continue;
23512
23513 p_se_hdr = ast_skip_blanks(p_se_hdr);
23514 ref_idx = strlen("refresher=");
23515 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
23516 p_se_hdr += ref_idx;
23517 p_se_hdr = ast_skip_blanks(p_se_hdr);
23518
23519 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
23520 *p_ref = SESSION_TIMER_REFRESHER_UAC;
23521 ast_debug(2, "Refresher: UAC\n");
23522 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
23523 *p_ref = SESSION_TIMER_REFRESHER_UAS;
23524 ast_debug(2, "Refresher: UAS\n");
23525 } else {
23526 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
23527 return -1;
23528 }
23529 break;
23530 }
23531 }
23532 return 0;
23533 }
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
23544 {
23545 int rtn;
23546 const char *p_hdrval;
23547 int minse;
23548
23549 p_hdrval = get_header(rsp, "Min-SE");
23550 if (ast_strlen_zero(p_hdrval)) {
23551 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
23552 return;
23553 }
23554 rtn = parse_minse(p_hdrval, &minse);
23555 if (rtn != 0) {
23556 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23557 return;
23558 }
23559 p->stimer->st_interval = minse;
23560 transmit_invite(p, SIP_INVITE, 1, 2);
23561 }
23562
23563
23564
23565
23566
23567
23568 int st_get_se(struct sip_pvt *p, int max)
23569 {
23570 if (max == TRUE) {
23571 if (p->stimer->st_cached_max_se) {
23572 return p->stimer->st_cached_max_se;
23573 } else if (p->peername) {
23574 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23575 if (pp) {
23576 p->stimer->st_cached_max_se = pp->stimer.st_max_se;
23577 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
23578 return (p->stimer->st_cached_max_se);
23579 }
23580 }
23581 p->stimer->st_cached_max_se = global_max_se;
23582 return (p->stimer->st_cached_max_se);
23583 } else {
23584 if (p->stimer->st_cached_min_se) {
23585 return p->stimer->st_cached_min_se;
23586 } else if (p->peername) {
23587 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23588 if (pp) {
23589 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
23590 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
23591 return (p->stimer->st_cached_min_se);
23592 }
23593 }
23594 p->stimer->st_cached_min_se = global_min_se;
23595 return (p->stimer->st_cached_min_se);
23596 }
23597 }
23598
23599
23600
23601
23602
23603 enum st_refresher st_get_refresher(struct sip_pvt *p)
23604 {
23605 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
23606 return p->stimer->st_cached_ref;
23607
23608 if (p->peername) {
23609 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23610 if (pp) {
23611 p->stimer->st_cached_ref = pp->stimer.st_ref;
23612 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
23613 return pp->stimer.st_ref;
23614 }
23615 }
23616
23617 p->stimer->st_cached_ref = global_st_refresher;
23618 return global_st_refresher;
23619 }
23620
23621
23622
23623
23624
23625
23626
23627
23628 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
23629 {
23630 if (!p->stimer)
23631 sip_st_alloc(p);
23632
23633 if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
23634 return p->stimer->st_cached_mode;
23635
23636 if (p->peername) {
23637 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23638 if (pp) {
23639 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
23640 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
23641 return pp->stimer.st_mode_oper;
23642 }
23643 }
23644
23645 p->stimer->st_cached_mode = global_st_mode;
23646 return global_st_mode;
23647 }
23648
23649
23650
23651 static int sip_poke_noanswer(const void *data)
23652 {
23653 struct sip_peer *peer = (struct sip_peer *)data;
23654
23655 peer->pokeexpire = -1;
23656
23657 if (peer->lastms > -1) {
23658 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
23659 if (sip_cfg.peer_rtupdate) {
23660 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
23661 }
23662 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
23663 if (sip_cfg.regextenonqualify) {
23664 register_peer_exten(peer, FALSE);
23665 }
23666 }
23667
23668 if (peer->call) {
23669 dialog_unlink_all(peer->call, TRUE, TRUE);
23670 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23671
23672 }
23673
23674
23675 if (peer->lastms > -1) {
23676 peer->lastms = -1;
23677 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
23678 }
23679
23680
23681 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23682 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
23683 unref_peer(_data, "removing poke peer ref"),
23684 unref_peer(peer, "removing poke peer ref"),
23685 ref_peer(peer, "adding poke peer ref"));
23686
23687
23688 unref_peer(peer, "release peer poke noanswer ref");
23689
23690 return 0;
23691 }
23692
23693
23694
23695
23696
23697
23698 static int sip_poke_peer(struct sip_peer *peer, int force)
23699 {
23700 struct sip_pvt *p;
23701 int xmitres = 0;
23702
23703 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
23704
23705
23706 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23707 unref_peer(peer, "removing poke peer ref"));
23708
23709 peer->lastms = 0;
23710 if (peer->call) {
23711 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23712 }
23713 return 0;
23714 }
23715 if (peer->call) {
23716 if (sipdebug) {
23717 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23718 }
23719 dialog_unlink_all(peer->call, TRUE, TRUE);
23720 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23721
23722 }
23723 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23724 return -1;
23725 }
23726 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23727
23728 p->sa = peer->addr;
23729 p->recv = peer->addr;
23730 copy_socket_data(&p->socket, &peer->socket);
23731 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23732 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23733
23734
23735 if (!ast_strlen_zero(peer->fullcontact))
23736 ast_string_field_set(p, fullcontact, peer->fullcontact);
23737
23738 if (!ast_strlen_zero(peer->tohost))
23739 ast_string_field_set(p, tohost, peer->tohost);
23740 else
23741 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23742
23743
23744 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23745 build_via(p);
23746 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23747 build_callid_pvt(p);
23748 ao2_t_link(dialogs, p, "Linking in under new name");
23749
23750 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23751 unref_peer(peer, "removing poke peer ref"));
23752
23753 if (p->relatedpeer)
23754 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23755 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23756 ast_set_flag(&p->flags[0], SIP_OUTGOING);
23757 #ifdef VOCAL_DATA_HACK
23758 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23759 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
23760 #else
23761 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
23762 #endif
23763 peer->ps = ast_tvnow();
23764 if (xmitres == XMIT_ERROR) {
23765
23766 sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
23767 } else if (!force) {
23768 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23769 unref_peer(_data, "removing poke peer ref"),
23770 unref_peer(peer, "removing poke peer ref"),
23771 ref_peer(peer, "adding poke peer ref"));
23772 }
23773 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23774 return 0;
23775 }
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810 static int sip_devicestate(void *data)
23811 {
23812 char *host;
23813 char *tmp;
23814 struct sip_peer *p;
23815
23816 int res = AST_DEVICE_INVALID;
23817
23818
23819 host = ast_strdupa(data ? data : "");
23820 if ((tmp = strchr(host, '@')))
23821 host = tmp + 1;
23822
23823 ast_debug(3, "Checking device state for peer %s\n", host);
23824
23825
23826
23827
23828
23829
23830
23831
23832 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23833 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845 if (p->onHold)
23846
23847 res = AST_DEVICE_ONHOLD;
23848 else if (p->inRinging) {
23849 if (p->inRinging == p->inUse)
23850 res = AST_DEVICE_RINGING;
23851 else
23852 res = AST_DEVICE_RINGINUSE;
23853 } else if (p->call_limit && (p->inUse == p->call_limit))
23854
23855 res = AST_DEVICE_BUSY;
23856 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23857
23858 res = AST_DEVICE_BUSY;
23859 else if (p->call_limit && p->inUse)
23860
23861 res = AST_DEVICE_INUSE;
23862 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
23863
23864 res = AST_DEVICE_UNAVAILABLE;
23865 else
23866 res = AST_DEVICE_NOT_INUSE;
23867 } else {
23868
23869 res = AST_DEVICE_UNAVAILABLE;
23870 }
23871 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23872 } else {
23873 res = AST_DEVICE_UNKNOWN;
23874 }
23875
23876 return res;
23877 }
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23890 {
23891 struct sip_pvt *p;
23892 struct ast_channel *tmpc = NULL;
23893 char *ext = NULL, *host;
23894 char tmp[256];
23895 char *dest = data;
23896 char *dnid;
23897 char *secret = NULL;
23898 char *md5secret = NULL;
23899 char *authname = NULL;
23900 char *trans = NULL;
23901 enum sip_transport transport = 0;
23902 int oldformat = format;
23903
23904
23905
23906
23907
23908
23909
23910
23911 format &= AST_FORMAT_AUDIO_MASK;
23912 if (!format) {
23913 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));
23914 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
23915 return NULL;
23916 }
23917 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23918
23919 if (ast_strlen_zero(dest)) {
23920 ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
23921 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
23922 return NULL;
23923 }
23924
23925 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23926 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23927 *cause = AST_CAUSE_SWITCH_CONGESTION;
23928 return NULL;
23929 }
23930
23931 p->outgoing_call = TRUE;
23932
23933 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23934 dialog_unlink_all(p, TRUE, TRUE);
23935 dialog_unref(p, "unref dialog p from mem fail");
23936
23937 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23938 *cause = AST_CAUSE_SWITCH_CONGESTION;
23939 return NULL;
23940 }
23941
23942
23943 ast_copy_string(tmp, dest, sizeof(tmp));
23944
23945
23946
23947 dnid = strchr(tmp, '!');
23948 if (dnid != NULL) {
23949 *dnid++ = '\0';
23950 ast_string_field_set(p, todnid, dnid);
23951 }
23952
23953
23954 host = strchr(tmp, '@');
23955 if (host) {
23956 *host++ = '\0';
23957 ext = tmp;
23958 secret = strchr(ext, ':');
23959 }
23960 if (secret) {
23961 *secret++ = '\0';
23962 md5secret = strchr(secret, ':');
23963 }
23964 if (md5secret) {
23965 *md5secret++ = '\0';
23966 authname = strchr(md5secret, ':');
23967 }
23968 if (authname) {
23969 *authname++ = '\0';
23970 trans = strchr(authname, ':');
23971 }
23972 if (trans) {
23973 *trans++ = '\0';
23974 if (!strcasecmp(trans, "tcp"))
23975 transport = SIP_TRANSPORT_TCP;
23976 else if (!strcasecmp(trans, "tls"))
23977 transport = SIP_TRANSPORT_TLS;
23978 else {
23979 if (strcasecmp(trans, "udp"))
23980 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23981 transport = SIP_TRANSPORT_UDP;
23982 }
23983 } else {
23984 transport = SIP_TRANSPORT_UDP;
23985 }
23986
23987 if (!host) {
23988 ext = strchr(tmp, '/');
23989 if (ext)
23990 *ext++ = '\0';
23991 host = tmp;
23992 }
23993
23994 set_socket_transport(&p->socket, transport);
23995
23996
23997
23998
23999
24000
24001 if (create_addr(p, host, NULL, 1)) {
24002 *cause = AST_CAUSE_UNREGISTERED;
24003 ast_debug(3, "Cant create SIP call - target device not registered\n");
24004 dialog_unlink_all(p, TRUE, TRUE);
24005 dialog_unref(p, "unref dialog p UNREGISTERED");
24006
24007 return NULL;
24008 }
24009 if (ast_strlen_zero(p->peername) && ext)
24010 ast_string_field_set(p, peername, ext);
24011
24012 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
24013 build_via(p);
24014 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
24015 build_callid_pvt(p);
24016 ao2_t_link(dialogs, p, "Linking in under new name");
24017
24018
24019
24020
24021
24022
24023 if (ext) {
24024 ast_string_field_set(p, username, ext);
24025 ast_string_field_set(p, fullcontact, NULL);
24026 }
24027 if (secret && !ast_strlen_zero(secret))
24028 ast_string_field_set(p, peersecret, secret);
24029
24030 if (md5secret && !ast_strlen_zero(md5secret))
24031 ast_string_field_set(p, peermd5secret, md5secret);
24032
24033 if (authname && !ast_strlen_zero(authname))
24034 ast_string_field_set(p, authname, authname);
24035 #if 0
24036 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
24037 #endif
24038 p->prefcodec = oldformat;
24039 p->jointcapability = oldformat & p->capability;
24040 sip_pvt_lock(p);
24041 tmpc = sip_new(p, AST_STATE_DOWN, host);
24042 if (sip_cfg.callevents)
24043 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
24044 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
24045 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
24046 sip_pvt_unlock(p);
24047 if (!tmpc) {
24048 dialog_unlink_all(p, TRUE, TRUE);
24049
24050 }
24051 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
24052 ast_update_use_count();
24053 restart_monitor();
24054 return tmpc;
24055 }
24056
24057
24058 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
24059 {
24060 if (ast_strlen_zero(value))
24061 return;
24062
24063 if (!ast_false(value)) {
24064 char buf[64];
24065 char *word, *next;
24066
24067 ast_copy_string(buf, value, sizeof(buf));
24068 next = buf;
24069 while ((word = strsep(&next, ","))) {
24070 if (!strcasecmp(word, "port"))
24071 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
24072 else if (!strcasecmp(word, "invite"))
24073 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
24074 else
24075 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
24076 }
24077 }
24078 }
24079
24080
24081
24082
24083
24084 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
24085 int *maxdatagram)
24086 {
24087 int res = 1;
24088
24089 if (!strcasecmp(v->name, "t38pt_udptl")) {
24090 char *buf = ast_strdupa(v->value);
24091 char *word, *next = buf;
24092
24093 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
24094
24095 while ((word = strsep(&next, ","))) {
24096 if (ast_true(word) || !strcasecmp(word, "fec")) {
24097 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
24098 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
24099 } else if (!strcasecmp(word, "redundancy")) {
24100 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
24101 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
24102 } else if (!strcasecmp(word, "none")) {
24103 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
24104 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
24105 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
24106 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
24107 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
24108 *maxdatagram = global_t38_maxdatagram;
24109 }
24110 }
24111 }
24112 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
24113 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
24114 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
24115 } else if (!strcasecmp(v->name, "forwardloopdetected")) {
24116 ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
24117 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
24118 } else {
24119 res = 0;
24120 }
24121
24122 return res;
24123 }
24124
24125
24126
24127
24128
24129
24130
24131
24132 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
24133 {
24134 int res = 1;
24135
24136 if (!strcasecmp(v->name, "trustrpid")) {
24137 ast_set_flag(&mask[0], SIP_TRUSTRPID);
24138 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
24139 } else if (!strcasecmp(v->name, "sendrpid")) {
24140 ast_set_flag(&mask[0], SIP_SENDRPID);
24141 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
24142 } else if (!strcasecmp(v->name, "g726nonstandard")) {
24143 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
24144 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
24145 } else if (!strcasecmp(v->name, "useclientcode")) {
24146 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
24147 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
24148 } else if (!strcasecmp(v->name, "dtmfmode")) {
24149 ast_set_flag(&mask[0], SIP_DTMF);
24150 ast_clear_flag(&flags[0], SIP_DTMF);
24151 if (!strcasecmp(v->value, "inband"))
24152 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
24153 else if (!strcasecmp(v->value, "rfc2833"))
24154 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
24155 else if (!strcasecmp(v->value, "info"))
24156 ast_set_flag(&flags[0], SIP_DTMF_INFO);
24157 else if (!strcasecmp(v->value, "shortinfo"))
24158 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
24159 else if (!strcasecmp(v->value, "auto"))
24160 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
24161 else {
24162 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
24163 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
24164 }
24165 } else if (!strcasecmp(v->name, "nat")) {
24166 ast_set_flag(&mask[0], SIP_NAT);
24167 ast_clear_flag(&flags[0], SIP_NAT);
24168 if (!strcasecmp(v->value, "never"))
24169 ast_set_flag(&flags[0], SIP_NAT_NEVER);
24170 else if (!strcasecmp(v->value, "route"))
24171 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
24172 else if (ast_true(v->value))
24173 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
24174 else
24175 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
24176 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
24177 ast_set_flag(&mask[0], SIP_REINVITE);
24178 ast_clear_flag(&flags[0], SIP_REINVITE);
24179 if (ast_true(v->value)) {
24180 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
24181 } else if (!ast_false(v->value)) {
24182 char buf[64];
24183 char *word, *next = buf;
24184
24185 ast_copy_string(buf, v->value, sizeof(buf));
24186 while ((word = strsep(&next, ","))) {
24187 if (!strcasecmp(word, "update")) {
24188 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
24189 } else if (!strcasecmp(word, "nonat")) {
24190 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
24191 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
24192 } else {
24193 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
24194 }
24195 }
24196 }
24197 } else if (!strcasecmp(v->name, "insecure")) {
24198 ast_set_flag(&mask[0], SIP_INSECURE);
24199 ast_clear_flag(&flags[0], SIP_INSECURE);
24200 set_insecure_flags(&flags[0], v->value, v->lineno);
24201 } else if (!strcasecmp(v->name, "progressinband")) {
24202 ast_set_flag(&mask[0], SIP_PROG_INBAND);
24203 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
24204 if (ast_true(v->value))
24205 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
24206 else if (strcasecmp(v->value, "never"))
24207 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
24208 } else if (!strcasecmp(v->name, "promiscredir")) {
24209 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
24210 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
24211 } else if (!strcasecmp(v->name, "videosupport")) {
24212 if (!strcasecmp(v->value, "always")) {
24213 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24214 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24215 } else {
24216 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
24217 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
24218 }
24219 } else if (!strcasecmp(v->name, "textsupport")) {
24220 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
24221 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
24222 res = 1;
24223 } else if (!strcasecmp(v->name, "allowoverlap")) {
24224 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
24225 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
24226 } else if (!strcasecmp(v->name, "allowsubscribe")) {
24227 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
24228 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
24229 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
24230 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
24231 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
24232 } else if (!strcasecmp(v->name, "faxdetect")) {
24233 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
24234 if (ast_true(v->value)) {
24235 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
24236 } else if (ast_false(v->value)) {
24237 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
24238 } else {
24239 char *buf = ast_strdupa(v->value);
24240 char *word, *next = buf;
24241
24242 while ((word = strsep(&next, ","))) {
24243 if (!strcasecmp(word, "cng")) {
24244 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
24245 } else if (!strcasecmp(word, "t38")) {
24246 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
24247 } else {
24248 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
24249 }
24250 }
24251 }
24252 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
24253 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
24254 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
24255 } else if (!strcasecmp(v->name, "buggymwi")) {
24256 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
24257 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
24258 } else
24259 res = 0;
24260
24261 return res;
24262 }
24263
24264
24265 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
24266 {
24267 struct domain *d;
24268
24269 if (ast_strlen_zero(domain)) {
24270 ast_log(LOG_WARNING, "Zero length domain.\n");
24271 return 1;
24272 }
24273
24274 if (!(d = ast_calloc(1, sizeof(*d))))
24275 return 0;
24276
24277 ast_copy_string(d->domain, domain, sizeof(d->domain));
24278
24279 if (!ast_strlen_zero(context))
24280 ast_copy_string(d->context, context, sizeof(d->context));
24281
24282 d->mode = mode;
24283
24284 AST_LIST_LOCK(&domain_list);
24285 AST_LIST_INSERT_TAIL(&domain_list, d, list);
24286 AST_LIST_UNLOCK(&domain_list);
24287
24288 if (sipdebug)
24289 ast_debug(1, "Added local SIP domain '%s'\n", domain);
24290
24291 return 1;
24292 }
24293
24294
24295 static int check_sip_domain(const char *domain, char *context, size_t len)
24296 {
24297 struct domain *d;
24298 int result = 0;
24299
24300 AST_LIST_LOCK(&domain_list);
24301 AST_LIST_TRAVERSE(&domain_list, d, list) {
24302 if (strcasecmp(d->domain, domain))
24303 continue;
24304
24305 if (len && !ast_strlen_zero(d->context))
24306 ast_copy_string(context, d->context, len);
24307
24308 result = 1;
24309 break;
24310 }
24311 AST_LIST_UNLOCK(&domain_list);
24312
24313 return result;
24314 }
24315
24316
24317 static void clear_sip_domains(void)
24318 {
24319 struct domain *d;
24320
24321 AST_LIST_LOCK(&domain_list);
24322 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
24323 ast_free(d);
24324 AST_LIST_UNLOCK(&domain_list);
24325 }
24326
24327
24328
24329 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
24330 {
24331 char authcopy[256];
24332 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
24333 struct sip_auth *a, *b, *auth;
24334
24335 if (ast_strlen_zero(configuration))
24336 return authlist;
24337
24338 ast_debug(1, "Auth config :: %s\n", configuration);
24339
24340 ast_copy_string(authcopy, configuration, sizeof(authcopy));
24341 username = authcopy;
24342
24343
24344 realm = strrchr(username, '@');
24345 if (realm)
24346 *realm++ = '\0';
24347 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
24348 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
24349 return authlist;
24350 }
24351
24352
24353 if ((secret = strchr(username, ':'))) {
24354 *secret++ = '\0';
24355 } else if ((md5secret = strchr(username, '#'))) {
24356 *md5secret++ = '\0';
24357 }
24358
24359 if (!(auth = ast_calloc(1, sizeof(*auth))))
24360 return authlist;
24361
24362 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
24363 ast_copy_string(auth->username, username, sizeof(auth->username));
24364 if (secret)
24365 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
24366 if (md5secret)
24367 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
24368
24369
24370 for (b = NULL, a = authlist; a ; b = a, a = a->next)
24371 ;
24372 if (b)
24373 b->next = auth;
24374 else
24375 authlist = auth;
24376
24377 ast_verb(3, "Added authentication for realm %s\n", realm);
24378
24379 return authlist;
24380
24381 }
24382
24383
24384 static int clear_realm_authentication(struct sip_auth *authlist)
24385 {
24386 struct sip_auth *a = authlist;
24387 struct sip_auth *b;
24388
24389 while (a) {
24390 b = a;
24391 a = a->next;
24392 ast_free(b);
24393 }
24394
24395 return 1;
24396 }
24397
24398
24399 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
24400 {
24401 struct sip_auth *a;
24402
24403 for (a = authlist; a; a = a->next) {
24404 if (!strcasecmp(a->realm, realm))
24405 break;
24406 }
24407
24408 return a;
24409 }
24410
24411
24412
24413
24414 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
24415 {
24416 struct ast_variable *tmpvar = NULL;
24417 char *varname = ast_strdupa(buf), *varval = NULL;
24418
24419 if ((varval = strchr(varname, '='))) {
24420 *varval++ = '\0';
24421 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
24422 tmpvar->next = list;
24423 list = tmpvar;
24424 }
24425 }
24426 return list;
24427 }
24428
24429
24430 static void set_peer_defaults(struct sip_peer *peer)
24431 {
24432 if (peer->expire == 0) {
24433
24434
24435
24436 peer->expire = -1;
24437 peer->pokeexpire = -1;
24438 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
24439 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
24440 }
24441 peer->type = SIP_TYPE_PEER;
24442 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
24443 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
24444 ast_string_field_set(peer, context, sip_cfg.default_context);
24445 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
24446 ast_string_field_set(peer, language, default_language);
24447 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
24448 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
24449 peer->addr.sin_family = AF_INET;
24450 peer->defaddr.sin_family = AF_INET;
24451 peer->capability = global_capability;
24452 peer->maxcallbitrate = default_maxcallbitrate;
24453 peer->rtptimeout = global_rtptimeout;
24454 peer->rtpholdtimeout = global_rtpholdtimeout;
24455 peer->rtpkeepalive = global_rtpkeepalive;
24456 peer->allowtransfer = sip_cfg.allowtransfer;
24457 peer->autoframing = global_autoframing;
24458 peer->t38_maxdatagram = global_t38_maxdatagram;
24459 peer->qualifyfreq = global_qualifyfreq;
24460 if (global_callcounter)
24461 peer->call_limit=INT_MAX;
24462 ast_string_field_set(peer, vmexten, default_vmexten);
24463 ast_string_field_set(peer, secret, "");
24464 ast_string_field_set(peer, remotesecret, "");
24465 ast_string_field_set(peer, md5secret, "");
24466 ast_string_field_set(peer, cid_num, "");
24467 ast_string_field_set(peer, cid_name, "");
24468 ast_string_field_set(peer, fromdomain, "");
24469 ast_string_field_set(peer, fromuser, "");
24470 ast_string_field_set(peer, regexten, "");
24471 peer->callgroup = 0;
24472 peer->pickupgroup = 0;
24473 peer->maxms = default_qualify;
24474 peer->prefs = default_prefs;
24475 peer->stimer.st_mode_oper = global_st_mode;
24476 peer->stimer.st_ref = global_st_refresher;
24477 peer->stimer.st_min_se = global_min_se;
24478 peer->stimer.st_max_se = global_max_se;
24479 peer->timer_t1 = global_t1;
24480 peer->timer_b = global_timer_b;
24481 clear_peer_mailboxes(peer);
24482 peer->transports = default_transports;
24483 peer->default_outbound_transport = default_primary_transport;
24484 }
24485
24486
24487 static struct sip_peer *temp_peer(const char *name)
24488 {
24489 struct sip_peer *peer;
24490
24491 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24492 return NULL;
24493
24494 if (ast_string_field_init(peer, 512)) {
24495 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24496 return NULL;
24497 }
24498
24499 ast_atomic_fetchadd_int(&apeerobjs, 1);
24500 set_peer_defaults(peer);
24501
24502 ast_copy_string(peer->name, name, sizeof(peer->name));
24503
24504 peer->selfdestruct = TRUE;
24505 peer->host_dynamic = TRUE;
24506 peer->prefs = default_prefs;
24507 reg_source_db(peer);
24508
24509 return peer;
24510 }
24511
24512
24513 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
24514 {
24515 char *next, *mbox, *context;
24516
24517 next = ast_strdupa(value);
24518
24519 while ((mbox = context = strsep(&next, ","))) {
24520 struct sip_mailbox *mailbox;
24521 int duplicate = 0;
24522
24523 strsep(&context, "@");
24524
24525 if (ast_strlen_zero(mbox)) {
24526 continue;
24527 }
24528
24529
24530 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24531 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
24532 duplicate = 1;
24533 break;
24534 }
24535 }
24536 if (duplicate) {
24537 continue;
24538 }
24539
24540 if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
24541 continue;
24542 }
24543
24544 mailbox->mailbox = ast_strdup(mbox);
24545 mailbox->context = ast_strdup(context);
24546
24547 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
24548 }
24549 }
24550
24551
24552 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
24553 {
24554 struct sip_peer *peer = NULL;
24555 struct ast_ha *oldha = NULL;
24556 int found = 0;
24557 int firstpass = 1;
24558 uint16_t port = 0;
24559 int format = 0;
24560 time_t regseconds = 0;
24561 struct ast_flags peerflags[2] = {{(0)}};
24562 struct ast_flags mask[2] = {{(0)}};
24563 char callback[256] = "";
24564 struct sip_peer tmp_peer;
24565 const char *srvlookup = NULL;
24566 static int deprecation_warning = 1;
24567 int alt_fullcontact = alt ? 1 : 0;
24568 struct ast_str *fullcontact = ast_str_alloca(512);
24569
24570 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24571
24572
24573
24574
24575
24576 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
24577 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
24578 }
24579
24580 if (peer) {
24581
24582 found++;
24583 if (!(peer->the_mark))
24584 firstpass = 0;
24585 } else {
24586 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24587 return NULL;
24588
24589 if (ast_string_field_init(peer, 512)) {
24590 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24591 return NULL;
24592 }
24593
24594 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24595 ast_atomic_fetchadd_int(&rpeerobjs, 1);
24596 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
24597 } else
24598 ast_atomic_fetchadd_int(&speerobjs, 1);
24599 }
24600
24601
24602 if (firstpass) {
24603 peer->lastmsgssent = -1;
24604 oldha = peer->ha;
24605 peer->ha = NULL;
24606 set_peer_defaults(peer);
24607 peer->type = 0;
24608 }
24609 if (!found && name)
24610 ast_copy_string(peer->name, name, sizeof(peer->name));
24611
24612
24613 if (peer->chanvars) {
24614 ast_variables_destroy(peer->chanvars);
24615 peer->chanvars = NULL;
24616
24617 }
24618
24619 if (found)
24620 peer->portinuri = 0;
24621
24622
24623 clear_realm_authentication(peer->auth);
24624 peer->auth = NULL;
24625
24626 peer->default_outbound_transport = 0;
24627 peer->transports = 0;
24628
24629 if (!devstate_only) {
24630 struct sip_mailbox *mailbox;
24631 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24632 mailbox->delme = 1;
24633 }
24634 }
24635
24636 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
24637 if (!devstate_only) {
24638 if (handle_common_options(&peerflags[0], &mask[0], v)) {
24639 continue;
24640 }
24641 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
24642 continue;
24643 }
24644 if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24645 char *val = ast_strdupa(v->value);
24646 char *trans;
24647
24648 while ((trans = strsep(&val, ","))) {
24649 trans = ast_skip_blanks(trans);
24650
24651 if (!strncasecmp(trans, "udp", 3)) {
24652 peer->transports |= SIP_TRANSPORT_UDP;
24653 } else if (!strncasecmp(trans, "tcp", 3)) {
24654 peer->transports |= SIP_TRANSPORT_TCP;
24655 } else if (!strncasecmp(trans, "tls", 3)) {
24656 peer->transports |= SIP_TRANSPORT_TLS;
24657 } else {
24658 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24659 }
24660
24661 if (!peer->default_outbound_transport) {
24662 peer->default_outbound_transport = peer->transports;
24663 }
24664 }
24665 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
24666 ast_get_time_t(v->value, ®seconds, 0, NULL);
24667 } else if (realtime && !strcasecmp(v->name, "name")) {
24668 ast_copy_string(peer->name, v->value, sizeof(peer->name));
24669 } else if (realtime && !strcasecmp(v->name, "useragent")) {
24670 ast_string_field_set(peer, useragent, v->value);
24671 } else if (!strcasecmp(v->name, "type")) {
24672 if (!strcasecmp(v->value, "peer")) {
24673 peer->type |= SIP_TYPE_PEER;
24674 } else if (!strcasecmp(v->value, "user")) {
24675 peer->type |= SIP_TYPE_USER;
24676 } else if (!strcasecmp(v->value, "friend")) {
24677 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
24678 }
24679 } else if (!strcasecmp(v->name, "remotesecret")) {
24680 ast_string_field_set(peer, remotesecret, v->value);
24681 } else if (!strcasecmp(v->name, "secret")) {
24682 ast_string_field_set(peer, secret, v->value);
24683 } else if (!strcasecmp(v->name, "md5secret")) {
24684 ast_string_field_set(peer, md5secret, v->value);
24685 } else if (!strcasecmp(v->name, "auth")) {
24686 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
24687 } else if (!strcasecmp(v->name, "callerid")) {
24688 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
24689
24690 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
24691 ast_string_field_set(peer, cid_name, cid_name);
24692 ast_string_field_set(peer, cid_num, cid_num);
24693 } else if (!strcasecmp(v->name, "fullname")) {
24694 ast_string_field_set(peer, cid_name, v->value);
24695 } else if (!strcasecmp(v->name, "trunkname")) {
24696
24697 ast_string_field_set(peer, cid_name, "");
24698 } else if (!strcasecmp(v->name, "cid_number")) {
24699 ast_string_field_set(peer, cid_num, v->value);
24700 } else if (!strcasecmp(v->name, "context")) {
24701 ast_string_field_set(peer, context, v->value);
24702 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
24703 } else if (!strcasecmp(v->name, "subscribecontext")) {
24704 ast_string_field_set(peer, subscribecontext, v->value);
24705 } else if (!strcasecmp(v->name, "fromdomain")) {
24706 ast_string_field_set(peer, fromdomain, v->value);
24707 } else if (!strcasecmp(v->name, "usereqphone")) {
24708 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
24709 } else if (!strcasecmp(v->name, "fromuser")) {
24710 ast_string_field_set(peer, fromuser, v->value);
24711 } else if (!strcasecmp(v->name, "outboundproxy")) {
24712 char *port, *next, *force, *proxyname;
24713 int forceopt = FALSE;
24714
24715 next = proxyname = ast_strdupa(v->value);
24716 if ((port = strchr(proxyname, ':'))) {
24717 *port++ = '\0';
24718 next = port;
24719 }
24720 if ((force = strchr(next, ','))) {
24721 *force++ = '\0';
24722 forceopt = strcmp(force, "force");
24723 }
24724
24725 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24726 } else if (!strcasecmp(v->name, "host")) {
24727 if (!strcasecmp(v->value, "dynamic")) {
24728
24729 if (!found || !peer->host_dynamic) {
24730
24731
24732 memset(&peer->addr.sin_addr, 0, 4);
24733 peer->addr.sin_port = 0;
24734 }
24735 peer->host_dynamic = TRUE;
24736 } else {
24737
24738 AST_SCHED_DEL_UNREF(sched, peer->expire,
24739 unref_peer(peer, "removing register expire ref"));
24740
24741 peer->addr.sin_port = 0;
24742 peer->host_dynamic = FALSE;
24743 srvlookup = v->value;
24744 }
24745 } else if (!strcasecmp(v->name, "defaultip")) {
24746 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24747 unref_peer(peer, "unref_peer: from build_peer defaultip");
24748 return NULL;
24749 }
24750 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24751 int ha_error = 0;
24752 if (!ast_strlen_zero(v->value)) {
24753 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24754 }
24755 if (ha_error) {
24756 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24757 }
24758 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24759 int ha_error = 0;
24760 if (!ast_strlen_zero(v->value)) {
24761 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24762 }
24763 if (ha_error) {
24764 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24765 }
24766 } else if (!strcasecmp(v->name, "port")) {
24767 peer->portinuri = 1;
24768 if (!(port = port_str2int(v->value, 0))) {
24769 if (realtime) {
24770
24771 peer->portinuri = 0;
24772 } else {
24773 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24774 }
24775 }
24776 } else if (!strcasecmp(v->name, "callingpres")) {
24777 peer->callingpres = ast_parse_caller_presentation(v->value);
24778 if (peer->callingpres == -1) {
24779 peer->callingpres = atoi(v->value);
24780 }
24781 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
24782 ast_string_field_set(peer, username, v->value);
24783 if (!strcasecmp(v->name, "username")) {
24784 if (deprecation_warning) {
24785 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24786 deprecation_warning = 0;
24787 }
24788 peer->deprecated_username = 1;
24789 }
24790 } else if (!strcasecmp(v->name, "language")) {
24791 ast_string_field_set(peer, language, v->value);
24792 } else if (!strcasecmp(v->name, "regexten")) {
24793 ast_string_field_set(peer, regexten, v->value);
24794 } else if (!strcasecmp(v->name, "callbackextension")) {
24795 ast_copy_string(callback, v->value, sizeof(callback));
24796 } else if (!strcasecmp(v->name, "amaflags")) {
24797 format = ast_cdr_amaflags2int(v->value);
24798 if (format < 0) {
24799 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24800 } else {
24801 peer->amaflags = format;
24802 }
24803 } else if (!strcasecmp(v->name, "accountcode")) {
24804 ast_string_field_set(peer, accountcode, v->value);
24805 } else if (!strcasecmp(v->name, "mohinterpret")) {
24806 ast_string_field_set(peer, mohinterpret, v->value);
24807 } else if (!strcasecmp(v->name, "mohsuggest")) {
24808 ast_string_field_set(peer, mohsuggest, v->value);
24809 } else if (!strcasecmp(v->name, "parkinglot")) {
24810 ast_string_field_set(peer, parkinglot, v->value);
24811 } else if (!strcasecmp(v->name, "mailbox")) {
24812 add_peer_mailboxes(peer, v->value);
24813 } else if (!strcasecmp(v->name, "hasvoicemail")) {
24814
24815
24816 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24817 add_peer_mailboxes(peer, name);
24818 }
24819 } else if (!strcasecmp(v->name, "subscribemwi")) {
24820 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24821 } else if (!strcasecmp(v->name, "vmexten")) {
24822 ast_string_field_set(peer, vmexten, v->value);
24823 } else if (!strcasecmp(v->name, "callgroup")) {
24824 peer->callgroup = ast_get_group(v->value);
24825 } else if (!strcasecmp(v->name, "allowtransfer")) {
24826 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24827 } else if (!strcasecmp(v->name, "pickupgroup")) {
24828 peer->pickupgroup = ast_get_group(v->value);
24829 } else if (!strcasecmp(v->name, "allow")) {
24830 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24831 if (error) {
24832 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24833 }
24834 } else if (!strcasecmp(v->name, "disallow")) {
24835 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24836 if (error) {
24837 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24838 }
24839 } else if (!strcasecmp(v->name, "registertrying")) {
24840 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24841 } else if (!strcasecmp(v->name, "autoframing")) {
24842 peer->autoframing = ast_true(v->value);
24843 } else if (!strcasecmp(v->name, "rtptimeout")) {
24844 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24845 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24846 peer->rtptimeout = global_rtptimeout;
24847 }
24848 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24849 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24850 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24851 peer->rtpholdtimeout = global_rtpholdtimeout;
24852 }
24853 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24854 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24855 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
24856 peer->rtpkeepalive = global_rtpkeepalive;
24857 }
24858 } else if (!strcasecmp(v->name, "timert1")) {
24859 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24860 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
24861 peer->timer_t1 = global_t1;
24862 }
24863
24864
24865 if (peer->timer_b < peer->timer_t1 * 64) {
24866 peer->timer_b = peer->timer_t1 * 64;
24867 }
24868 } else if (!strcasecmp(v->name, "timerb")) {
24869 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24870 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
24871 peer->timer_b = global_timer_b;
24872 }
24873 if (peer->timer_b < peer->timer_t1 * 64) {
24874 static int warning = 0;
24875 if (warning++ % 20 == 0) {
24876 ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24877 }
24878 }
24879 } else if (!strcasecmp(v->name, "setvar")) {
24880 peer->chanvars = add_var(v->value, peer->chanvars);
24881 } else if (!strcasecmp(v->name, "qualifyfreq")) {
24882 int i;
24883 if (sscanf(v->value, "%30d", &i) == 1) {
24884 peer->qualifyfreq = i * 1000;
24885 } else {
24886 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24887 peer->qualifyfreq = global_qualifyfreq;
24888 }
24889 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24890 peer->maxcallbitrate = atoi(v->value);
24891 if (peer->maxcallbitrate < 0) {
24892 peer->maxcallbitrate = default_maxcallbitrate;
24893 }
24894 } else if (!strcasecmp(v->name, "session-timers")) {
24895 int i = (int) str2stmode(v->value);
24896 if (i < 0) {
24897 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24898 peer->stimer.st_mode_oper = global_st_mode;
24899 } else {
24900 peer->stimer.st_mode_oper = i;
24901 }
24902 } else if (!strcasecmp(v->name, "session-expires")) {
24903 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24904 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24905 peer->stimer.st_max_se = global_max_se;
24906 }
24907 } else if (!strcasecmp(v->name, "session-minse")) {
24908 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24909 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24910 peer->stimer.st_min_se = global_min_se;
24911 }
24912 if (peer->stimer.st_min_se < 90) {
24913 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);
24914 peer->stimer.st_min_se = global_min_se;
24915 }
24916 } else if (!strcasecmp(v->name, "session-refresher")) {
24917 int i = (int) str2strefresher(v->value);
24918 if (i < 0) {
24919 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24920 peer->stimer.st_ref = global_st_refresher;
24921 } else {
24922 peer->stimer.st_ref = i;
24923 }
24924 }
24925 }
24926
24927
24928 if (realtime && !strcasecmp(v->name, "lastms")) {
24929 sscanf(v->value, "%30d", &peer->lastms);
24930 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24931 inet_aton(v->value, &(peer->addr.sin_addr));
24932 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24933 if (alt_fullcontact && !alt) {
24934
24935
24936
24937
24938
24939 alt_fullcontact = 0;
24940 ast_str_reset(fullcontact);
24941 }
24942
24943 if (fullcontact->used > 0) {
24944 ast_str_append(&fullcontact, 0, ";%s", v->value);
24945 } else {
24946 ast_str_set(&fullcontact, 0, "%s", v->value);
24947 }
24948 } else if (!strcasecmp(v->name, "qualify")) {
24949 if (!strcasecmp(v->value, "no")) {
24950 peer->maxms = 0;
24951 } else if (!strcasecmp(v->value, "yes")) {
24952 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24953 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24954 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);
24955 peer->maxms = 0;
24956 }
24957 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24958
24959
24960
24961
24962 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);
24963 peer->maxms = 0;
24964 }
24965 } else if (!strcasecmp(v->name, "callcounter")) {
24966 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24967 } else if (!strcasecmp(v->name, "call-limit")) {
24968 peer->call_limit = atoi(v->value);
24969 if (peer->call_limit < 0) {
24970 peer->call_limit = 0;
24971 }
24972 } else if (!strcasecmp(v->name, "busylevel")) {
24973 peer->busy_level = atoi(v->value);
24974 if (peer->busy_level < 0) {
24975 peer->busy_level = 0;
24976 }
24977 }
24978 }
24979
24980 if (!devstate_only) {
24981 struct sip_mailbox *mailbox;
24982 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24983 if (mailbox->delme) {
24984 AST_LIST_REMOVE_CURRENT(entry);
24985 destroy_mailbox(mailbox);
24986 }
24987 }
24988 AST_LIST_TRAVERSE_SAFE_END;
24989 }
24990
24991 if (!peer->default_outbound_transport) {
24992
24993 peer->transports = default_transports;
24994
24995 peer->default_outbound_transport = default_primary_transport;
24996 }
24997
24998
24999
25000
25001
25002 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
25003 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
25004
25005 set_socket_transport(&peer->socket, peer->default_outbound_transport);
25006 }
25007
25008 if (port && !realtime && peer->host_dynamic) {
25009 peer->defaddr.sin_port = htons(port);
25010 } else if (port) {
25011 peer->addr.sin_port = htons(port);
25012 }
25013
25014 if (ast_str_strlen(fullcontact)) {
25015 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
25016 peer->rt_fromcontact = TRUE;
25017
25018
25019
25020
25021
25022
25023
25024
25025 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
25026 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
25027 }
25028 }
25029
25030 if (srvlookup && peer->dnsmgr == NULL) {
25031 char transport[MAXHOSTNAMELEN];
25032 char _srvlookup[MAXHOSTNAMELEN];
25033 char *params;
25034
25035 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
25036 if ((params = strchr(_srvlookup, ';'))) {
25037 *params++ = '\0';
25038 }
25039
25040 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
25041
25042 if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
25043 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
25044 unref_peer(peer, "getting rid of a peer pointer");
25045 return NULL;
25046 }
25047
25048 ast_string_field_set(peer, tohost, srvlookup);
25049 if (global_dynamic_exclude_static) {
25050 int err = 0;
25051 global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
25052 if (err) {
25053 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25054 }
25055 }
25056 }
25057
25058 if (!peer->addr.sin_port) {
25059 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
25060 }
25061 if (!peer->defaddr.sin_port) {
25062 peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
25063 }
25064 if (!peer->socket.port) {
25065 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
25066 }
25067
25068 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
25069 time_t nowtime = time(NULL);
25070
25071 if ((nowtime - regseconds) > 0) {
25072 destroy_association(peer);
25073 memset(&peer->addr, 0, sizeof(peer->addr));
25074 peer->lastms = -1;
25075 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
25076 }
25077 }
25078
25079
25080 if (!devstate_only && realtime && peer->lastms > 0) {
25081 ref_peer(peer, "schedule qualify");
25082 sip_poke_peer(peer, 0);
25083 }
25084
25085 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
25086 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
25087 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
25088 sip_cfg.allowsubscribe = TRUE;
25089 }
25090 if (peer->host_dynamic && !peer->is_realtime) {
25091 reg_source_db(peer);
25092 }
25093
25094
25095
25096 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
25097 !AST_LIST_EMPTY(&peer->mailboxes)) {
25098 add_peer_mwi_subs(peer);
25099
25100
25101
25102 sip_send_mwi_to_peer(peer, NULL, 1);
25103 }
25104
25105 peer->the_mark = 0;
25106
25107 ast_free_ha(oldha);
25108 if (!ast_strlen_zero(callback)) {
25109 char *reg_string;
25110 if (asprintf(®_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, callback) < 0) {
25111 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
25112 } else if (reg_string) {
25113 sip_register(reg_string, 0);
25114 ast_free(reg_string);
25115 }
25116 }
25117 return peer;
25118 }
25119
25120 static int peer_markall_func(void *device, void *arg, int flags)
25121 {
25122 struct sip_peer *peer = device;
25123 peer->the_mark = 1;
25124 return 0;
25125 }
25126
25127
25128
25129
25130
25131
25132
25133 static int reload_config(enum channelreloadreason reason)
25134 {
25135 struct ast_config *cfg, *ucfg;
25136 struct ast_variable *v;
25137 struct sip_peer *peer;
25138 char *cat, *stringp, *context, *oldregcontext;
25139 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
25140 struct ast_flags dummy[2];
25141 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
25142 int auto_sip_domains = FALSE;
25143 struct sockaddr_in old_bindaddr = bindaddr;
25144 int registry_count = 0, peer_count = 0;
25145 time_t run_start, run_end;
25146
25147 run_start = time(0);
25148 ast_unload_realtime("sipregs");
25149 ast_unload_realtime("sippeers");
25150 cfg = ast_config_load(config, config_flags);
25151
25152
25153 if (!cfg) {
25154 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
25155 return -1;
25156 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
25157 ucfg = ast_config_load("users.conf", config_flags);
25158 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
25159 return 1;
25160 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
25161 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
25162 return 1;
25163 }
25164
25165 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
25166 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25167 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
25168 ast_config_destroy(ucfg);
25169 return 1;
25170 }
25171 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
25172 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
25173 return 1;
25174 } else {
25175 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
25176 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
25177 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
25178 ast_config_destroy(cfg);
25179 return 1;
25180 }
25181 }
25182
25183
25184 memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
25185 memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
25186
25187 ast_free_ha(global_contact_ha);
25188 global_contact_ha = NULL;
25189
25190 default_tls_cfg.enabled = FALSE;
25191
25192 sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
25193 sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
25194
25195 if (reason != CHANNEL_MODULE_LOAD) {
25196 ast_debug(4, "--------------- SIP reload started\n");
25197
25198 clear_realm_authentication(authl);
25199 clear_sip_domains();
25200 authl = NULL;
25201
25202
25203
25204 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
25205
25206 ASTOBJ_RDLOCK(iterator);
25207 if (iterator->call) {
25208 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
25209
25210 dialog_unlink_all(iterator->call, TRUE, TRUE);
25211 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
25212 }
25213 if (iterator->expire > -1) {
25214 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
25215 }
25216 if (iterator->timeout > -1) {
25217 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
25218 }
25219 ASTOBJ_UNLOCK(iterator);
25220
25221 } while(0));
25222
25223
25224 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
25225 ast_debug(4, "--------------- Done destroying registry list\n");
25226 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
25227 }
25228
25229
25230 if (reason != CHANNEL_MODULE_LOAD) {
25231 ast_free(default_tls_cfg.certfile);
25232 ast_free(default_tls_cfg.cipher);
25233 ast_free(default_tls_cfg.cafile);
25234 ast_free(default_tls_cfg.capath);
25235 }
25236 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
25237 default_tls_cfg.cipher = ast_strdup("");
25238 default_tls_cfg.cafile = ast_strdup("");
25239 default_tls_cfg.capath = ast_strdup("");
25240
25241
25242
25243 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
25244 oldregcontext = oldcontexts;
25245
25246
25247
25248 sipdebug &= sip_debug_console;
25249 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
25250 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
25251
25252
25253 memset(&bindaddr, 0, sizeof(bindaddr));
25254 memset(&stunaddr, 0, sizeof(stunaddr));
25255 memset(&internip, 0, sizeof(internip));
25256
25257
25258 ast_free_ha(localaddr);
25259 memset(&localaddr, 0, sizeof(localaddr));
25260 memset(&externip, 0, sizeof(externip));
25261 memset(&default_prefs, 0 , sizeof(default_prefs));
25262 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
25263 sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
25264 sip_cfg.outboundproxy.ip.sin_family = AF_INET;
25265 sip_cfg.outboundproxy.force = FALSE;
25266 default_transports = 0;
25267 default_primary_transport = 0;
25268 ourport_tcp = STANDARD_SIP_PORT;
25269 ourport_tls = STANDARD_TLS_PORT;
25270 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
25271 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
25272 global_tos_sip = DEFAULT_TOS_SIP;
25273 global_tos_audio = DEFAULT_TOS_AUDIO;
25274 global_tos_video = DEFAULT_TOS_VIDEO;
25275 global_tos_text = DEFAULT_TOS_TEXT;
25276 global_cos_sip = DEFAULT_COS_SIP;
25277 global_cos_audio = DEFAULT_COS_AUDIO;
25278 global_cos_video = DEFAULT_COS_VIDEO;
25279 global_cos_text = DEFAULT_COS_TEXT;
25280
25281 externhost[0] = '\0';
25282 externexpire = 0;
25283 externrefresh = 10;
25284
25285
25286 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
25287 global_regcontext[0] = '\0';
25288 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
25289 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
25290 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
25291 sip_cfg.notifyhold = FALSE;
25292 sip_cfg.directrtpsetup = FALSE;
25293 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
25294 sip_cfg.allowsubscribe = FALSE;
25295 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
25296 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
25297 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
25298 global_prematuremediafilter = TRUE;
25299 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
25300 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
25301 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
25302 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
25303 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25304 global_regattempts_max = 0;
25305 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
25306 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
25307 global_autoframing = 0;
25308 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
25309 global_callcounter = DEFAULT_CALLCOUNTER;
25310 global_match_auth_username = FALSE;
25311 global_rtptimeout = 0;
25312 global_rtpholdtimeout = 0;
25313 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
25314 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
25315 sip_cfg.rtautoclear = 120;
25316 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
25317 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
25318 sip_cfg.peer_rtupdate = TRUE;
25319 global_dynamic_exclude_static = 0;
25320
25321
25322 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25323 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25324 global_min_se = DEFAULT_MIN_SE;
25325 global_max_se = DEFAULT_MAX_SE;
25326
25327
25328 global_qualify_gap = DEFAULT_QUALIFY_GAP;
25329 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25330
25331
25332 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
25333 sip_cfg.default_subscribecontext[0] = '\0';
25334 default_language[0] = '\0';
25335 default_fromdomain[0] = '\0';
25336 default_qualify = DEFAULT_QUALIFY;
25337 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25338 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
25339 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
25340 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
25341 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
25342 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
25343 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
25344 ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
25345
25346
25347 dumphistory = FALSE;
25348 recordhistory = FALSE;
25349 sipdebug &= ~sip_debug_config;
25350
25351
25352 global_relaxdtmf = FALSE;
25353 sip_cfg.callevents = DEFAULT_CALLEVENTS;
25354 global_authfailureevents = FALSE;
25355 global_t1 = DEFAULT_TIMER_T1;
25356 global_timer_b = 64 * DEFAULT_TIMER_T1;
25357 global_t1min = DEFAULT_T1MIN;
25358 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25359 global_t38_maxdatagram = -1;
25360 global_shrinkcallerid = 1;
25361 authlimit = DEFAULT_AUTHLIMIT;
25362 authtimeout = DEFAULT_AUTHTIMEOUT;
25363
25364 sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
25365
25366
25367 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
25368
25369 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
25370 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
25371 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
25372 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
25373
25374
25375
25376 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
25377 if (handle_common_options(&global_flags[0], &dummy[0], v))
25378 continue;
25379 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
25380 continue;
25381 }
25382
25383 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
25384 continue;
25385
25386 if (!strcasecmp(v->name, "context")) {
25387 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
25388 } else if (!strcasecmp(v->name, "subscribecontext")) {
25389 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
25390 } else if (!strcasecmp(v->name, "callcounter")) {
25391 global_callcounter = ast_true(v->value) ? 1 : 0;
25392 } else if (!strcasecmp(v->name, "allowguest")) {
25393 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
25394 } else if (!strcasecmp(v->name, "realm")) {
25395 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
25396 } else if (!strcasecmp(v->name, "useragent")) {
25397 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
25398 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
25399 } else if (!strcasecmp(v->name, "sdpsession")) {
25400 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
25401 } else if (!strcasecmp(v->name, "sdpowner")) {
25402
25403 if (!strstr(v->value, " "))
25404 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
25405 else
25406 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
25407 } else if (!strcasecmp(v->name, "allowtransfer")) {
25408 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
25409 } else if (!strcasecmp(v->name, "rtcachefriends")) {
25410 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
25411 } else if (!strcasecmp(v->name, "rtsavesysname")) {
25412 sip_cfg.rtsave_sysname = ast_true(v->value);
25413 } else if (!strcasecmp(v->name, "rtupdate")) {
25414 sip_cfg.peer_rtupdate = ast_true(v->value);
25415 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
25416 sip_cfg.ignore_regexpire = ast_true(v->value);
25417 } else if (!strcasecmp(v->name, "timert1")) {
25418
25419
25420
25421 global_t1 = atoi(v->value);
25422
25423 global_timer_b = global_t1 * 64;
25424 } else if (!strcasecmp(v->name, "t1min")) {
25425 global_t1min = atoi(v->value);
25426 } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
25427 char *val = ast_strdupa(v->value);
25428 char *trans;
25429
25430 while ((trans = strsep(&val, ","))) {
25431 trans = ast_skip_blanks(trans);
25432
25433 if (!strncasecmp(trans, "udp", 3))
25434 default_transports |= SIP_TRANSPORT_UDP;
25435 else if (!strncasecmp(trans, "tcp", 3))
25436 default_transports |= SIP_TRANSPORT_TCP;
25437 else if (!strncasecmp(trans, "tls", 3))
25438 default_transports |= SIP_TRANSPORT_TLS;
25439 else
25440 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
25441 if (default_primary_transport == 0) {
25442 default_primary_transport = default_transports;
25443 }
25444 }
25445 } else if (!strcasecmp(v->name, "tcpenable")) {
25446 sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
25447 ast_debug(2, "Enabling TCP socket for listening\n");
25448 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
25449 int family = sip_tcp_desc.local_address.sin_family;
25450 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
25451 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
25452 sip_tcp_desc.local_address.sin_family = family;
25453 ast_debug(2, "Setting TCP socket address to %s\n", v->value);
25454 } else if (!strcasecmp(v->name, "tlsenable")) {
25455 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
25456 sip_tls_desc.local_address.sin_family = AF_INET;
25457 } else if (!strcasecmp(v->name, "tlscertfile")) {
25458 ast_free(default_tls_cfg.certfile);
25459 default_tls_cfg.certfile = ast_strdup(v->value);
25460 } else if (!strcasecmp(v->name, "tlscipher")) {
25461 ast_free(default_tls_cfg.cipher);
25462 default_tls_cfg.cipher = ast_strdup(v->value);
25463 } else if (!strcasecmp(v->name, "tlscafile")) {
25464 ast_free(default_tls_cfg.cafile);
25465 default_tls_cfg.cafile = ast_strdup(v->value);
25466 } else if (!strcasecmp(v->name, "tlscapath")) {
25467 ast_free(default_tls_cfg.capath);
25468 default_tls_cfg.capath = ast_strdup(v->value);
25469 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
25470 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
25471 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
25472 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
25473 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
25474 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
25475 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
25476 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
25477 global_dynamic_exclude_static = ast_true(v->value);
25478 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
25479 int ha_error = 0;
25480 global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
25481 if (ha_error) {
25482 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25483 }
25484 } else if (!strcasecmp(v->name, "rtautoclear")) {
25485 int i = atoi(v->value);
25486 if (i > 0)
25487 sip_cfg.rtautoclear = i;
25488 else
25489 i = 0;
25490 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
25491 } else if (!strcasecmp(v->name, "usereqphone")) {
25492 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
25493 } else if (!strcasecmp(v->name, "prematuremedia")) {
25494 global_prematuremediafilter = ast_true(v->value);
25495 } else if (!strcasecmp(v->name, "relaxdtmf")) {
25496 global_relaxdtmf = ast_true(v->value);
25497 } else if (!strcasecmp(v->name, "vmexten")) {
25498 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
25499 } else if (!strcasecmp(v->name, "rtptimeout")) {
25500 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
25501 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
25502 global_rtptimeout = 0;
25503 }
25504 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
25505 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
25506 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
25507 global_rtpholdtimeout = 0;
25508 }
25509 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
25510 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
25511 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
25512 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
25513 }
25514 } else if (!strcasecmp(v->name, "compactheaders")) {
25515 sip_cfg.compactheaders = ast_true(v->value);
25516 } else if (!strcasecmp(v->name, "notifymimetype")) {
25517 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
25518 } else if (!strcasecmp(v->name, "directrtpsetup")) {
25519 sip_cfg.directrtpsetup = ast_true(v->value);
25520 } else if (!strcasecmp(v->name, "notifyringing")) {
25521 sip_cfg.notifyringing = ast_true(v->value);
25522 } else if (!strcasecmp(v->name, "notifyhold")) {
25523 sip_cfg.notifyhold = ast_true(v->value);
25524 } else if (!strcasecmp(v->name, "notifycid")) {
25525 if (!strcasecmp(v->value, "ignore-context")) {
25526 sip_cfg.notifycid = IGNORE_CONTEXT;
25527 } else {
25528 sip_cfg.notifycid = ast_true(v->value);
25529 }
25530 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
25531 sip_cfg.alwaysauthreject = ast_true(v->value);
25532 } else if (!strcasecmp(v->name, "mohinterpret")) {
25533 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
25534 } else if (!strcasecmp(v->name, "mohsuggest")) {
25535 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
25536 } else if (!strcasecmp(v->name, "language")) {
25537 ast_copy_string(default_language, v->value, sizeof(default_language));
25538 } else if (!strcasecmp(v->name, "regcontext")) {
25539 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
25540 stringp = newcontexts;
25541
25542 cleanup_stale_contexts(stringp, oldregcontext);
25543
25544 while ((context = strsep(&stringp, "&"))) {
25545 ast_copy_string(used_context, context, sizeof(used_context));
25546 ast_context_find_or_create(NULL, NULL, context, "SIP");
25547 }
25548 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
25549 } else if (!strcasecmp(v->name, "regextenonqualify")) {
25550 sip_cfg.regextenonqualify = ast_true(v->value);
25551 } else if (!strcasecmp(v->name, "callerid")) {
25552 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
25553 } else if (!strcasecmp(v->name, "fromdomain")) {
25554 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
25555 } else if (!strcasecmp(v->name, "outboundproxy")) {
25556 int portnum;
25557 char *tok, *proxyname;
25558
25559 if (ast_strlen_zero(v->value)) {
25560 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
25561 continue;
25562 }
25563
25564 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
25565
25566 sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
25567
25568 sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
25569
25570 if ((tok = strtok(NULL, ","))) {
25571 sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
25572 } else {
25573 sip_cfg.outboundproxy.force = FALSE;
25574 }
25575
25576 if (ast_strlen_zero(proxyname)) {
25577 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
25578 sip_cfg.outboundproxy.name[0] = '\0';
25579 continue;
25580 }
25581
25582 ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
25583
25584 proxy_update(&sip_cfg.outboundproxy);
25585 } else if (!strcasecmp(v->name, "autocreatepeer")) {
25586 sip_cfg.autocreatepeer = ast_true(v->value);
25587 } else if (!strcasecmp(v->name, "match_auth_username")) {
25588 global_match_auth_username = ast_true(v->value);
25589 } else if (!strcasecmp(v->name, "srvlookup")) {
25590 sip_cfg.srvlookup = ast_true(v->value);
25591 } else if (!strcasecmp(v->name, "pedantic")) {
25592 sip_cfg.pedanticsipchecking = ast_true(v->value);
25593 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
25594 max_expiry = atoi(v->value);
25595 if (max_expiry < 1)
25596 max_expiry = DEFAULT_MAX_EXPIRY;
25597 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
25598 min_expiry = atoi(v->value);
25599 if (min_expiry < 1)
25600 min_expiry = DEFAULT_MIN_EXPIRY;
25601 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
25602 default_expiry = atoi(v->value);
25603 if (default_expiry < 1)
25604 default_expiry = DEFAULT_DEFAULT_EXPIRY;
25605 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
25606 mwi_expiry = atoi(v->value);
25607 if (mwi_expiry < 1)
25608 mwi_expiry = DEFAULT_MWI_EXPIRY;
25609 } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
25610 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
25611 &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
25612 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
25613 v->name, v->value, v->lineno, config);
25614 }
25615 } else if (!strcasecmp(v->name, "tcpauthlimit")) {
25616 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
25617 &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
25618 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
25619 v->name, v->value, v->lineno, config);
25620 }
25621 } else if (!strcasecmp(v->name, "sipdebug")) {
25622 if (ast_true(v->value))
25623 sipdebug |= sip_debug_config;
25624 } else if (!strcasecmp(v->name, "dumphistory")) {
25625 dumphistory = ast_true(v->value);
25626 } else if (!strcasecmp(v->name, "recordhistory")) {
25627 recordhistory = ast_true(v->value);
25628 } else if (!strcasecmp(v->name, "registertimeout")) {
25629 global_reg_timeout = atoi(v->value);
25630 if (global_reg_timeout < 1)
25631 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25632 } else if (!strcasecmp(v->name, "registerattempts")) {
25633 global_regattempts_max = atoi(v->value);
25634 } else if (!strcasecmp(v->name, "stunaddr")) {
25635 stunaddr.sin_port = htons(3478);
25636 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
25637 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
25638 externexpire = time(NULL);
25639 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
25640 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
25641 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
25642 } else if (!strcasecmp(v->name, "localnet")) {
25643 struct ast_ha *na;
25644 int ha_error = 0;
25645
25646 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
25647 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
25648 else
25649 localaddr = na;
25650 if (ha_error)
25651 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
25652 } else if (!strcasecmp(v->name, "externip")) {
25653 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
25654 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
25655 externexpire = 0;
25656
25657 if (!externip.sin_port)
25658 externip.sin_port = bindaddr.sin_port;
25659 } else if (!strcasecmp(v->name, "externhost")) {
25660 ast_copy_string(externhost, v->value, sizeof(externhost));
25661 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
25662 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
25663 externexpire = time(NULL);
25664
25665 if (!externip.sin_port)
25666 externip.sin_port = bindaddr.sin_port;
25667 } else if (!strcasecmp(v->name, "externrefresh")) {
25668 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
25669 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
25670 externrefresh = 10;
25671 }
25672 } else if (!strcasecmp(v->name, "allow")) {
25673 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
25674 if (error)
25675 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25676 } else if (!strcasecmp(v->name, "disallow")) {
25677 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
25678 if (error)
25679 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25680 } else if (!strcasecmp(v->name, "autoframing")) {
25681 global_autoframing = ast_true(v->value);
25682 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
25683 sip_cfg.allow_external_domains = ast_true(v->value);
25684 } else if (!strcasecmp(v->name, "autodomain")) {
25685 auto_sip_domains = ast_true(v->value);
25686 } else if (!strcasecmp(v->name, "domain")) {
25687 char *domain = ast_strdupa(v->value);
25688 char *cntx = strchr(domain, ',');
25689
25690 if (cntx)
25691 *cntx++ = '\0';
25692
25693 if (ast_strlen_zero(cntx))
25694 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
25695 if (ast_strlen_zero(domain))
25696 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
25697 else
25698 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
25699 } else if (!strcasecmp(v->name, "register")) {
25700 if (sip_register(v->value, v->lineno) == 0)
25701 registry_count++;
25702 } else if (!strcasecmp(v->name, "mwi")) {
25703 sip_subscribe_mwi(v->value, v->lineno);
25704 } else if (!strcasecmp(v->name, "tos_sip")) {
25705 if (ast_str2tos(v->value, &global_tos_sip))
25706 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25707 } else if (!strcasecmp(v->name, "tos_audio")) {
25708 if (ast_str2tos(v->value, &global_tos_audio))
25709 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25710 } else if (!strcasecmp(v->name, "tos_video")) {
25711 if (ast_str2tos(v->value, &global_tos_video))
25712 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
25713 } else if (!strcasecmp(v->name, "tos_text")) {
25714 if (ast_str2tos(v->value, &global_tos_text))
25715 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
25716 } else if (!strcasecmp(v->name, "cos_sip")) {
25717 if (ast_str2cos(v->value, &global_cos_sip))
25718 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25719 } else if (!strcasecmp(v->name, "cos_audio")) {
25720 if (ast_str2cos(v->value, &global_cos_audio))
25721 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25722 } else if (!strcasecmp(v->name, "cos_video")) {
25723 if (ast_str2cos(v->value, &global_cos_video))
25724 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
25725 } else if (!strcasecmp(v->name, "cos_text")) {
25726 if (ast_str2cos(v->value, &global_cos_text))
25727 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
25728 } else if (!strcasecmp(v->name, "bindport")) {
25729 int i;
25730 if (sscanf(v->value, "%5d", &i) == 1) {
25731 bindaddr.sin_port = htons(i);
25732 } else {
25733 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
25734 }
25735 } else if (!strcasecmp(v->name, "qualify")) {
25736 if (!strcasecmp(v->value, "no")) {
25737 default_qualify = 0;
25738 } else if (!strcasecmp(v->value, "yes")) {
25739 default_qualify = DEFAULT_MAXMS;
25740 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25741 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25742 default_qualify = 0;
25743 }
25744 } else if (!strcasecmp(v->name, "qualifyfreq")) {
25745 int i;
25746 if (sscanf(v->value, "%30d", &i) == 1)
25747 global_qualifyfreq = i * 1000;
25748 else {
25749 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25750 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25751 }
25752 } else if (!strcasecmp(v->name, "callevents")) {
25753 sip_cfg.callevents = ast_true(v->value);
25754 } else if (!strcasecmp(v->name, "authfailureevents")) {
25755 global_authfailureevents = ast_true(v->value);
25756 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25757 default_maxcallbitrate = atoi(v->value);
25758 if (default_maxcallbitrate < 0)
25759 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25760 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25761 sip_cfg.matchexterniplocally = ast_true(v->value);
25762 } else if (!strcasecmp(v->name, "session-timers")) {
25763 int i = (int) str2stmode(v->value);
25764 if (i < 0) {
25765 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25766 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25767 } else {
25768 global_st_mode = i;
25769 }
25770 } else if (!strcasecmp(v->name, "session-expires")) {
25771 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25772 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25773 global_max_se = DEFAULT_MAX_SE;
25774 }
25775 } else if (!strcasecmp(v->name, "session-minse")) {
25776 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25777 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25778 global_min_se = DEFAULT_MIN_SE;
25779 }
25780 if (global_min_se < 90) {
25781 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);
25782 global_min_se = DEFAULT_MIN_SE;
25783 }
25784 } else if (!strcasecmp(v->name, "session-refresher")) {
25785 int i = (int) str2strefresher(v->value);
25786 if (i < 0) {
25787 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25788 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25789 } else {
25790 global_st_refresher = i;
25791 }
25792 } else if (!strcasecmp(v->name, "qualifygap")) {
25793 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25794 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25795 global_qualify_gap = DEFAULT_QUALIFY_GAP;
25796 }
25797 } else if (!strcasecmp(v->name, "qualifypeers")) {
25798 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25799 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25800 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25801 }
25802 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25803 if (ast_true(v->value)) {
25804 global_shrinkcallerid = 1;
25805 } else if (ast_false(v->value)) {
25806 global_shrinkcallerid = 0;
25807 } else {
25808 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25809 }
25810 }
25811 }
25812
25813 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25814 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25815 sip_cfg.allow_external_domains = 1;
25816 }
25817
25818 if (default_transports == 0) {
25819 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25820 }
25821
25822
25823 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25824
25825 if (!strcasecmp(v->name, "auth"))
25826 authl = add_realm_authentication(authl, v->value, v->lineno);
25827 }
25828
25829
25830 bindaddr.sin_family = AF_INET;
25831 internip = bindaddr;
25832 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25833 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25834 ast_config_destroy(cfg);
25835 return 0;
25836 }
25837
25838 ast_mutex_lock(&netlock);
25839 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25840 close(sipsock);
25841 sipsock = -1;
25842 }
25843 if (sipsock < 0) {
25844 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25845 if (sipsock < 0) {
25846 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25847 ast_config_destroy(cfg);
25848 ast_mutex_unlock(&netlock);
25849 return -1;
25850 } else {
25851
25852 const int reuseFlag = 1;
25853
25854 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25855 (const char*)&reuseFlag,
25856 sizeof reuseFlag);
25857
25858 ast_enable_packet_fragmentation(sipsock);
25859
25860 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25861 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25862 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25863 strerror(errno));
25864 close(sipsock);
25865 sipsock = -1;
25866 } else {
25867 ast_verb(2, "SIP Listening on %s:%d\n",
25868 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25869 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25870 }
25871 }
25872 } else {
25873 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25874 }
25875 if (stunaddr.sin_addr.s_addr != 0) {
25876 ast_debug(1, "stun to %s:%d\n",
25877 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25878 ast_stun_request(sipsock, &stunaddr,
25879 NULL, &externip);
25880 ast_debug(1, "STUN sees us at %s:%d\n",
25881 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25882 }
25883 ast_mutex_unlock(&netlock);
25884
25885
25886 ast_tcptls_server_start(&sip_tcp_desc);
25887 if (sip_tcp_desc.accept_fd == -1 && sip_tcp_desc.local_address.sin_family == AF_INET) {
25888
25889 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25890 sip_tcp_desc.local_address.sin_family = 0;
25891 } else {
25892 ast_debug(2, "SIP TCP server started\n");
25893 }
25894
25895
25896 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25897
25898 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25899 ast_tcptls_server_start(&sip_tls_desc);
25900 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25901 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25902 sip_tls_desc.tls_cfg = NULL;
25903 }
25904 } else if (sip_tls_desc.tls_cfg->enabled) {
25905 sip_tls_desc.tls_cfg = NULL;
25906 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25907 }
25908
25909 if (ucfg) {
25910 struct ast_variable *gen;
25911 int genhassip, genregistersip;
25912 const char *hassip, *registersip;
25913
25914 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25915 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25916 gen = ast_variable_browse(ucfg, "general");
25917 cat = ast_category_browse(ucfg, NULL);
25918 while (cat) {
25919 if (strcasecmp(cat, "general")) {
25920 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25921 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25922 if (ast_true(hassip) || (!hassip && genhassip)) {
25923 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25924 if (peer) {
25925
25926 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25927 ao2_t_link(peers, peer, "link peer into peer table");
25928 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25929 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25930 }
25931
25932 unref_peer(peer, "unref_peer: from reload_config");
25933 peer_count++;
25934 }
25935 }
25936 if (ast_true(registersip) || (!registersip && genregistersip)) {
25937 char tmp[256];
25938 const char *host = ast_variable_retrieve(ucfg, cat, "host");
25939 const char *username = ast_variable_retrieve(ucfg, cat, "username");
25940 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25941 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25942 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25943 if (!host)
25944 host = ast_variable_retrieve(ucfg, "general", "host");
25945 if (!username)
25946 username = ast_variable_retrieve(ucfg, "general", "username");
25947 if (!secret)
25948 secret = ast_variable_retrieve(ucfg, "general", "secret");
25949 if (!contact)
25950 contact = "s";
25951 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25952 if (!ast_strlen_zero(secret)) {
25953 if (!ast_strlen_zero(authuser)) {
25954 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25955 } else {
25956 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25957 }
25958 } else if (!ast_strlen_zero(authuser)) {
25959 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25960 } else {
25961 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25962 }
25963 if (sip_register(tmp, 0) == 0)
25964 registry_count++;
25965 }
25966 }
25967 }
25968 cat = ast_category_browse(ucfg, cat);
25969 }
25970 ast_config_destroy(ucfg);
25971 }
25972
25973
25974 cat = NULL;
25975 while ( (cat = ast_category_browse(cfg, cat)) ) {
25976 const char *utype;
25977 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25978 continue;
25979 utype = ast_variable_retrieve(cfg, cat, "type");
25980 if (!utype) {
25981 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25982 continue;
25983 } else {
25984 if (!strcasecmp(utype, "user")) {
25985 ;
25986 } else if (!strcasecmp(utype, "friend")) {
25987 ;
25988 } else if (!strcasecmp(utype, "peer")) {
25989 ;
25990 } else {
25991 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25992 continue;
25993 }
25994 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25995 if (peer) {
25996 ao2_t_link(peers, peer, "link peer into peers table");
25997 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25998 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25999 }
26000 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
26001 peer_count++;
26002 }
26003 }
26004 }
26005
26006
26007
26008
26009
26010
26011 if (auto_sip_domains) {
26012 char temp[MAXHOSTNAMELEN];
26013
26014
26015 if (bindaddr.sin_addr.s_addr) {
26016 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
26017 } else if (internip.sin_addr.s_addr) {
26018
26019 add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
26020 } else {
26021 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
26022 }
26023
26024
26025 if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
26026 add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
26027
26028
26029 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))
26030 add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
26031
26032
26033 if (externip.sin_addr.s_addr)
26034 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
26035
26036
26037 if (!ast_strlen_zero(externhost))
26038 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
26039
26040
26041 if (!gethostname(temp, sizeof(temp)))
26042 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
26043 }
26044
26045
26046 ast_config_destroy(cfg);
26047
26048
26049 if (notify_types)
26050 ast_config_destroy(notify_types);
26051 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
26052 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
26053 notify_types = NULL;
26054 }
26055
26056
26057 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);
26058 run_end = time(0);
26059 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
26060
26061 return 0;
26062 }
26063
26064 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
26065 {
26066 struct sip_pvt *p;
26067 struct ast_udptl *udptl = NULL;
26068
26069 p = chan->tech_pvt;
26070 if (!p)
26071 return NULL;
26072
26073 sip_pvt_lock(p);
26074 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26075 udptl = p->udptl;
26076 sip_pvt_unlock(p);
26077 return udptl;
26078 }
26079
26080 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
26081 {
26082 struct sip_pvt *p;
26083
26084 p = chan->tech_pvt;
26085 if (!p)
26086 return -1;
26087 sip_pvt_lock(p);
26088 if (udptl)
26089 ast_udptl_get_peer(udptl, &p->udptlredirip);
26090 else
26091 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
26092 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
26093 if (!p->pendinginvite) {
26094 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);
26095 transmit_reinvite_with_sdp(p, TRUE, FALSE);
26096 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
26097 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);
26098 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
26099 }
26100 }
26101
26102 p->lastrtprx = p->lastrtptx = time(NULL);
26103 sip_pvt_unlock(p);
26104 return 0;
26105 }
26106
26107
26108 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
26109 {
26110 struct sip_pvt *p = NULL;
26111 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
26112
26113 if (!(p = chan->tech_pvt))
26114 return AST_RTP_GET_FAILED;
26115
26116 sip_pvt_lock(p);
26117 if (!(p->rtp)) {
26118 sip_pvt_unlock(p);
26119 return AST_RTP_GET_FAILED;
26120 }
26121
26122 *rtp = p->rtp;
26123
26124 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
26125 res = AST_RTP_TRY_PARTIAL;
26126 else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26127 res = AST_RTP_TRY_NATIVE;
26128 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
26129 res = AST_RTP_GET_FAILED;
26130
26131 sip_pvt_unlock(p);
26132
26133 return res;
26134 }
26135
26136
26137 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
26138 {
26139 struct sip_pvt *p = NULL;
26140 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
26141
26142 if (!(p = chan->tech_pvt))
26143 return AST_RTP_GET_FAILED;
26144
26145 sip_pvt_lock(p);
26146 if (!(p->vrtp)) {
26147 sip_pvt_unlock(p);
26148 return AST_RTP_GET_FAILED;
26149 }
26150
26151 *rtp = p->vrtp;
26152
26153 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26154 res = AST_RTP_TRY_NATIVE;
26155
26156 sip_pvt_unlock(p);
26157
26158 return res;
26159 }
26160
26161
26162 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
26163 {
26164 struct sip_pvt *p = NULL;
26165 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
26166
26167 if (!(p = chan->tech_pvt))
26168 return AST_RTP_GET_FAILED;
26169
26170 sip_pvt_lock(p);
26171 if (!(p->trtp)) {
26172 sip_pvt_unlock(p);
26173 return AST_RTP_GET_FAILED;
26174 }
26175
26176 *rtp = p->trtp;
26177
26178 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26179 res = AST_RTP_TRY_NATIVE;
26180
26181 sip_pvt_unlock(p);
26182
26183 return res;
26184 }
26185
26186
26187 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)
26188 {
26189 struct sip_pvt *p;
26190 int changed = 0;
26191
26192 p = chan->tech_pvt;
26193 if (!p)
26194 return -1;
26195
26196
26197 if ((rtp || vrtp || trtp) &&
26198 !ast_bridged_channel(chan) &&
26199 !sip_cfg.directrtpsetup) {
26200 return 0;
26201 }
26202
26203 sip_pvt_lock(p);
26204 if (p->alreadygone) {
26205
26206 sip_pvt_unlock(p);
26207 return 0;
26208 }
26209
26210
26211
26212
26213 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
26214 sip_pvt_unlock(p);
26215 return 0;
26216 }
26217
26218 if (rtp) {
26219 changed |= ast_rtp_get_peer(rtp, &p->redirip);
26220 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
26221 memset(&p->redirip, 0, sizeof(p->redirip));
26222 changed = 1;
26223 }
26224 if (vrtp) {
26225 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
26226 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
26227 memset(&p->vredirip, 0, sizeof(p->vredirip));
26228 changed = 1;
26229 }
26230 if (trtp) {
26231 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
26232 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
26233 memset(&p->tredirip, 0, sizeof(p->tredirip));
26234 changed = 1;
26235 }
26236 if (codecs && (p->redircodecs != codecs)) {
26237 p->redircodecs = codecs;
26238 changed = 1;
26239 }
26240 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
26241 if (chan->_state != AST_STATE_UP) {
26242 if (p->do_history)
26243 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
26244 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));
26245 } else if (!p->pendinginvite) {
26246 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));
26247 transmit_reinvite_with_sdp(p, FALSE, FALSE);
26248 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
26249 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));
26250
26251 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
26252 }
26253 }
26254
26255 p->lastrtprx = p->lastrtptx = time(NULL);
26256 sip_pvt_unlock(p);
26257 return 0;
26258 }
26259
26260 static char *app_dtmfmode = "SIPDtmfMode";
26261 static char *app_sipaddheader = "SIPAddHeader";
26262 static char *app_sipremoveheader = "SIPRemoveHeader";
26263
26264
26265 static int sip_dtmfmode(struct ast_channel *chan, void *data)
26266 {
26267 struct sip_pvt *p;
26268 char *mode = data;
26269
26270 if (!data) {
26271 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
26272 return 0;
26273 }
26274 ast_channel_lock(chan);
26275 if (!IS_SIP_TECH(chan->tech)) {
26276 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
26277 ast_channel_unlock(chan);
26278 return 0;
26279 }
26280 p = chan->tech_pvt;
26281 if (!p) {
26282 ast_channel_unlock(chan);
26283 return 0;
26284 }
26285 sip_pvt_lock(p);
26286 if (!strcasecmp(mode, "info")) {
26287 ast_clear_flag(&p->flags[0], SIP_DTMF);
26288 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
26289 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26290 } else if (!strcasecmp(mode, "shortinfo")) {
26291 ast_clear_flag(&p->flags[0], SIP_DTMF);
26292 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
26293 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26294 } else if (!strcasecmp(mode, "rfc2833")) {
26295 ast_clear_flag(&p->flags[0], SIP_DTMF);
26296 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
26297 p->jointnoncodeccapability |= AST_RTP_DTMF;
26298 } else if (!strcasecmp(mode, "inband")) {
26299 ast_clear_flag(&p->flags[0], SIP_DTMF);
26300 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
26301 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26302 } else
26303 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
26304 if (p->rtp)
26305 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
26306 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
26307 if (!p->dsp) {
26308 p->dsp = ast_dsp_new();
26309 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
26310 }
26311 } else {
26312 if (p->dsp) {
26313 ast_dsp_free(p->dsp);
26314 p->dsp = NULL;
26315 }
26316 }
26317 sip_pvt_unlock(p);
26318 ast_channel_unlock(chan);
26319 return 0;
26320 }
26321
26322
26323 static int sip_addheader(struct ast_channel *chan, void *data)
26324 {
26325 int no = 0;
26326 int ok = FALSE;
26327 char varbuf[30];
26328 char *inbuf = data, *subbuf;
26329
26330 if (ast_strlen_zero(inbuf)) {
26331 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
26332 return 0;
26333 }
26334 ast_channel_lock(chan);
26335
26336
26337 while (!ok && no <= 50) {
26338 no++;
26339 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
26340
26341
26342 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
26343 ok = TRUE;
26344 }
26345 }
26346 if (ok) {
26347 size_t len = strlen(inbuf);
26348 subbuf = alloca(len + 1);
26349 ast_get_encoded_str(inbuf, subbuf, len + 1);
26350 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
26351 if (sipdebug) {
26352 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
26353 }
26354 } else {
26355 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
26356 }
26357 ast_channel_unlock(chan);
26358 return 0;
26359 }
26360
26361
26362 static int sip_removeheader(struct ast_channel *chan, void *data)
26363 {
26364 struct ast_var_t *newvariable;
26365 struct varshead *headp;
26366 int removeall = 0;
26367 char *inbuf = (char *) data;
26368
26369 if (ast_strlen_zero(inbuf)) {
26370 removeall = 1;
26371 }
26372 ast_channel_lock(chan);
26373
26374 headp=&chan->varshead;
26375 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
26376 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
26377 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
26378 if (sipdebug)
26379 ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
26380 ast_var_value(newvariable),
26381 ast_var_name(newvariable));
26382 AST_LIST_REMOVE_CURRENT(entries);
26383 ast_var_delete(newvariable);
26384 }
26385 }
26386 }
26387 AST_LIST_TRAVERSE_SAFE_END;
26388
26389 ast_channel_unlock(chan);
26390 return 0;
26391 }
26392
26393
26394
26395
26396
26397
26398
26399 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
26400 {
26401 char *cdest;
26402 char *extension, *host, *port;
26403 char tmp[80];
26404
26405 cdest = ast_strdupa(dest);
26406
26407 extension = strsep(&cdest, "@");
26408 host = strsep(&cdest, ":");
26409 port = strsep(&cdest, ":");
26410 if (ast_strlen_zero(extension)) {
26411 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
26412 return 0;
26413 }
26414
26415
26416 if (!host) {
26417 char *localtmp;
26418
26419 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
26420 if (ast_strlen_zero(tmp)) {
26421 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
26422 return 0;
26423 }
26424 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
26425 && (localtmp = strchr(localtmp, '@'))) {
26426 char lhost[80], lport[80];
26427
26428 memset(lhost, 0, sizeof(lhost));
26429 memset(lport, 0, sizeof(lport));
26430 localtmp++;
26431
26432 sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
26433 if (ast_strlen_zero(lhost)) {
26434 ast_log(LOG_ERROR, "Can't find the host address\n");
26435 return 0;
26436 }
26437 host = ast_strdupa(lhost);
26438 if (!ast_strlen_zero(lport)) {
26439 port = ast_strdupa(lport);
26440 }
26441 }
26442 }
26443
26444 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
26445 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
26446
26447 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
26448 sip_alreadygone(p);
26449
26450 return 0;
26451 }
26452
26453
26454 static int sip_get_codec(struct ast_channel *chan)
26455 {
26456 struct sip_pvt *p = chan->tech_pvt;
26457 return p->jointcapability ? p->jointcapability : p->capability;
26458 }
26459
26460
26461 static void sip_poke_all_peers(void)
26462 {
26463 int ms = 0, num = 0;
26464 struct ao2_iterator i;
26465 struct sip_peer *peer;
26466
26467 if (!speerobjs)
26468 return;
26469
26470 i = ao2_iterator_init(peers, 0);
26471 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
26472 ao2_lock(peer);
26473 if (num == global_qualify_peers) {
26474 ms += global_qualify_gap;
26475 num = 0;
26476 } else {
26477 num++;
26478 }
26479 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
26480 unref_peer(_data, "removing poke peer ref"),
26481 unref_peer(peer, "removing poke peer ref"),
26482 ref_peer(peer, "adding poke peer ref"));
26483 ao2_unlock(peer);
26484 unref_peer(peer, "toss iterator peer ptr");
26485 }
26486 ao2_iterator_destroy(&i);
26487 }
26488
26489
26490 static void sip_send_all_registers(void)
26491 {
26492 int ms;
26493 int regspacing;
26494 if (!regobjs)
26495 return;
26496 regspacing = default_expiry * 1000/regobjs;
26497 if (regspacing > 100)
26498 regspacing = 100;
26499 ms = regspacing;
26500 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
26501 ASTOBJ_WRLOCK(iterator);
26502 ms += regspacing;
26503 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
26504 registry_unref(_data, "REPLACE sched del decs the refcount"),
26505 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
26506 registry_addref(iterator, "REPLACE sched add incs the refcount"));
26507 ASTOBJ_UNLOCK(iterator);
26508 } while (0)
26509 );
26510 }
26511
26512
26513 static void sip_send_all_mwi_subscriptions(void)
26514 {
26515 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
26516 ASTOBJ_WRLOCK(iterator);
26517 AST_SCHED_DEL(sched, iterator->resub);
26518 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
26519 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
26520 }
26521 ASTOBJ_UNLOCK(iterator);
26522 } while (0));
26523 }
26524
26525
26526 static int sip_do_reload(enum channelreloadreason reason)
26527 {
26528 time_t start_poke, end_poke;
26529
26530 reload_config(reason);
26531 ast_sched_dump(sched);
26532
26533 start_poke = time(0);
26534
26535 unlink_marked_peers_from_tables();
26536
26537 ast_debug(4, "--------------- Done destroying pruned peers\n");
26538
26539
26540 sip_poke_all_peers();
26541
26542
26543 sip_send_all_registers();
26544
26545 sip_send_all_mwi_subscriptions();
26546
26547 end_poke = time(0);
26548
26549 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
26550
26551 ast_debug(4, "--------------- SIP reload done\n");
26552
26553 return 0;
26554 }
26555
26556
26557 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
26558 {
26559
26560 switch (cmd) {
26561 case CLI_INIT:
26562 e->command = "sip reload";
26563 e->usage =
26564 "Usage: sip reload\n"
26565 " Reloads SIP configuration from sip.conf\n";
26566 return NULL;
26567 case CLI_GENERATE:
26568 return NULL;
26569 }
26570
26571 ast_mutex_lock(&sip_reload_lock);
26572 if (sip_reloading)
26573 ast_verbose("Previous SIP reload not yet done\n");
26574 else {
26575 sip_reloading = TRUE;
26576 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
26577 }
26578 ast_mutex_unlock(&sip_reload_lock);
26579 restart_monitor();
26580
26581 return CLI_SUCCESS;
26582 }
26583
26584
26585 static int reload(void)
26586 {
26587 if (sip_reload(0, 0, NULL))
26588 return 0;
26589 return 1;
26590 }
26591
26592
26593 static struct ast_cli_entry cli_sip[] = {
26594 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
26595 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
26596 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
26597 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
26598 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
26599 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
26600 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
26601 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
26602 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
26603 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
26604 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
26605 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
26606 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
26607 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
26608 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
26609 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
26610 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
26611 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
26612 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
26613 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
26614 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
26615 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
26616 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
26617 };
26618
26619
26620 static int load_module(void)
26621 {
26622 ast_verbose("SIP channel loading...\n");
26623
26624
26625 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
26626 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
26627 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
26628 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
26629
26630 ASTOBJ_CONTAINER_INIT(®l);
26631 ASTOBJ_CONTAINER_INIT(&submwil);
26632
26633 if (!(sched = sched_context_create())) {
26634 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
26635 return AST_MODULE_LOAD_FAILURE;
26636 }
26637
26638 if (!(io = io_context_create())) {
26639 ast_log(LOG_ERROR, "Unable to create I/O context\n");
26640 sched_context_destroy(sched);
26641 return AST_MODULE_LOAD_FAILURE;
26642 }
26643
26644 sip_reloadreason = CHANNEL_MODULE_LOAD;
26645
26646 if(reload_config(sip_reloadreason))
26647 return AST_MODULE_LOAD_DECLINE;
26648
26649
26650
26651
26652
26653 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
26654 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
26655
26656
26657 if (ast_channel_register(&sip_tech)) {
26658 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
26659 io_context_destroy(io);
26660 sched_context_destroy(sched);
26661 return AST_MODULE_LOAD_FAILURE;
26662 }
26663
26664
26665 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
26666
26667
26668 ast_rtp_proto_register(&sip_rtp);
26669
26670
26671 ast_udptl_proto_register(&sip_udptl);
26672
26673
26674 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
26675 ast_register_application_xml(app_sipaddheader, sip_addheader);
26676 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
26677
26678
26679 ast_custom_function_register(&sip_header_function);
26680 ast_custom_function_register(&sippeer_function);
26681 ast_custom_function_register(&sipchaninfo_function);
26682 ast_custom_function_register(&checksipdomain_function);
26683
26684
26685 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
26686 "List SIP peers (text format)", mandescr_show_peers);
26687 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
26688 "Show SIP peer (text format)", mandescr_show_peer);
26689 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
26690 "Show SIP peer (text format)", mandescr_show_peer);
26691 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
26692 "Show SIP registrations (text format)", mandescr_show_registry);
26693 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
26694 "Send a SIP notify", mandescr_sipnotify);
26695 sip_poke_all_peers();
26696 sip_send_all_registers();
26697 sip_send_all_mwi_subscriptions();
26698
26699
26700 restart_monitor();
26701
26702 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
26703 "name", RQ_CHAR, 10,
26704 "ipaddr", RQ_CHAR, 15,
26705 "port", RQ_UINTEGER2, 5,
26706 "regseconds", RQ_INTEGER4, 11,
26707 "defaultuser", RQ_CHAR, 10,
26708 "fullcontact", RQ_CHAR, 35,
26709 "regserver", RQ_CHAR, 20,
26710 "useragent", RQ_CHAR, 20,
26711 "lastms", RQ_INTEGER4, 11,
26712 SENTINEL);
26713
26714 return AST_MODULE_LOAD_SUCCESS;
26715 }
26716
26717
26718 static int unload_module(void)
26719 {
26720 struct sip_pvt *p;
26721 struct sip_threadinfo *th;
26722 struct ast_context *con;
26723 struct ao2_iterator i;
26724
26725 ast_sched_dump(sched);
26726
26727
26728 ast_channel_unregister(&sip_tech);
26729
26730
26731 ast_custom_function_unregister(&sipchaninfo_function);
26732 ast_custom_function_unregister(&sippeer_function);
26733 ast_custom_function_unregister(&sip_header_function);
26734 ast_custom_function_unregister(&checksipdomain_function);
26735
26736
26737 ast_unregister_application(app_dtmfmode);
26738 ast_unregister_application(app_sipaddheader);
26739 ast_unregister_application(app_sipremoveheader);
26740
26741
26742 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26743
26744
26745 ast_rtp_proto_unregister(&sip_rtp);
26746
26747
26748 ast_udptl_proto_unregister(&sip_udptl);
26749
26750
26751 ast_manager_unregister("SIPpeers");
26752 ast_manager_unregister("SIPshowpeer");
26753 ast_manager_unregister("SIPqualifypeer");
26754 ast_manager_unregister("SIPshowregistry");
26755 ast_manager_unregister("SIPnotify");
26756
26757
26758 if (sip_tcp_desc.master)
26759 ast_tcptls_server_stop(&sip_tcp_desc);
26760 if (sip_tls_desc.master)
26761 ast_tcptls_server_stop(&sip_tls_desc);
26762
26763
26764 i = ao2_iterator_init(threadt, 0);
26765 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26766 pthread_t thread = th->threadid;
26767 th->stop = 1;
26768 pthread_kill(thread, SIGURG);
26769 pthread_join(thread, NULL);
26770 ao2_t_ref(th, -1, "decrement ref from iterator");
26771 }
26772 ao2_iterator_destroy(&i);
26773
26774
26775 i = ao2_iterator_init(dialogs, 0);
26776 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26777 if (p->owner)
26778 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26779 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26780 }
26781 ao2_iterator_destroy(&i);
26782
26783 unlink_all_peers_from_tables();
26784
26785 ast_mutex_lock(&monlock);
26786 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26787 pthread_cancel(monitor_thread);
26788 pthread_kill(monitor_thread, SIGURG);
26789 pthread_join(monitor_thread, NULL);
26790 }
26791 monitor_thread = AST_PTHREADT_STOP;
26792 ast_mutex_unlock(&monlock);
26793
26794
26795 i = ao2_iterator_init(dialogs, 0);
26796 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26797 dialog_unlink_all(p, TRUE, TRUE);
26798 ao2_t_ref(p, -1, "throw away iterator result");
26799 }
26800 ao2_iterator_destroy(&i);
26801
26802
26803 ast_free_ha(localaddr);
26804
26805 clear_realm_authentication(authl);
26806
26807
26808 if (default_tls_cfg.certfile)
26809 ast_free(default_tls_cfg.certfile);
26810 if (default_tls_cfg.cipher)
26811 ast_free(default_tls_cfg.cipher);
26812 if (default_tls_cfg.cafile)
26813 ast_free(default_tls_cfg.cafile);
26814 if (default_tls_cfg.capath)
26815 ast_free(default_tls_cfg.capath);
26816
26817 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
26818 ASTOBJ_CONTAINER_DESTROY(®l);
26819 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26820 ASTOBJ_CONTAINER_DESTROY(&submwil);
26821
26822 ao2_t_ref(peers, -1, "unref the peers table");
26823 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26824 ao2_t_ref(dialogs, -1, "unref the dialogs table");
26825 ao2_t_ref(threadt, -1, "unref the thread table");
26826
26827 clear_sip_domains();
26828 ast_free_ha(global_contact_ha);
26829 close(sipsock);
26830 sched_context_destroy(sched);
26831 con = ast_context_find(used_context);
26832 if (con)
26833 ast_context_destroy(con, "SIP");
26834 ast_unload_realtime("sipregs");
26835 ast_unload_realtime("sippeers");
26836
26837 return 0;
26838 }
26839
26840 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26841 .load = load_module,
26842 .unload = unload_module,
26843 .reload = reload,
26844 );